<template lang="pug">
el-dialog( :close-on-click-modal="false", :visible.sync="visible", :append-to-body="true", :before-close="handleClose" )
  .title-bold(slot="title") {{ id ? '编辑用户' : '新增用户' }}
  el-form( :model="dataForm", :rules="dataRule", ref="dataForm", label-width="100px" )
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="所属机构:", prop="orgId")
          el-input.mywidth(readonly v-model="dataForm.orgId", placeholder="请填写所属机构", clearable)
      el-col(:span="12")
        el-form-item(label="用户姓名:", prop="name")
          el-input.mywidth(v-model="dataForm.name", placeholder="请填写姓名", clearable)
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="用户账号:", prop="username")
          el-input.mywidth( v-model="dataForm.username", placeholder="请填写账号名称", clearable @input='e => dataForm.username = inputMe(e)')
      //- el-col(:span=' 12' v-if='false')
      //-     el-form-item(label='确认密码:', prop='comfirmPassword', :class="{ 'is-required': !dataForm.id }")
      //-         el-input(v-model='dataForm.comfirmPassword', type='password', placeholder='确认密码' clearable)
      el-col(:span="12")
        el-form-item(label="用户岗位:", prop="job")
          el-select.mywidth(v-model="dataForm.job", placeholder="请选择用户岗位", clearable )
            el-option( v-for="(item, index) in allJob", :key="index", :label="item.name", :value="item.id" )
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="工种:", prop="work")
          el-input.mywidth(v-model="dataForm.work", placeholder="请填写工种", clearable)
      el-col(:span="12")
        el-form-item(label="手机号码:", prop="mobile")
          el-input.mywidth(v-model="dataForm.mobile", placeholder="请填写手机号码", clearable)
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="身份证号:", prop="idCard")
          el-input.mywidth(v-model="dataForm.idCard", placeholder="请填写身份证号", clearable)
      el-col(:span="12")
        el-form-item(label="电子邮箱:", prop="email")
          el-input.mywidth( v-model="dataForm.email", placeholder="请填写电子邮箱地址", clearable )
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="学历:", prop="education")
          el-select.mywidth(  v-model="dataForm.education", placeholder="请选择学历", clearable )
            el-option( v-for="(item, index) in educations", :key="index", :label="item.name", :value="item.name" )
      el-col(:span="12")
        el-form-item(label="民族:", prop="nation")
          el-select.mywidth(  v-model="dataForm.nation", placeholder="请选择民族", clearable )
            el-option( v-for="(item, index) in nations", :key="index", :label="item.name", :value="item.id.toString()" )
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="入职时间:", prop="entryTime")
          el-date-picker.mywidth(v-model="dataForm.entryTime", value-format="yyyy-MM-dd", type="date", placeholder="选择入职时间", clearable)
      el-col(:span="12")
        el-form-item(label="工号:", prop="jobNumber")
          el-input.mywidth( v-model="dataForm.jobNumber", placeholder="请填写工号", clearable )
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="政治面貌:", prop="politicCountenances")
          el-select.mywidth(  v-model="dataForm.politicCountenance", placeholder="请选择政治面貌", clearable )
            el-option( v-for="(item, index) in politicCountenances", :key="index", :label="item.name", :value="item.name" )
      el-col(:span="12")
        el-form-item(v-if="show", label="初始密码:", prop="password")
          el-input( v-model="dataForm.password", type="password", placeholder="初始密码", clearable @input='e => dataForm.password = inputMe(e)')
    //- el-row(:span="24")
    //-   el-col(:span="12")
    //-     el-form-item(label="指纹信息:", prop="byx1")
    //-       el-input.mywidth( v-model="dataForm.byx1", placeholder="请录入指纹", clearable )
      //- el-col(v-if="id", :span="12")
        el-form-item &nbsp;
    el-row(:span="24")
      el-col(:span="12")
        el-form-item(label="性别:", size="mini", prop="gender")
          el-radio-group(v-model="dataForm.gender")
            el-radio(:label="1") 男
            el-radio(:label="0") 女
      el-col(:span="12")
        el-form-item(label="账号状态:", size="mini", prop="status")
          el-radio-group(v-model="dataForm.status")
            el-radio(:label="1") 正常
            el-radio(:label="0") 禁用
      //- el-form-item(label='用户介绍:', prop='detail' v-show="false")
      //-     el-input(type="textarea" :rows=5 resize="none" v-model="dataForm.detail",  placeholder='请填写用户介绍' clearable)
      //- el-checkbox-group(v-model='dataForm.roleIdList')
      //-   el-checkbox(v-for='role in roleList', :key='role.roleId', :label='role.roleId') {{ role.roleName }}
  div(slot="footer", align="center")
    el-button(type="primary", size="medium", @click="cancel") 取消
    el-button( type="primary", size="medium", @click="dataFormSubmit()", v-prevent-re-click) 保存
</template>

<script>
// import { isEmail, isMobile } from '@/util/validate'
export default {
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error('密码不能为空'))
      } else {
        callback()
      }
    }
    var validatecardNumber = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('身份证号码不能为空'))
      } else {
        if (!this.checkIDCard(value)) {
          callback(new Error('请输入正确的身份证号码'))
        }
        callback()
      }
    }
    // var validateComfirmPassword = (rule, value, callback) => {
    //     if (!this.dataForm.id && !/\S/.test(value)) {
    //         callback(new Error('确认密码不能为空'))
    //     } else if (this.dataForm.password !== value) {
    //         callback(new Error('确认密码与密码输入不一致'))
    //     } else {
    //         callback()
    //     }
    // }
    return {
      id: '',
      show: false,
      clickFlag: false,
      visible: false,
      roleList: [],
      allJob: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      nations: [],
      checkedNode: {},
      sysOrgList: [],
      dataListSelections: [],
      educations: [
        { id: '1', name: '高中' },
        { id: '2', name: '中专' },
        { id: '3', name: '大专' },
        { id: '4', name: '本科' },
        { id: '5', name: '硕士研究生' },
        { id: '6', name: '博士研究生' },
        { id: '7', name: '其它' }
      ],
      politicCountenances: [
        { id: '1', name: '共青团员' },
        { id: '2', name: '预备党员' },
        { id: '3', name: '党员' },
        { id: '4', name: '群众' },
        { id: '5', name: '其它' }
      ],
      dataForm: {
        userId: '',
        orgId: '',
        name: '',
        username: '',
        password: '',
        comfirmPassword: '',
        job: '',
        work: '',
        mobile: '',
        idCard: '',
        email: '',
        education: '',
        nation: '',
        entryTime: '',
        jobNumber: '',
        politicCountenance: '',
        gender: 1,
        status: 1,
        stationId: localStorage.getItem('stationId')
        // byx1:'',
      },
      dataRule: {
        orgId: [
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: ['change', 'blur']
          }
        ],
        // roleId: [
        //   { required: true, message: '至少选择一个角色', trigger: 'blur' }],
        username: [
          { required: true, message: '账户名称不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: ['change', 'blur']
          }
        ],
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: ['change', 'blur']
          }
        ],
        work: [
          {
            min: 1,
            max: 100,
            message: '长度在 1 到 100 个字符',
            trigger: ['change', 'blur']
          }
        ],
        password: [
          { required: true, validator: validatePassword, trigger: 'blur' },
          {
            min: 1,
            max: 30,
            message: '长度在 1 到 30 个字符',
            trigger: ['change', 'blur']
          }
        ],
        // comfirmPassword: [
        //     { validator: validateComfirmPassword, trigger: 'blur' }
        // ],
        email: [
          {
            required: true,
            type: 'email',
            message: '请输入正确的E-mail',
            trigger: ['change', 'blur']
          }
        ],
        status: [
          { required: true, message: '必须选择一个状态', trigger: 'blur' }
        ],
        idCard: [
          { required: true, message: '身份证号码不能为空', trigger: 'blur' },
          { validator: validatecardNumber, trigger: ['change', 'blur'] }
        ],
        jobNumber: [
          {
            min: 0,
            max: 100,
            message: '长度在 0 到 100 个字符',
            trigger: ['change', 'blur']
          }
        ],
        // byx1: [
        //   {
        //     min: 0,
        //     max: 100,
        //     message: '长度在 0 到 100 个字符',
        //     trigger: ['change', 'blur']
        //   }
        // ],
        // detail: [
        //     {
        //         min: 1,
        //         max: 300,
        //         message: '长度在 1 到 300 个字符',
        //         trigger: 'blur'
        //     }
        // ],
        mobile: [
          {
            required: true,
            pattern: /^1[12345789]\d{9}$/,
            message: '请输入正确的手机号码'
          }
        ]
      }
    }
  },
  mounted() {
    // this.initOrgTreeList()
    this.getAllJob()
    this.getNation()
  },
  methods: {
    init(id) {
      this.clickFlag = false
      this.visible = true
      this.id = id || ''
      if (id) {
        //移除输入密码框
        this.show = false
        this.dataForm.password = null
        this.dataForm.comfirmPassword = null
        this.$http({
          url: this.$http.adornUrl('/sys/user/info/' + id),
          method: 'get',
          params: this.$http.adornParams()
        }).then((data) => {
          // console.log(data)
          this.dataForm = data.user || {}
          this.dataForm.stationId = localStorage.getItem('stationId')
          if (this.allJob) {
              let flag = true
              this.allJob.forEach(element => {
                if (this.dataForm.job === element.id) {
                    flag = false
                    return false
                }
              })

              if (flag) {
                this.dataForm.job = ''
              }
          }
        })
      } else {
        this.show = true
        this.dataForm = {
          user_id: '',
          orgId: JSON.parse(localStorage.getItem('sysSystem')).name,
          name: '',
          username: '',
          password: '',
          comfirmPassword: '',
          job: '',
          work: '',
          mobile: '',
          idCard: '',
          email: '',
          education: '',
          nation: '',
          entryTime: '',
          jobNumber: '',
          politicCountenance: '',
          gender: 1,
          status: 1,
          stationId: localStorage.getItem('stationId')
          // byx1: ''
        }
      }
    },
    inputMe(e) {
      return e.replace(/[<>！?:"：？@!,.;']/g, '')
    },
    //身份证校验
    checkIDCard(idcode) {
      // 加权因子
      var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 校验码
      var check_code = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']

      var code = idcode + ''
      var last = idcode[17] //最后一位

      var seventeen = code.substring(0, 17)

      // ISO 7064:1983.MOD 11-2
      // 判断最后一位校验码是否正确
      var arr = seventeen.split('')
      var len = arr.length
      var num = 0
      for (var i = 0; i < len; i++) {
        num = num + arr[i] * weight_factor[i]
      }

      // 获取余数
      var resisue = num % 11
      var last_no = check_code[resisue]

      // 格式的正则
      // 正则思路
      /*
              第一位不可能是0
              第二位到第六位可以是0-9
              第七位到第十位是年份，所以七八位为19或者20
              十一位和十二位是月份，这两位是01-12之间的数值
              十三位和十四位是日期，是从01-31之间的数值
              十五，十六，十七都是数字0-9
              十八位可能是数字0-9，也可能是X
              */
      var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/

      // 判断格式是否正确
      var format = idcard_patter.test(idcode)

      // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
      return !!(last === last_no && format)
    },
    //关闭前
    handleClose() {
      this.visible = false
      this.$refs.dataForm.resetFields()
    },
    //获取民族信息
    getNation() {
      this.$http({
        url: this.$http.adornUrl('/emPerson/getAllNation'),
        method: 'get'
      }).then((data) => {
        // console.log("data", data);
        if (data && data.code === 0) {
          this.nations = data.result
        }
      })
    },
    //获取职业字典信息
    getAllJob() {
      this.$http({
        url: this.$http.adornUrl('/sysDictionary/getAllJobList'),
        method: 'get',
        params: this.$http.adornParams({
          stationId: localStorage.getItem('stationId')
        })
      }).then((data) => {
        if (data && data.code === 0) {
          this.allJob = data.list
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    // 获取所属部门列表
    // initOrgTreeList() {
    //     this.$http({
    //         url: this.$http.adornUrl('/sysOrg/orgAllList'),
    //         method: 'GET'
    //     }).then(data => {
    //         if (data) {
    //             this.treeData = data.list
    //             if (this.dataForm.orgId) {
    //                 this.checkedNode = this.$refs.tree.getNode(this.dataForm.orgId).data
    //             } else {
    //                 this.checkedNode = this.treeData[0]
    //             }
    //         }
    //     })
    // },
    // 多选
    selectionChangeHandle(val) {
      this.dataListSelections = val
    },
    //机构树节点点击事件
    // treeHandleNodeClick(node) {
    //     console.log('树节点选中事件：', node)
    //     this.dataForm.orgId = node.id
    //     this.dataForm.orgName = node.name
    //     this.checkedNode = node
    // },
    //机构选择事件
    // orgChange() {
    //     this.$refs.tree.setCurrentKey(this.dataForm.orgId)//设置选中的值
    // },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.clickFlag = true
          let sta = localStorage.getItem('stationId')
          let submitBean = { ...this.dataForm }
          submitBean.stationId = sta
          submitBean.orgId = sta
          this.$http({
            url: this.$http.adornUrl(
              `/sys/user/${!submitBean.userId ? 'save' : 'update'}`
            ),
            method: 'post',
            data: submitBean
          })
            .then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500
                })
                this.handleClose()
                this.$emit('refreshdatalist')
              }
              this.clickFlag = false
            })
            .catch((data) => {
              this.$message.error(data.msg)
              this.clickFlag = false
            })
        }
      })
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', this.dataForm.userId ? '编辑用户' : '新增用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.handleClose()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    }
  }
}
</script>
<style>
.el-table__header {
  width: 100% !important;
}

.el-table__body {
  width: 100% !important;
}
</style>
