<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title">预案管理</div>
    </div>
    <div class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <el-button
            type="primary"
            class="search-table-container--button"
            :icon="Plus"
            v-if="planManagementPremissions"
            @click="handleAdd"
            >添加预案
          </el-button>
          <BasicSearch
            :searchConfig="EMERGENCY_PLAN_MANAGEMENT_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #planType>
              <el-select v-model="searchData.planType" placeholder="请输入预案类型" filterable>
                <el-option
                  v-for="item in planTypeDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
            <template #eventType>
              <el-select v-model="searchData.eventType" placeholder="请选择事件类型" filterable>
                <el-option
                  v-for="item in emergencyEventDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
          </BasicSearch>
        </header>
        <BasicTable
          :tableData="tableData"
          :tableConfig="tableConfig"
          @update:pageSize="handleSizeChange"
          @update:pageNumber="handleCurrentChange"
        >
          <template #planType="scope">
            <span>{{ getPlanType(scope.row.planType) }}</span>
          </template>
          <template #eventType="scope">
            <span>{{ getEmergencyEvent(scope.row.eventType) }}</span>
          </template>
          <template #status="scope">
            <span
              :class="
                scope.row.status === EMERGENCY_PLAN_STATUS.APPROVAL_IN_PROGRESS ||
                scope.row.status === EMERGENCY_PLAN_STATUS.RETURNED
                  ? 'highlight-text'
                  : ''
              "
              @click="handleViewApprovalProcess(scope.row)"
              >{{ getEmergencyPlanStatusLabel(scope.row.status) }}</span
            >
          </template>
          <template #isDisabled="scope">
            <div
              style="cursor: pointer; width: 50px; margin: auto"
              @click="handleChangeDisable(scope.row.id, scope.row.isDisabled)"
            >
              <el-switch
                v-model="scope.row.isDisabled"
                :active-value="0"
                :inactive-value="1"
                style="pointer-events: none"
              />
            </div>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton text="查看" @click="handleView(scope.row.id)" />
              <ActionButton
                v-if="planManagementPremissions && scope.row.status !== EMERGENCY_PLAN_STATUS.APPROVAL_IN_PROGRESS"
                text="编辑"
                @click="handleEdit(scope.row.id)"
              />
              <ActionButton
                v-if="planManagementPremissions && scope.row.status !== EMERGENCY_PLAN_STATUS.APPROVAL_IN_PROGRESS"
                text="删除"
                :popconfirm="{ title: '确认删除' }"
                @confirm="handleDelete(scope.row.id)"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
  </div>
  <BasicDialog ref="basicDialogRef" title="审批流程" width="1000">
    <template #form>
      <BasicTable :tableData="approvalProcessData" :tableConfig="approvalProcessConfig">
        <template #approvalType="scope">
          <span>{{ APPROVAL_TYPE_MAP[scope.row.approvalType] }}</span>
        </template>
        <template #approvalStatus="scope">
          <span>{{ APPROVAL_STATUS_MAP[scope.row.approvalStatus] }}</span>
        </template>
        <template #approvalTime="scope">
          <span v-if="scope.row.approvalStatus !== APPROVAL_STATUS.OHTER">{{ scope.row.approvalTime }}</span>
        </template>
      </BasicTable>
    </template>
  </BasicDialog>
</template>

<script setup lang="ts">
  import { useRouter } from 'vue-router';
  import { ref, reactive, onMounted } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage, ElSwitch } from 'element-plus';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import BasicDialog from '@/components/BasicDialog.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useEmergencyHook } from '../src/hoos';
  import { useEmergencyPlanHook } from './src/hook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type {
    PlanEmergencyListQuery,
    PlanEmergencyListResponse,
    ApprovalProcessList,
    ApprovalProcessResponse,
    ProcessInfoListType,
  } from '@/types/emergency-plan';
  import {
    getEmergencyPlanList,
    deleteEmergencyPlan,
    updateEmergencyPlanDisabled,
    queryApprovalProcess,
  } from '@/api/emergency-plan';
  import {
    EMERGENCY_PLAN_MANAGEMENT_SEARCH_CONFIG,
    EMERGENCY_PLAN_MANAGEMENT_TABLE_OPTIONS,
    EMERGENCY_PLAN_MANAGEMENT_TABLE_COLUMNS,
    TABLE_MAX_HEIGHT_DEFAULT,
    TABLE_MAX_HEIGHT_PERMISSION,
    APPROVAL_PROCESS_TABLE_COLUMNS,
    APPROVAL_PROCESS_TABLE_OPTIONS,
  } from './src/config';
  import { EMERGENCY_PERMISSIONS } from '@/views/emergency/src/constant';
  import {
    EMERGENCY_PLAN_STATUS,
    APPROVAL_TYPE_MAP,
    APPROVAL_STATUS_MAP,
    APPROVAL_STATUS,
    APPROVAL_TYPE,
  } from './src/constant';

  const router = useRouter();
  const planManagementPremissions = ref<boolean>(false);
  const { tableConfig, pagination } = useTableConfig(
    EMERGENCY_PLAN_MANAGEMENT_TABLE_COLUMNS,
    EMERGENCY_PLAN_MANAGEMENT_TABLE_OPTIONS,
  );
  // 添加合并单元格方法
  const mergeApprovalProcess = ({ column, rowIndex }) => {
    // 合并流程步骤列
    if (column.label === '流程步骤' || column.label === '节点描述') {
      if (
        rowIndex > 0 &&
        approvalProcessData.value[rowIndex].approvalOrder === approvalProcessData.value[rowIndex - 1].approvalOrder
      ) {
        return {
          rowspan: 0,
          colspan: 0,
        };
      } else {
        let count = 1;
        for (let i = rowIndex + 1; i < approvalProcessData.value.length; i++) {
          if (approvalProcessData.value[i].approvalOrder === approvalProcessData.value[rowIndex].approvalOrder) {
            count++;
          } else {
            break;
          }
        }
        return {
          rowspan: count,
          colspan: 1,
        };
      }
    }

    // 其他列正常显示
    return {
      rowspan: 1,
      colspan: 1,
    };
  };
  // 高亮表格
  const highlightCell = ({ rowIndex }) => {
    // 找到应该高亮的行索引
    const findHighlightRowIndex = () => {
      // 遍历所有行，寻找符合条件的行
      for (let i = 0; i < approvalProcessData.value.length; i++) {
        const row = approvalProcessData.value[i];

        // 如果没有审批时间，返回该行索引
        if (!row.approvalTime) {
          return i;
        }

        // 如果有审批时间且状态为退回，返回该行索引
        if (row.approvalTime && row.approvalStatus === APPROVAL_STATUS.REJECTED) {
          return i;
        }
      }

      // 如果没有找到符合条件的行，返回最后一行索引
      return approvalProcessData.value.length - 1;
    };

    // 获取应该高亮的行索引
    const highlightRowIndex = findHighlightRowIndex();

    // 如果当前行是应该高亮的行，则高亮
    if (rowIndex === highlightRowIndex) {
      return 'row--highlight';
    }

    // 特殊处理：如果高亮行是或签，且当前行与高亮行属于同一流程步骤，也高亮
    const highlightRow = approvalProcessData.value[highlightRowIndex];
    if (highlightRow) {
      // 检查当前行是否与高亮行属于同一流程步骤
      const currentRow = approvalProcessData.value[rowIndex];
      if (currentRow && currentRow.approvalOrder === highlightRow.approvalOrder) {
        return 'row--highlight';
      }
    }

    return '';
  };
  const { tableConfig: approvalProcessConfig } = useTableConfig(
    APPROVAL_PROCESS_TABLE_COLUMNS,
    {
      ...APPROVAL_PROCESS_TABLE_OPTIONS,
      spanMethod: mergeApprovalProcess,
      rowClassName: highlightCell,
    },
    false,
  );

  const { emergencyEventDice, getEmergencyEventDict, getEmergencyEvent } = useEmergencyHook();
  const { planTypeDice, getPlanTypeDict, getPlanType, getEmergencyPlanStatusLabel } = useEmergencyPlanHook();
  const { permissions } = useUserInfoHook();
  let planManagementListQuery: QueryPageRequest<PlanEmergencyListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const tableData = ref<PlanEmergencyListResponse[]>([]);
  const searchData = reactive({
    planName: null,
    planType: null,
    eventType: null,
    professionalTestSite: null,
    status: null,
  });
  const handleSearch = () => {
    planManagementListQuery.queryParam = {};
    if (searchData.planName) {
      planManagementListQuery.queryParam.planName = searchData.planName;
    }
    if (searchData.planType) {
      planManagementListQuery.queryParam.planType = searchData.planType;
    }
    if (searchData.eventType) {
      planManagementListQuery.queryParam.eventType = searchData.eventType;
    }
    if (searchData.professionalTestSite) {
      planManagementListQuery.queryParam.professionalTestSite = searchData.professionalTestSite;
    }
    if (searchData.status !== null) {
      planManagementListQuery.queryParam.status = searchData.status;
    }
    getTableData();
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getEmergencyPlanList(planManagementListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    planManagementListQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    planManagementListQuery.pageNumber = value;
    getTableData();
  };

  const handleChangeDisable = async (id: number, value: number) => {
    if (!planManagementPremissions.value) {
      ElMessage.error('暂无权限');
      return false;
    }
    try {
      await updateEmergencyPlanDisabled({ planId: id, isDisabled: value === 1 ? 0 : 1 });
      ElMessage.success('操作成功');
    } catch (error) {
      ElMessage.error('操作失败');
    }
    getTableData();
    return false;
  };
  const defaultName = 'plan-management-detail';
  const handleAdd = () => {
    router.push({
      name: defaultName,
      query: {
        type: 'add',
      },
    });
  };
  const handleEdit = (id: number) => {
    router.push({
      name: defaultName,
      query: {
        id,
        type: 'edit',
      },
    });
  };
  const handleView = (id: number) => {
    router.push({
      name: defaultName,
      query: {
        id,
        type: 'view',
      },
    });
  };
  const handleDelete = async (id: number) => {
    await deleteEmergencyPlan(id);
    ElMessage.success('删除成功');
    await getTableData();
  };
  const basicDialogRef = ref<InstanceType<typeof BasicDialog>>();
  const approvalProcessData = ref<ApprovalProcessList[]>([]);
  const handleViewApprovalProcess = async (row: PlanEmergencyListResponse) => {
    if (row.status !== EMERGENCY_PLAN_STATUS.APPROVAL_IN_PROGRESS && row.status !== EMERGENCY_PLAN_STATUS.RETURNED)
      return;

    const res = await queryApprovalProcess(row.approvalTemplateId, row.id);

    // 处理审批流程数据
    approvalProcessData.value = [];
    res.forEach((item: ApprovalProcessResponse) => {
      if (item.processInfoList && item.processInfoList.length > 0) {
        item.processInfoList.forEach((process: ProcessInfoListType) => {
          approvalProcessData.value.push({
            approvalOrder: item.approvalOrder,
            nodeDescription: item.nodeDescription,
            approvalType: process.approvalType,
            approverName: process.approverName,
            approvalContent: process.approvalContent,
            approvalStatus: process.approvalStatus,
            approvalTime: process.approvalTime,
          });
        });
      }
    });

    basicDialogRef.value?.openDialog();
  };

  onMounted(() => {
    getPlanTypeDict();
    getEmergencyEventDict();
    getTableData();
    planManagementPremissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.PLANE_MANAGEMENT),
    );
    tableConfig.maxHeight = planManagementPremissions.value ? TABLE_MAX_HEIGHT_PERMISSION : TABLE_MAX_HEIGHT_DEFAULT;
  });
</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 *;
  .highlight-text {
    cursor: pointer;
    color: $primary-color;
  }
</style>
