<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 #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>
      </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 } 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, 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,
  } from './src/config';
  import { EMERGENCY_PERMISSIONS } from '@/views/emergency/src/constant';
  import { EMERGENCY_PLAN_STATUS, APPROVAL_TYPE_MAP,APPROVAL_STATUS_MAP } 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 { tableConfig: approvalProcessConfig } = useTableConfig(APPROVAL_PROCESS_TABLE_COLUMNS, {}, 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,
    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.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 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>
