<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="danger"
            size="medium"
            class="search-table-container--button start-event-btn"
            v-if="emergencyProcedureManagePermission"
            @click="handleAddEmergencyEvent"
          >
            <template #icon>
              <SvgIcon iconName="start-emergency-event" color="#fff" />
            </template>
            <span>启动应急事件</span>
          </el-button>
          <BasicSearch
            :searchConfig="PROCEDURE_LIST_SEARCH_CONFIG"
            :searchData="searchData"
            @update:search-data="handleSearch"
          >
            <template #emergencyType>
              <el-select v-model="searchData.emergencyType" placeholder="全部" clearable>
                <el-option
                  v-for="item in emergencyEventDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemValue"
                />
              </el-select>
            </template>
          </BasicSearch>
        </header>
        <BasicTable
          :tableData="tableData"
          :tableConfig="tableConfig"
          @update:page-number="handleCurrentPageChange"
          @update:page-size="handlePageSizeChange"
        >
          <template #status="scope">
            <span :style="{ color: scope.row.status === EMERGENCY_PROCEDURE_STATUS.INPROGRESS ? 'red' : '' }">
              {{ getEmergencyStatus(scope.row.status) }}
            </span>
          </template>
          <template #action="scope">
            <div class="action-container--div" v-if="scope.row.status === EMERGENCY_PROCEDURE_STATUS.INPROGRESS">
              <ActionButton
                text="指挥中心"
                @click="handleOpenCommandCenter(scope.row)"
                v-if="emergencyCommandCenterManagePermission"
              />
              <ActionButton
                text="修改"
                @click="handleEditEmergencyEvent(scope.row)"
                v-if="emergencyProcedureManagePermission"
              />
              <ActionButton
                text="处置完成"
                @click="handleFinishEmergencyEvent(scope.row)"
                v-if="emergencyProcedureCompletePermission"
              />
              <ActionButton
                text="关闭"
                :popconfirm="{
                  title: '是否关闭应急事件？',
                }"
                @confirm="handleCloseEmergencyEvent(scope.row)"
                v-if="emergencyProcedureManagePermission"
              />
            </div>
            <div class="action-container--div" v-if="scope.row.status === EMERGENCY_PROCEDURE_STATUS.HASFINISHED">
              <ActionButton text="应急报表" @click="handleOpenEmergencyReport(scope.row)" />
            </div>
          </template>
        </BasicTable>
      </div>
    </div>
  </div>
  <EmergencyEventManage
    v-if="emergencyEventManageDialog"
    :dialog-type="emergencyEventManageType"
    :event-type-options="emergencyEventDice"
    :original-event-form="originalEventForm"
    @close="handleCloseEmergencyEventManageDialog"
    @confirm="handleConfirmEmergencyEventManageDialog"
  />
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import SvgIcon from '@/components/SvgIcon/SvgIcon.vue';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import type { QueryPageRequest } from '@/types/basic-query';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { EMERGENCY_PERMISSIONS } from '@/views/emergency/src/constant';
  import {
    PROCEDURE_LIST_SEARCH_CONFIG,
    PROCEDURE_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    PROCEDURE_LIST_TABLE_MAX_HEIGHT_PERMISSION,
    PROCEDURE_LIST_TABLE_OPTIONS,
    PROCEDURE_LIST_TABLE_COLUMNS,
  } from './config';
  import { useEmergencyProcedureHook } from './hooks';
  import { EMERGENCY_PROCEDURE_STATUS } from './constant';
  import {
    ProcedureListQuery,
    EmergencyProcedureManageStruct,
    getEmergencyProcedureList,
    createEmergencyProcedure,
    updateEmergencyProcedure,
  } from '@/api/emergency-procedure';
  import EmergencyEventManage from './components/EmergencyEventManage.vue';

  const { tableConfig, pagination } = useTableConfig(PROCEDURE_LIST_TABLE_COLUMNS, PROCEDURE_LIST_TABLE_OPTIONS);
  const { emergencyEventDice, getEmergencyEventDict, getEmergencyStatus } = useEmergencyProcedureHook();

  const router = useRouter();

  const { permissions, menus } = useUserInfoHook();
  const emergencyProcedureManagePermission = ref<Boolean>(false);
  const emergencyProcedureCompletePermission = ref<Boolean>(false);
  const emergencyCommandCenterManagePermission = ref<Boolean>(false);
  const commandCenterMenuPermission = ref<Boolean>(false);

  const searchData = reactive({
    emergencyType: '',
    procedureName: '',
    procedureStartTime: ['', ''],
    status: undefined,
  });

  const emergencyProcedureQuery: QueryPageRequest<ProcedureListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const tableData = ref<EmergencyProcedureManageStruct[]>([]);

  const emergencyEventManageDialog = ref(false);
  const emergencyEventManageType = ref('add');
  const originalEventForm = ref<EmergencyProcedureManageStruct>();

  const handleSearch = () => {
    emergencyProcedureQuery.queryParam = {};
    if (searchData.emergencyType) {
      emergencyProcedureQuery.queryParam.eventType = searchData.emergencyType;
    }
    if (searchData.procedureName) {
      emergencyProcedureQuery.queryParam.eventName = searchData.procedureName;
    }
    if (searchData.procedureStartTime) {
      emergencyProcedureQuery.queryParam.startTimeStart = searchData.procedureStartTime[0];
      emergencyProcedureQuery.queryParam.startTimeEnd = searchData.procedureStartTime[1];
    }
    if (searchData.status) {
      emergencyProcedureQuery.queryParam.status = searchData.status;
    }
    getTableData();
  };

  // 启动应急事件
  const handleAddEmergencyEvent = () => {
    emergencyEventManageType.value = 'add';
    emergencyEventManageDialog.value = true;
  };

  // 关闭应急事件管理弹窗
  const handleCloseEmergencyEventManageDialog = () => {
    emergencyEventManageDialog.value = false;
    originalEventForm.value = undefined;
  };

  // 确认应急事件管理弹窗
  const handleConfirmEmergencyEventManageDialog = (form) => {
    emergencyEventManageDialog.value = false;
    if (emergencyEventManageType.value === 'add') {
      createEmergencyProcedure(form).then(() => {
        ElMessage({
          message: '应急事件启动成功',
          type: 'success',
        });
        getTableData();
        originalEventForm.value = undefined;
      });
    } else {
      updateEmergencyProcedure({
        id: originalEventForm.value?.id,
        ...form,
      }).then(() => {
        ElMessage({
          message: '应急事件修改成功',
          type: 'success',
        });
        getTableData();
        originalEventForm.value = undefined;
      });
    }
  };

  // 打开指挥中心
  const handleOpenCommandCenter = (row) => {
    if (!commandCenterMenuPermission.value) {
      ElMessage({
        message: '请添加应急指挥中心页面菜单权限',
        type: 'warning',
      });
      return;
    }
    const routerUrl = router.resolve({
      name: 'command-center',
      params: {
        id: row.id,
      },
    });
    window.open(routerUrl.href, '_blank');
  };

  // 修改
  const handleEditEmergencyEvent = (row) => {
    emergencyEventManageType.value = 'edit';
    emergencyEventManageDialog.value = true;
    originalEventForm.value = row;
  };

  // 处置完成
  const handleFinishEmergencyEvent = (row) => {
    router.push({
      name: 'emergency-procedure-complete',
      params: {
        id: row.id,
      },
    });
  };

  // 关闭
  const handleCloseEmergencyEvent = (row) => {
    updateEmergencyProcedure({
      id: row.id,
      status: EMERGENCY_PROCEDURE_STATUS.HASCLOSED,
    }).then(() => {
      ElMessage({
        message: '应急事件已关闭',
        type: 'success',
      });
      getTableData();
    });
  };

  // 应急报表
  const handleOpenEmergencyReport = (row) => {
    router.push({
      name: 'emergency-procedure-report',
      params: {
        id: row.id,
      },
    });
  };

  const handleCurrentPageChange = (pageNumber: number) => {
    pagination.pageNumber = pageNumber;
    emergencyProcedureQuery.pageNumber = pageNumber;
    getTableData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    emergencyProcedureQuery.pageSize = pageSize;
    getTableData();
  };

  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getEmergencyProcedureList(emergencyProcedureQuery);
    tableData.value = res?.records || [];
    pagination.total = res?.totalRow || 0;
    tableConfig.loading = false;
  };

  onMounted(() => {
    getEmergencyEventDict();
    getTableData();
    // 应急处置-应急事件启动管理权限：增改关
    emergencyProcedureManagePermission.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.EMERGENCY_PROCEDURE_MANAGE),
    );
    // 应急处置-应急处置管理权限：完成
    emergencyProcedureCompletePermission.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.EMERGENCY_PROCEDURE_COMPLETE),
    );
    // 应急处置-应急指挥中心管理权限：打开、编辑
    emergencyCommandCenterManagePermission.value = Boolean(
      permissions.find((item: { code: string }) => item.code === EMERGENCY_PERMISSIONS.EMERGENCY_COMMAND_CENTER_MANAGE),
    );
    // 指挥中心菜单权限
    commandCenterMenuPermission.value = Boolean(menus.find((item) => item.name === '应急指挥中心页面'));

    tableConfig.maxHeight = emergencyProcedureManagePermission.value
      ? PROCEDURE_LIST_TABLE_MAX_HEIGHT_PERMISSION
      : PROCEDURE_LIST_TABLE_MAX_HEIGHT_DEFAULT;
  });
</script>

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

  .el-select {
    --el-select-width: 200px !important;
  }

  .start-event-btn {
    background-color: #ec2828;
  }
</style>
