<template>
  <div class="disaster-precaution-container">
    <header class="disaster-precaution-container__header">
      <img :src="BackIcon" alt="back" class="back-icon" @click="router.back()" />
      <span class="disaster-precaution-container__title">灾害预防检查任务</span>
    </header>
    <main class="disaster-precaution-container__main">
      <div class="disaster-precaution">
        <p class="title">
          任务名称：<span class="content">{{ taskExecutionDetailList?.name }}</span>
        </p>
        <p class="title">
          被检查自查单位：<span class="content">{{ taskExecutionDetailList?.deptName }}</span>
        </p>
        <TemplateTableMerge
          ref="templateTableMergeRef"
          :operation-type="operationType"
          :main-table="templateDetailList?.inspectTemplateDetailVOs || []"
          :opinion-data="templateDetailList?.deptOpinion || {} as ContentItem"
          :result-data="templateDetailList?.inspectResult || {} as ContentItem"
          :height="
            operationType === 'check' ? 'calc(50vh - 65px)' : operationType === 'view' ? 'calc(70vh - 100px)' : '50vh'
          "
          @validate-change="handleValidateChange"
        />
        <el-form style="max-width: 400px" :model="formModel" label-width="auto" v-if="operationType === 'check'">
          <el-form-item label="选择审批领导" prop="reviewerId" :rules="[{ required: true, message: '请选择审批领导' }]">
            <el-tree-select
              v-model="formModel.reviewerId"
              :data="treeData"
              node-key="id"
              :props="{
                label: 'label',
                children: 'children',
                disabled: (data) => !data.isUser || (data.id && disabledIds.includes(data.id)),
              }"
              placeholder="请选择审批领导"
              check-strictly
              filterable
              default-expand-all
            />
          </el-form-item>
        </el-form>
      </div>
    </main>
    <footer class="disaster-precaution-container__footer" v-if="operationType !== 'view'">
      <el-button @click="router.back()">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :disabled="submitDisabled"> 提交 </el-button>
    </footer>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref, computed, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import { useRoute, useRouter } from 'vue-router';
  import BackIcon from 'assets/svg/back.svg';
  import TemplateTableMerge from './src/components/TemplateTableMerge.vue';
  import { getTaskExecutionDetail, saveTaskDetail, saveTaskApproval } from '@/api/disaster-precaution';
  import { useUserInfoHook } from '@/views/disaster/hooks/userInfo';
  import type {
    TaskExecutionDetailResponse,
    TemplateDetailResponse,
    ContentItem,
    SaveTaskDetailRequest,
  } from '@/types/disaster-precaution';

  const { getUserFirstLevelTreeList, treeData, id: userId } = useUserInfoHook();

  // 需要禁用的用户ID列表
  const disabledIds = computed(() => {
    const ids = [userId];
    return ids;
  });

  interface FormModel {
    reviewerId: number | undefined;
  }

  type OperationType = 'view' | 'approve' | 'check';
  const templateTableMergeRef = ref<InstanceType<typeof TemplateTableMerge>>();
  const isFormValid = ref(false); // 表单验证状态
  const formModel = reactive<FormModel>({
    reviewerId: undefined,
  });

  const route = useRoute();
  const router = useRouter();
  const id = Number(route.params.id);
  const operationType = String(route.query.operationType) as OperationType;
  const taskExecutionDetailList = ref<TaskExecutionDetailResponse>();
  const templateDetailList = ref<TemplateDetailResponse>();

  const getTaskExecutionDetailList = async () => {
    const res = await getTaskExecutionDetail(id);
    taskExecutionDetailList.value = res;
    if (res.reviewerId) {
      formModel.reviewerId = res.reviewerId;
    }
    templateDetailList.value = JSON.parse(res.detail) as TemplateDetailResponse;
  };

  // 处理验证状态变化
  const handleValidateChange = (isValid: boolean) => {
    isFormValid.value = Boolean(isValid);
  };

  const submitDisabled = computed(() => {
    return !Boolean(formModel.reviewerId) || !isFormValid.value;
  });

  const handleSubmit = async () => {
    if (!templateTableMergeRef.value) return;

    const { mainTable, opinionData, resultData } = templateTableMergeRef.value.getTableData();
    const saveTaskDetailRequest: SaveTaskDetailRequest = {
      id,
      deptOpinion: opinionData,
      inspectResult: resultData,
      inspectDetails: mainTable,
      reviewerId: formModel.reviewerId as number,
    };
    // 执行提交逻辑
    if (operationType === 'check') {
      await saveTaskDetail(saveTaskDetailRequest);
    } else {
      await saveTaskApproval(saveTaskDetailRequest);
    }
    ElMessage.success('提交成功');
    router.back();
  };

  onMounted(() => {
    getTaskExecutionDetailList();
    getUserFirstLevelTreeList();
  });
</script>

<style lang="scss" scoped>
  @use '../style/disaster.scss' as *;
  .disaster-precaution-container__header {
    flex-direction: row !important;
    justify-content: flex-start !important;
    gap: 8cpx !important;
  }
  .title,
  .content {
    font-size: 14cpx;
  }
  .title {
    color: rgba($text-color, 0.85);
  }
  .content {
    color: rgba($text-color, 0.65);
  }
</style>
