<template>
       <!--搜索区域-->
    <a-col :md="24" :sm="24" :order="1"  class="flex-container-nowidth">
      <div class="table-page-search-wrapper">
            <a-form layout="inline">
              <a-row :gutter="48">

                <a-col :md="6" :sm="24">
                  <a-form-item label="账号">
                    <a-input v-model="queryParams.account" placeholder="请输入" />
                  </a-form-item>
                </a-col>

                  <a-col :md="6" :sm="24">
                      <a-form-item label="姓名">
                          <a-input v-model="queryParams.name" placeholder="请输入" />
                      </a-form-item>
                  </a-col>


                  <a-col :md="6" :sm="24">
                      <a-form-item label="电话">
                          <a-input v-model="queryParams.phone" placeholder="请输入" />
                      </a-form-item>
                  </a-col>

                <a-col :md="6" :sm="24">
                  <a-form-item label="部门">
                    <treecheck @select="treeSelect"  ref="tree1" :createFun="getList"></treecheck>
                  </a-form-item>
                </a-col>

                <a-col :md="6" :sm="24">
                  <a-form-item label="使用状态">
                    <a-select v-model="queryParams.status" placeholder="请选择" default-value="1">
<!--                      <a-select-option value="1,2,3">全部</a-select-option>-->
                      <a-select-option value="1">正常</a-select-option>
                      <a-select-option value="2">冻结</a-select-option>
                      <a-select-option value="3">已失效</a-select-option>
                    </a-select>
                  </a-form-item>
                </a-col>
                <template v-if="advanced">

                </template>
                <a-col :md="6" :sm="24">
                    <a-button type="primary" icon="search" @click="reflashTable" >搜索</a-button>
                    <a-button style="margin-left: 8px" type="primary" icon="plus" @click="handleAdd">添加</a-button>
                </a-col>
              </a-row>
            </a-form>
          </div>
        <s-table
          ref="table"
          size="small"
          class="flex-filling"
          style="word-break: break-all;"
          bordered
          :columns="columns"
          :data="rowdata"
        >
          <template slot="createtime" slot-scope="text" >
            {{ text | dayjs}}
          </template>
            <template slot="roleName" slot-scope="text, record">
                <a-tooltip placement="left">
                    <template slot="title">
                        {{text}}
                    </template>
                    <div style="width: 180px; overflow:hidden;text-overflow:ellipsis; white-space: nowrap;" >
                        {{text}}
                    </div>
                </a-tooltip>
            </template>
          <template slot="operation" slot-scope="text, record" v-if="record.status != 3">
            <span>
              <a @click="toggle(record.id)">修改</a>
              <a-divider type="vertical"/>
              <a-popconfirm title="是否要删除此行？" @confirm="remove(record.id)">
                <a>删除</a>
              </a-popconfirm>
               <a-divider type="vertical"/>
               <a @click="updatePassword(record.id)">密码修改</a>

            </span>
          </template>
          <template slot="status" slot-scope="text, record" v-if="record.status != 3">
            <a-switch checkedChildren="正常" @change="changeDongjie($event,record.id)" unCheckedChildren="冻结" :defaultChecked="record.status==2?false:true" />
          </template>
        </s-table>
      <!-- 修改密码 -->
      <a-modal title="密码修改" v-model="editpaswordmodel" @ok="editPassword" @cancel="editPasswordcancel">
        <a-form :form="EditPassFrom">
          <a-form-item label="新密码" >
            <a-input placeholder="新密码"  v-decorator="['editpassword',{rules: [{ required: true, message: '新密码不能为空！' }]}]"  type="password"></a-input>
          </a-form-item>
          <a-form-item label="确认密码" >
            <a-input placeholder="确认密码"  v-decorator="['editrepassword',{rules: [{ required: true, message: '确认密码不能为空' }, { validator: this.compareToFirstPassword,}]}]"  type="password"></a-input>
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 添加用户 -->
      <a-modal title="添加用户" v-model="add_user" @ok="handleOk" destroyOnClose="true">
        <a-form>
          <a-form-item label="账号" >
            <a-input placeholder="清输入账号" v-model="modelData.account"></a-input>
          </a-form-item>
          <a-form-item label="姓名" >
            <a-input placeholder="请输入姓名" v-model="modelData.name"></a-input>
          </a-form-item>
          <!--<a-form-item label="出生日期" >
            <j-date
                v-model="modelData.birthday"
                :showTime="true"
                date-format="YYYY-MM-DD"
                style="width:45%"
                placeholder="请选择开始时间"
              ></j-date>
          </a-form-item>-->
          <a-form-item label="密码" >
            <a-input placeholder="请输入密码" v-model="modelData.password"></a-input>
          </a-form-item>
          <a-form-item label="重复密码" >
            <a-input placeholder="请再次输入密码" v-model="modelData.rePassword"></a-input>
          </a-form-item>
          <a-form-item label="邮箱" >
            <a-input placeholder="请输入邮箱" v-model="modelData.email"></a-input>
          </a-form-item>
          <!--<a-form-item label="性别" >
            <a-radio-group defaultValue="1" v-model="modelData.sex">
              <a-radio value="1">男</a-radio>
              <a-radio value="2">女</a-radio>
            </a-radio-group>
          </a-form-item>-->
          <a-form-item label="角色" >
            <!-- <a-input placeholder="请输入部门" v-model="modelData.content" @click="handelDepartment"></a-input> -->
            <treecheck ref="tree3" @selectcheck="contentSelectCheck1" :treeCheckable="true" :createFun="userRoleTreeList"></treecheck>
          </a-form-item>
          <a-form-item label="部门" >
            <!-- <a-input placeholder="请输入部门" v-model="modelData.content" @click="handelDepartment"></a-input> -->
            <treecheck ref="tree1" @select="contentSelect1" :createFun="getList"></treecheck>
          </a-form-item>
          <a-form-item label="电话" >
            <a-input placeholder="请输入电话" v-model="modelData.phone"></a-input>
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 修改用户信息 -->
      <a-modal title="编辑用户" v-model="visible" @ok="handleUpdata">
        <a-form>
          <a-form-item label="账号" >
            <a-input placeholder="清输入账号" v-model="showModals.account"></a-input>
          </a-form-item>
          <a-form-item label="姓名" >
            <a-input placeholder="请输入姓名" v-model="showModals.name"></a-input>
          </a-form-item>
          <!--<a-form-item label="出生日期" >
            <j-date
                v-model="showModals.birthday"
                :showTime="true"
                date-format="YYYY-MM-DD"
                style="width:45%"
                placeholder="请选择开始时间"
              ></j-date>
          </a-form-item>-->
          <a-form-item label="邮箱" >
            <a-input placeholder="请输入邮箱" v-model="showModals.email"></a-input>
          </a-form-item>
          <!--<a-form-item label="性别" >
            <a-radio-group defaultValue="1" v-model="showModals.sex">
              <a-radio value="1">男</a-radio>
              <a-radio value="2">女</a-radio>
            </a-radio-group>
          </a-form-item>-->
          <a-form-item label="角色" >
            <!-- <a-input placeholder="请输入部门" v-model="modelData.content" @click="handelDepartment"></a-input> -->
            <treecheck ref="tree4" @selectcheck="contentSelectCheck2" :treeCheckable="true" :createFun="userRoleTreeList"></treecheck>
          </a-form-item>
          <a-form-item label="部门" >
            <!-- <a-input placeholder="请输入部门" v-model="modelData.content" @click="handelDepartment"></a-input> -->
            <treecheck ref="tree2" @select="contentSelect2" :createFun="getList"></treecheck>
          </a-form-item>
          <a-form-item label="电话" >
            <a-input placeholder="请输入电话" v-model="showModals.phone"></a-input>
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 重置密码 -->
      <a-modal title="重置密码" v-model="resetPassw" @ok="resetPassword">
        <p>是否重置密码为111111 ?</p>
      </a-modal>

      <!-- 部门 -->
      <a-modal title="部门选择" v-model="Department" @ok="confirmD">
        <treeList></treeList>
        <br />
        <br />
        <br />
        <br />
        <br />
      </a-modal>

      <!-- 分配角色 -->
      <a-modal title="角色分配" v-model="reol" @ok="reolConfirm">
        <treeList></treeList>
        <br />
        <br />
        <br />
        <br />
        <br />
      </a-modal>
    </a-col>
</template>
<script>
import STable from '@/components/table'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import AInput from 'ant-design-vue/es/input/Input'
import treeList from '@/components/sysmanage/treeList'
import treecheck from '@/components/sysmanage/treeCheck'
import JDate from '@/components/jeecg/JDate'
import {notification} from 'ant-design-vue'
import { unique } from '@/utils/util'
import {
  getList,
  tabList,
  getUserInfo,
  deleteList,
  resetPass,
  getAddUser,
  userRoleTreeList,
  getEditUser,
  userFreeze,
  userUnFreeze,
  changeOtherPwd
} from '@/api/system'

export default {
  name:"systemUser",
  components: {
    ATextarea,
    STable,
    AInput,
    treeList,
    treecheck,
    JDate
  },
  data() {
    return {
      EditPassFrom: this.$form.createForm(this, { name: 'modify'},),
      EditPassMess:"不能为空！",
      //修改密码窗口
      editpaswordmodel:false,
      editpasswordfrom:{
        newPwd:"",
        rePwd:"",
        changeId:"",
      },
      settings:{ y: 500,x:2000 },
      advanced:false,//控制菜单展开
      getList:getList,
      userRoleTreeList:userRoleTreeList,
      columns: [
        { dataIndex: 'account',width:150,fixed: 'left', sort: true, title: '账号', customRender(text,data){
            if(data.status == 3){
              return text.replace(/_del/g,"")+"(已删除)";
            }
            return text;
          } },
        { dataIndex: 'name',width:100,fixed: 'left',sort: true, title: '姓名',  },
        /*{ dataIndex: 'sexName',width:200, sort: true, title: '性别', sorter: true },*/
        { dataIndex: 'roleName',width:200,fixed: 'left', sort: true, title: '角色', scopedSlots: {customRender: 'roleName'}},
        { dataIndex: 'deptName',width:150, sort: true, title: '部门'},
        { dataIndex: 'email',width:180, sort: true, title: '邮箱' },
        { dataIndex: 'phone',width:150, sort: true, title: '电话' },
        { dataIndex: 'createtime',width:150, sort: true, title: '创建时间',  scopedSlots: { customRender: 'createtime' }},
        { dataIndex: 'status',width:100,fixed: 'right', sort: true, title: '状态',  scopedSlots: { customRender: 'status' } },
        {
          dataIndex: 'center',
          toolbar: '#tableBar',
          title: '操作',
          width: 200,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      //查询条件
      queryParams: {
        account: '',
        status:"1",
        deptid:"",
        name:"",
        phone:""
      },
      modelData: {
        account: '',
        name: '',
        //birthday:'',
        //sex: '1',
        email: '',
        phone: '',
        updateTime: '',
        password: '',
        rePassword: '',
        deptid:"",
        deptName:"",
        roleid:""
      },
      showModals: {
        name: '',
        //birthday: '',
        email: '',
        deptName: '',
        phone: '',
        //sex: '1',
        account: '',
        id: '',
        deptid: '',
        roleid:""
      },
      rowdata: parameter => {
        let params = {
          page: parameter.pageNo,
          limit: parameter.pageSize
        }
        let obj = this.queryParams
        return tabList(Object.assign(params, obj)).then(res => {
          let data = {
            data: res.rows,
            pageSize: parameter.pageSize,
            pageNo: parameter.pageNo,
            totalCount: res.total
          }
          return data
        })
      },
      visible: false,
      resetPassw: false,
      add_user: false,
      Department: false,
      reol: false
    }
  },
  methods: {
    //密码加密
    getPass(text){
      /*let keyss = setMaxDigits(130);
      keyss = new RSAKeyPair("10001","","a5d210338760bdbe2baabef73c410582e812dad8d9669d8c6ebfe026450e5cc10005290f17a0474c7351031edbff81bd8217a518bdf1a02855f53105ead0370e8a9e30b8560feab1d333a0b055b29419476b0eea1ea54315662ddfc46ec066f076e9490ec34c825afad9e44cf38e5ab600f3136acfe3a0ac0e672e2cb8e50371");
      let password = encryptedString(keyss,text);*/
      let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAcsbUyeRD2lQGPEnu5LbXOL2lycUJwK/8BsoZD3b932l4JehAvOKR/YNzs6EG4gnZ7gaXLCnWbE5kB1wuUooo6bv8fSAg0W5QmM1TH8zaIImdAaN6c8mw5dUS/2VJ/2GHI54R1NJziX9VHecpf2DrHnWngETsNytmXaVl3JiXywIDAQAB";
      let encrypt = new window.JSEncrypt();
      encrypt.setPublicKey(publicKey);
      var encryptPwd = encrypt.encryptLong(text);
      return encryptPwd;
      //return text;
    },
    //提交密码修改
    editPassword() {
      this.EditPassFrom.validateFields(err => {
        if (!err) {
          this.editpasswordfrom.newPwd= encodeURIComponent(this.getPass(this.EditPassFrom.getFieldValue('editpassword')))
          this.editpasswordfrom.rePwd=this.editpasswordfrom.newPwd
          changeOtherPwd(this.editpasswordfrom).then(res => {
            if (res.code == 200) {
              this.EditPassFrom.setFieldsValue({editpassword:""});
              this.EditPassFrom.setFieldsValue({editrepassword:""});
              if(res.message==undefined){
                this.$message.success(res.data != "" ? res.data : "修改成功", 5);
              }else {
                this.$message.success(res.message != "" ? res.message : "修改成功", 5);
              }

            }else{
              if(res.message==undefined){
                this.$message.error(res.data != "" ? res.data : "失败修改", 5);
              }else {
                this.$message.error(res.message != "" ? res.message : "失败修改", 5);
              }
            }
            this.editpaswordmodel = false
          })
        }
      })
    },
    editPasswordcancel(){
      this.editpaswordmodel=false
      this.EditPassFrom.setFieldsValue({
        editpassword:'',
        editrepassword:''
      })
    },
    compareToFirstPassword  (rule, value, callback) {
      const form = this.EditPassFrom;
      if (value && value !== form.getFieldValue('editpassword')) {
        callback('两次输入的密码不一样！');
      } else {
        callback()
      }
    },
    changeDongjie(event,id){
      if(event){
        userUnFreeze({userId:id}).then(res =>{
          if(res.code == 200){
            notification.success({ message: '系统提示', description: '解冻成功'})
          }else{
            notification.error({ message: '系统提示', description: '解冻失败'})
          }
        });
      }else{
        userFreeze({userId:id}).then(res =>{
          if(res.code == 200){
            notification.success({ message: '系统提示', description: '冻结成功'})
          }else{
            notification.error({ message: '系统提示', description: '冻结失败'})
          }
        });
      }

    },
    reflashTable() {
      this.$refs.table.refresh({ search: true })
    },
    //树级筛选
    treeSelect(data){
      let id = "";
      if(data){
        id = data.id;
      }
      this.queryParams.deptid = id;
      this.reflashTable();

    },
    contentSelect1(data){
      this.modelData.deptid = data.id;
      this.modelData.deptName = data.name;
    },
    contentSelect2(data){
      this.showModals.deptid = data.id;
      this.showModals.deptName = data.name;
    },
    contentSelectCheck1(data){
      let list = data.list;
      let textlist = new Array();
      let pObj = {};
      list.forEach(element => {
        /*if(element.plist){
          element.plist.forEach(item2 =>{
            textlist.push(item2);
          })
        }*/
        if(element !== undefined){
        if(!pObj[element.pId]){
          pObj[element.pId] = {len:element.plen,list:[element.id]}
        }else{
          pObj[element.pId].list.push(element.id)
        }
        }
        //textlist.push(element.id);
      });
      for (let name in pObj) {
        if(pObj[name].len === pObj[name].list.length){
          textlist.push(name)
          textlist = [...textlist,...pObj[name].list];
        }else{
          textlist = [...textlist,...pObj[name].list];
        }
      }
      this.modelData.roleid = textlist.join(",");
    },
    contentSelectCheck2(data){
      let list = data.list;
      let textlist = new Array();
      let pObj = {};
      list.forEach(element => {
        /*if(element.plist){
          element.plist.forEach(item2 =>{
            textlist.push(item2);
          })
        }*/
        if(!pObj[element.pId]){
          pObj[element.pId] = {len:element.plen,list:[element.id]}
        }else{
          pObj[element.pId].list.push(element.id)
        }
        //textlist.push(element.id);
      });
      for (let name in pObj) {
        if(pObj[name].len === pObj[name].list.length){
          textlist.push(name)
          textlist = [...textlist,...pObj[name].list];
        }else{
          textlist = [...textlist,...pObj[name].list];
        }
      }
      this.showModals.roleid = textlist.join(",");
    },
    //清除新增弹窗
    clearModelData(){
        this.modelData.account = '';
        this.modelData.name = '';
        this.modelData.birthday = '';
        this.modelData.sex= '1';
        this.modelData.email= '';
        this.modelData.phone= '';
        this.modelData.updateTime= '';
        this.modelData.password= '';
        this.modelData.rePassword= '';
        this.modelData.deptid= '';
        this.modelData.deptName= '';

    },
    // 添加用户
    handleAdd: function() {
      this.add_user = true
      this.clearModelData()
      // this.tree.createList()
    },
    handleOk() {
      let that = this
      this.add_user = false
      console.log(that.modelData)
      getAddUser(that.modelData).then(() => {
        that.clearModelData();
        that.$refs.table.refresh({ search: true })
      })
    },

    // 删除
    remove(userId) {
      let that = this
      deleteList({ userId }).then(() => {
        that.$refs.table.refresh({ search: true })
      })
    },
    // 修改
    toggle(userId) {
      let that = this;
      that.visible = true;
      getUserInfo({userId}).then(res =>{
        let user = res.user;
        that.showModals.deptName = res.deptName
        that.showModals.deptid = user.deptid
        that.showModals.name = user.name;
        that.showModals.birthday = user.birthday;
        that.showModals.email = user.email;
        that.showModals.phone = user.phone;
        that.showModals.sex = user.sex+"";
        that.showModals.account = user.account;
        that.showModals.id = user.id;
        that.showModals.roleid = user.roleid;
        that.$refs.tree2.setValue(user.deptid);
        that.$refs.tree4.setValue2(user.roleid);

      })


    },
    handleUpdata() {
      this.visible = false
      let that = this
      getEditUser(that.showModals).then((res) => {
        that.showModals.deptName = ''
        that.showModals.deptid = ''
        that.showModals.name = ''
        that.showModals.birthday = ''
        that.showModals.email = ''
        that.showModals.phone = ''
        that.showModals.sex = '1'
        that.showModals.account = ''
        that.showModals.id = ''
        that.showModals.roleid = ''
        if(res.code == 200){
          that.$notification.success({message: "系统提示", description: res.message, duration: 4})
        }else {
          that.$notification.error({message: "系统提示", description: res.message, duration: 4})
        }
        that.$refs.table.refresh({ search: true })
      })
    },
    updatePassword(userid){
      this.editpaswordmodel=true
      this.editpasswordfrom.changeId=userid;
    },
    // 重置密码
    Password(data) {
      this.showModals.userId = data.userId
      this.resetPassw = true
    },
    resetPassword() {
      let that = this
      that.resetPassw = false
      resetPass(that.showModals).then(() => {
        that.showModals.userId = ''
        that.$refs.table.refresh({ search: true })
      })
    },

    // 部门选择
    handelDepartment() {
      this.Department = true
    },
    confirmD() {
      this.Department = false
      this.modelData.content = '开发部'
    },
    reolConfirm() {
      this.reol = false
    }
  }
}

</script>


