<script lang="ts" setup>
import { computed, defineComponent, h, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';

// @ts-ignore
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
// @ts-ignore
import { useTabs } from '@vben/hooks';
import { useUserStore } from '@vben/stores';

import dayjs from 'dayjs';
import {
  ElButton,
  ElDescriptions,
  ElDescriptionsItem,
  ElMessage,
  ElMessageBox,
  ElTag,
} from 'element-plus';
import { keyBy } from 'lodash-es';

// @ts-ignore
import { closeTask, getTaskDetail, transferTask } from '#/api/schedule';
// @ts-ignore
import { confirmDoneTask, handleLicense } from '#/api/task/confirm';
// @ts-ignore
import AttachmentViewer from '#/components/AttachmentViewer.vue';
// @ts-ignore
import { SelectUsers } from '#/components/selectUsers';
// @ts-ignore: 忽略
// @ts-ignore
import { taskLevelOptions, taskStatusOptions } from '#/utils/dicts';
// @ts-ignore: 应急防护月检
import emergencyInfoPage from '#/views/oilstation/emergency/index.vue';
// @ts-ignore: 灭火器档案
import extinguisherInfoPage from '#/views/oilstation/extinguisher/index.vue';
// @ts-ignore: 过滤器档案
import filterInfoPage from '#/views/oilstation/filter/index.vue';
// @ts-ignore: 急救箱档案
import firstaidkitInfoPage from '#/views/oilstation/firstaidkit/index.vue';
// @ts-ignore: 证照档案
import idPhotoInfoPage from '#/views/oilstation/idphoto/index.vue';

// @ts-ignore
import AdditiveComponent from './components/additive.vue';
// @ts-ignore
import BiddingComponent from './components/bidding.vue';
// @ts-ignore
import CheckComponent from './components/check.vue';
// 引入检查项组件、评论组件和查阅组件
// @ts-ignore
import CommentComponent from './components/comment.vue';
// @ts-ignore
import CompetitionComponent from './components/competition.vue';
// @ts-ignore
import EmergencyComponent from './components/emergency.vue';
// @ts-ignore
import EntranceComponent from './components/entrance.vue';
// 引入班组日志组件
// @ts-ignore
import GroupLogComponent from './components/group-log.vue';
// @ts-ignore
import GunCheck2Component from './components/gun-check2.vue';
// @ts-ignore
import GunCheckComponent from './components/gun-check.vue';
// @ts-ignore
import JoinEmergencyComponent from './components/join-emergency.vue';
// @ts-ignore
import MeetingComponent from './components/meeting.vue';
// @ts-ignore
import ManagementPlanComponent from './components/plan.vue';
// @ts-ignore
import SalesSurveyComponent from './components/sales-survey.vue';
// @ts-ignore
import TankWaterComponent from './components/tank-water.vue';
// @ts-ignore
import WeeklyEvaluationComponent from './components/weekly-evaluation.vue';
// @ts-ignore
import WeeklyReportComponent from './components/weekly-report.vue';
import { mobileTaskTypes } from './config-data';
import {
  AdditiveDrawer,
  CompetitionDrawer,
  EmergencyWyDrawer,
  EntranceDrawer,
  GroupLogDrawer,
  GunCheck2Drawer,
  GunCheckDrawer,
  JoinEmergencyDrawer,
  ManagementPlanDrawer,
  MeetingDrawer,
  OperatingPlanDrawer,
  SalesSurveyDrawer,
  TankWaterDrawer,
  UploadDrawer,
  WeeklyEvaluationDrawer,
  WeeklyReportDrawer,
} from './drawer';

const userStore = useUserStore();

const { refreshTab } = useTabs();

const route = useRoute();
// const router = useRouter();
const taskId = ref(Number(route.params.id));

// 图片预览相关
const previewVisible = ref(false);
const previewImages = ref<string[]>([]);

// 关闭图片预览
const closePreview = () => {
  previewVisible.value = false;
};

// 下载文件
const downloadFile = (fileUrl: string, fileName: string) => {
  // 创建临时链接
  const link = document.createElement('a');
  // 设置下载属性，强制所有文件下载
  link.download = fileName;
  // 使用 rel="noopener noreferrer" 提高安全性
  link.rel = 'noopener noreferrer';
  // 对于图片等浏览器会直接打开的文件，使用 fetch 方式获取 blob 再下载
  fetch(fileUrl)
    .then((response) => response.blob())
    .then((blob) => {
      // 创建 blob URL
      const blobUrl = URL.createObjectURL(blob);
      link.href = blobUrl;
      // 触发下载
      document.body.append(link);
      link.click();
      // 清理
      link.remove();
      // 释放 blob URL
      setTimeout(() => {
        URL.revokeObjectURL(blobUrl);
      }, 100);
    })
    .catch((error) => {
      console.error('下载失败:', error);
      // 如果 fetch 失败，回退到直接下载
      link.href = fileUrl;
      document.body.append(link);
      link.click();
      link.remove();
    });
};

// 状态标签配置
const statusConfig: any = keyBy(taskStatusOptions, 'value');

// 优先级标签配置
const priorityConfig: any = keyBy(taskLevelOptions, 'value');

// 关闭任务
const handleCloseTask = () => {
  // console.log('关闭任务');
  // 二次确认并输入关闭原因
  ElMessageBox.prompt('请输入关闭原因', '确认关闭', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then((reason) => {
    // 关闭任务
    closeTask({
      taskId: taskId.value,
      cancelReason: reason.value,
    }).then(() => {
      ElMessage.success('任务关闭成功');
      // 刷新任务详情
      getTaskDetail(taskId.value).then((res) => {
        taskInfo.value = res;
      });
    });
  });
};

const getTaskTime = () => {
  return `${dayjs(taskInfo.value.startTime).format('MM-DD HH:mm')}~${dayjs(taskInfo.value.endTime).format('MM-DD HH:mm')}`;
};

const executorRef: any = ref(null);

const [ExecutorModal, executorModalApi] = useVbenModal({
  title: '选择考试执行人',
  width: 1000,
  height: 800,
  showCancelBtn: false,
  onConfirm: async () => {
    const users = await executorRef.value.confirmSelection();
    if (users?.length) {
      if (users.length !== 1) {
        ElMessage.error('请选择一个执行人');
        return;
      }

      // 二次确认
      const confirm = await ElMessageBox.confirm(
        `确认将任务分配给 ${users[0].name} 吗？`,
        '确认分配',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        },
      );
      if (confirm !== 'confirm') {
        return;
      }

      transferTask({
        id: taskId.value,
        executorId: users[0].id,
      }).then(() => {
        ElMessage.success('任务转交成功');
        // 刷新任务详情
        getTaskDetail(taskId.value).then((res) => {
          taskInfo.value = res;
        });
      });

      executorModalApi.close();
    }
  },
});

// 转交任务
const handleTransferTask = () => {
  // console.log('转交任务');
  executorModalApi.open();
};

const taskInfo: any = ref({});
const taskOther: any = ref({
  taskTypeName: '',
});

const taskResult: any = ref({
  content: '',
  images: [],
  files: [],
  fileNames: [],
});

const oneSelf = computed(() => {
  return taskInfo.value.executorId === Number(userStore.userInfo?.userId);
});

const buttons = ref({
  deal: false,
  transfer: false,
  close: false,
});

const init = async () => {
  const res = await getTaskDetail(taskId.value);
  taskInfo.value = res;
  if (!taskInfo.value.status) {
    taskInfo.value.status = 0;
  }
  if (taskInfo.value.status === 1) {
    const userId = Number(userStore.userInfo?.userId);
    const isExecutor = taskInfo.value.executorId === userId;
    const isCreator = userStore?.userInfo?.username === taskInfo.value.createBy;
    const isHeadquarters = userStore?.userInfo?.post?.type === '"headquarters"';
    const isMobileTask = mobileTaskTypes.includes(taskInfo.value.formType);

    if (isExecutor && !isMobileTask) {
      buttons.value.deal = true;
    }

    if (isCreator || isHeadquarters || isExecutor) {
      if (taskInfo.value.executorId !== userId) {
        buttons.value.close = true;
      }

      if (taskInfo.value.taskTemplate?.isMust === 0) {
        buttons.value.close = true;
      }

      if (taskInfo.value.authStatus === 0 && taskInfo.value.isLicensable) {
        buttons.value.transfer = true;
      }
    }
  }

  taskOther.value.taskTypeName = taskInfo.value?.formTypeName || '-';

  if (!taskInfo.value.executorName && taskInfo.value.taskList?.length) {
    taskInfo.value.executorName = taskInfo.value.taskList[0].executorName;
  }

  if (taskInfo.value.formType === 'photo') {
    const result = taskInfo.value?.taskList?.[0] || {};
    if (result.remark) {
      taskResult.value.content = result.remark;
    }
    if (result?.attachmentUrl?.length) {
      taskResult.value.images = result.attachmentUrl;
    }
  } else if (taskInfo.value.formType === 'upload') {
    // attachmentUrl
    const result = taskInfo.value?.taskList?.[0] || {};
    if (result.remark) {
      taskResult.value.content = result.remark;
    }
    if (result?.attachmentUrl?.length) {
      taskResult.value.files = result.attachmentUrl;
      taskResult.value.fileNames = result.attachmentName.split(',');
    }
  } else {
    // taskResult.value = taskInfo.value?.taskList?.[0] || {};
  }

  if (taskInfo.value?.taskTemplate) {
    taskOther.value.taskFrequencyName =
      taskInfo.value?.taskTemplate?.taskFrequencyName || '-';
  }
};

// 动态组件包装器，根据 taskInfo 动态渲染正确的抽屉组件
const DynamicDrawerComponent = defineComponent({
  setup() {
    return () => {
      let Component = null;
      if (taskInfo.value.formType === 'upload') {
        Component = UploadDrawer;
      } else if (taskInfo.value.formType === 'form') {
        switch (taskInfo.value.subFormType) {
          case 'additive_inventory':
          case 'additive_inventory2': {
            Component = AdditiveDrawer;
            break;
          }
          case 'competition_price_survey': {
            Component = CompetitionDrawer;
            break;
          }
          case 'competition_sales_survey': {
            Component = SalesSurveyDrawer;
            break;
          }
          case 'emergency_wy': {
            Component = EmergencyWyDrawer;
            break;
          }
          case 'employee_weekly_evaluation': {
            Component = WeeklyEvaluationDrawer;
            break;
          }
          case 'entrance_rate_survey': {
            Component = EntranceDrawer;
            break;
          }
          case 'filter_maintenance': {
            break;
          }
          case 'group_log': {
            Component = GroupLogDrawer;
            break;
          }
          case 'management_plan': {
            Component = ManagementPlanDrawer;
            break;
          }
          case 'meeting': {
            Component = MeetingDrawer;
            break;
          }
          case 'oil_gun_self_test': {
            Component = GunCheckDrawer;
            break;
          }
          case 'oil_gun_self_test_height': {
            Component = GunCheck2Drawer;
            break;
          }
          case 'operating_plan': {
            Component = OperatingPlanDrawer;
            break;
          }
          case 'operating_weekly_report': {
            Component = WeeklyReportDrawer;
            break;
          }
          case 'participate_emergency_wy':
          case 'participate_oil_station_meeting': {
            Component = JoinEmergencyDrawer;
            break;
          }
          case 'tank_water': {
            Component = TankWaterDrawer;
            break;
          }
          default: {
            // ElMessage.error('当前任务无法处理');
            Component = null;
          }
        }
      }
      return Component ? h(Component) : null;
    };
  },
});

const [DealDrawer, dealDrawerApi] = useVbenDrawer({
  connectedComponent: DynamicDrawerComponent,
  onConfirm: () => {
    // 刷新当前页面
    refreshTab();
  },
});

const dealAnnualExaminationTask = async () => {
  // 二次弹框确认
  const confirm = await ElMessageBox.confirm(
    `确认完成任务 ${taskInfo.value.taskName} 吗？`,
    '确认完成',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  );
  if (confirm !== 'confirm') {
    return;
  }

  try {
    await handleLicense(taskInfo.value.id || 0);

    init();
    ElMessage.success('处理任务成功');
  } catch {
    ElMessage.error('处理任务失败');
  }
};

const dealTaskEvent = async () => {
  // 二次弹框确认
  const confirm = await ElMessageBox.confirm(
    `确认完成任务 ${taskInfo.value.taskName} 吗？`,
    '确认完成',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  );
  if (confirm !== 'confirm') {
    return;
  }

  try {
    await confirmDoneTask(taskInfo.value.id || 0);

    init();
    ElMessage.success('确认完成任务成功');
  } catch {
    ElMessage.error('确认完成任务失败');
  }
};

/**
 * 处理任务
 */
const dealEvent = async () => {
  let params: any = {};
  let isModelPage = false;
  switch (taskInfo.value.formType) {
    case 'confirm': {
      await dealTaskEvent();

      return;
    }
    case 'form': {
      if (
        ['annualExamination_task', 'replacement_task'].includes(
          taskInfo.value.subFormType,
        )
      ) {
        try {
          await dealAnnualExaminationTask();
        } catch {
          ElMessage.error('处理任务失败');
        }
        return;
      }

      params = {
        taskId: taskInfo.value.taskList?.[0]?.id || '',
        taskName: taskInfo.value.taskName,
        taskList: taskInfo.value.taskList || [],
        remark: taskResult.value.content,
        stationId: taskInfo.value.stationId || 0,
        subFormType: taskInfo.value.subFormType,
        attachmentUrl: taskResult.value.images,
      };

      if (
        [
          'ambulance_check',
          'emergency_protection_monthly_check',
          'filter_maintenance',
          'fire_extinguisher_check',
        ].includes(taskInfo.value.subFormType)
      ) {
        isModelPage = true;
      }

      break;
    }
    case 'upload': {
      params = {
        taskId: taskInfo.value.taskList?.[0]?.id || '',
        taskName: taskInfo.value.taskName,
      };

      break;
    }
    default: {
      return ElMessage.error('当前任务无法处理');
    }
  }
  if (isModelPage) {
    pageModalApi.open();
  } else {
    dealDrawerApi.setData(params).open();
  }
};

const [PageModal, pageModalApi] = useVbenModal({
  title: taskInfo.value.taskName || '确认任务',
  fullscreen: true,
  onConfirm: async () => {
    // 二次提醒确认是否完成任务
    await dealTaskEvent();
    pageModalApi.close();
  },
});

onMounted(async () => {
  await init();
});
</script>

<template>
  <Page title="" :auto-content-height="true">
    <template #description>
      <!-- 任务头部信息 -->
      <div class="flex items-center justify-between">
        <div class="flex items-center">
          <div
            class="task-icon mr-4 flex h-12 w-12 items-center justify-center rounded-full bg-green-500"
          >
            <img
              :src="taskInfo.iconUrl ? taskInfo.iconUrl[0] : '/icon/4.png'"
              alt="任务图标"
              class="h-6 w-6"
            />
          </div>
          <div>
            <h2 class="mb-1 text-xl font-bold">
              {{ taskInfo.taskName }}
              <span
                v-if="mobileTaskTypes.includes(taskInfo.formType)"
                class="ml-2 text-sm text-red-500"
                >请在手机端钉钉完成
              </span>
            </h2>
            <div class="flex items-center space-x-2">
              <ElTag
                :type="priorityConfig[taskInfo.level]?.color || 'info'"
                size="small"
                effect="dark"
              >
                {{ priorityConfig[taskInfo.level]?.label || taskInfo.level }}
              </ElTag>
              <ElTag
                :type="statusConfig[`${taskInfo.status || 0}`]?.color || 'info'"
                size="small"
                effect="dark"
              >
                {{
                  statusConfig[`${taskInfo.status || 0}`]?.label ||
                  taskInfo.status
                }}
                <!-- {{ taskInfo.status }} -->
              </ElTag>
              <ElTag
                v-if="taskInfo.isLicensable && taskInfo.authStatus === 0"
                size="small"
                effect="dark"
                color="#215ACD"
              >
                可授权
              </ElTag>
              <ElTag
                v-if="taskInfo.isLicensable && taskInfo.authStatus === 1"
                size="small"
                color="#339169"
                effect="dark"
              >
                已授权
              </ElTag>
              <ElTag
                v-if="taskInfo.isLicensable && taskInfo.authStatus === 2"
                size="small"
                color="#EB5E12"
                effect="dark"
              >
                被授权
              </ElTag>
            </div>
          </div>
        </div>
        <div class="flex items-center space-x-4">
          <ElButton v-if="buttons.deal" type="primary" @click="dealEvent">
            处理任务
          </ElButton>
          <ElButton
            type="primary"
            v-if="buttons.transfer"
            @click="handleTransferTask"
          >
            转交任务
          </ElButton>
          <ElButton v-if="buttons.close" type="danger" @click="handleCloseTask">
            关闭任务
          </ElButton>
        </div>
      </div>
    </template>
    <!-- <div>
      <span style="font-size: 20px; font-weight: 400">运营异常-任务详情</span>
    </div> -->
    <div class="boxdev">
      <div>
        <!-- 基础信息组件 -->
        <ElCard>
          <template #header>
            <div class="flex items-center gap-4">
              <div
                style="width: 4px; height: 12px; background-color: #215acd"
              ></div>
              <span
                class="text-lg font-bold text-gray-800"
                style="font-size: 14px; font-weight: 600"
              >
                任务信息
              </span>
            </div>
          </template>
          <ElDescriptions class="task-info" :column="4">
            <ElDescriptionsItem label="场站:">
              {{ taskInfo.stationName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="标准指引:">
              {{ taskInfo.standardGuide || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="执行人:">
              {{ taskInfo.executorName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="计划时间:">
              {{ taskInfo.displayDate || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="创建:">
              {{ taskInfo.createBy || '' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="任务类型:">
              {{ taskInfo.subFormTypeName || taskOther.taskTypeName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="任务负责人:">
              {{ taskInfo.taskLeaderName || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="任务频率:">
              {{ taskOther.taskFrequencyName || '-' }}
            </ElDescriptionsItem>
            <!-- <ElDescriptionsItem label="负责人:">
              {{ taskInfo.executorName }}
            </ElDescriptionsItem> -->
            <ElDescriptionsItem label="任务时间:" :span="4">
              {{ getTaskTime() || '-' }}
            </ElDescriptionsItem>

            <ElDescriptionsItem label="任务描述:" :span="4">
              <div v-html="taskInfo.description"></div>
            </ElDescriptionsItem>
            <ElDescriptionsItem
              v-if="
                taskInfo.descriptionFilesUrl &&
                taskInfo.descriptionFilesUrl.length > 0
              "
              label="详情附件:"
              :span="4"
            >
              <AttachmentViewer :files="taskInfo.descriptionFilesUrl" />
            </ElDescriptionsItem>

            <ElDescriptionsItem
              v-if="taskResult.handleContent || taskInfo.cancelReason"
              label="处理情况:"
              :span="4"
            >
              {{ taskResult.handleContent || taskInfo.cancelReason || '' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="处理时间:" :span="4">
              {{ taskInfo.completeTime || taskInfo.cancelTime || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem
              v-if="taskResult.files && taskResult.files.length > 0"
              label="处理附件:"
              :span="4"
            >
              <div class="attachment-list">
                <div
                  v-for="(file, index) in taskResult.files"
                  :key="index"
                  class="attachment-item"
                  @click="
                    () =>
                      downloadFile(
                        file,
                        taskResult.fileNames[index] || `附件${+index + 1}`,
                      )
                  "
                >
                  <span class="attachment-name">{{
                    taskResult.fileNames[index] || `附件${+index + 1}`
                  }}</span>
                </div>
              </div>
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElCard>

        <!--竞价-->
        <ElCard v-if="taskInfo.formType === 'bidding'">
          <template #header>
            <div class="flex items-center gap-4">
              <div
                style="width: 4px; height: 12px; background-color: #215acd"
              ></div>
              <span
                class="text-lg font-bold text-gray-800"
                style="font-size: 14px; font-weight: 600"
              >
                竞价信息
              </span>
            </div>
          </template>
          <BiddingComponent />
        </ElCard>

        <!-- 检查项组件 -->
        <ElCard v-if="taskInfo.formType === 'inspection'">
          <template #header>
            <div class="flex items-center gap-4">
              <div
                style="width: 4px; height: 12px; background-color: #215acd"
              ></div>
              <span
                class="text-lg font-bold text-gray-800"
                style="font-size: 14px; font-weight: 600"
              >
                检查项
              </span>
            </div>
          </template>
          <CheckComponent :task-detail="taskInfo.taskList[0]" />
        </ElCard>

        <!-- 班组日志组件 -->
        <GroupLogComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' && taskInfo.subFormType === 'group_log'
          "
        />
        <!-- 管理计划组件 -->
        <ManagementPlanComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'management_plan'
          "
        />

        <!-- 销售调查组件 -->
        <SalesSurveyComponent
          :task-detail="taskInfo.taskList"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'competition_sales_survey'
          "
        />

        <!-- 紧急情况组件 -->
        <EmergencyComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'emergency_wy'
          "
        />

        <!-- 会议组件 -->
        <MeetingComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' && taskInfo.subFormType === 'meeting'
          "
        />

        <!-- 入场率调查组件 -->
        <EntranceComponent
          :task-list="taskInfo.taskList"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'entrance_rate_survey'
          "
        />

        <!-- 竞价结果组件 -->
        <CompetitionComponent
          :task-detail="taskInfo.taskList"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'competition_price_survey'
          "
        />

        <!-- 周评级组件 -->
        <WeeklyEvaluationComponent
          :task-detail="taskInfo.taskList"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'employee_weekly_evaluation'
          "
        />

        <!-- 枪试检查组件 -->
        <GunCheckComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'oil_gun_self_test'
          "
        />

        <!-- 枪试检查高度型组件 -->
        <GunCheck2Component
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'oil_gun_self_test_height'
          "
        />

        <!-- 参与紧急情况组件 -->
        <JoinEmergencyComponent
          :task-detail="{
            ...taskInfo.taskList[0],
            subFormType: taskInfo.subFormType,
          }"
          v-if="
            taskInfo.formType === 'form' &&
            [
              'participate_oil_station_meeting',
              'participate_emergency_wy',
            ].includes(taskInfo.subFormType)
          "
        />

        <!-- 量缸试水组件 -->
        <TankWaterComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'tank_water'
          "
        />
        <!-- 处理信息组件 -->
        <AdditiveComponent
          :task-detail="taskInfo.taskList"
          v-if="
            taskInfo.formType === 'form' &&
            ['additive_inventory', 'additive_inventory2'].includes(
              taskInfo.subFormType,
            )
          "
        />

        <!-- 周报信息 -->
        <WeeklyReportComponent
          :task-detail="taskInfo.taskList[0]"
          v-if="
            taskInfo.formType === 'form' &&
            taskInfo.subFormType === 'operating_weekly_report'
          "
        />
      </div>

      <div style="width: 412px" v-if="taskInfo.status === 3">
        <!-- 评论组件 -->
        <ElCard>
          <template #header>
            <div class="flex items-center gap-4">
              <div
                style="width: 4px; height: 12px; background-color: #215acd"
              ></div>
              <span
                class="text-lg font-bold text-gray-800"
                style="font-size: 14px; font-weight: 600"
              >
                评论
              </span>
            </div>
          </template>
          <CommentComponent :task-id="taskId" :task-detail="taskInfo" />
        </ElCard>
      </div>
    </div>
    <!-- 图片预览组件 -->
    <ElImageViewer
      v-if="previewVisible"
      :url-list="previewImages"
      @close="closePreview"
    />
    <ExecutorModal class="w-[700px]">
      <SelectUsers
        ref="executorRef"
        :params="{
          stationId: taskInfo.stationId,
        }"
        :only-users="true"
        :user-params="{
          stationId: taskInfo.stationId,
        }"
      />
    </ExecutorModal>

    <DealDrawer class="w-3/5" @reload="refreshTab()" />
    <PageModal>
      <!-- 应急防护月检 -->
      <emergencyInfoPage
        v-if="taskInfo.subFormType === 'emergency_protection_monthly_check'"
      />
      <!-- 灭火器档案 -->
      <extinguisherInfoPage
        v-if="taskInfo.subFormType === 'fire_extinguisher_check'"
      />
      <!-- 急救箱档案 -->
      <firstaidkitInfoPage v-if="taskInfo.subFormType === 'ambulance_check'" />
      <!-- 过滤器档案 -->
      <filterInfoPage v-if="taskInfo.subFormType === 'filter_maintenance'" />
      <!-- 证照档案 -->
      <idPhotoInfoPage v-if="taskInfo.subFormType === 'idphoto_check'" />
    </PageModal>
  </Page>
</template>

<style scoped lang="scss">
.boxdev {
  display: flex;
  gap: 20px;
  height: 100%;
  overflow: hidden;
}
.boxdev :deep(.el-card) {
  border: none !important;
  box-shadow: none !important;
  // background: transparent !important;
}
.boxdev :deep(.el-card__header) {
  padding-top: 18px !important;
  padding-bottom: 4px !important;
  padding-left: 0px !important;

  border-bottom: none !important;
}
.boxdev :deep(.el-card__body) {
  padding-top: 0px !important;
}
::v-deep .el-descriptions__body {
  background: #ffffff00 !important;
}
.boxdev > div:nth-child(1) {
  flex: 1;
  min-width: 0;
  overflow-y: auto;
}
.boxdev > div:nth-child(2) {
  width: 28%;
  overflow-y: auto;
}
.task-detail-container {
  width: 100%;
  height: 100%;
}

.task-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.task-icon {
  img {
    filter: invert(1);
  }
}

.task-info {
  // border: 1px solid red;
  :deep(.el-descriptions__label) {
    font-size: 14px;
    font-weight: 400;
    color: var(--text-color-secondary);
  }

  :deep(.el-descriptions__content) {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color-primary);
  }
  :deep(.el-descriptions__table) {
    background: transparent !important;
  }
}

.task-images {
  display: flex;
  gap: 12px;
  margin-top: 4px;

  .task-image {
    width: 60px;
    height: 60px;
    cursor: pointer;
    object-fit: cover;
    border-radius: 4px;
    transition: transform 0.2s;
  }
}

.attachment-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  &:hover {
    background-color: #e7f5ff;
    border-color: #91d5ff;
    color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    transform: translateY(-1px);
  }

  &::before {
    content: '';
    display: inline-block;
    width: 20px;
    height: 20px;
    background-color: #409eff;
    border-radius: 4px;
    background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ffffff'%3E%3Cpath d='M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z'/%3E%3C/svg%3E");
    background-size: 12px;
    background-position: center;
    background-repeat: no-repeat;
    flex-shrink: 0;
  }
}

.attachment-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  transition: color 0.3s ease;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.attachment-item:hover .attachment-name {
  color: #409eff;
}

.attachment-item::after {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23909399'%3E%3Cpath d='M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z'/%3E%3C/svg%3E");
  background-size: 14px;
  background-position: center;
  background-repeat: no-repeat;
  flex-shrink: 0;
  transition: transform 0.3s ease;
}

.attachment-item:hover::after {
  transform: translateX(4px);
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23409eff'%3E%3Cpath d='M8.59 16.59L13.17 12 8.59 7.41 10 6l6 6-6 6-1.41-1.41z'/%3E%3C/svg%3E");
}
</style>
