<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="120px">
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="工号" prop="workNo">
              <el-input :disabled="!!formData.id" v-model="formData.workNo" placeholder="请输入工号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="formData.name" placeholder="请输入姓名"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="手机号" prop="tel">
              <el-input v-model="formData.tel" placeholder="请输入手机号"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="formData.sex">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.SYSTEM_USER_SEX)"
                          :key="dict.value" :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="工作日期" prop="workDate">
              <el-date-picker clearable v-model="formData.workDate" type="date" value-format="timestamp"
                              placeholder="选择工作日期"
                              @blur="getWorkYear"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工龄(年)" prop="workYear">
              <el-input disabled v-model="formData.workYear" placeholder="工龄"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="joinedDate">
              <el-date-picker clearable v-model="formData.joinedDate" type="date" value-format="timestamp"
                              placeholder="选择入职日期"
                              @blur="getJoinedYear"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="司龄(年)" prop="joinedYear">
              <el-input disabled v-model="formData.joinedYear" placeholder="司龄"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item v-if="formData.id === undefined" label="登录账号" prop="loginAccount">
              <el-input v-model="formData.loginAccount" placeholder="请输入登录账号" maxlength="16"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="formData.id === undefined" label="登录密码" prop="password">
              <el-input v-model="formData.password" placeholder="请输入登录密码" type="password" maxlength="16" show-password/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="学历" prop="education">
              <el-select v-model="formData.education" placeholder="请选择学历">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.COMPANY_STAFF_EDU)"
                           :key="dict.value" :label="dict.label" :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="员工角色" prop="roleIds">
          <el-select
            style="width: 100%"
            filterable
            clearable
            v-model="formData.roleIds" multiple placeholder="请选择员工角色"
          >
            <el-option
              v-for="(item, index) in roleList"
              :key="index"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="技能标签" prop="labelsArray">
          <el-select
            style="width: 100%"
            filterable
            allow-create
            v-model="formData.labelsArray" multiple placeholder="请选择技能标签"
          >
            <el-option
              v-for="(item, index) in labelOptions"
              :key="index"
              :label="item.labelName"
              :value="item.labelName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="家庭住址" prop="address">
          <el-input type="textarea"
                    :autosize="{ minRows: 2, maxRows: 5}" v-model="formData.address" placeholder="请输入家庭住址"/>
        </el-form-item>
        <el-form-item label="个人简介" prop="content">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5}"
            placeholder="请输入内容"
            v-model="formData.content"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="附件" prop="fileUrls">
          <file-upload v-model="formData.fileUrls"></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as StaffApi from '@/api/company/staff'
import Editor from '@/components/Editor'
import FileUpload from '@/components/FileUpload'

export default {
  name: 'StaffForm',
  components: {
    Editor,
    FileUpload
  },
  data() {
    const validateWorkNo = async(rule, value, callback) => {
      const res = await StaffApi.checkWorkNo(value)
      return res.data ? callback() : !this.formData.id ? callback(new Error()) : callback
    }
    return {
      // 弹出层标题
      dialogTitle: '',
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        corpId: undefined,
        userId: undefined,
        deptId: undefined,
        workNo: undefined,
        name: undefined,
        tel: undefined,
        sex: '1',
        address: undefined,
        workDate: undefined,
        workYear: undefined,
        joinedDate: undefined,
        joinedYear: undefined,
        education: undefined,
        content: undefined,
        uniqueCode: undefined,
        fileUrls: undefined,
        loginAccount: undefined,
        password: undefined,
        labelsArray: undefined,
        roleIds: undefined
      },
      // 表单校验
      formRules: {
        workNo: [
          { required: true, message: '工号不能为空', trigger: 'blur' },
          { validator: validateWorkNo, message: '工号已存在', trigger: 'blur' }
        ],
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        tel: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
            message: '请输入正确的手机号',
            trigger: ['blur', 'change']
          }
        ],
        sex: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
        address: [{ required: true, message: '家庭住址不能为空', trigger: 'blur' }],
        workYear: [{ required: true, message: '工龄不能为空', trigger: 'blur' }],
        joinedYear: [{ required: true, message: '司龄不能为空', trigger: 'blur' }],
        education: [{ required: true, message: '学历不能为空', trigger: 'blur' }],
        loginAccount: [
          { required: true, message: '登录账号不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '登录账号长度在6~20个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '登录密码不能为空', trigger: 'blur' },
          { min: 6, max: 20, message: '登录密码长度在6~20个字符', trigger: 'blur' },

        ],
        workDate: [{ required: true, message: '工作日期不能为空', trigger: 'blur' }],
        joinedDate: [{ required: true, message: '入职日期不能为空', trigger: 'blur' }]
      },
      labelOptions: [],
      nowDate: new Date(),
      roleList: []
    }
  },
  methods: {
    // 获取角色列表
    async listRoles() {
      const res = await StaffApi.getRoleList()
      this.roleList = res.data
    },
    /** 获取标签 */
    async listLabels() {
      try {
        const res = await StaffApi.getLabels()
        this.labelOptions = res.data.map(item => ({
          labelName: item.labelName
        }))
      } finally {
      }
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true
      this.dialogTitle = id ? '修改员工信息' : '新增员工信息'
      await this.listLabels()
      await this.listRoles()
      this.reset()
      // 修改时，设置数据
      if (id) {
        this.formData.id = id
        this.formLoading = true
        try {
          const res = await StaffApi.getStaff(id)
          this.formData = res.data
          this.formData.workDate = new Date(this.formData.workDate)
          this.formData.joinedDate = new Date(this.formData.joinedDate)
          this.title = '修改企业管理-员工信息'
        } finally {
          this.formLoading = false
        }
      }
      this.title = '新增企业管理-员工信息'
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs['formRef'].validate()
      this.formLoading = true
      try {
        const data = this.formData
        // 修改的提交
        if (data.id) {
          await StaffApi.updateStaff(data)
          this.$modal.msgSuccess('修改成功')
          this.dialogVisible = false
          this.$emit('success')
          return
        }
        // 添加的提交
        await StaffApi.createStaff(data)
        this.$modal.msgSuccess('新增成功')
        this.dialogVisible = false
        this.$emit('success')
      } finally {
        this.formLoading = false
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        corpId: undefined,
        userId: undefined,
        deptId: undefined,
        workNo: undefined,
        name: undefined,
        tel: undefined,
        sex: '1',
        address: undefined,
        workDate: undefined,
        workYear: undefined,
        joinedDate: undefined,
        joinedYear: undefined,
        education: undefined,
        content: undefined,
        uniqueCode: undefined,
        fileIds: undefined,
        loginAccount: undefined,
        password: undefined,
        roleIds: undefined
      }
      this.resetForm('formRef')
    },
    // 获取工龄
    getWorkYear() {
      this.formData.workYear = this.getYearsByDate(this.formData.workDate)
    },
    // 获取司龄
    getJoinedYear() {
      this.formData.joinedYear = this.getYearsByDate(this.formData.joinedDate)
    },
    // 计算输入日期至今隔了多少年
    getYearsByDate(date) {
      if (!date) {
        return '0'
      }
      const inputDate = new Date(date)
      let years = this.nowDate.getFullYear() - inputDate.getFullYear()
      if (
        this.nowDate.getMonth() < inputDate.getMonth() ||
        (this.nowDate.getMonth() === inputDate.getMonth() && this.nowDate.getDate() < inputDate.getDate())
      ) {
        years--
      }
      return years >= 0 ? years : '0'
    }
  }
}
</script>
