<template>
  <el-dialog
    :model-value="props.modelValue"
    @update:model-value="$emit('update:modelValue', $event)"
    :title="props.dialogInfo.title"
    width="600"
    @close="clearData"
  >
    <el-form ref="formRef" label-width="auto" :model="formData" :rules="rules">
      <el-form-item label="计划和名称" prop="planName">
        <el-input :disabled="isView" v-model="formData.planName" size="large" />
      </el-form-item>
      <el-form-item label="执行部门" prop="execDepartmentId">
        <el-cascader
          :disabled="isView"
          style="width: 100%"
          v-model="formData.execDepartmentId"
          size="large"
          ref="cascaderRef"
          :options="firstLevelDepts"
          :props="cascaderProp"
          :show-all-levels="false"
          placeholder="请选择责任部门"
          filterable
          @change="handleChangeDept('execDepartmentId')"
        />
      </el-form-item>

      <el-form-item label="执行人" prop="executor">
        <el-select
          :disabled="isView"
          multiple
          v-model="formData.executor"
          placeholder="请选择"
          size="large"
          style="width: 100%"
          filterable
        >
          <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="计划内容" prop="planContent">
        <el-input :disabled="isView" v-model="formData.planContent" type="textarea" :rows="6" size="large" />
      </el-form-item>
      <el-form-item prop="planStartDate" label="计划开始日期">
        <el-date-picker
          :disabled="isView"
          v-model="formData.planStartDate"
          size="large"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          style="width: 100%"
          placeholder="计划开始日期"
        />
      </el-form-item>
      <el-form-item prop="planEndDate" label="计划结束日期">
        <el-date-picker
          :disabled="isView"
          v-model="formData.planEndDate"
          style="width: 100%"
          size="large"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          placeholder="计划结束日期"
        />
      </el-form-item>
      <el-form-item prop="teamName" label="是否推送">
        <el-radio-group :disabled="isView" v-model="formData.status">
          <el-radio :value="1">待开始</el-radio>
          <el-radio :value="2">进行中</el-radio>
          <el-radio :value="3">已完成</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <div>
        <el-button type="primary" @click="submitForm" :loading="submitLoading" :disabled="isView"> 保存 </el-button>
        <el-button @click="handleCancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
  import { ref, reactive, watch, onMounted, computed } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { getAllDepartments } from '@/api/auth/dept';
  import { formatDeptTree } from '@/views/disaster/utils/formatDeptTree';
  import dayjs from 'dayjs';
  import {
    queryAvailableUserList,
    safetyHazardInventoryQueryPlanDetail,
  } from '@/api/production-safety/responsibility-implementation';

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const props = defineProps<{
    modelValue: boolean;
    dialogInfo: { [key: string]: any };
  }>();
  const formRef = ref<FormInstance>();
  const emit = defineEmits(['close', 'submit', 'update:modelValue']);
  const submitLoading = ref(false);
  const showDialog = ref(false);
  const firstLevelDepts = ref<any[]>([]);
  const cascaderProp = {
    expandTrigger: 'click',
    checkStrictly: true,
    value: 'id',
    label: 'deptName',
  };
  const cascaderRef = ref<any>();
  const userOptions = ref<any[]>([]);
  const isView = computed(() => props.dialogInfo.type === 'view');

  const formData = reactive<any>({
    planName: '',
    execDepartment: '',
    execDepartmentId: [],
    planStartDate: null,
    planEndDate: null,
    status: 1,
    executor: '',
    planContent: '',
  });
  const rules = reactive<Record<string, any>>({
    planName: [{ required: true, message: '请输入计划和名称' }],
    planContent: [{ required: true, message: '请输入计划内容' }],
    execDepartment: [{ required: true, message: '请输入执行部门' }],
    planStartDate: [
      { required: true, message: '请选择计划开始日期' },
      {
        validator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if (value && formData.planEndDate) {
              if (dayjs(value).isAfter(formData.planEndDate)) {
                reject(new Error('开始日期不能大于结束日期'));
                return;
              }
            }
            resolve(true);
          });
        },
      },
    ],
    planEndDate: [
      { required: true, message: '请选择计划结束日期' },
      {
        validator: (rule, value) => {
          return new Promise((resolve, reject) => {
            if (value && formData.planStartDate) {
              if (dayjs(value).isBefore(formData.planStartDate)) {
                reject(new Error('结束日期不能小于开始日期'));
                return;
              }
            }
            resolve(true);
          });
        },
      },
    ],
    executor: [{ required: true, message: '请输入执行人' }],
  });

  const handleQueryAvailableUserList = (deptName, realname = '') => {
    return queryAvailableUserList({
      pageNumber: 1,
      pageSize: 200,
      queryParam: {
        deptName,
        realname,
      },
    }).then((res: any) => {
      userOptions.value = (res.records || []).map((u: any) => ({
        value: u.userId || u.id,
        label: u.realname,
      }));
      // switch (prop) {
      //   case 'safetyResponsibleCenter':
      //     formValue.safetyCenterManager = null;
      //     safetyCenterManagerOptions.value = (res.records || []).map((u: any) => ({
      //       value: u.userId || u.id,
      //       label: u.realname,
      //     }));
      //     break;
      //   case 'safetyResponsibleDepartment':
      //     alert('');
      //     formValue.safetyDepartmentManager = null;
      //     formValue.safetySpecificPerson = null;
      //     safetyDepartmentUserOptions.value = (res.records || []).map((u: any) => ({
      //       value: u.userId || u.id,
      //       label: u.realname,
      //     }));
      //     break;
      //   default:
      //     break;
      // }
    });
  };

  function dialogShow() {
    showDialog.value = true;
  }
  function dialogHide() {
    showDialog.value = false;
  }

  const getDeptData = () => {
    return getAllDepartments().then((res) => {
      firstLevelDepts.value = formatDeptTree(res);
    });
  };

  const handleChangeDept = (prop) => {
    const cascader = cascaderRef.value;
    const deptInfo = cascader?.getCheckedNodes();
    formData['execDepartmentId'] = deptInfo[0].pathValues;
    formData['execDepartment'] = deptInfo[0].label;
    formRef.value?.validateField('execDepartment');
    // nextTick(() => {
    //   handleQueryAvailableUserList(deptInfo[0].label, prop);
    // });
  };

  const handleCancel = () => {
    emit('update:modelValue', false);
  };
  function clearData() {
    formRef.value?.resetFields();
    Object.assign(formData, {
      planName: '',
      execDepartment: '',
      planStartDate: null,
      planEndDate: null,
      status: 0,
      execPerson: '',
    });
  }

  function submitForm() {
    formRef.value?.validate((valid) => {
      if (!valid) {
        return;
      }
      emit('submit', formData, submitLoading);
    });
  }

  const handlesafetyHazardInventoryQueryPlanDetail = async (id) => {
    const res = await safetyHazardInventoryQueryPlanDetail(id as string);
    return res;
  };

  onMounted(async () => {
    await Promise.all([getDeptData(), handleQueryAvailableUserList('')]);
    if (props.dialogInfo.type !== 'add') {
      handlesafetyHazardInventoryQueryPlanDetail(props.dialogInfo.currentRow.id).then((res) => {
        Object.assign(formData, {
          ...res,
          execDepartmentId: res.execDepartmentId ? res.execDepartmentId.split(',').map((item) => Number(item)) : [],
          executor: res.executor ? res.executor.split(',').map((item) => Number(item)) : [],
        });
      });
    }
  });

  defineExpose({
    submitLoading,
    dialogShow,
    dialogHide,
  });
</script>

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