<template>
  <layout-card>
    <el-form
      ref="formRef"
      :rules="rules"
      :model="data.form"
      label-width="130px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-row>
            <el-col :span="24">
              <el-form-item label="角色" prop="ROLE_ID">
                <el-select
                  v-model="data.form.ROLE_ID"
                  :disabled="data.form.ISMAIN === '1'"
                >
                  <template v-for="item in data.roleList" :key="item.role_ID">
                    <el-option
                      v-if="item.ismain !== '1'"
                      :label="item.role_NAME"
                      :value="item.role_ID"
                    />
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <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="24">
              <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="24">
              <el-form-item label="用户名" prop="USERNAME">
                <el-input
                  v-model="data.form.USERNAME"
                  :disabled="!!USER_ID"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="定位卡号" prop="CARDNO">
                <el-input
                  v-model="data.form.CARDNO"
                  maxlength="5"
                  minlength="5"
                  show-word-limit
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="姓名" prop="NAME">
                <el-input v-model="data.form.NAME" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <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="24">
              <el-form-item label="部门排序" prop="SORT">
                <el-input
                  v-model.number="data.form.SORT"
                  placeholder="请输入"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="邮箱" prop="EMAIL">
                <el-input v-model="data.form.EMAIL" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <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 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-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="24">
              <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="24">
              <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="24">
              <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>
            <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-row>
        </el-col>
        <el-col v-if="data.form.ISSTUDENT === 'true'" :span="12">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="身份证号" prop="USER_ID_CARD">
                <el-input
                  v-model="data.form.USER_ID_CARD"
                  placeholder="请输入"
                  @blur="fnChangeIdCard"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <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="12">
              <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="12">
              <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="12">
              <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="12">
              <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="12">
              <el-form-item label="人员类型" prop="PERSONNEL_TYPE">
                <el-select v-model="data.form.PERSONNEL_TYPE">
                  <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="12">
              <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="12">
              <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="12">
              <el-form-item label="工种" prop="TYPE_OF_WORK">
                <layout-select-create
                  v-model="data.form.TYPE_OF_WORK"
                  :list="data.jobTypeList"
                  @delete-option="fnDictionaryDelete($event, 'WORK_TYPE')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <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="12">
              <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="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-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-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,
  getUserView,
  setDictionaryDelete,
  setUserAdd,
  setUserEdit,
} 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 "./components/scheduling.vue";
import { InfoFilled } from "@element-plus/icons-vue";
import {
  addingPrefixToFile,
  idCardGetDateAndGender,
  image2Base64,
} from "@/assets/js/utils.js";
import {
  layoutFnGetDegreeOfEducation,
  layoutFnGetDuties,
  layoutFnGetEmploymentSituation,
  layoutFnGetJobType,
  layoutFnGetNation,
  layoutFnGetPersonnelType,
  layoutFnGetPoliticalLandscape,
  layoutFnGetProfessionalTitle,
} from "@/assets/js/data_dictionary.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { debounce } from "throttle-debounce";
import {
  getVerifyDeduplicationUser,
  getVerifyDuplicateEmail,
  setUploadImg,
} from "@/request/api.js";
import useFormValidate from "@/assets/js/useFormValidate.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,
        USERNAME: data.form.USERNAME,
      });
      callback();
    } catch {
      callback(new Error("邮箱重复"));
    }
  } else {
    callback();
  }
};
const fnHasUser = async (rule, value, callback) => {
  if (value) {
    const resData = await getVerifyDeduplicationUser({
      USERNAME: value,
      VERIFYUSER_ID: data.form.USER_ID,
    });
    if (resData?.pd?.USER_ID) callback(new Error("用户名重复"));
    else callback();
  } else {
    callback();
  }
};
const rules = {
  NAME: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  USERNAME: [
    { 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: "请输入正确的手机号码",
    },
    { validator: fnHasUser, trigger: "blur" },
  ],
  EMAIL: [
    { required: false, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/,
      message: "请输入正确的邮箱",
    },
    { validator: fnHasEmail, trigger: "blur" },
  ],
  ROLE_ID: [{ required: true, message: "请选择角色", trigger: "change" }],
  DEPARTMENT_ID: [{ required: true, message: "请选择部门", trigger: "change" }],
  DUTIES_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" },
  ],
  POST: [{ required: true, message: "职务不能为空", trigger: "change" }],
  TYPE_OF_WORK: [
    { required: true, message: "工种不能为空", trigger: "change" },
  ],
  ENTRY_DATE: [
    { required: true, message: "请选择入职日期", trigger: "change" },
  ],
  CARDNO: [
    { required: false, message: "请输入定位卡号", trigger: "blur" },
    {
      pattern: /^-?[0-9]\d*$/,
      message: "请输入正确的定位卡号",
      trigger: "blur",
    },
  ],
  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" }],
  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",
    },
  ],
  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: [],
  allUser: 0,
  USERS_NUM: 0,
  oldPostId: "",
  oldDepartId: "",
  form: {
    ROLE_ID: "",
    CARDNO: "",
    DEPARTMENT_ID: "",
    POST_ID: "",
    USERNAME: "",
    NAME: "",
    SORT: "",
    EMAIL: "",
    SHIFTDUTYONE: "",
    SHIFTDUTYTWO: "",
    periodStr: "",
    BZ: "",
    IS_SAFETY: 0,
    ISHEAD: "0",
    ISLEADER: "0",
    ISSTUDENT: "false",
    USER_ID_CARD: "",
    NATION: "",
    SEX: "",
    POLITICAL_OUTLOOK: "",
    DATE_OF_BIRTH: "",
    DEGREE_OF_EDUCATION: "",
    PERSONNEL_TYPE: "",
    DUTIES: "",
    TITLE: "",
    TYPE_OF_WORK: "",
    ENTRY_DATE: "",
    WORKING_DATE: "",
    INCUMBENCY: "",
    faceFile: [],
    userCerFile: [],
  },
  scheduleInfo: {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  },
  scheduleVisible: false,
});
const fnGetData = async () => {
  if (!USER_ID) return;
  const resData = await getUserView({ USER_ID });
  const form = resData.pd;
  form.PASSWORD = "666666";
  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);
  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;
};
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 layoutFnGetPersonnelType();
  data.personnelTypeList = personnelTypeList;
  const { value: dutiesList } = await layoutFnGetDuties();
  data.dutiesList = dutiesList;
  const { value: professionalTitleList } = await layoutFnGetProfessionalTitle();
  data.professionalTitleList = professionalTitleList;
  const { value: jobTypeList } = await layoutFnGetJobType();
  data.jobTypeList = jobTypeList;
  const { value: employmentSituationList } =
    await layoutFnGetEmploymentSituation();
  data.employmentSituationList = employmentSituationList;
};
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;
    } else if (DICTTYPE === "WORK_TYPE") {
      DICTIONARIES_ID = data.jobTypeList[index].DICTIONARIES_ID;
      msgTitle = "工种：" + data.jobTypeList[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);
    } else if (DICTTYPE === "WORK_TYPE") {
      data.jobTypeList.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);
    const form = { ...data.form };
    form.WORKSTATUS = data.scheduleInfo.WORKSTATUS;
    form.DURATION = data.scheduleInfo.DURATION;
    form.WORKPERIOD = data.scheduleInfo.WORKPERIOD;
    if (fnFindValueInList("dutiesList", form.DUTIES)) {
      form.letDutiesType = "select";
      form.DUTIESValue = "";
    } else {
      form.letDutiesType = "value";
      form.DUTIESValue = form.DUTIES;
    }
    if (fnFindValueInList("professionalTitleList", form.TITLE)) {
      form.letTitleType = "select";
      form.letTitleValue = "";
    } else {
      form.letTitleType = "value";
      form.letTitleValue = form.TITLE;
    }
    if (fnFindValueInList("jobTypeList", form.TYPE_OF_WORK)) {
      form.letTypeOfWorkType = "select";
      form.letTypeOfWorkValue = "";
    } else {
      form.letTypeOfWorkType = "value";
      form.letTypeOfWorkValue = form.TYPE_OF_WORK;
    }
    if (data.form.faceFile?.[0]?.raw) {
      const resData = await image2Base64(data.form.faceFile[0].url);
      form.USERAVATARPREFIX = resData.substring(
        0,
        resData.indexOf("base64,") + 7
      );
      form.USERAVATARURL = resData.substring(resData.indexOf("base64,") + 7);
    }
    if (!USER_ID) {
      if (data.allUser > data.USERS_NUM) {
        ElMessage.error("已超过可创建用户数量");
        return;
      }
      const resData = await setUserAdd({ ...form });
      if (data.form.ISSTUDENT === "true") await fnUploadImage(resData.USER_ID);
    } else {
      if (
        data.oldDepartId !== data.form.DEPARTMENT_ID ||
        data.oldPostId !== data.form.POST_ID
      ) {
        await ElMessageBox.confirm(
          "如变更了部门或岗位，保存后将删除该用户所有清单，是否确定？",
          { type: "warning" }
        );
        form.OPERATIONTYPE = 1;
      }
      await setUserEdit({ ...form });
      if (data.form.ISSTUDENT === "true")
        await fnUploadImage(data.form.USER_ID);
    }
    ElMessage.success("操作成功");
    router.back();
  },
  { atBegin: true }
);
const fnUploadImage = async (USER_ID) => {
  const formData = new FormData();
  for (let i = 0; i < data.form.userCerFile.length; i++) {
    if (data.form.userCerFile[i].raw)
      formData.append("FFILE", data.form.userCerFile[i].raw);
  }
  formData.append("FOREIGN_KEY", USER_ID);
  formData.append("TYPE", 18);
  await setUploadImg(formData);
};
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>
