<template>
  <a-modal
    :title="modalTitle"
    :width="900"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-divider orientation="left">基本信息</a-divider>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item style="display: none;">
              <a-input v-decorator="['id']" />
            </a-form-item>

            <a-form-item style="display: none;">
              <a-input v-decorator="['userId']" />
            </a-form-item>

            <a-form-item label="用户名" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入用户名"
                :disabled="registerDisabled"
                v-decorator="[
                  'userName',
                  { rules: [{ required: true, message: '请输入用户名!' }] },
                ]"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入姓名"
                :disabled="registerDisabled"
                v-decorator="['name', { rules: [{ required: true, message: '请输入姓名！' }] }]"
              />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="身份证" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                placeholder="请输入身份证"
                v-decorator="[
                  'idCardNo',
                  { rules: [{ required: true, message: '请输入身份证！' }] },
                ]"
                @blur="idCardNoBlur"
              />
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="年龄" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input readOnly v-decorator="['age']" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-radio-group
                readOnly
                v-decorator="['sex', { rules: [{ required: true, message: '请选择性别！' }] }]"
              >
                <a-radio :value="1">男</a-radio>
                <a-radio :value="2">女</a-radio>
              </a-radio-group>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-input
                :disabled="type == 2"
                placeholder="请输入手机号"
                v-decorator="['phone', { rules: [{ required: true, message: '请输入手机号！' }] }]"
              />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="24" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="岗位"
              :labelCol="{ span: 3 }"
              :wrapperCol="{ span: 20 }"
              has-feedback
            >
              <a-select
                style="width: 100%"
                placeholder="请选择岗位"
                v-decorator="['jobs', { rules: [{ required: true, message: '请选择岗位！' }] }]"
              >
                <a-select-option v-for="(item, index) in jobsData" :key="index" :value="item.value">
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="工种" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                style="width: 100%"
                placeholder="请选择工种"
                v-decorator="['workType', { rules: [{ required: true, message: '请选择工种！' }] }]"
              >
                <a-select-option
                  v-for="(item, index) in workTypeData"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="学历" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
              <a-select
                style="width: 100%"
                placeholder="请选择学历"
                v-decorator="['degreeId', { rules: [{ required: true, message: '请选择学历！' }] }]"
              >
                <a-select-option
                  v-for="(item, index) in degreeData"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="24" :sm="24">
          <a-form :form="form">
            <a-form-item label="人员类型" :labelCol="{ span: 3 }" :wrapperCol="{ span: 20 }">
              <a-checkbox-group
                v-decorator="['type', { rules: [{ required: true, message: '请选择人员类型！' }] }]"
              >
                <a-checkbox
                  name="type"
                  v-for="(item, index) in typeData"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.name }}
                </a-checkbox>
              </a-checkbox-group>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="部门信息"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input
                v-if="type == 1"
                readOnly
                @click="openOrgTree"
                v-decorator="['orgName', { rules: [{ required: true, message: '请选择机构！' }] }]"
              />
              <a-input
                v-else
                readOnly
                v-decorator="['orgName', { rules: [{ required: true, message: '请选择机构！' }] }]"
              />
            </a-form-item>
            <a-form-item style="display: none;">
              <a-input v-decorator="['orgId']" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
      <a-row :gutter="24" v-if="type == 1">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item
              label="年度计划学时"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              has-feedback
            >
              <a-input placeholder="请输入年度计划学时" v-decorator="['planClassHour']" />
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-divider orientation="left">上传身份证</a-divider>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="身份证正面" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <db-upload v-model="fileList" max="1" type="img"></db-upload>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="身份证反面" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <db-upload v-model="fileList2" max="1" type="img"></db-upload>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>

      <a-divider orientation="left">人脸识别图像</a-divider>
      <a-row :gutter="24">
        <a-col :md="12" :sm="24">
          <a-form :form="form">
            <a-form-item label="图像" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <db-upload v-model="fileList3" max="1" type="img" fileSize="500"></db-upload>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-spin>

    <org-tree @selectOrg="selectOrg($event)" ref="orgModal" />
  </a-modal>
</template>

<script>
import { personAddOrUpdate, personGet } from '@/api/person/person'
import { dictionaryDropDown } from '@/api/sys/dictionaryItem'
import OrgTree from '../org/OrgTree'
import DbUpload from '@/components/DbUpload/DbUpload.vue'
export default {
  components: {
    OrgTree,
    DbUpload
  },
  props: {
    type: {
      type: [String, Number],
      default: 1 // 1: 默认原来的类型 2: 注册弹出的修改框
    }
  },
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      modalTitle: '新增人员',
      visible: false,
      confirmLoading: false,
      registerDisabled: false,
      form: this.$form.createForm(this),
      jobsData: [],
      workTypeData: [],
      degreeData: [],
      typeData: [],
      fileList: [],
      fileList2: [],
      fileList3: [],
      isRegister: 0
    }
  },
  mounted () {
    this.dictionaryDropDown()
  },
  methods: {
    // 注册信息编辑 新增人员初始化方法
    registerEdit (record) {
      this.modalTitle = '审核人员'
      this.confirmLoading = true
      this.visible = true
      this.isRegister = 1

      this.registerDisabled = true
      setTimeout(() => {
        // 基本信息加入表单
        this.form.setFieldsValue({
          name: record.name,
          userName: record.userName,
          phone: record.phone,
          orgId: record.orgId,
          orgName: record.orgName,
          id: record.personId, // 审核注册信息 需要把personId带入
          userId: record.userId
        })
      }, 100)

      this.confirmLoading = false
    },
    // 编辑初始化方法
    edit (record) {
      this.modalTitle = '编辑人员'
      this.confirmLoading = true
      this.visible = true
      this.isRegister = 0

      this.registerDisabled = true

      // 基本信息加入表单
      personGet({ id: record.id }).then(res => {
        if (res.code === 200) {
          const data = res.data
          // 默认选中的多选框
          const type = (data.type && data.type.split(',')) || []
          const typeIntArr = [] // 保存转换后的整型字符串
          type.forEach(item => {
            typeIntArr.push(+item)
          })
          this.form.getFieldDecorator('type', {
            valuePropName: 'checked',
            initialValue: typeIntArr
          })

          if (data.idPhotoFace) {
            this.fileList = JSON.parse(data.idPhotoFace)
          }
          if (data.idPhotoBack) {
            this.fileList2 = JSON.parse(data.idPhotoBack)
          }
          if (data.avatar) {
            this.fileList3.push({
              uid: 1,
              name: 'image.jpg',
              url: data.avatar
            })
          }
          this.form.setFieldsValue({
            id: data.id,
            userId: data.userId,
            name: data.name,
            userName: data.userName,
            idCardNo: data.idCardNo,
            // age: data.age,
            // sex: data.sex,
            phone: data.phone,
            jobs: data.jobs ? parseInt(data.jobs) : undefined,
            workType: data.workType ? parseInt(data.workType) : undefined,
            degreeId: data.degreeId,
            orgId: data.orgId,
            orgName: data.orgName,
            planClassHour: data.planClassHour
          })
          // 动态赋值年龄和性别
          this.analyzeIdCardNo(data.idCardNo)
        } else {
          this.$message.error('查询失败：' + res.msg)
        }
      })
      this.confirmLoading = false
    },
    /**
     * 获取字典数据
     */
    dictionaryDropDown () {
      this.formLoading = true
      // 岗位
      dictionaryDropDown({ dictionaryCode: '0002' }).then(res => {
        this.jobsData = res.data
      })
      // 工种
      dictionaryDropDown({ dictionaryCode: '0003' }).then(res => {
        this.workTypeData = res.data
      })
      // 学历
      dictionaryDropDown({ dictionaryCode: '0004' }).then(res => {
        this.degreeData = res.data
      })
      // 人员类型
      dictionaryDropDown({ dictionaryCode: '0005' }).then(res => {
        this.typeData = res.data
        this.formLoading = false
      })
    },
    handleSubmit () {
      const {
        form: { validateFields }
      } = this
      this.confirmLoading = true

      const _this = this
      validateFields((errors, values) => {
        if (!errors) {
          values.type = values.type.join(',')
          values.idPhotoFace = JSON.stringify(this.fileList)
          values.idPhotoBack = JSON.stringify(this.fileList2)
          if (this.fileList3.length > 0) values.avatar = this.fileList3[0].url

          // 如果是注册审核的，弹出提示框
          if (_this.isRegister === 1) {
            this.$confirm({
              title: '提示',
              content: '确认通过审核吗?',
              onOk () {
                values.isRegister = 1 // 审核通过
                _this.addOrUpdate(values)
              },
              onCancel () {}
            })
          } else {
            _this.addOrUpdate(values)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    addOrUpdate (values) {
      personAddOrUpdate(values).then(
        res => {
          this.confirmLoading = false
          if (res.code === 200) {
            this.$message.success('操作成功')
            this.$emit('ok', values)

            this.handleCancel()
          } else {
            this.$message.error('操作失败：' + res.msg)
          }
        },
        err => {
          this.$message.error(err)
        }
      )
    },
    idCardNoBlur (event) {
      const idCardNo = event.target.value
      this.analyzeIdCardNo(idCardNo)
    },
    analyzeIdCardNo (idCardNo) {
      // 如果用户身份证号码为undefined则返回空
      if (!idCardNo) {
        return
      }

      // 获取性别
      if (parseInt(idCardNo.substr(16, 1)) % 2 === 1) {
        this.form.setFieldsValue({ sex: 1 })
      } else {
        this.form.setFieldsValue({ sex: 2 })
      }

      // 获取出生日期
      var yearBirth = idCardNo.substring(6, 10)
      var monthBirth = idCardNo.substring(10, 12)
      var dayBirth = idCardNo.substring(12, 14)
      // 获取当前年月日并计算年龄
      var myDate = new Date()
      var monthNow = myDate.getMonth() + 1
      var dayNow = myDate.getDate()
      var age = myDate.getFullYear() - yearBirth
      if (monthNow < monthBirth || (monthNow === monthBirth && dayNow < dayBirth)) {
        age--
      }
      // 得到年龄
      this.form.setFieldsValue({ age })
    },
    openOrgTree () {
      this.$refs.orgModal.loadOrg()
    },
    selectOrg (orgData) {
      this.form.setFieldsValue({ orgId: orgData.id })
      this.form.setFieldsValue({ orgName: orgData.name })
    },
    handleCancel () {
      this.form.resetFields()
      this.fileList = []
      this.fileList2 = []
      this.fileList3 = []
      this.visible = false
    }
  }
}
</script>
