<template>
  <div class="app-container">
    <el-form  :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="选择搜索条件">
        <el-select v-model="queryParams.searchField" placeholder="请选择搜索条件" clearable >
          <el-option
            v-for="dict in dict.type.buyer_employee_search_fields"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入"
          clearable
          style="width: 120px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学历">
        <el-select v-model="queryParams.education" style="width: 120px" placeholder="请选择学历" clearable>
          <el-option
            v-for="dict in dict.type.buyer_employee_education"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="人员状态">
        <el-select v-model="queryParams.employeeStatus" style="width: 120px" placeholder="请选择人员状态" clearable>
          <el-option
            v-for="dict in dict.type.employee_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工类型" prop="employeeType">
        <el-select v-model="queryParams.employeeType" style="width: 120px" placeholder="请选择类型" clearable>
          <el-option
            v-for="dict in dict.type.employee_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="queryParams.sex" style="width: 120px" placeholder="请选择性别" clearable>
          <el-option
            v-for="dict in dict.type.sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['buyer:employee:add']"
        >新增人员
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          ref="fileUpload"
          class="upload-demo"
          :action="uploadUrl"
          multiple
          :headers="headers"
          :on-error="handleUploadError"
          :before-upload="handleBeforeUpload"
          :on-success="handleUploadSuccess"
          :on-exceed="handleExceed"
          :limit="limit"
          :show-file-list="false"
          :file-list="fileList"
        >
          <el-button
            type="primary"
            size="mini"
            v-hasPermi="['buyer:employee:edit']"
          >导入Excel
          </el-button>
        </el-upload>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          @click="handleExport"
          v-hasPermi="['buyer:employee:export']"
        >下载Excel模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buyer:employee:remove']"
        >批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table stripe v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="sex">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.sex" />
        </template>
      </el-table-column>
      <el-table-column label="证件号码" align="center" prop="idNumber" />
      <el-table-column label="出生日期" align="center" prop="birthdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.birthdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="学历" align="center" prop="education" />
      <el-table-column label="毕业院校" align="center" prop="college" />
      <el-table-column label="所学专业" align="center" prop="major" />
      <el-table-column label="部门" align="center" prop="dept" />
      <el-table-column label="职务" align="center" prop="post" />
      <el-table-column label="职称" align="center" prop="professional" />
      <el-table-column label="员工类型" align="center" prop="employeeType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.employee_type" :value="scope.row.employeeType" />
        </template>
      </el-table-column>
      <el-table-column label="员工状态" align="center" prop="employeeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.employee_status" :value="scope.row.employeeStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['buyer:employee:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['buyer:employee:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业信息员工对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" inline :rules="rules" class="modal-inline-form" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" width="600px"/>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="证件号码" prop="idNumber">
          <el-input v-model="form.idNumber" placeholder="请输入证件号码" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birthdate">
          <el-date-picker
            clearable
            v-model="form.birthdate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择出生日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学历" prop="education">
          <el-select v-model="form.education" placeholder="请选择学历">
            <el-option
              v-for="dict in dict.type.buyer_employee_education"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="毕业院校" prop="college">
          <el-input v-model="form.college" placeholder="请输入毕业院校" />
        </el-form-item>
        <el-form-item label="所学专业" prop="major">
          <el-input v-model="form.major" placeholder="请输入专业" />
        </el-form-item>
        <el-form-item label="职称" prop="professional">
          <el-input v-model="form.professional" placeholder="请输入职称" />
        </el-form-item>
        <el-form-item label="部门" prop="dept">
          <el-input v-model="form.dept" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="职务" prop="post">
          <el-input v-model="form.post" placeholder="请输入职务" />
        </el-form-item>
        <el-form-item label="员工类型" prop="employeeType">
          <el-select v-model="form.employeeType" placeholder="请选择员工类型">
            <el-option
              v-for="dict in dict.type.employee_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="员工状态" prop="employeeStatus">
          <el-radio-group v-model="form.employeeStatus">
            <el-radio
              v-for="dict in dict.type.employee_status"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="入职日期" prop="hiredate">
          <el-date-picker
            clearable
            v-model="form.hiredate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入职日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="离职日期" prop="resignationDate" v-if="form.employeeStatus === '2'">
          <el-date-picker
            clearable
            v-model="form.resignationDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择离职日期"
          >
          </el-date-picker>
        </el-form-item>
        <row>
          <hr>
          <el-form-item label="学历职称证明（最多三张图片）" label-width="100%" prop="buyerFileInfos">
            <FileUploadMultiple v-model:value="form.buyerFileInfos" :limit="3" :file-size="10" :drag="true" :fileType="null"></FileUploadMultiple>
          </el-form-item>
        </row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee, checkEmployeeExits } from '@/api/buyer/employee'
import { getToken } from '@/utils/auth'

export default {
  name: 'Employee',
  dicts: [
    'employee_status',
    'employee_type',
    'buyer_employee_search_fields',
    'buyer_employee_education',
    'sys_user_sex'
  ],
  data() {
    let checkResignationDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择离职时间'))
      } else {
        callback()
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业信息员工表格数据
      employeeList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sex: null,
        idNumber: null,
        professional: null,
        employeeType: null,
        employeeStatus: null,
        resignationDate: null,
        wages: null,
        searchField: null,
        keyword: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '证件号码不能为空', trigger: 'blur' },
          {pattern: /(^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$)/,
            message: '证件号码不合规则请检查', trigger: 'blur'}
        ],
        employeeStatus: [
          { required: true, message: '请选择员工状态', trigger: 'blur' },
        ],
        resignationDate: [
          { validator: checkResignationDate, trigger: 'blur' }
        ]
      },
      fileList: [],
      uploadUrl: process.env.VUE_APP_BASE_API + '/buyer/employee/importTable',
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      fileType: ['xls', 'xlsx', 'csv'],
      limit: 1
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询企业信息员工列表 */
    getList() {
      this.loading = true
      listEmployee(this.addSearchField(this.queryParams, this.queryParams.searchField, this.queryParams.keyword))
        .then(response => {
          this.employeeList = response.rows
          this.total = response.total
          this.loading = false
        })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remarks: null,
        delFlag: null,
        deptId: null,
        name: null,
        sex: null,
        idNumber: null,
        birthdate: null,
        education: null,
        college: null,
        major: null,
        post: null,
        professional: null,
        hiredate: null,
        employeeType: null,
        employeeStatus: null,
        resignationDate: null,
        wages: null,
        buyerFileInfos: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams= {
        pageNum: 1,
          pageSize: 10,
          sex: null,
          idNumber: null,
          professional: null,
          employeeType: null,
          employeeStatus: null,
          resignationDate: null,
          wages: null,
          searchField: null,
          keyword: null
      },
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加企业信息员工'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getEmployee(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改企业信息员工'
      })
    },
    /** 提交按钮 */
    submitForm() {
      // 验证身份证和出生日期
      //获取出生日期 birthdate
      let birthday = this.form.idNumber.substring(6, 10) + "-" + this.form.idNumber.substring(10, 12) + "-" + this.form.idNumber.substring(12, 14)
      if(this.form.birthdate && birthday != this.form.birthdate){
        this.$modal.msgError('证件号码和出生日期不符合请检查后重试！')
        return
      }

      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEmployee(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            checkEmployeeExits({ idNumber: this.form.idNumber }).then(res => {
              if (res.repeat) {
                this.$modal.msgWarning(res.msg)
              } else {
                addEmployee(this.form).then(response => {
                  this.$modal.msgSuccess('新增成功')
                  this.open = false
                  this.getList()
                })
              }
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除企业人员选中的数据项？').then(function() {
        return delEmployee(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buyer/employee/downTemplate', {}, `企业人员台账模板.xlsx`)
    },
    // 导入失败
    handleUploadError(err) {
      this.$modal.msgError('导入失败，请重试')
      this.$modal.closeLoading()
    },
    // 导入前校检格式和大小
    handleBeforeUpload(file) {
      // 校检文件类型
      if (this.fileType) {
        let fileExtension = ''
        if (file.name.lastIndexOf('.') > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true
          if (fileExtension && fileExtension.indexOf(type) > -1) return true
          return false
        })
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请导入${this.fileType.join('/')}格式文件!`)
          return false
        }
      }
      // 校检文件大小
      this.$modal.loading('正在导入文件，请稍候...')
      return true
    },
    // 导入成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('导入成功')
        this.$refs.fileUpload.handleRemove(file)
        this.getList()
      } else {
        this.$modal.closeLoading()
        this.$modal.msgError(res.msg)
        this.$refs.fileUpload.handleRemove(file)
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`导入文件数量不能超过 ${this.limit} 个!`)
    }
  }
}
</script>
<style scoped lang="scss">
.modal-inline-form {
  display: flex;
  flex-wrap: wrap;

  .el-form-item {
    width: calc(50% - 20px);
  }

  .el-input {
    width: 217px;
  }
}
</style>
