<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> 安全考核管理 </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <div style="position: relative">
            <el-button type="primary" :icon="Plus" class="search-table-container--button" @click="handleCreate"> 添加 </el-button>
          </div>

          <div class="act-search">
            <section class="select-box">
              <div class="select-box--item">
                <span>安全考核表名称：</span>
                <el-input
                  v-model="tableQuery.queryParam.exName"
                  placeholder="搜索安全考核表名称"
                  class="act-search-input"
                />
              </div>
              <div class="select-box--item">
                <span>状态：</span>
                <el-select v-model="tableQuery.queryParam.status" placeholder="请选择状态" clearable>
                  <el-option
                    v-for="item in TABLE_SYSTEM_STATUS_OPTIONS"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>所属部门：</span>
                <el-input
                  v-model="tableQuery.queryParam.deptName"
                  placeholder="请输入所属部门"
                  class="act-search-input"
                />
              </div>
              <div>
                <span>计划日期范围：</span>
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </section>
          </div>
        </header>

        <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #evaluationTableName="scope">
              <span class="evaluation-table-name">{{ scope.row.evaluationTableName }}</span>
            </template>
            <template #evaluationDocument="scope">
              <!-- <div
                class="file-container--div"
                v-for="item in parseAttachments(scope.row.evaluationDocument)"
                :key="item.fileUrl"
              >
                <img
                  class="file-container--div__icon"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  :src="FILE_TYPE_ICON[item.fileType]"
                />
                <span
                  class="file-container--div__name"
                  @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
                  >{{ item.fileName }}</span
                >
                <img
                  class="file-container--div__download"
                  :src="DownloadIcon"
                  @click="downloadFile(item.fileUrl, item.fileName)"
                />
              </div> -->
              <div class="file-list">
                <div class="file-item" v-for="file in scope.row.evaluationDocument" :key="file.fileId">
                  <!-- <img
                    class="file-container--div__icon"
                    @click="previewOnline(file.fileUrl, file.fileType as keyof typeof FILE_TYPE_ICON)"
                    :src="FILE_TYPE_ICON[file.fileType]"
                  /> -->
                  <span class="file-item--name">{{ file.fileName }}</span>
                  <div class="file-item--footer">
                    <el-button link type="primary" @click="previewOnline(file.fileUrl, file.fileType)"
                      >预览</el-button
                    >
                    <el-button link type="primary" @click.stop="downloadFile(file.fileUrl, file.fileName)"
                      >下载</el-button
                    >
                  </div>
                </div>
              </div>
            </template>
            <template #status="scope">
              <span>
                {{ TABLE_SYSTEM_STATUS_LABEL[String(scope.row.status)] || '-' }}
              </span>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <!-- 未下发：编辑 / 删除 / 下发 -->
                <template v-if="Number(scope.row.status) === 0">
                  <ActionButton text="编辑" @click="handleEdit(scope.row.id)" />
                  <ActionButton
                    text="删除"
                    :popconfirm="{
                      title: '确定要删除?',
                    }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="下发" @click="handleIssue(scope.row)" />
                </template>

                <!-- 待反馈：作废 / 考核对象 -->
                <template v-else-if="Number(scope.row.status) === 2">
                  <ActionButton text="下发" @click="handleIssue(scope.row)" />
                  <ActionButton
                    text="作废"
                    :popconfirm="{
                      title: '确定要作废?',
                    }"
                    @confirm="handleCancel(scope.row.id)"
                  />
                  <ActionButton text="考核对象" @click="handleTarget(scope.row.id)" />
                </template>

                <!-- 待复核：评分 / 作废 / 考核对象 -->
                <template v-else-if="Number(scope.row.status) === 3">
                  <ActionButton text="复核" @click="handleScore(scope.row.id)" />
                  <ActionButton
                    text="作废"
                    :popconfirm="{
                      title: '确定要作废?',
                    }"
                    @confirm="handleCancel(scope.row.id)"
                  />
                  <ActionButton text="考核对象" @click="handleTarget(scope.row.id)" />
                </template>

                <!-- 待审核：审核 / 作废 / 考核对象 -->
                <template v-else-if="Number(scope.row.status) === 4">
                  <ActionButton text="审核" @click="handleAudit(scope.row.id)" />
                  <ActionButton
                    text="作废"
                    :popconfirm="{
                      title: '确定要作废?',
                    }"
                    @confirm="handleCancel(scope.row.id)"
                  />
                  <ActionButton text="考核对象" @click="handleTarget(scope.row.id)" />
                </template>

                <!-- 已作废：删除 / 考核对象 -->
                <template v-else-if="Number(scope.row.status) === 5">
                  <ActionButton
                    text="删除"
                    :popconfirm="{
                      title: '确定要删除?',
                    }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="考核对象" @click="handleTarget(scope.row.id)" />
                </template>

                <!-- 已完成：删除 / 考核对象 / 部门排序 / 先进个人 -->
                <template v-else-if="Number(scope.row.status) === 1">
                  <ActionButton
                    text="删除"
                    :popconfirm="{
                      title: '确定要删除?',
                    }"
                    @confirm="handleDelete(scope.row.id)"
                  />
                  <ActionButton text="考核对象" @click="handleTarget(scope.row.id)" />
                  <ActionButton text="部门排序" @click="handleAdvancedGroup(scope.row.id)" />
                  <ActionButton text="先进个人" @click="handleAdvancedIndividual(scope.row.id)" />
                </template>
              </div>
            </template>
          </BasicTable>
        </div>
      </div>

      <!-- 下发弹窗 -->
      <el-dialog v-model="issueDialogVisible" title="下发考核表" width="480px" destroy-on-close>
        <el-form :model="issueForm" label-width="130px" class="issue-dialog-form">
          <el-form-item label="部门名称：">
            <el-cascader
              ref="issueDeptCascaderRef"
              v-model="issueDeptIds"
              :options="deptTree"
              :props="cascaderDeptProp"
              :show-all-levels="false"
              placeholder="请选择部门（可多选）"
              filterable
              clearable
              collapse-tags
              collapse-tags-tooltip
              style="width: 100%"
              @change="handleIssueDeptChange"
            />
          </el-form-item>
          <el-form-item label="用户名称分组：">
            <el-select
              v-model="issueForm.userGroupId"
              placeholder="请选择用户组"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option v-for="item in userGroupOptions" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门复核人：">
            <el-select
              v-model="issueForm.deptSelfApproveUserId"
              placeholder="请选择部门复核人"
              filterable
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="user in deptSelfApproveUserList"
                :key="user.value"
                :label="user.label"
                :value="user.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="计划开始日期：">
            <el-date-picker
              v-model="issueForm.startDate"
              type="date"
              placeholder="请选择计划开始日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="width: 100%"
              :disabled="showTimeDisabled"
              :disabled-date="(date: Date) => {
                if (issueForm.endDate) {
                  return date > new Date(issueForm.endDate);
                }
                return false;
              }"
            />
          </el-form-item>
          <el-form-item label="计划结束日期：">
            <el-date-picker
              :disabled="showTimeDisabled"
              v-model="issueForm.endDate"
              type="date"
              placeholder="请选择计划结束日期"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              style="width: 100%"
              :disabled-date="(date: Date) => {
                if (issueForm.startDate) {
                  return date < new Date(issueForm.startDate);
                }
                return false;
              }"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="issueDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleIssueConfirm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </main>
    <PreviewOnline ref="previewOnlineRef" />
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { TABLE_OPTIONS, EVALUATION_SYSTEM_TABLE_COLUMNS } from './configs/tables';
  import { TABLE_SYSTEM_STATUS_OPTIONS, TABLE_SYSTEM_STATUS_LABEL } from './configs/status';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import {
    querySecurityExamine,
    deleteSecurityExamine,
    saveSecurityExamineIssue,
    updateSecurityExamineRepeal,
    querySecurityExamineSelfApprove,
  } from '@/api/evaluationSystem';
  import type { EvaluationSystemQueryParam } from '@/api/evaluationSystem';
  import { ElMessage } from 'element-plus';
  import { Plus } from "@element-plus/icons-vue"
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import { downloadFile } from '@/views/disaster/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import { getAllDepartments } from '@/api/auth/dept';
  import type { DeptTree } from '@/types/dept/type';
  import { queryUserGroupPage } from '@/api/system/person-group';
  import type { PersonGroupListItem } from '@/types/person-group/type';
  import type { SecurityExamineSelfApproveUser } from '@/api/evaluationSystem';

  const router = useRouter();

  const showTimeDisabled = ref(false);

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(EVALUATION_SYSTEM_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableData = ref<any[]>([]);

  // 日期范围（用于日期选择器）
  const dateRange = ref<[string, string] | null>(null);

  // 下发弹窗相关
  const issueDialogVisible = ref(false);
  const currentIssueId = ref<number | null>(null);
  const issueForm = reactive({
    departmentName: '',
    startDate: '',
    endDate: '',
    userGroupId: undefined as number | undefined,
    deptSelfApproveUserId: undefined as number | undefined, // 部门自评审核人ID
  });
  const issueDeptIds = ref<number[]>([]);

  // 用户组（用于选择用户名称）
  const userGroupOptions = ref<PersonGroupListItem[]>([]);

  // 部门自评审核人用户列表
  const deptSelfApproveUserList = ref<SecurityExamineSelfApproveUser[]>([]);

  // 部门树（复用物品领取记录的部门字段下拉框逻辑）
  const issueDeptCascaderRef = ref();
  const deptTree = ref<DeptTree[]>([]);
  const cascaderDeptProp = {
    checkStrictly: true,
    expandTrigger: 'hover' as const,
    value: 'id',
    label: 'deptName',
    emitPath: false,
    multiple: true,
  };

  const getDeptTreeData = async () => {
    try {
      const res = await getAllDepartments();
      deptTree.value = (res?.[0]?.children ?? []).map(dept => ({
        ...dept,
        children: []
      }));
    } catch (e) {
      console.error('获取部门树失败:', e);
    }
  };

  // 获取用户组列表（用于下发时选择用户名称）
  const getUserGroupOptions = async () => {
    try {
      const res = await queryUserGroupPage({
        pageNumber: 1,
        pageSize: 9999,
        queryParam: '',
      });
      userGroupOptions.value = res?.records ?? [];
    } catch (e) {
      console.error('获取用户组列表失败:', e);
      userGroupOptions.value = [];
    }
  };

  // 获取部门自评审核人用户列表（根据考核表ID查询）
  const getDeptSelfApproveUserList = async (id: number) => {
    try {
      const res = await querySecurityExamineSelfApprove(id);
      deptSelfApproveUserList.value = res || [];
    } catch (e) {
      console.error('获取部门自评审核人列表失败:', e);
      deptSelfApproveUserList.value = [];
    }
  };

  const tableQuery = reactive<QueryPageRequest<EvaluationSystemQueryParam>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {
      exName: '', // 考核表名称
      status: undefined, // 状态（数字或 undefined）
      deptName: '', // 所属部门
      planStartTime: '', // 计划开始时间
      planEndTime: '', // 计划结束时间
    },
  });

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableData();
  };

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableData();
  };

  async function getTableData() {
    tableConfig.loading = true;
    try {
      const res = await querySecurityExamine(tableQuery);
      if (res) {
        // 映射返回数据字段到表格字段
        tableData.value = res.records.map((item) => ({
          id: item.id,
          evaluationTableName: item.exName, // 考核表名称
          status: item.status, // 状态
          statusName: item.statusName, // 状态名称
          issueDepartment: item.deptNames, // 下发部门
          issueCount: item.issueNum, // 下发数（接口未返回，暂时设为0）
          feedbackCount: item.replyNum, // 反馈数（接口未返回，暂时设为0）
          feedbackRatio: item.replyRate, // 反馈比例（接口未返回，暂时设为0%）
          evaluationDocument: JSON.parse(item.attachments || '[]'), // 考核文档
          plannedCompletionTime:
            item.planStartTime && item.planEndTime
              ? `${item.planStartTime} 至 ${item.planEndTime}`
              : item.planStartTime || item.planEndTime || '-', // 计划完成时间
          planStartTime: item.planStartTime || '', // 计划开始时间
          planEndTime: item.planEndTime || '', // 计划结束时间
        }));
        pagination.total = res.totalRow;
      }
    } catch (e) {
      console.error('获取安全考核管理列表失败:', e);
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  }

  const handleSearch = () => {
    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      tableQuery.queryParam.planStartTime = dateRange.value[0];
      tableQuery.queryParam.planEndTime = dateRange.value[1];
    } else {
      tableQuery.queryParam.planStartTime = '';
      tableQuery.queryParam.planEndTime = '';
    }
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableData();
  };

  const handleReset = () => {
    tableQuery.queryParam.exName = '';
    tableQuery.queryParam.status = undefined;
    tableQuery.queryParam.deptName = '';
    tableQuery.queryParam.planStartTime = '';
    tableQuery.queryParam.planEndTime = '';
    dateRange.value = null;
    handleSearch();
  };

  const handleCreate = () => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        operate: 'evaluationSystem-create',
      },
    });
  };

  const handleEdit = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-edit',
      },
    });
  };

  const handleDelete = async (id: number) => {
    try {
      await deleteSecurityExamine(id);
      ElMessage.success('删除成功');
      getTableData();
    } catch (e: any) {
      console.error('删除失败:', e);
      ElMessage.error(e?.message || e?.data || '删除失败，请重试');
    }
  };

  // 下发考核表
  const handleIssue = async (row: any) => {
    currentIssueId.value = row.id;
    issueForm.departmentName = '';
    issueForm.startDate = row.planStartTime;
    issueForm.endDate = row.planEndTime;
    issueForm.userGroupId = undefined;
    issueForm.deptSelfApproveUserId = undefined;
    issueDeptIds.value = [];
    issueDialogVisible.value = true;
    if(row.planStartTime && row.planEndTime && row.status === 2) {
      showTimeDisabled.value = true;
    } else {
      showTimeDisabled.value = false;
    }
    // 弹窗打开时才加载下发弹窗所需数据
    await Promise.all([getDeptTreeData(), getUserGroupOptions(), getDeptSelfApproveUserList(row.id)]);
  };

  const handleIssueDeptChange = () => {
    const nodes = issueDeptCascaderRef.value?.getCheckedNodes?.() ?? [];
    issueForm.departmentName = nodes
      .map((n: { label?: string; pathLabels?: string[] }) => n.pathLabels?.join('/') || n.label || '')
      .filter(Boolean)
      .join('，');
  };

  const handleIssueConfirm = async () => {
    if (!currentIssueId.value) {
      ElMessage.error('缺少考核表ID');
      return;
    }
    if (!issueDeptIds.value?.length) {
      ElMessage.error('请至少选择一个部门');
      return;
    }

    // 验证日期：开始日期不能大于结束日期
    if (issueForm.startDate && issueForm.endDate) {
      const startDate = new Date(issueForm.startDate);
      const endDate = new Date(issueForm.endDate);
      if (startDate > endDate) {
        ElMessage.error('计划开始日期不能大于计划结束日期');
        return;
      }
    }

    try {
      const payload = {
        id: currentIssueId.value,
        deptNames: issueForm.departmentName,
        deptIds: issueDeptIds.value,
        getUserGroupId: issueForm.userGroupId,
        deptSelfApproveUserId: issueForm.deptSelfApproveUserId,
        planStartTime: issueForm.startDate || undefined,
        planEndTime: issueForm.endDate || undefined,
      };
      await saveSecurityExamineIssue(payload);
      ElMessage.success('下发成功');
      issueDialogVisible.value = false;
      getTableData();
    } catch (e) {
      console.error('下发失败:', e);
      ElMessage.error(e?.message || e?.data || '下发失败，请重试');
    }
  };

  // 作废
  const handleCancel = async (id: number) => {
    try {
      await updateSecurityExamineRepeal(id);
      ElMessage.success('作废成功');
      getTableData();
    } catch (e: any) {
      console.error('作废失败:', e);
      ElMessage.error(e?.message || e?.data || '作废失败，请重试');
    }
  };

  // 评分：跳转到考核对象列表，并仅展示“待复核”tab
  const handleScore = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-target',
        singleStatus: '3', // 3 表示“待复核”
      },
    });
  };

  // 审核：跳转到考核对象列表，并仅展示“待审核”tab
  const handleAudit = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-target',
        singleStatus: '4', // 4 表示“待审核”
      },
    });
  };

  // 考核对象
  const handleTarget = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-target',
      },
    });
  };

  // 部门排序
  const handleAdvancedGroup = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-advanced-group',
      },
    });
  };

  // 先进个人
  const handleAdvancedIndividual = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-advanced-person',
      },
    });
  };

  const handleView = (id: number) => {
    router.push({
      name: 'EvaluationSystemItem',
      query: {
        id,
        operate: 'evaluationSystem-view',
      },
    });
  };

  // 预览
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const previewOnline = (url: string | undefined, type: keyof typeof FILE_TYPE_ICON) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  // 解析逗号分隔的URL字符串为文件列表
  const parseAttachments = (
    attachmentsStr: string | undefined,
  ): Array<{
    fileUrl: string;
    fileName: string;
    fileType: string;
  }> => {
    if (!attachmentsStr || !attachmentsStr.trim()) {
      return [];
    }

    // 按逗号分割URL
    const urls = attachmentsStr
      .split(',')
      .map((url) => url.trim())
      .filter((url) => url);

    return urls.map((url) => {
      // 从URL中提取文件名
      const urlParts = url.split('/');
      const fileName = urlParts[urlParts.length - 1] || '未知文件';

      // 根据文件扩展名判断文件类型
      const extension = fileName.split('.').pop()?.toLowerCase() || '';
      let fileType = 'pdf';
      if (extension === 'doc' || extension === 'docx') {
        fileType = 'word';
      } else if (extension === 'xls' || extension === 'xlsx') {
        fileType = 'excel';
      } else if (extension === 'ppt' || extension === 'pptx') {
        fileType = 'ppt';
      }

      return {
        fileUrl: url,
        fileName,
        fileType,
      };
    });
  };

  onMounted(() => {
    getTableData();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/styles/basic-table-file.scss' as *;
  @use '@/views/traffic/violation/style/act-search-table.scss' as *;

  .evaluation-table-name {
    color: #1777ff;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
  }

  .issue-dialog-form {
    :deep(.el-form-item__content) {
      width: 100%;
    }
  }
</style>
