<template>
  <layout-card>
    <el-form
      ref="formRef"
      :rules="rules"
      :model="data.form"
      label-width="160px"
    >
      <el-row :gutter="20">
        <el-col :span="24">
          <el-divider content-position="left">基本信息</el-divider>
        </el-col>
        <el-col :span="8">
          <el-form-item label="人员类型" prop="PERSONNEL_TYPE">
            <el-select v-model="data.form.PERSONNEL_TYPE" multiple>
              <el-option
                v-for="item in data.personnelTypeList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="身份证号" prop="USER_ID_CARD">
            <el-input
              v-model="data.form.USER_ID_CARD"
              :disabled="!!USER_ID"
              placeholder="请输入"
              @blur="fnChangeIdCard"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="姓名" prop="NAME">
            <el-input v-model="data.form.NAME" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="手机号" prop="PHONE">
            <el-input v-model="data.form.PHONE" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="出生年月" prop="DATE_OF_BIRTH">
            <el-date-picker
              v-model="data.form.DATE_OF_BIRTH"
              type="date"
              placeholder="选择日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别" prop="SEX">
            <el-select v-model="data.form.SEX">
              <el-option
                v-for="item in [
                  { NAME: '男', DICTIONARIES_ID: '1' },
                  { NAME: '女', DICTIONARIES_ID: '0' },
                ]"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="民族" prop="NATION">
            <el-select v-model="data.form.NATION">
              <el-option
                v-for="item in data.nationList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="文化程度" prop="DEGREE_OF_EDUCATION">
            <el-select v-model="data.form.DEGREE_OF_EDUCATION">
              <el-option
                v-for="item in data.degreeOfEducationList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="政治面貌" prop="POLITICAL_OUTLOOK">
            <el-select v-model="data.form.POLITICAL_OUTLOOK">
              <el-option
                v-for="item in data.politicalLandscapeList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="参加工作日期" prop="WORKING_DATE">
            <el-date-picker
              v-model="data.form.WORKING_DATE"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="邮箱" prop="EMAIL">
            <el-input v-model="data.form.EMAIL" placeholder="请输入" />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">入职信息</el-divider>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门" prop="DEPARTMENT_ID">
            <layout-department
              v-model="data.form.DEPARTMENT_ID"
              @update:model-value="data.form.POST_ID = ''"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="岗位" prop="POST_ID">
            <el-select v-model="data.form.POST_ID">
              <el-option
                v-for="item in data.postList"
                :key="item.POST_ID"
                :label="item.NAME"
                :value="item.POST_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门排序" prop="SORT">
            <el-input v-model.number="data.form.SORT" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职务" prop="DUTIES">
            <layout-select-create
              v-model="data.form.DUTIES"
              :list="data.dutiesList"
              @delete-option="fnDictionaryDelete($event, 'POSITION')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职称" prop="TITLE">
            <layout-select-create
              v-model="data.form.TITLE"
              :list="data.professionalTitleList"
              @delete-option="fnDictionaryDelete($event, 'JOB_TITLE')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入职日期" prop="ENTRY_DATE">
            <el-date-picker
              v-model="data.form.ENTRY_DATE"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="12">
              <el-row>
                <el-col :span="10">
                  <el-form-item label="排班" prop="SHIFTDUTYONE">
                    <el-select
                      v-model="data.form.SHIFTDUTYONE"
                      @change="fnChangeSchedulingOne"
                    >
                      <el-option
                        v-for="item in data.schedulingList"
                        :key="item.SHIFTWORKRULES_ID"
                        :label="item.NAME"
                        :value="item.SHIFTWORKRULES_ID"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="10">
                  <el-form-item label-width="10px" prop="SHIFTDUTYTWO">
                    <el-select
                      v-model="data.form.SHIFTDUTYTWO"
                      @change="fnChangeSchedulingTwo"
                    >
                      <el-option
                        v-for="item in data.schedulingList1"
                        :key="item.SHIFTWORKRULES_ID"
                        :label="item.NAME"
                        :value="item.SHIFTWORKRULES_ID"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label-width="10px">
                    <el-button @click="data.scheduleVisible = true">
                      当前班状
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="12">
              <el-row>
                <el-col v-show="data.periodList.length > 0" :span="24">
                  <el-form-item label="当前班次" prop="periodStr">
                    <el-radio-group
                      v-model="data.form.periodStr"
                      @change="fnChangePeriod"
                    >
                      <el-radio-button
                        v-for="(item, index) in data.periodList"
                        :key="index"
                        :label="item.periodStr"
                      >
                        {{ item.period.WORKSTATUS === "1" ? "上班" : "休班" }}
                      </el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="BZ">
            <el-input
              v-model="data.form.BZ"
              :autosize="{
                minRows: 3,
              }"
              type="textarea"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否安全管理人员" prop="IS_SAFETY">
            <el-radio-group v-model="data.form.IS_SAFETY">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否主要负责人" prop="ISHEAD">
            <el-radio-group v-model="data.form.ISHEAD">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否部门领导" prop="ISLEADER">
            <el-radio-group v-model="data.form.ISLEADER">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
            <!--                <el-tooltip
                  content="温馨提示：部门领导可以审核离岗申请，查看同部门清单数据"
                  placement="top-start"
                >
                  <el-icon color="red" size="16" class="ml-10">
                    <info-filled />
                  </el-icon>
                </el-tooltip>-->
          </el-form-item>
          <!--            <el-col :span="24">
              <el-form-item label="是否在线学习人员">
                <el-switch
                  v-model="data.form.ISSTUDENT"
                  active-value="true"
                  inactive-value="false"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                />
              </el-form-item>
            </el-col>-->
        </el-col>

        <!--        <el-col :span="12">
          <el-form-item label="在职情况" prop="INCUMBENCY">
            <el-select v-model="data.form.INCUMBENCY">
              <el-option
                v-for="item in data.employmentSituationList"
                :key="item.DICTIONARIES_ID"
                :label="item.NAME"
                :value="item.DICTIONARIES_ID"
              />
            </el-select>
          </el-form-item>
        </el-col>-->

        <el-col :span="24">
          <el-divider content-position="left">身份证</el-divider>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="15">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="身份证（正面）" prop="ID_CARD_FRONT">
                    <layout-upload
                      v-model:file-list="data.fileForm.ID_CARD_FRONT"
                      accept=".jpg,.jpeg,.png"
                      list-type="picture-card"
                    >
                    </layout-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证（背面）" prop="ID_CARD_BACK">
                    <layout-upload
                      v-model:file-list="data.fileForm.ID_CARD_BACK"
                      accept=".jpg,.jpeg,.png"
                      list-type="picture-card"
                    >
                    </layout-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="9">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="有效期限（身份证）" prop="dates">
                    <el-date-picker
                      v-model="data.form.ID_CARD_VALIDITY"
                      type="daterange"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      range-separator="至"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="住址" prop="ID_CARD_ADDRESS">
                    <el-input
                      v-model="data.form.ID_CARD_ADDRESS"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="签发机关" prop="ID_CARD_ORGAN">
                    <el-input
                      v-model="data.form.ID_CARD_ORGAN"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">驾驶证</el-divider>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="9">
              <el-row>
                <el-col>
                  <el-form-item label="驾驶证" :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'DRIVER_LICENSE':''">
                    <layout-upload
                      v-model:file-list="data.fileForm.DRIVER_LICENSE"
                      accept=".jpg,.jpeg,.png"
                      list-type="picture-card"
                    >
                    </layout-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="15">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="证号" :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'DRIVER_LICENSE_NO':''">
                    <el-input
                      v-model="data.form.DRIVER_LICENSE_NO"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="准驾车型" :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'DRIVING_MODEL_ARR':''">
                    <el-select v-model="data.form.DRIVING_MODEL_ARR" multiple>
                      <el-option
                        v-for="item in data.drivingModelList"
                        :key="item.DICTIONARIES_ID"
                        :label="item.NAME"
                        :value="item.DICTIONARIES_ID"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="国籍" :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'DRIVING_NATIONALITY':''">
                    <el-select v-model="data.form.DRIVING_NATIONALITY">
                      <el-option
                        v-for="item in data.nationalityList"
                        :key="item.NAME"
                        :label="item.NAME"
                        :value="item.NAME"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item
                    label="初次领证日期"
                    :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'DRIVER_LICENSE_ISSUE_DATE':''"
                  >
                    <el-date-picker
                      v-model="data.form.DRIVER_LICENSE_ISSUE_DATE"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="有效期限" :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'dates':''">
                    <el-date-picker
                      v-model="data.form.DRIVER_LICENSE_VALIDITY"
                      type="daterange"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      range-separator="至"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="签发机关" :prop="data.form.PERSONNEL_TYPE.join()!=='23e18d4618ea44fea78bfe7021d4b5f1'?'DRIVER_LICENSE_ORGAN':''">
                    <el-input
                      v-model="data.form.DRIVER_LICENSE_ORGAN"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">从业资格证</el-divider>
        </el-col>
        <el-col :span="24">
          <el-row>
            <el-col :span="9">
              <el-row>
                <el-col>
                  <el-form-item
                    label="从业资格证"
                    prop="QUALIFICATION_CERTIFICATE"
                  >
                    <layout-upload
                      v-model:file-list="
                        data.fileForm.QUALIFICATION_CERTIFICATE
                      "
                      accept=".jpg,.jpeg,.png"
                      list-type="picture-card"
                    >
                    </layout-upload>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="15">
              <el-row>
                <el-col :span="24">
                  <el-form-item
                    label="证号"
                    prop="QUALIFICATION_CERTIFICATE_NO"
                  >
                    <el-input
                      v-model="data.form.QUALIFICATION_CERTIFICATE_NO"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    label="从业资格类别"
                    prop="QUALIFICATION_CERTIFICATE_CATEGORY_ARR"
                  >
                    <el-select
                      v-model="data.form.QUALIFICATION_CERTIFICATE_CATEGORY_ARR"
                      multiple
                    >
                      <el-option
                        v-for="item in data.qualificationCertificateCategoryList"
                        :key="item.DICTIONARIES_ID"
                        :label="item.NAME"
                        :value="item.DICTIONARIES_ID"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    label="国籍"
                    prop="QUALIFICATION_CERTIFICATE_NATIONALITY"
                  >
                    <el-select
                      v-model="data.form.QUALIFICATION_CERTIFICATE_NATIONALITY"
                    >
                      <el-option
                        v-for="item in data.nationalityList"
                        :key="item.NAME"
                        :label="item.NAME"
                        :value="item.NAME"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="24">
                  <el-form-item
                    label="初次领证日期"
                    prop="QUALIFICATION_CERTIFICATE_ISSUE_DATE"
                  >
                    <el-date-picker
                      v-model="data.form.QUALIFICATION_CERTIFICATE_ISSUE_DATE"
                      type="date"
                      placeholder="选择日期"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="有效期限" prop="dates">
                    <el-date-picker
                      v-model="data.form.QUALIFICATION_CERTIFICATE_VALIDITY"
                      type="daterange"
                      value-format="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      range-separator="至"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item
                    label="签发机关"
                    prop="QUALIFICATION_CERTIFICATE_ORGAN"
                  >
                    <el-input
                      v-model="data.form.QUALIFICATION_CERTIFICATE_ORGAN"
                      placeholder="请输入"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="24">
          <el-divider content-position="left">人员认证</el-divider>
        </el-col>
        <el-col>
          <el-form-item label="上传人脸照片" prop="faceFile">
            <layout-upload
              v-model:file-list="data.form.faceFile"
              accept=".jpg,.jpeg,.png"
              list-type="picture-card"
            >
              <template #tip>
                <div style="line-height: 1.6" class="mt-10">
                  <div style="color: red; font-size: 12px">
                    * 图像格式：JPEG、JPG、PNG、BMP
                  </div>
                  <div style="color: red; font-size: 12px">
                    * 图像大小：不超过3M。
                  </div>
                  <div style="color: red; font-size: 12px">
                    *
                    图像分辨率：大于32×32像素，小于4096×4096像素，人脸占比不低于64×64像素。
                  </div>
                  <div style="color: red; font-size: 12px">
                    （如无合适照片请该人员登陆秦安APP中进行人脸照片采集）
                  </div>
                </div>
              </template>
            </layout-upload>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="24">
          <el-form-item label="证书信息" prop="userCerFile">
            <layout-upload
              v-model:file-list="data.form.userCerFile"
              accept=".jpg,.jpeg,.png"
              list-type="picture-card"
              :limit="99"
              delete-to-server
            />
          </el-form-item>
        </el-col>-->
      </el-row>
    </el-form>
    <div class="tc mt-10">
      <el-button type="primary" @click="fnSubmit">保存</el-button>
    </div>
    <scheduling
      :id="data.form.SHIFTDUTYTWO"
      v-model:visible="data.scheduleVisible"
      :info="data.scheduleInfo"
    />
  </layout-card>
</template>

<script setup>
import { reactive, ref, watch, watchEffect } from "vue";
import {
  getUserCurrentShiftList,
  getUserInfo,
  getUserScheduling,
  setDictionaryDelete,
} from "@/request/enterprise_management.js";
import LayoutDepartment from "@/components/department/index.vue";
import LayoutUpload from "@/components/upload/index.vue";
import LayoutSelectCreate from "@/components/select_create/index.vue";
import { getPostListAll } from "@/request/data_dictionary.js";
import { useRoute, useRouter } from "vue-router";
import Scheduling from "../user/components/scheduling.vue";
import {
  addingPrefixFile,
  addingPrefixToFile,
  idCardGetDateAndGender,
  image2Base64,
} from "@/assets/js/utils.js";
import {
  layoutFnGetDegreeOfEducation,
  layoutFnGetDrivingModel,
  layoutFnGetDuties,
  layoutFnGetEmploymentSituation,
  layoutFnGetNation,
  layoutFnGetNationality,
  layoutFnGetPersonnelTypeTraffic,
  layoutFnGetPoliticalLandscape,
  layoutFnGetProfessionalTitle,
  layoutFnGetQualificationCertificateCategory,
} from "@/assets/js/data_dictionary.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { debounce } from "throttle-debounce";
import {
  getVerifyDeduplicationUserIdCard,
  getVerifyDuplicateEmail,
} from "@/request/api.js";
import useFormValidate from "@/assets/js/useFormValidate.js";
import {
  getPractitionerForEdit,
  setPractitionerAdd,
  setPractitionerEdit,
} from "@/request/user_practitioner.js";

const route = useRoute();
const router = useRouter();
const { USER_ID } = route.query;
const fnHasEmail = async (rule, value, callback) => {
  if (value) {
    try {
      await getVerifyDuplicateEmail({
        EMAIL: value,
        PHONE: data.form.PHONE,
      });
      callback();
    } catch {
      callback(new Error("邮箱重复"));
    }
  } else {
    callback();
  }
};
const fnHasUserIdCard = async (rule, value, callback) => {
  if (value) {
    const resData = await getVerifyDeduplicationUserIdCard({
      USER_ID_CARD: value,
      VERIFYUSER_ID: data.form.USER_ID,
    });
    if (resData?.pd?.USER_ID) callback(new Error("身份证号重复"));
    else callback();
  } else {
    callback();
  }
};
const rules = {
  USER_ID_CARD: [
    { required: true, message: "身份证号不能为空", trigger: "blur" },
    {
      pattern:
        /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[0-2])(([0-2][1-9])|10|20|30|31)\d{3}(\d|X|x)$/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
    { validator: fnHasUserIdCard, trigger: "blur" },
  ],
  NAME: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  PHONE: [
    { required: true, message: "请输入手机号码", trigger: "blur" },
    { min: 11, max: 11, message: "请输入11位手机号码", 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: "请输入正确的手机号码",
    },
  ],
  EMAIL: [
    { required: false, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
      message: "请输入正确的邮箱",
    },
    { validator: fnHasEmail, trigger: "blur" },
  ],
  DEPARTMENT_ID: [{ required: true, message: "请选择部门", trigger: "change" }],
  POST_ID: [{ required: true, message: "请选择岗位", trigger: "change" }],
  SORT: [
    { required: true, message: "请输入排序", trigger: "blur" },
    { type: "number", message: "请输入数字类型", trigger: "blur" },
  ],
  NATION: [{ required: true, message: "民族不能为空", trigger: "change" }],
  SEX: [{ required: true, message: "性别不能为空", trigger: "change" }],
  POLITICAL_OUTLOOK: [
    { required: true, message: "政治面貌不能为空", trigger: "change" },
  ],
  DATE_OF_BIRTH: [
    { required: true, message: "请选择出生年月", trigger: "change" },
  ],
  DEGREE_OF_EDUCATION: [
    { required: true, message: "文化程度不能为空", trigger: "change" },
  ],
  PERSONNEL_TYPE: [
    { required: true, message: "人员类型不能为空", trigger: "change" },
  ],
  POST: [{ required: true, message: "职务不能为空", trigger: "change" }],
  ENTRY_DATE: [
    { required: true, message: "请选择入职日期", trigger: "change" },
  ],
  WORKING_DATE: [
    { required: true, message: "请选择参加工作日期", trigger: "change" },
  ],
  INCUMBENCY: [
    { required: true, message: "在职情况不能为空", trigger: "change" },
  ],
  TITLE: [{ required: true, message: "职称不能为空", trigger: "change" }],
  DUTIES: [{ required: true, message: "职务不能为空", trigger: "change" }],
  SHIFTDUTYONE: [{ required: true, message: "请选择排班", trigger: "change" }],
  SHIFTDUTYTWO: [{ required: true, message: "请选择排班", trigger: "change" }],
  periodStr: [
    { required: true, message: "请选择完整的排班类型", trigger: "change" },
  ],
};
const formRef = ref(null);
const data = reactive({
  roleList: [],
  postList: [],
  schedulingList: [],
  schedulingList1: [],
  periodList: [],
  nationList: [],
  politicalLandscapeList: [],
  degreeOfEducationList: [],
  personnelTypeList: [],
  dutiesList: [],
  professionalTitleList: [],
  jobTypeList: [],
  employmentSituationList: [],
  drivingModelList: [],
  nationalityList: [],
  qualificationCertificateCategoryList: [],
  allUser: 0,
  USERS_NUM: 0,
  oldPostId: "",
  oldDepartId: "",
  fileForm: {
    // 身份证照片
    ID_CARD_FRONT: "",
    ID_CARD_BACK: "",
    // 驾驶证照片
    DRIVER_LICENSE: "",
    // 道路运输从业人员从业资格证照片
    QUALIFICATION_CERTIFICATE: "",
  },
  form: {
    USERNAME: "",
    USER_ID_CARD: "",
    NAME: "",
    PHONE: "",
    CARDNO: "",
    DEPARTMENT_ID: "",
    POST_ID: "",
    SORT: "",
    EMAIL: "",
    SHIFTDUTYONE: "",
    SHIFTDUTYTWO: "",
    periodStr: "",
    BZ: "",
    IS_SAFETY: 0,
    ISHEAD: "0",
    ISLEADER: "0",
    ISSTUDENT: "true",
    NATION: "",
    SEX: "",
    POLITICAL_OUTLOOK: "",
    DATE_OF_BIRTH: "",
    DEGREE_OF_EDUCATION: "",
    PERSONNEL_TYPE: [],
    DUTIES: "",
    TITLE: "",
    ENTRY_DATE: "",
    WORKING_DATE: "",
    INCUMBENCY: "",
    faceFile: [],
    userCerFile: [],

    // 身份证照片
    ID_CARD_FRONT: "",
    ID_CARD_BACK: "",
    // 身份证有效期
    ID_CARD_VALIDITY: [],
    ID_CARD_VALIDITY_START: "",
    ID_CARD_VALIDITY_END: "",
    // 身份证住址
    ID_CARD_ADDRESS: "",
    // 身份证签发机关
    ID_CARD_ORGAN: "",

    // 驾驶证照片
    DRIVER_LICENSE: "",
    // 驾驶证号
    DRIVER_LICENSE_NO: "",
    // 准驾车型
    DRIVING_MODEL_ARR: [],
    DRIVING_MODEL: "",
    // 国籍
    DRIVING_NATIONALITY: "中国",
    // 初次领证日期
    DRIVER_LICENSE_ISSUE_DATE: "",
    // 驾驶证有效期
    DRIVER_LICENSE_VALIDITY: [],
    // 驾驶证有效期（起始）
    DRIVER_LICENSE_VALIDITY_START: "",
    // 驾驶证有效期（截止）
    DRIVER_LICENSE_VALIDITY_END: "",
    // 驾驶证签发机关
    DRIVER_LICENSE_ORGAN: "",

    // 道路运输从业人员从业资格证照片
    QUALIFICATION_CERTIFICATE: "",
    // 道路运输从业人员从业资格证号
    QUALIFICATION_CERTIFICATE_NO: "",
    // 从业资格类别
    QUALIFICATION_CERTIFICATE_CATEGORY_ARR: [],
    QUALIFICATION_CERTIFICATE_CATEGORY: "",
    // 道路运输从业人员从业资格证号
    QUALIFICATION_CERTIFICATE_NATIONALITY: "中国",
    // 初次领证日期
    QUALIFICATION_CERTIFICATE_ISSUE_DATE: "",
    // 从业资格证有效期
    QUALIFICATION_CERTIFICATE_VALIDITY: [],
    // 从业资格证有效期（起始）
    QUALIFICATION_CERTIFICATE_VALIDITY_START: "",
    // 从业资格证有效期（截止）
    QUALIFICATION_CERTIFICATE_VALIDITY_END: "",
    // 道路运输从业人员从业资格证签发机关
    QUALIFICATION_CERTIFICATE_ORGAN: "",
  },
  scheduleInfo: {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  },
  scheduleVisible: false,
});
const fnGetData = async () => {
  if (!USER_ID) return;
  const resData = await getPractitionerForEdit({ USER_ID });
  const form = resData.pd;
  form.PASSWORD = "Aa@123456";
  form.periodStr = resData.periodStr;
  form.ISSTUDENT = resData.pd.ISSTUDENT.toString();
  if (form.USERAVATARURL_CONVERT)
    form.faceFile = [
      { url: form.USERAVATARPREFIX + form.USERAVATARURL_CONVERT },
    ];
  data.scheduleInfo = resData.period;
  data.oldPostId = form.POST_ID;
  data.oldDepartId = form.DEPARTMENT_ID;
  form.userCerFile = addingPrefixToFile(resData.userCerList);
  form.PERSONNEL_TYPE = form.PERSONNEL_TYPE.split(",")
  resData.certificateList.forEach((item) => {
    if (item.CERTIFICATE_CATEGORY === "1") {
      data.fileForm.ID_CARD_FRONT = addingPrefixFile(item.ID_PHOTO_FRONT);
      data.fileForm.ID_CARD_BACK = addingPrefixFile(item.ID_PHOTO_BACK);
      form.ID_CARD_FRONT = item.ID_PHOTO_FRONT;
      form.ID_CARD_BACK = item.ID_PHOTO_BACK;
      form.USER_ID_CARD = item.ID_NO;
      form.ID_CARD_VALIDITY = [item.ID_VALIDITY_START, item.ID_VALIDITY_END];
      form.ID_CARD_VALIDITY_START = item.ID_VALIDITY_START;
      form.ID_CARD_VALIDITY_END = item.ID_VALIDITY_END;
      form.ID_CARD_ADDRESS = item.ID_ADDRESS;
      form.ID_CARD_ORGAN = item.ID_ORGAN;
    } else if (item.CERTIFICATE_CATEGORY === "2") {
      data.fileForm.DRIVER_LICENSE = addingPrefixFile(item.ID_PHOTO_FRONT);
      form.DRIVER_LICENSE = item.ID_PHOTO_FRONT;
      form.DRIVER_LICENSE_NO = item.ID_NO;
      form.DRIVING_NATIONALITY = item.ID_NATIONALITY;
      form.DRIVER_LICENSE_ISSUE_DATE = item.ID_ISSUE_DATE;
      form.DRIVER_LICENSE_VALIDITY = [
        item.ID_VALIDITY_START,
        item.ID_VALIDITY_END,
      ];
      form.DRIVER_LICENSE_VALIDITY_START = item.ID_VALIDITY_START;
      form.DRIVER_LICENSE_VALIDITY_END = item.ID_VALIDITY_END;
      form.DRIVER_LICENSE_ORGAN = item.ID_ORGAN;
      form.DRIVING_MODEL_ARR = item.ALLOW_QUALIFICATION
        ? item.ALLOW_QUALIFICATION.split(",")
        : [];
    } else if (item.CERTIFICATE_CATEGORY === "3") {
      data.fileForm.QUALIFICATION_CERTIFICATE = addingPrefixFile(
        item.ID_PHOTO_FRONT
      );
      form.QUALIFICATION_CERTIFICATE = item.ID_PHOTO_FRONT;
      form.QUALIFICATION_CERTIFICATE_NO = item.ID_NO;
      form.QUALIFICATION_CERTIFICATE_NATIONALITY = item.ID_NATIONALITY;
      form.QUALIFICATION_CERTIFICATE_ISSUE_DATE = item.ID_ISSUE_DATE;
      form.QUALIFICATION_CERTIFICATE_VALIDITY = [
        item.ID_VALIDITY_START,
        item.ID_VALIDITY_END,
      ];
      form.QUALIFICATION_CERTIFICATE_VALIDITY_START = item.ID_VALIDITY_START;
      form.QUALIFICATION_CERTIFICATE_VALIDITY_END = item.ID_VALIDITY_END;
      form.QUALIFICATION_CERTIFICATE_ORGAN = item.ID_ORGAN;
      form.QUALIFICATION_CERTIFICATE_CATEGORY_ARR = item.ALLOW_QUALIFICATION
        ? item.ALLOW_QUALIFICATION.split(",")
        : [];
    }
  });
  data.form = { ...data.form, ...form };
};
fnGetData();
const fnGetUserRole = async () => {
  const resData = await getUserInfo();
  data.roleList = resData.roleList;
  data.allUser = resData.allUser;
  data.USERS_NUM = resData.USERS_NUM.USERS_NUM;
};
fnGetUserRole();
const fnGetPost = async (DEPARTMENT_ID) => {
  const resData = await getPostListAll({ DEPARTMENT_ID });
  data.postList = resData.postList;
};
const fnGetUserScheduling = async (PARENTID, list) => {
  const resData = await getUserScheduling({ PARENTID });
  data[list] = resData.varList;
};
fnGetUserScheduling("0", "schedulingList");
const fnChangeSchedulingOne = () => {
  data.form.SHIFTDUTYTWO = "";
  data.periodList = [];
  data.scheduleInfo = {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  };
  data.form.periodStr = "";
};
const fnChangeSchedulingTwo = () => {
  data.scheduleInfo = {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  };
  data.form.periodStr = "";
};
const fnGetUserCurrentShiftList = async (SHIFTWORKRULES_ID) => {
  const resData = await getUserCurrentShiftList({ SHIFTWORKRULES_ID });
  data.periodList = resData.varList;
};
const fnChangePeriod = (event) => {
  for (let i = 0; i < data.periodList.length; i++) {
    if (data.periodList[i].periodStr === event) {
      data.scheduleInfo = data.periodList[i].period;
      break;
    }
  }
};
const fnChangeIdCard = () => {
  const { sex, date } = idCardGetDateAndGender(data.form.USER_ID_CARD);
  data.form.SEX = sex;
  data.form.DATE_OF_BIRTH = date;
  data.form.DRIVER_LICENSE_NO = data.form.USER_ID_CARD;
  data.form.QUALIFICATION_CERTIFICATE_NO = data.form.USER_ID_CARD;
};
const fnGetLevels = async () => {
  const { value: nationList } = await layoutFnGetNation();
  data.nationList = nationList;
  const { value: politicalLandscapeList } =
    await layoutFnGetPoliticalLandscape();
  data.politicalLandscapeList = politicalLandscapeList;
  const { value: degreeOfEducationList } = await layoutFnGetDegreeOfEducation();
  data.degreeOfEducationList = degreeOfEducationList;
  const { value: personnelTypeList } = await layoutFnGetPersonnelTypeTraffic({
    DICTIONARIES_ID: "0b62f92b0b624aab8e89a77304a64d5e",
    BIANMA: "TRAFFIC_EMPLOYMENT_DRIVE",
  });
  data.personnelTypeList = personnelTypeList;
  const { value: dutiesList } = await layoutFnGetDuties();
  data.dutiesList = dutiesList;
  const { value: professionalTitleList } = await layoutFnGetProfessionalTitle();
  data.professionalTitleList = professionalTitleList;
  const { value: employmentSituationList } =
    await layoutFnGetEmploymentSituation();
  data.employmentSituationList = employmentSituationList;
  const { value: drivingModelList } = await layoutFnGetDrivingModel();
  data.drivingModelList = drivingModelList;
  const { value: nationalityList } = await layoutFnGetNationality();
  data.nationalityList = nationalityList;
  const { value: qualificationCertificateCategoryList } =
    await layoutFnGetQualificationCertificateCategory();
  data.qualificationCertificateCategoryList =
    qualificationCertificateCategoryList;
  data.qualificationCertificateCategoryList.forEach((item) => {
    item.NAME = "（" + item.BIANMA + "） " + item.NAME;
  });
};
fnGetLevels();
const fnDictionaryDelete = debounce(
  1000,
  async (index, DICTTYPE) => {
    let DICTIONARIES_ID = "";
    let msgTitle = "";
    if (DICTTYPE === "POSITION") {
      DICTIONARIES_ID = data.dutiesList[index].DICTIONARIES_ID;
      msgTitle = "职务：" + data.dutiesList[index].NAME;
    } else if (DICTTYPE === "JOB_TITLE") {
      DICTIONARIES_ID = data.professionalTitleList[index].DICTIONARIES_ID;
      msgTitle = "职称：" + data.professionalTitleList[index].NAME;
    }
    await ElMessageBox.confirm(
      "删除此分类会同时删除其他相关已编辑过的人员信息中的分类设置，确定要删除（" +
        msgTitle +
        "）吗？",
      { type: "warning" }
    );
    await setDictionaryDelete({ DICTIONARIES_ID, DICTTYPE });
    if (DICTTYPE === "POSITION") {
      data.dutiesList.splice(index, 1);
    } else if (DICTTYPE === "JOB_TITLE") {
      data.professionalTitleList.splice(index, 1);
    }
  },
  {
    atBegin: true,
  }
);
watchEffect(() => {
  if (data.form.DEPARTMENT_ID) fnGetPost(data.form.DEPARTMENT_ID);
  if (data.form.SHIFTDUTYONE)
    fnGetUserScheduling(data.form.SHIFTDUTYONE, "schedulingList1");
  if (data.form.SHIFTDUTYTWO) fnGetUserCurrentShiftList(data.form.SHIFTDUTYTWO);
});
const stop = watch(
  () => data.form.ISSTUDENT,
  (val) => {
    if (val === "true") {
      fnGetLevels();
      stop && stop();
    }
  }
);
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    data.form.WORKSTATUS = data.scheduleInfo.WORKSTATUS;
    data.form.DURATION = data.scheduleInfo.DURATION;
    data.form.WORKPERIOD = data.scheduleInfo.WORKPERIOD;
    if (fnFindValueInList("dutiesList", data.form.DUTIES)) {
      data.form.letDutiesType = "select";
      data.form.DUTIESValue = "";
    } else {
      data.form.letDutiesType = "value";
      data.form.DUTIESValue = data.form.DUTIES;
    }
    if (fnFindValueInList("professionalTitleList", data.form.TITLE)) {
      data.form.letTitleType = "select";
      data.form.letTitleValue = "";
    } else {
      data.form.letTitleType = "value";
      data.form.letTitleValue = data.form.TITLE;
    }

    if (data.form.faceFile?.[0]?.raw) {
      const resData = await image2Base64(data.form.faceFile[0].url);
      data.form.USERAVATARPREFIX = resData.substring(
        0,
        resData.indexOf("base64,") + 7
      );
      data.form.USERAVATARURL = resData.substring(
        resData.indexOf("base64,") + 7
      );
    } else if (data.form.faceFile?.[0]?.url) {
      data.form.USERAVATARURL = data.form.USERAVATARURL_CONVERT;
    } else {
      data.form.USERAVATARPREFIX = "";
      data.form.USERAVATARURL = "";
    }
    data.form.ID_CARD_VALIDITY_START = data.form.ID_CARD_VALIDITY[0] || "";
    data.form.ID_CARD_VALIDITY_END = data.form.ID_CARD_VALIDITY[1] || "";
    data.form.DRIVING_MODEL = data.form.DRIVING_MODEL_ARR.join(",");
    data.form.DRIVER_LICENSE_VALIDITY_START =
      data.form.DRIVER_LICENSE_VALIDITY[0] || "";
    data.form.DRIVER_LICENSE_VALIDITY_END =
      data.form.DRIVER_LICENSE_VALIDITY[1] || "";
    data.form.QUALIFICATION_CERTIFICATE_CATEGORY =
      data.form.QUALIFICATION_CERTIFICATE_CATEGORY_ARR.join(",");
    data.form.QUALIFICATION_CERTIFICATE_VALIDITY_START =
      data.form.QUALIFICATION_CERTIFICATE_VALIDITY[0] || "";
    data.form.QUALIFICATION_CERTIFICATE_VALIDITY_END =
      data.form.QUALIFICATION_CERTIFICATE_VALIDITY[1] || "";
    const formData = new FormData();
    Object.keys(data.form).forEach((key) => {
      formData.append(key, data.form[key]);
    });
    formData.PERSONNEL_TYPE = data.form.PERSONNEL_TYPE.join(",")
    formData.delete("ID_CARD_VALIDITY");
    formData.delete("DRIVING_MODEL_ARR");
    formData.delete("DRIVER_LICENSE_VALIDITY");
    formData.delete("QUALIFICATION_CERTIFICATE_CATEGORY_ARR");
    formData.delete("QUALIFICATION_CERTIFICATE_VALIDITY");
    data.fileForm.ID_CARD_FRONT?.[0]?.raw &&
      formData.append("idCardFrontFiles", data.fileForm.ID_CARD_FRONT[0].raw);
    data.fileForm.ID_CARD_BACK?.[0]?.raw &&
      formData.append("idCardBackFiles", data.fileForm.ID_CARD_BACK[0].raw);
    data.fileForm.DRIVER_LICENSE?.[0]?.raw &&
      formData.append(
        "driverLicenseFiles",
        data.fileForm.DRIVER_LICENSE[0].raw
      );
    data.fileForm.QUALIFICATION_CERTIFICATE?.[0]?.raw &&
      formData.append(
        "qualificationCertificateFiles",
        data.fileForm.QUALIFICATION_CERTIFICATE[0].raw
      );
    if (!USER_ID) {
      // if (data.allUser > data.USERS_NUM) {
      //   ElMessage.error("已超过可创建用户数量");
      //   return;
      // }
      await setPractitionerAdd(formData);
    } else {
      if (
        data.oldDepartId !== data.form.DEPARTMENT_ID ||
        data.oldPostId !== data.form.POST_ID
      ) {
        await ElMessageBox.confirm(
          "如变更了部门或岗位，保存后将删除该用户所有清单，是否确定？",
          { type: "warning" }
        );
        data.form.OPERATIONTYPE = 1;
      }
      await setPractitionerEdit(formData);
    }
    ElMessage.success("操作成功");
    router.back();
  },
  { atBegin: true }
);
const fnFindValueInList = (list, value) => {
  let existence = false;
  for (let i = 0; i < data[list].length; i++) {
    if (data[list][i].DICTIONARIES_ID === value) {
      existence = true;
      break;
    }
  }
  return existence;
};
</script>

<style scoped lang="scss"></style>
