<template>
  <el-dialog
    v-model="visible"
    :title="form.APPLY_TYPE === '1' ? '入职审核' : '离职审核'"
    :before-close="fnClose"
  >
    <el-form ref="formRef" :rules="rules" :model="form" label-width="150px">
      <el-form-item label="审核结果" prop="REVIEW_RESULT">
        <el-radio-group v-model="form.REVIEW_RESULT">
          <el-radio label="1">是</el-radio>
          <el-radio label="-1">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="审核意见" prop="REVIEW_COMMENTS">
        <el-input v-model="form.REVIEW_COMMENTS" />
      </el-form-item>
      <div v-if="form.APPLY_TYPE === '1'">
        <el-divider v-if="form.REVIEW_RESULT === '1'" content-position="left">
          工作安排
        </el-divider>
        <el-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="部门"
          prop="DEPARTMENT_ID"
        >
          <layout-department
            v-model="form.DEPARTMENT_ID"
            @update:model-value="form.POST_ID = ''"
          />
        </el-form-item>
        <el-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="岗位"
          prop="POST_ID"
        >
          <el-select v-model="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-row v-if="form.REVIEW_RESULT === '1'">
          <el-col :span="10">
            <el-form-item label="排班" prop="SHIFTDUTYONE">
              <el-select
                v-model="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="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-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="当前班次"
          prop="periodStr"
        >
          <el-radio-group v-model="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-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="部门排序"
          prop="SORT"
        >
          <el-input v-model.number="form.SORT" placeholder="请输入" />
        </el-form-item>
        <el-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="职务"
          prop="DUTIES"
        >
          <layout-select-create
            v-model="form.DUTIES"
            :list="data.dutiesList"
            @delete-option="fnDictionaryDelete($event, 'POSITION')"
          />
        </el-form-item>
        <el-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="职称"
          prop="TITLE"
        >
          <layout-select-create
            v-model="form.TITLE"
            :list="data.professionalTitleList"
            @delete-option="fnDictionaryDelete($event, 'JOB_TITLE')"
          />
        </el-form-item>
        <el-form-item
          v-if="form.REVIEW_RESULT === '1'"
          label="入职日期"
          prop="ENTRY_DATE"
        >
          <el-date-picker
            v-model="form.ENTRY_DATE"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="fnClose">取消</el-button>
      <el-button type="primary" @click="fnSubmit"> 确定 </el-button>
    </template>
  </el-dialog>

  <scheduling
    :id="form.SHIFTDUTYTWO"
    v-model:visible="data.scheduleVisible"
    :info="data.scheduleInfo"
  />
</template>

<script setup>
import { reactive, ref, watch, watchEffect } from "vue";
import { useVModels } from "@vueuse/core";
import LayoutDepartment from "@/components/department/index.vue";
import LayoutSelectCreate from "@/components/select_create/index.vue";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessageBox, ElMessage } from "element-plus";
import { debounce } from "throttle-debounce";
import { getPostListAll } from "@/request/data_dictionary.js";
import {
  getUserCurrentShiftList,
  getUserScheduling,
  setDictionaryDelete,
} from "@/request/enterprise_management.js";
import {
  layoutFnGetDuties,
  layoutFnGetProfessionalTitle,
} from "@/assets/js/data_dictionary.js";
import { setPractitionerReview } from "@/request/user_practitioner.js";

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false,
  },
  form: {
    type: Object,
    required: true,
    default: () => ({}),
  },
});
const emits = defineEmits(["update:visible", "update:form", "get-data"]);
const { visible, form } = useVModels(props, emits);
const formRef = ref(null);
const data = reactive({
  postList: [],
  schedulingList: [],
  schedulingList1: [],
  periodList: [],
  dutiesList: [],
  professionalTitleList: [],
  scheduleInfo: {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  },
  scheduleVisible: false,
});
const rules = {
  REVIEW_RESULT: [
    { required: true, message: "审核结果不能为空", trigger: "blur" },
  ],
  REVIEW_COMMENTS: [
    { required: true, message: "审核意见不能为空", trigger: "change" },
  ],
  DEPARTMENT_ID: [{ required: true, message: "请选择部门", trigger: "change" }],
  POST_ID: [{ required: true, message: "请选择岗位", trigger: "change" }],
  SHIFTDUTYONE: [{ required: true, message: "请选择排班", trigger: "change" }],
  SHIFTDUTYTWO: [{ required: true, message: "请选择排班", trigger: "change" }],
  periodStr: [
    { required: true, message: "请选择完整的排班类型", trigger: "change" },
  ],
  SORT: [
    { required: true, message: "请输入排序", trigger: "blur" },
    { type: "number", message: "请输入数字类型", trigger: "blur" },
  ],
  INCUMBENCY: [
    { required: true, message: "在职情况不能为空", trigger: "change" },
  ],
  TITLE: [{ required: true, message: "职称不能为空", trigger: "change" }],
  DUTIES: [{ required: true, message: "职务不能为空", trigger: "change" }],
  ENTRY_DATE: [
    { required: true, message: "请选择入职日期", trigger: "change" },
  ],
};
watchEffect(() => {
  if (form.value.DEPARTMENT_ID) fnGetPost(form.value.DEPARTMENT_ID);
  if (form.value.SHIFTDUTYONE)
    fnGetUserScheduling(form.value.SHIFTDUTYONE, "schedulingList1");
  if (form.value.SHIFTDUTYTWO)
    fnGetUserCurrentShiftList(form.value.SHIFTDUTYTWO);
});

const fnGetPost = async (DEPARTMENT_ID) => {
  const resData = await getPostListAll({ DEPARTMENT_ID });
  data.postList = resData.postList;
};

const stop = watch(
  () => form.value.REVIEW_RESULT,
  (val) => {
    if (val === "1") {
      fnGetLevels();
      stop && stop();
    }
  }
);

const fnGetLevels = async () => {
  const { value: dutiesList } = await layoutFnGetDuties();
  data.dutiesList = dutiesList;
  const { value: professionalTitleList } = await layoutFnGetProfessionalTitle();
  data.professionalTitleList = professionalTitleList;
};
const fnGetUserScheduling = async (PARENTID, list) => {
  const resData = await getUserScheduling({ PARENTID });
  data[list] = resData.varList;
};
fnGetUserScheduling("0", "schedulingList");
const fnChangeSchedulingOne = () => {
  form.SHIFTDUTYTWO = "";
  data.periodList = [];
  data.scheduleInfo = {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  };
  form.periodStr = "";
};
const fnChangeSchedulingTwo = () => {
  data.scheduleInfo = {
    WORKSTATUS: "",
    DURATION: "",
    WORKPERIOD: "",
  };
  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 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,
  }
);

const fnClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};
const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    form.value.WORKSTATUS = data.scheduleInfo.WORKSTATUS;
    form.value.DURATION = data.scheduleInfo.DURATION;
    form.value.WORKPERIOD = data.scheduleInfo.WORKPERIOD;
    if (fnFindValueInList("dutiesList", form.value.DUTIES)) {
      form.value.letDutiesType = "select";
      form.value.DUTIESValue = "";
    } else {
      form.value.letDutiesType = "value";
      form.value.DUTIESValue = form.value.DUTIES;
    }
    if (fnFindValueInList("professionalTitleList", form.value.TITLE)) {
      form.value.letTitleType = "select";
      form.value.letTitleValue = "";
    } else {
      form.value.letTitleType = "value";
      form.value.letTitleValue = form.value.TITLE;
    }

    if (form.value.APPLY_TYPE === "1" && form.value.REVIEW_RESULT === "1")
      form.value.INCUMBENCY = "bd4d802e94354230b1bb19cfabd7f810"; // 在职：bd4d802e94354230b1bb19cfabd7f810
    else if (form.value.APPLY_TYPE === "3" && form.value.REVIEW_RESULT === "1")
      form.value.INCUMBENCY = "4dd28e91b104410b85c25a792c424172"; // 离职：4dd28e91b104410b85c25a792c424172
    // console.log(form.value);
    await setPractitionerReview({ ...form.value });
    ElMessage.success("操作成功");
    fnClose();
    emits("get-data");
  },
  { 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>
