<template>
  <div>
    <BasicForm ref="basicFormRef" :formData="ruleFormData" :formRules="formRules" :formConfig="ruleFormConfig">
      <template #personInChargeName>
        <el-select
          v-model="ruleFormData.personInChargeName"
          placeholder="请输入负责人姓名"
          value-key="id"
          filterable
          remote
          :remote-method="remoteMethod"
          :loading="loading"
          @change="selectKeeper"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.id"
            :label="`${item.realname}（${item.username}）${item.deptName}`"
            :value="item"
          />
        </el-select>
      </template>
      <template #drillDeptIdList>
        <el-cascader
          v-model="ruleFormData.drillDeptIdList"
          :options="deptTree"
          :props="cascaderProp"
          clearable
          collapse-tags
          :show-all-levels="false"
          :max-collapse-tags="3"
          placeholder="请选择演练部门"
        />
      </template>
      <template #drillScript>
        <UploadFiles
          ref="uploadFilesRef"
          label="上传材料"
          :fileList="unformatAttachment(props.drillData.drillScript)"
          :maxCount="1"
          @uploadSuccess="
            (files) => {
              fileList = files;
              ruleFormData.drillScript = files;
            }
          "
        />
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import BasicForm from '@/components/BasicForm.vue';
  import { useFormConfigHook } from '@/hooks/useFormConfigHook';
  import { DrillPlanItemDetail, ExecuteDrillPlanRuleForm } from '../types';
  import {
    DRILL_EXECUTE_FORM_CONFIG,
    INS_DRILL_EXECUTE_FORM_RULES,
    DEP_DRILL_EXECUTE_FORM_RULES,
    DRILL_EXECUTE_FORM_DATA,
  } from '../configs/plan/form';
  import { DeptTree } from '@/types/dept/type';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { QueryUserInfoByUserNameRes } from '@/types/person-group/type';
  import { queryUserInfoByUserName } from '@/api/system/person-group';
  import UploadFiles from '@/components/UploadFiles/UploadFiles.vue';
  import { unformatAttachment } from '@/components/UploadFiles/utils';

  const props = defineProps<{
    insName: string;
    drillData: DrillPlanItemDetail;
  }>();

  const basicFormRef = ref<InstanceType<typeof BasicForm>>();

  const { ruleFormConfig, ruleFormData, formRules, cloneRuleFormData, beforeRouteLeave } =
    useFormConfigHook<ExecuteDrillPlanRuleForm>(
      DRILL_EXECUTE_FORM_CONFIG,
      props.drillData
        ? {
            drillPlanId: props.drillData.id,
            drillTime: props.drillData.drillTime,
            drillLocation: props.drillData.drillLocation,
            personInChargeId: props.drillData.personInChargeId,
            personInChargeName: props.drillData.personInChargeName,
            drillDeptIdList: stringToArray(props.drillData.drillDeptIdList),
            drillScript: props.drillData.drillScript,
          }
        : DRILL_EXECUTE_FORM_DATA,
      props.drillData.drillScope === props.insName ? INS_DRILL_EXECUTE_FORM_RULES : DEP_DRILL_EXECUTE_FORM_RULES,
    );

  const cascaderProp = {
    multiple: true,
    expandTrigger: 'hover',
    checkStrictly: true,
    emitPath: false,
    value: 'id',
    label: 'deptName',
  };

  const deptTree = ref<DeptTree[]>();
  const loadDeptTreeData = async () => {
    const result = await getAllDepartments();
    cloneRuleFormData();
    deptTree.value = result[0].children;
  };

  const userOptions = ref<QueryUserInfoByUserNameRes[]>([]);
  const loading = ref<boolean>(false);

  const fileList = ref();
  fileList.value = unformatAttachment(props.drillData.drillScript);

  const remoteMethod = async (query: string) => {
    if (!query) {
      userOptions.value = [];
      return;
    }
    loading.value = true;
    userOptions.value = await queryUserInfoByUserName(query);
    loading.value = false;
  };

  onMounted(() => {
    beforeRouteLeave();
    loadDeptTreeData();
  });

  const formValidate = async () => {
    if (!basicFormRef.value) return;
    const validateResult = await basicFormRef.value.validateForm();
    return validateResult;
  };

  const formClearValidate = () => {
    if (!basicFormRef.value) return;
    basicFormRef.value.clearValidate();
  };

  function getFormData() {
    cloneRuleFormData();
    return ruleFormData;
  }

  defineExpose({
    formValidate,
    formClearValidate,
    getFormData,
  });

  function selectKeeper(value) {
    if (!value) return;
    ruleFormData.personInChargeId = value.id;
    ruleFormData.personInChargeName = value.realname;
  }

  function stringToArray(str?: string): number[] | undefined {
    if (!str) return undefined;
    return JSON.parse(str);
  }
</script>

<style scoped></style>
