<template>
  <div>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      :title="modalTitle"
    >
      <div>
        <Form
          id="edit-form-staff-info-edit"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="80"
          inline
        >
          <Form-item label="姓名" prop="name" class="width-48">
            <el-tooltip content="长度为0-20" placement="bottom-start">
              <el-input v-model="formObj.name" name="name" placeholder="请输入姓名" style="width: 100%" />
            </el-tooltip>
          </Form-item>
          <Form-item label="性别" prop="sex" style="width: 45%">
            <el-radio-group v-model="formObj.sex" @on-change="_selectSex">
              <el-radio v-for="item in sexList" :key="item.value" :label="item.value">
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </Form-item>

          <Form-item label="工号" prop="number" class="width-48">
            <el-input v-model="formObj.number" name="number" style="width: 100%" :maxlength="20" placeholder="请输入工号" />
          </Form-item>
          <Form-item label="所属部门" style="width: 98.6%;">
            <el-input v-model="formObj.orgNames" placeholder="请选择所属部门" readonly @click.native="_selOrg" />
          </Form-item>

          <Form-item label="员工类型" prop="levelName" class="width-48">
            <el-input
              v-model="formObj.levelName"
              name="levelName"
              placeholder="请选择员工类型"
              @click.native="_selectLevelZtree"
            />
          </Form-item>
          <Form-item label="年龄" prop="age" class="width-48">
            <InputNumber v-model="formObj.age" min="1" placeholder="请输入年龄" style="width: 320px;" />
          </Form-item>
          <Form-item label="入职时间" prop="entryTime" class="width-48">
            <DatePicker
              v-model="formObj.entryTime"
              type="date"
              placeholder="请选择入职时间"
              style="width: 320px;"
            />
          </Form-item>
          <Form-item label="参加工作时间" prop="workTime" class="width-48">
            <DatePicker
              v-model="formObj.workTime"
              type="date"
              placeholder="请选择参加工作时间"
              style="width: 320px;"
            />
          </Form-item>
          <Form-item label="试用期时间" prop="probatioDate" class="width-48">
            <DatePicker
              v-model="probatioDate"
              type="daterange"
              placeholder="请选择试用期时间"
              style="width: 320px;"
              @on-change="_probatioDateChange"
            />
          </Form-item>
          <Form-item label="入职转正时间" prop="becomeDate" class="width-48">
            <DatePicker
              v-model="formObj.becomeDate"
              type="date"
              placeholder="请选择入职转正时间"
              style="width: 320px;"
            />
          </Form-item>
          <Form-item label="专业" prop="profession" class="width-48">
            <Input v-model="formObj.profession" name="profession" placeholder="请输入专业" /></Input>
          </Form-item>
          <Form-item label="学历" prop="education" class="width-48">
            <Input v-model="formObj.education" name="education" placeholder="请输入学历" /></Input>
          </Form-item>
          <Form-item label="毕业时间" prop="graduationTime" class="width-48">
            <DatePicker
              v-model="formObj.graduationTime"
              type="date"
              name="graduationTime"
              placeholder="请选择毕业时间"
              style="width: 320px;"
            />
          </Form-item>
          <Form-item label="毕业院校" prop="graduatedSchool" class="width-48">
            <Input v-model="formObj.graduatedSchool" name="graduatedSchool" placeholder="请输入毕业院校" /></Input>
          </Form-item>
          <Form-item label="岗位" prop="post" class="width-48">
            <Input v-model="formObj.post" name="post" placeholder="请输入岗位" /></Input>
          </Form-item>
          <Form-item label="合同到期时间" prop="expireDate" class="width-48">
            <DatePicker
              v-model="formObj.expireDate"
              type="date"
              placeholder="请选择合同到期时间"
              style="width: 320px;"
            />
          </Form-item>
          <Form-item label="状态" prop="status" class="width-48">
            <el-radio v-model="formObj.status" label="1">
              在职
            </el-radio>
            <el-radio v-model="formObj.status" label="0">
              离职
            </el-radio>
          </Form-item>
          <Form-item label="是否内审员" prop="ifAuditor" class="width-48">
            <el-radio v-model="formObj.ifAuditor" label="1">
              是
            </el-radio>
            <el-radio v-model="formObj.ifAuditor" label="0">
              否
            </el-radio>
          </Form-item>
          <Form-item label="备注" prop="remark" class="width-48">
            <Input v-model="formObj.remark" name="remark" placeholder="请输入备注" />
          </Form-item>
          <input v-model="formObj.orgIds" name="orgIds" type="hidden">
          <input v-model="formObj.levelId" name="levelId" type="hidden">
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </el-dialog>
    <!--分配组织-->
    <selOrgTree ref="orgModal" @on-result-change="_orgData" />
    <!--分配角色-->
    <selRoleTree ref="roleModal" @on-result-change="_roleData" />

    <!--选择上级菜单tree-->
    <selectResourceTree ref="ztreeLevelModal" @on-result-change="_treeData" />
  </div>
</template>
<script>
/**
 * 添加编辑
 */
import { staffInfo } from '../../../api'
import global from '../../../api/config'
import selOrgTree from './tree/selOrgTree'
import selRoleTree from './tree/selRoleTree'
import selectResourceTree from './tree/selectEquipLocationTree'
export default {
  components: { selOrgTree, selRoleTree, selectResourceTree },
  data() {
    const validateName = (rule, value, callback) => {
      // 验证名称
      if (value === '') {
        callback(new Error('账号不能为空！'))
      } else {
        callback()
      }
    }
    const validatePass = (rule, value, callback) => {
      // // 验证密码，必须是数字和字母的结合
      // if (this.formObj.password === undefined) {
      //   // 编辑
      //   callback()
      // } else if (value === '' || undefined === value) {
      //   // 添加
      //   callback(new Error('请输入您的密码'))
      // } else if (value.length < 6) {
      //   callback(new Error('密码长度不能小于6位'))
      // } else if (value === this.formObj.password.replace(/[^a-zA-Z]/g, '')) {
      //   // 只输入英文
      //   callback(new Error('请输入数字和字母结合的密码'))
      // } else if (value === this.formObj.password.replace(/\D/g, '')) {
      //   // 只输入数字
      //   callback(new Error('请输入数字和字母结合的密码'))
      // } else {
      //   if (this.formObj.passwordCheck !== '' && this.id !== '') {
      //     // 对第二个密码框单独验证
      //     this.$refs.formObj.validateField('passwordCheck')
      //   }
      //   callback()
      // }
    }
    const validatePassCheck = (rule, value, callback) => {
      if (this.formObj.password === '' && value === '') {
        callback(new Error('请再次输入您的密码'))
      } else if (value !== this.formObj.password) {
        callback(new Error('两次输入的密码不匹配'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      // 验证手机号
      const reg = /^((\+?86)|(\(\+86\)))?1\d{10}$/ // 支持+86格式的手机号
      if (this.formObj.mobile === '') {
        callback(new Error('请输入您的手机号'))
      } else if (!reg.test(this.formObj.mobile)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }
    const validateQq = (rule, value, callback) => {
      // 验证qq
      const reg = /^[0-9]*$/
      if (value === undefined) {
        callback()
      } else if (!reg.test(value)) {
        callback(new Error('请输入数字!'))
      } else {
        callback()
      }
    }
    return {
      id: '',
      modalTitle: '添加',
      formObj: {
        name: '',
        sex: '1',
        number: '',
        orgNames: '',
        levelName: '',
        // latestTitle:'',
        age: 1,
        entryTime: '',
        workTime: '',
        probatioStartDate: '', // 试用期开始
        probatioEndDate: '', // 试用期结束
        becomeDate: '', // 入职转正
        profession: '',
        education: '',
        graduationTime: '',
        graduatedSchool: '',
        post: '',
        remark: '',
        status: '1',
        ifAuditor: '0',
        expireDate: '', // 合同到期时间
        orgIds: '',
        levelId: ''
      },
      fileObj: {
        relId: 0,
        type: 1
      },
      probatioDate: [], // 试用期
      accreditList: [
        { value: 'NORMAL', label: '普通' },
        { value: 'ALLOW', label: '允许进入后台' }
      ],
      notifyWechatList: [{ value: 0, name: '否' }, { value: 1, name: '是' }],
      sexList: [{ value: 0, name: '男' }, { value: 1, name: '女' }],
      statusList: [
        { value: 'PENDING_ACTIVATION', label: '待激活' },
        { value: 'NORMAL', label: '正常' },
        { value: 'DISABLED', label: '禁用' }
      ],
      ruleValidate: {
        username: [
          { required: true, validator: validateName, trigger: 'blur' }
        ],
        password: [{ validator: validatePass, trigger: 'blur' }],
        passwordCheck: [{ validator: validatePassCheck, trigger: 'blur' }],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        email: [{ type: 'email', message: '邮箱格式不正确', trigger: 'blur' }],
        qq: [{ validator: validateQq, trigger: 'blur' }],
        realname: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ]
      },
      orgNameList: '',
      roleNameList: '',
      roleIds: [],
      imgUrl: '',
      action: global.baseURL + '/v1/file_signature/',
      showModal: false,
      showSign: false,
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ]
    }
  },
  methods: {
    // modal
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _ok() {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize('edit-form-staff-info-edit')
          data.sex = this.formObj.sex
          if (this.age) {
            data.age = this.age
          }
          data.status = this.formObj.status
          data.ifAuditor = this.formObj.ifAuditor
          // 入职时间
          if (this.formObj.entryTime) {
            data.entryTime = this.$dateformat(
              this.formObj.entryTime,
              'yyyy-mm-dd'
            )
          }
          // 参加工作时间
          if (this.formObj.workTime) {
            data.workTime = this.$dateformat(
              this.formObj.workTime,
              'yyyy-mm-dd'
            )
          }
          // 试用期开始
          if (this.formObj.probatioStartDate) {
            data.probatioStartDate = this.formObj.probatioStartDate
          }
          // 试用期结束
          if (this.formObj.probatioEndDate) {
            data.probatioEndDate = this.formObj.probatioEndDate
          }
          // 入职转正
          if (this.formObj.becomeDate) {
            data.becomeDate = this.$dateformat(
              this.formObj.becomeDate,
              'yyyy-mm-dd'
            )
          }
          // 合同到期时间
          if (this.formObj.expireDate) {
            data.expireDate = this.$dateformat(
              this.formObj.expireDate,
              'yyyy-mm-dd'
            )
          }
          this.$extend(data, {
            orgIds: this.formObj.orgIds,
            orgNames: this.formObj.orgNames
          })
          this._save(data)
        } else {
          this.$message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    _probatioDateChange(date) {
      this.formObj.probatioStartDate = date[0]
      this.formObj.probatioEndDate = date[1]
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加
      if (this.$string(this.id).isEmpty()) {
        const result = await staffInfo.add(data)
        this._resultChange(result, '添加成功')
      } else {
        // 编辑
        const result = await staffInfo.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      }
    },
    _cancel() {
      this.showModal = false
    },
    _selectLevelZtree() {
      this.$refs.ztreeLevelModal._open()
    },
    _treeData(result) {
      if (result === undefined) {
        // 未选中数据的时候
        this.formObj.levelName = ''
      } else {
        // 选中数据以后
        this.formObj.levelName = result.name
        alert(result.id)
        this.formObj.levelId = result.id
        alert(this.formObj.levelId)
      }
    },
    _open(formObj, roleNames) {
      this.showModal = true
      this.$nextTick(() => {
        this.$refs.formObj.resetFields()
        this._hideLoading()
        if (this.$string(formObj).isEmpty()) {
          this.id = ''
          this.formObj.id = this.id
          this.fileList = []
          this.modalTitle = '添加人员信息'
          this.age = 1
        } else {
          this.id = formObj.id
          this.formObj = formObj
          this.fileObj.relId = formObj.id
          this.age = formObj.age ? formObj.age : ''
          if (formObj.sex !== undefined) {
            this.formObj.sex = formObj.sex.toString()
          }
          if (formObj.status !== undefined) {
            this.formObj.status = formObj.status.toString()
          }
          if (formObj.ifAuditor !== undefined) {
            this.formObj.ifAuditor = formObj.ifAuditor.toString()
          }
          if (this.formObj.orgIds !== undefined) {
            this.formObj.orgIds = formObj.orgIds
          }
          if (this.formObj.orgNames !== undefined) {
            this.formObj.orgNames = formObj.orgNames
          }
          if (formObj.fileList.length === 0) {
            this.fileList = []
          } else {
            this.fileList = formObj.fileList // 文件集合
          }
          if (formObj.entryTime) {
            this.formObj.entryTime = this.$dateformat(
              formObj.entryTime,
              'yyyy-mm-dd'
            )
          }
          if (formObj.workTime) {
            this.formObj.workTime = this.$dateformat(
              formObj.workTime,
              'yyyy-mm-dd'
            )
          }
          if (formObj.graduationTime) {
            this.formObj.graduationTime = this.$dateformat(
              formObj.graduationTime,
              'yyyy-mm-dd'
            )
          }
          // 试用期开始
          if (formObj.probatioStartDate) {
            this.formObj.probatioStartDate = this.$dateformat(
              formObj.probatioStartDate,
              'yyyy-mm-dd'
            )
          }
          // 试用期结束
          if (formObj.probatioEndDate) {
            this.formObj.probatioEndDate = this.$dateformat(
              formObj.probatioEndDate,
              'yyyy-mm-dd'
            )
          }
          // 入职转正
          if (formObj.becomeDate) {
            this.formObj.becomeDate = this.$dateformat(
              formObj.becomeDate,
              'yyyy-mm-dd'
            )
          }
          // 合同到期时间
          if (formObj.expireDate) {
            this.formObj.expireDate = this.$dateformat(
              formObj.expireDate,
              'yyyy-mm-dd'
            )
          }
          // this.$refs.ztreeOrgModal._editOrgZtee(this.id); //编辑回显组织名称
          this.modalTitle = '编辑人员信息'
        }
      })
    },
    _selOrg() {
      // 选组织
      if (this.$string(this.id).isEmpty()) {
        // 添加
        this.$refs.orgModal._openOrginZtree()
      } else {
        // 编辑回显id
        this.$refs.orgModal._openOrginZtree(this.id)
      }
    },
    _orgData(result) {
      if (result.idsList.length > 0) {
        this.formObj.orgNames = result.namesList[0]
        this.formObj.orgIds = result.idsList[0]
      } else {
        this.formObj.orgNames = ''
        this.formObj.orgIds = ''
      }
    },
    _selRole() {
      // 选角色
      if (this.$string(this.id).isEmpty()) {
        // 添加
        this.$refs.roleModal._openRoleZtree()
      } else {
        // 编辑回显id
        this.$refs.roleModal._openRoleZtree(this.id)
      }
    },
    _roleData(result) {
      if (result.idsList.length > 0) {
        this.roleNameList = result.namesList.join(',')
        this.roleIds = result.idsList
      } else {
        this.roleNameList = ''
        this.roleIds = []
      }
    },
    _selectAccredit(data) {
      this.formObj.accredit = data
    },
    _selectNotifyWechat(data) {
      this.formObj.notifyWechat = data
    },
    _selectSex(data) {
      this.formObj.sex = data
    },
    _selectStatus(data) {
      this.formObj.status = data
    }
  }
}
</script>
