<template>
  <a-modal :width="1000" :dialogStyle="dialogStyle" title="员工信息" :visible="visible" @ok="handleSubmit()" @cancel="handleCancel" cancelText="关闭">

    <template slot="title">
      <div style="width: 100%;">
        <span>{{ title }}</span>
        <span style="display:inline-block;width:calc(100% - 51px);padding-right:10px;text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height:20px;width:20px;border:0px"></a-button>
        </span>
      </div>
    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form" style="overflow-y: auto;height: 650px;">
        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入员工姓名" v-decorator="[ 'realname', validatorRules.realname]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="英文名" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入英文名" v-decorator="[ 'egName', validatorRules.egName]" />
            </a-form-item>
          </a-col>
          
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入邮箱" v-decorator="[ 'email', validatorRules.email]" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="证件类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-model="sfzType" placeholder="请选择证件类型">
                <a-select-option value="0">中国身份证</a-select-option>
                <a-select-option value="1">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="身份证" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input  placeholder="请输入身份证号码" v-decorator="[ 'sfzCode', validatorRules.sfzCode]" />
            </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8" :lg="8">
              <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select v-decorator="[ 'sex',validatorRules.sex]" placeholder="请选择性别"
                  :getPopupContainer="(target) => target.parentNode">
                  <a-select-option :value="1">男</a-select-option>
                  <a-select-option :value="2">女</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
        </a-row>

        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
          <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-date-picker style="width: 100%" placeholder="请选择生日"
              v-decorator="['birthday', {initialValue:!model.birthday?null:moment(model.birthday,dateFormat)}]"
              :getCalendarContainer="node => node.parentNode" />
          </a-form-item>
          </a-col>
            <a-col :md="6" :sm="8" :lg="8">
                <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input placeholder="请输入手机号码" v-decorator="[ 'phone', validatorRules.phone]" />
                </a-form-item>
            </a-col>
            <a-col :md="6" :sm="8" :lg="8">
              <a-form-item label="公积金" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input  placeholder="请输入公积金账号"  v-decorator="['syFund',validatorRules.syFund]" />
                </a-form-item>
              </a-col>
            </a-col>
        </a-row>

        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="银行卡" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入银行卡号"  v-decorator="['bankCard', validatorRules.bankCard]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入开户行" v-decorator="['bankAddr', {}]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="*部门" :labelCol="labelCol" :wrapperCol="wrapperCol" v-show="!departDisabled">
              <a-input-search placeholder="点击选择部门" v-model="checkedDepartNameString" readOnly @search="onSearch">
                <a-button slot="enterButton" icon="search">选择</a-button>
              </a-input-search>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="工资一" :labelCol="labelCol" :wrapperCol="wrapperCol" >
              <a-input-number id="inputNumber" placeholder="请输入基本工资" style="width: 210px;" v-decorator="['wagesOne',validatorRules.wagesOne]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="工资二" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number placeholder="请输入基本工资" style="width: 210px;" v-decorator="['wagesTwo', {}]" />
            </a-form-item>
          </a-col>
          <!-- <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="社保基数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number placeholder="请输入社保基数" style="width: 210px;" v-decorator="['security', {}]" />
            </a-form-item>
          </a-col> -->
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="职务" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-search placeholder="点击选择职位" v-model="zwName" readOnly @search="zw()">
                <a-button slot="enterButton" icon="search">选择</a-button>
              </a-input-search>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="人员类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="[ 'category', {initialValue:101}]" placeholder="请选择人员类别"
                :getPopupContainer="(target) => target.parentNode" @change="handleChangeStatus">
                <a-select-option :value="101">正式工</a-select-option>
                <a-select-option :value="103">实习生</a-select-option>
                <a-select-option :value="104">劳务工</a-select-option>
                <a-select-option :value="105">劳务外包5+2</a-select-option>
                <a-select-option :value="106">劳务外包6+1</a-select-option>
                <a-select-option :value="102">顾问</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="缴交基数" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number :disabled="personType" controls="false" style="width: 210px;" placeholder="请输入缴交基数" v-decorator="['wagesBase', {}]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="入职日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker style="width: 100%" placeholder="请选择入职日期"
                v-decorator="['entryDate', {initialValue:!model.entryDate?moment(new Date(),dateFormat):moment(model.entryDate,dateFormat)}]"
                :getCalendarContainer="node => node.parentNode" />
            </a-form-item>
          </a-col>
          
        </a-row>
        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="联系人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入紧急联系人" v-decorator="[ 'urgentName',{}]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入紧急联系人电话" v-decorator="[ 'urgentPhone', {}]" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="身份类型" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group v-model="identity" @change="identityChange">
                <a-radio value="1">普通员工</a-radio>
                <a-radio value="2">上级</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="家庭住址" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入家庭住址" v-decorator="[ 'addr', {}]" />
            </a-form-item>
          </a-col>
         <a-col :md="6" :sm="8" :lg="8">
           <a-form-item label="雇佣状态" :labelCol="labelCol" :wrapperCol="wrapperCol">
             <a-select v-decorator="[ 'employmentStatus', {initialValue:10}]" placeholder="请选择雇佣状态"
               :getPopupContainer="(target) => target.parentNode" >
               <a-select-option :value="10">在职</a-select-option>
               <a-select-option :value="20">离退</a-select-option>
               <a-select-option :value="30">离职</a-select-option>
             </a-select>
           </a-form-item>
         </a-col>
            <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="是否打卡" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="[ 'isAttendance', {initialValue:'0'}]" placeholder="请选择"
                :getPopupContainer="(target) => target.parentNode">
                <a-select-option value="0">是</a-select-option>
                <a-select-option value="1">否</a-select-option>
              </a-select>
            </a-form-item>
            
          </a-col>
          
        </a-row>
        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea placeholder="请输备注" v-decorator="[ 'remarks', {}]" />
            </a-form-item>
          </a-col>
         <a-col :md="6" :sm="8" :lg="8">
          <a-form-item label="附件上传" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <a-button icon="search" @click="uploads()" style="width: 210px;">选择</a-button>
          </a-form-item>
         </a-col>
        <a-col :lg="8">
          <a-form-item label="同步信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-dict-select-tag v-decorator="['infoSy', {initialValue:3}]" placeholder="请选择同步" :type="'radio'"
              :triggerChange="true" dictCode="info_sy" />
          </a-form-item>
        </a-col>
        </a-row>
           
        <!-- <a-row>
          <a-col :lg="8">
            <a-form-item label="同步信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-dict-select-tag v-decorator="['infoSy', {initialValue:3}]" placeholder="请选择同步" :type="'radio'"
                :triggerChange="true" dictCode="info_sy" />
            </a-form-item>
          </a-col>
          
        </a-row> -->
        <a-row>
          <a-col :md="6" :sm="8" :lg="8">
            <a-form-model-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
               <j-image-upload  class="avatar-uploader" text="上传" v-model="model.avatar" ></j-image-upload>
             </a-form-model-item>
          </a-col>
        </a-row>

      </a-form>
    </a-spin>
    <depart-window ref="departWindow" @ok="modalFormOk"></depart-window>

    <a-modal title="附件" :visible="visiblet" @ok="saveUpload()" @cancel="handleCancelts()" footer="">
      <a-upload action="http://58.34.141.138:8085/jeecg-boot/sys/common/upload" list-type="picture" :file-list="fileLists"
        @change="t" method="post" @download="handleDownload" :showUploadList="{
              showRemoveIcon: true,
              showDownloadIcon: true
            }"
            :remove="handleRemove"
            >
            
        <a-button>
          <a-icon type="upload" />上传
        </a-button>
      </a-upload>
    </a-modal>
    <a-modal v-model="visibles" title="职务" @ok="zwOk()">
     <a-table rowKey="id" bordered :data-source="dataSources" :columns="columnst"  :pagination="ipaginations" @change="handleTableChanges"
     :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChanges,type: 'radio'}"
     >
       
     </a-table>
    </a-modal>
  </a-modal>
  
  
</template>

<script>
  import pick from 'lodash.pick'
  import moment from 'moment'
  import Vue from 'vue'
  // 引入搜索部门弹出框的组件
  import departWindow from './DepartWindow'
  import JSelectPosition from '@/components/jeecgbiz/JSelectPosition'
  import {
    ACCESS_TOKEN
  } from "@/store/mutation-types"
  import {
    getAction,
    httpAction,
    deleteAction
  } from '@/api/manage'
  import {
    addUser,
    editUser,
    queryUserRole,
    queryall
  } from '@/api/api'
  import {
    disabledAuthFilter
  } from "@/utils/authFilter"
  import {
    duplicateCheck
  } from '@/api/api'
  import JImageUpload from '../../../components/jeecg/JImageUpload'
  import py from '../../../mixins/vue-py.js'
  export default {
    name: "UserModal",
    components: {
      JImageUpload,
      departWindow,
      JSelectPosition
    },
    data() {
      return {
        selectedRowKeys:[],
        selectionRows:[],
        departDisabled: false, //是否是我的部门调用该页面
        roleDisabled: false, //是否是角色维护调用该页面
        modalWidth: 800,
        drawerWidth: 700,
        titles: "新增员工",
        visibles:false,
        personType:false,
        dataSources:[],
        modaltoggleFlag: true,
        sfzCode: "",
        bankCard: "",
        bankAddr: "",
        syFund: "",
        visiblet: false,
        phone: "",
        isSalary: "0",
        email: "",
        isAttendance: "0",
        zwName:"",
        zwCode:"",
        sfzType: "0",
        ipaginations:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        fileLists: [],
        confirmDirty: false,
        files: [],
        selectedDepartKeys: [], //保存用户选择部门id
        checkedDepartKeys: [],
        checkedDepartNames: [], // 保存部门的名称 =>title
        checkedDepartNameString: "", // 保存部门的名称 =>title
        resultDepartOptions: [],
        userId: "", //保存用户id
        disableSubmit: false,
        userDepartModel: {
          userId: '',
          departIdList: []
        }, // 保存SysUserDepart的用户部门中间表数据需要的对象
        dateFormat: "YYYY-MM-DD",
        validatorRules: {
          phone: {
            rules: [{
              required: true,
              message: '请输入手机号!'
            }, {
              validator: this.validatePhone
            }]
          },
          email: {
            rules: [{
              required: true,
              message: '请输入邮箱'
            }, {
              validator: this.validateEmail
            }]
          },
          realname: {
            rules: [{
              required: true,
              message: '请输入姓名'
            }, {
              validator: this.validateRealname
            }]
          },
          egName: {
            rules: [{
              required: true,
              message: '请输入英文名'
            }, {
              validator: this.validateEgname
            }]
          },
          sfzCode: {
            rules: [{
              required: true,
              message: '请输入身份证号'
            }, {
              validator: this.validateSfzCode
            }]
          },
          sex: {
            rules: [{
              required: true,
              message: '请选择性别'
            }]
          },
          bankCard: {
            rules: [{
              required: true,
              message: '请输入银行账号'
            },
            {validator: this.validatebankCard}
            ]
          },
          syFund: {
            rules: [{
              required: true,
              message: '请输入公积金账号'
            },
            {validator: this.validatesyFund}
            ]
          },
          wagesOne: {
            rules: [{
              required: true,
              message: '请输入基本工资'
            }
           
            ]
          }
        },
        columnst:[{
          title: '职位编码',
          dataIndex: 'code',
        },{
          title: '职位名称',
          dataIndex: 'name',
        },{
          title: '部门',
          dataIndex: 'deptName',
        },
        ],
        departIdShow: false,
        departIds: [], //负责部门id
        title: "操作",
        visible: false,
        dialogStyle:{
          top:"15px"
        },
        model: {},
        roleList: [],
        selectedRole: [],
        realname: "",
        egName: "",
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          },
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 16
          },
        },
        uploadLoading: false,
        confirmLoading: false,
        headers: {},
        form: this.$form.createForm(this),
        picUrl: "",
        url: {
          fileUpload: window._CONFIG['domianURL'] + "/sys/common/upload",
          userWithDepart: "/sys/user/userDepartList", // 引入为指定用户查看部门信息需要的url
          userId: "/sys/user/generateUserId", // 引入生成添加用户情况下的url
          syncUserByUserName: "/act/process/extActProcess/doSyncUserByUserName", //同步用户到工作流
          queryTenantList: '/sys/tenant/queryList',
          xzupload: '/sys/common/static',
          sysFile: '/sysFile/sysFile/queryByUserId',
          delSysFile:'/sysFile/sysFile/deleteById',
          post:'/sys/position/listByDept'
        },
        identity: "1",
        fileList: [],
        tenantList: [],
        currentTenant: []
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      this.headers = {
        "X-Access-Token": token
      }
      this.initTenantList()

    },

    computed: {
      uploadAction: function() {
        return this.url.fileUpload;
      }
    },
    methods: {
      zwOk(){
        if(this.selectionRows!=null&&this.selectionRows.length>0){
        this.zwName=this.selectionRows[0].name;
        this.zwCode=this.selectionRows[0].code;
        }
        this.visibles=false;
      },
      onSelectChanges(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows=selectionRows;
      },
     handleTableChanges(pagination, filters, sorter) {
       //分页、排序、筛选变化时触发
       //TODO 筛选
       if (Object.keys(sorter).length > 0) {
         this.isorter.column = sorter.field;
         this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
       }
       this.ipaginations = pagination;
       this.queryzw();
     },
      zw(){
        if(this.userDepartModel.departIdList==null||this.userDepartModel.departIdList.length<1){
          this.$message.warning('请先选择部门!');
          return;
        }
        this.visibles=true;
       this.queryzw();
      },
      queryzw(){
        getAction(this.url.post, {
          pageNo:this.ipaginations.current,
          pageSize: this.ipaginations.pageSize,
          deptId:this.userDepartModel.departIdList.join(",")
        }).then((res) => {
          if (res.success) {
           this.dataSources = res.result.records||res.result;
           if(res.result.total)
           {
             this.ipaginations.total = res.result.total+1;
           }else{
             this.ipaginationstotal = 0+1;
           }
          } 
        }).finally(() => {
        });
      },
      handleRemove(file){
        if(this.userId!=null&&this.userId!=""){
        deleteAction(this.url.delSysFile, {userid:this.userId,name:file.name}).then((res) => {
          if (res.success) {
          } 
        }).finally(() => {
        });
        }
      },
      handleCancelts() {
       // this.fileList = [];
        this.visiblet = false;
      },
      // 文件下载
      handleDownload(file) {
        window.location.href = "http://58.34.141.138:8085/jeecg-boot/sys/common/static/" + file.response.message;
      },
      t(info) {
        // this.files = [];
        // let {
        //   fileList
        // } = info
        // const status = info.file.status
        // if (status !== 'uploading') {}
        // if (status === 'done') {
        //   var list = fileList.fileList;
        //   for (var i = 0; i < list.length; i++) {
        //     this.files.push(list[i].response.message);
        //   }
        // }
        this.fileLists = info.fileList //重点
        //console.log(info)
      },
      saveUpload() {
        this.visiblet = false;
      },
      uploads() {
        this.visiblet = true;
      },
      isDisabledAuth(code) {
        return disabledAuthFilter(code);
      },
      getBirth(idCard) {
        var birthday = "";
        if (idCard != null && idCard != "") {
          if (idCard.length == 15) {
            birthday = "19" + idCard.slice(6, 12);
          } else if (idCard.length == 18) {
            birthday = idCard.slice(6, 14);
          }
          //通过正则表达式来指定输出格式为:1990-01-01
        }

        if (birthday != "" && birthday != null) {
          this.form.setFieldsValue({
            birthday: birthday.replace(/(.{4})(.{2})/, "$1-$2-")
          })

          if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
            this.form.setFieldsValue({
              sex: 1
            })
          } else {
            this.form.setFieldsValue({
              sex: 2
            })
          }
        }



      },
      handleChangeStatus(e){
        if(e==101){
          this.personType=false;
        }else{
          this.personType=true;
          this.form.setFieldsValue({
            wagesBase: null
          })
        }
      },
      queryFiles(e) {
        getAction(this.url.sysFile, {
          userid: e
        }).then(res => {
          if (res.success) {
            if (res.result.length > 0) {
              this.fileLists = [];
              for (var i = 0; i < res.result.length; i++) {
                const rs = {
                  message: res.result[i].txtName
                };
                const fileInfo = {
                  uid: res.result[i].id,
                  name: res.result[i].txtName,
                  status: "done",
                  response: rs,
                  url: "http://58.34.141.138:8085/jeecg-boot/" + res.result[i].txtName,
                };
                this.fileLists.push(fileInfo)
              }
            }
          }
        })
      },
      initTenantList() {
        getAction(this.url.queryTenantList).then(res => {
          if (res.success) {
            this.tenantList = res.result
          }
        })
      },
      //窗口最大化切换
      toggleScreen() {
        if (this.modaltoggleFlag) {
          this.modalWidth = window.innerWidth;
        } else {
          this.modalWidth = 800;
        }
        this.modaltoggleFlag = !this.modaltoggleFlag;
      },
      initialRoleList() {
        queryall().then((res) => {
          if (res.success) {
            this.roleList = res.result;
          } else {
            console.log(res.message);
          }
        });
      },
      loadUserRoles(userid) {
        queryUserRole({
          userid: userid
        }).then((res) => {
          if (res.success) {
            this.selectedRole = res.result;
          } else {
            console.log(res.message);
          }
        });
      },
      refresh() {
        this.selectedDepartKeys = [];
        this.checkedDepartKeys = [];
        this.checkedDepartNames = [];
        this.checkedDepartNameString = "";
        this.userId = ""
        this.resultDepartOptions = [];
        this.departId = [];
        this.departIdShow = false;
        this.currentTenant = []
        this.sfzCode = "";
        this.realname = "";
        this.egName = "";
        this.syFund = "";
        this.isAttendance = 0;
        this.isSalary = 0;
        this.bankAddr = "";
        this.bankCard = "";
        this.phone = "";
        this.email = "";
        this.zwCode="";
        this.zwName="";
        this.selectedRowKeys=[];
        this.selectionRows=[];
      },
      add() {
        this.picUrl = "";
        this.refresh();

        this.edit({
          activitiSync: '1'
        });
      },
      edit(record) {
        this.realname = record.realname;
        this.egName = record.egName;
        this.resetScreenSize(); // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
        let that = this;

        //that.initialRoleList();
        that.checkedDepartNameString = "";
        that.form.resetFields();
        if (record.hasOwnProperty("id")) {
          that.loadUserRoles(record.id);
          setTimeout(() => {
            this.fileList = record.avatar;
          }, 5)
        }
        if (record.sfzType != null && record.sfzType != "") {
          this.sfzType = record.sfzType;
        }
        that.visible = true;
        that.model = Object.assign({}, record);
        this.zwCode=record.post;
        this.zwName=record.post_dictText;
        that.$nextTick(() => {
          that.form.setFieldsValue(pick(this.model, 'sex', 'email', 'phone', 'urgentName', 'urgentPhone',
            'bankAddr', 'bankCard', 'realname', 'egName', 'sfzCode','isAttendance','remarks','addr',
            'infoSy', 'syFund', 'category', 'employmentStatus', 'wagesOne', 'wagesTwo', 'security','wagesBase'))
        });
        //身份为上级显示负责部门，否则不显示
        if (this.model.userIdentity == "2") {
          this.identity = "2";
          this.departIdShow = true;
        } else {
          this.identity = "1";
          this.departIdShow = false;
        }
       
        //update-begin-author:taoyan date:2020710 for:多租户配置
        if (!record.relTenantIds || record.relTenantIds.length == 0) {
          this.currentTenant = []
        } else {
          this.currentTenant = record.relTenantIds.split(',').map(Number);
        }

        if (record.id != null && record.id != "") {
          this.userId = record.id;
          this.queryFiles(record.id)
        }
        
        // 调用查询用户对应的部门信息的方法
        that.checkedDepartKeys = [];
        that.loadCheckedDeparts();
        if (this.userId != null && this.userId != "") {
          this.queryFiles(this.userId)
        }
      },
      //
      loadCheckedDeparts() {
        var id= this.userId
        let that = this;
        if (!that.userId) {
          return
        }
        getAction(that.url.userWithDepart, {
          userId: that.userId
        }).then((res) => {
          that.checkedDepartNames = [];
          if (res.success) {
            var depart = [];
            var departId = [];
            for (let i = 0; i < res.result.length; i++) {
              that.checkedDepartNames.push(res.result[i].title);
              this.checkedDepartNameString = this.checkedDepartNames.join(",");
              that.checkedDepartKeys.push(res.result[i].key);
              //新增负责部门选择下拉框
              depart.push({
                key: res.result[i].key,
                title: res.result[i].title
              })
              departId.push(res.result[i].key)
            }
            that.resultDepartOptions = depart;
            //判断部门id是否存在，不存在择直接默认当前所在部门
            if (this.model.departIds) {
              this.departIds = this.model.departIds.split(",");
            } else {
              this.departIds = departId;
            }
            that.userDepartModel.departIdList = that.checkedDepartKeys
          } else {
            console.log(res.message);
          }
        })
      },
      close() {
        this.$emit('close');
        this.visible = false;
        this.disableSubmit = false;
        this.selectedRole = [];
        this.userDepartModel = {
          userId: '',
          departIdList: []
        };
        this.checkedDepartNames = [];
        this.checkedDepartNameString = '';
        this.checkedDepartKeys = [];
        this.selectedDepartKeys = [];
        this.resultDepartOptions = [];
        this.departIds = [];
        this.departIdShow = false;
        this.fileLists=[];
        this.identity = "1";
        this.bankAddr = "";
        this.bankCard = "";
        this.syFund = "";
      },
      moment,
      handleSubmit() {
        if (this.userDepartModel.departIdList.join(",") == "" || this.userDepartModel.departIdList.join(",") == null) {
          this.$message.warning('请选择部门!');
          return;
        }
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            if (!values.birthday) {
              values.birthday = '';
            } else {
              values.birthday = values.birthday;
            }
            let formData = Object.assign(this.model, values);
            // if (that.fileList != '') {
            //   formData.avatar = that.fileList;
            // } else {
            //   formData.avatar = null;
            // }
            formData.sfzType = this.sfzType;
            var a = this.fileLists;
            var txt = [];
            console.log(this.fileLists)
            if (this.fileLists != null && this.fileLists.length > 0) {
              for (var i = 0; i < this.fileLists.length; i++) {
                txt.push(this.fileLists[i].response.message)
              }
              formData.txt = txt.join(",");
            }
            formData.post=this.zwCode;
            //formData.selectedroles = this.selectedRole.length>0?this.selectedRole.join(","):'';
            formData.selecteddeparts = this.userDepartModel.departIdList.length > 0 ? this.userDepartModel
              .departIdList.join(",") : '';
            formData.userIdentity = this.identity;
            formData.departIds = this.userDepartModel.departIdList.join(",");
            //如果是上级择传入departIds,否则为空
            if (this.identity === "2") {
              formData.departIds = this.departIds.join(",");
            } else {
              formData.departIds = "";
            }

            // that.addDepartsToUser(that,formData); // 调用根据当前用户添加部门信息的方法
            let obj;
            if (!this.model.id) {
              formData.id = this.userId;
              obj = addUser(formData);
            } else {
              obj = editUser(formData);
            }
            obj.then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.checkedDepartNames = [];
              that.userDepartModel.departIdList = {
                userId: '',
                departIdList: []
              };
              that.close();
            })

          } else {
            console.log("1")
          }
        })
      },
      handleCancel() {
        this.close()
      },
      validateRealname(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          this.realname = value;
          if (this.egName != null && this.egName != "") {
            var emil = "@gksports.com.cn";
            var name = py.chineseToPinYin(value.substr(0, 1))
            this.form.setFieldsValue({
              email: this.egName + "." + name + emil
            })
          }
          callback()
        }
      },
      validateSfzCode(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (this.sfzType == "0") {
            if (value.length==15&&RegExp(/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/).test(value)) {
              this.getBirth(value)
            }else if(value.length==18&&RegExp(/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/).test(value)){
              this.getBirth(value)
            }else{
              callback("请输入正确格式的身份证号码!");
            }
            
          }
          callback()
        }
      },
      validateEgname(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          this.egName = value;
          if (this.realname != null && this.realname != "") {
            var emil = "@gksports.com.cn";
            var name = py.chineseToPinYin(this.realname.substr(0, 1))
            this.form.setFieldsValue({
              email: value + "." + name + emil
            })
          }
          callback()
        }
      },
      validatesyFund(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if(value.length!=9&&value.length!=12){
           callback('请输入正确格式的公积金账号');
          }
          callback()
        }
      },
      validatePhone(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          //update-begin--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
          if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
            //update-end--Author:kangxiaolin  Date:20190826 for：[05] 手机号不支持199号码段--------------------
            var params = {
              tableName: 'sys_user',
              fieldName: 'phone',
              fieldVal: value,
              dataId: this.userId
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback("手机号已存在!")
              }
            })
          } else {
            callback("请输入正确格式的手机号码!");
          }
        }
      },
      validatebankCard(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if(value.length!=19&&value.length!=17&&value.length!=16){
           callback('请输入正确格式的银行卡账号');
          }
          callback()
        }
      },
      validateEmail(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(
              /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
            ).test(value)) {
            var params = {
              tableName: 'sys_user',
              fieldName: 'email',
              fieldVal: value,
              dataId: this.userId
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback("邮箱已存在!")
              }
            })
          } else {
            callback("请输入正确格式的邮箱!")
          }
        }
      },

      handleConfirmBlur(e) {
        const value = e.target.value;
        this.confirmDirty = this.confirmDirty || !!value
      },

      normFile(e) {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
          return e
        }
        return e && e.fileList
      },
      beforeUpload: function(file) {
        var fileType = file.type;
        if (fileType.indexOf('image') < 0) {
          this.$message.warning('请上传图片');
          return false;
        }
        //TODO 验证文件大小
      },
      handleChange(info) {
        this.picUrl = "";
        if (info.file.status === 'uploading') {
          this.uploadLoading = true;
          return
        }
        if (info.file.status === 'done') {
          var response = info.file.response;
          this.uploadLoading = false;
          console.log(response);
          if (response.success) {
            this.model.avatar = response.message;
            this.picUrl = "Has no pic url yet";
          } else {
            this.$message.warning(response.message);
          }
        }
      },
      // 搜索用户对应的部门API
      onSearch() {
        console.log(this.$refs.departWindow)
        this.$refs.departWindow.add(this.checkedDepartKeys, this.userId);
      },

      // 获取用户对应部门弹出框提交给返回的数据
      modalFormOk(formData) {
        this.checkedDepartNames = [];
        this.selectedDepartKeys = [];
        this.checkedDepartNameString = '';
        this.userId = formData.userId;
        this.userDepartModel.userId = formData.userId;
        this.departIds = [];
        this.resultDepartOptions = [];
        var depart = [];
        for (let i = 0; i < formData.departIdList.length; i++) {
          this.selectedDepartKeys.push(formData.departIdList[i].key);
          this.checkedDepartNames.push(formData.departIdList[i].title);
          this.checkedDepartNameString = this.checkedDepartNames.join(",");
          //新增部门选择，如果上面部门选择后不为空直接付给负责部门
          depart.push({
            key: formData.departIdList[i].key,
            title: formData.departIdList[i].title
          })
          this.departIds.push(formData.departIdList[i].key)
        }
        this.resultDepartOptions = depart;
        this.userDepartModel.departIdList = this.selectedDepartKeys;
        this.checkedDepartKeys = this.selectedDepartKeys //更新当前的选择keys
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth;
        } else {
          this.drawerWidth = 700;
        }
      },
      identityChange(e) {
        if (e.target.value === "1") {
          this.departIdShow = false;
        } else {
          this.departIdShow = true;
        }
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader>.ant-upload {
    width: 104px;
    height: 104px;
  }

  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td {
    padding-top: 10px;
    padding-bottom: 10px;
  }

  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>
