<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <BreadcrumbBack />
      <span class="breadcrumb-title">{{ headTitle }}</span>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <div
          class="export-file"
          @click="exportTaskDetailToPDF(id, taskExecutionDetailList?.name || '')"
          v-if="operationType === 'view'"
        >
          <el-button type="primary">
            <template #icon>
              <img :src="ExportIcon" />
            </template>
            导出预防检查任务单
          </el-button>
        </div>
        <p class="title">
          任务名称：<span class="content">{{ taskExecutionDetailList?.name }}</span>
        </p>
        <p class="title">
          被检查（自查）所/部/中心：<span class="content">{{ taskExecutionDetailList?.deptName }}</span>
        </p>
        <div class="template-table-merge-container">
          <TemplateTableMerge
            ref="templateTableMergeRef"
            :operation-type="operationType"
            :main-table="templateDetailList?.inspectTemplateDetailVOs || []"
            :opinion-data="templateDetailList?.deptOpinion || opinionData"
            :result-data="templateDetailList?.inspectResult || resultData"
            @validate-change="handleValidateChange"
          />
        </div>
        <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="safety-platform-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 { useRoute, useRouter } from 'vue-router';
  import { onMounted, ref, computed, reactive } from 'vue';
  import { ElMessage } from 'element-plus';
  import TemplateTableMerge from './src/components/TemplateTableMerge.vue';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import { exportTaskDetailToPDF } from './src/utils';
  import type {
    TaskExecutionDetailResponse,
    TemplateDetailResponse,
    ContentItem,
    SaveTaskDetailRequest,
  } from '@/types/disaster-precaution';
  import { getTaskExecutionDetail, saveTaskDetail, saveTaskApproval } from '@/api/disaster-precaution';
  import ExportIcon from 'assets/svg/export.svg';

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

  const opinionData = ref<ContentItem>({} as ContentItem);
  const resultData = ref<ContentItem>({} as ContentItem);

  // 需要禁用的用户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();
  };

  const headTitle = computed(() => {
    if (operationType === 'view') {
      return '灾害预防检查任务单';
    } else {
      return '任务执行';
    }
  });

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

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use './src/style/common.scss' as *;
  @use './src/style/task-template.scss' as *;
</style>
