<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>
          <!-- 按钮 -->
          <el-button type="primary" class="search-table-container--button" :icon="Plus" @click="handleCreateDrillPlan">
            创建演练计划
          </el-button>
          <!-- 搜索栏 -->
          <BasicSearch
            :searchConfig="DRILL_PLAN_LIST_SEARCH_CONFIG"
            :searchData="searchData"
            @update:search-data="handleSearch"
          >
            <template #drillScope>
              <el-select v-model="searchData.drillScope" placeholder="全部" filterable>
                <el-option
                  v-for="item in [{ itemCode: undefined, itemValue: '全部' }, ...drillScopeDice]"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
          </BasicSearch>
        </header>
        <!-- 表格 -->
        <BasicTable
          :tableConfig="tableConfig"
          :tableData="tableData"
          @update:page-size="handleSizeChange"
          @update:page-number="handleCurrentChange"
        >
          <template #drillScope="scope">
            <div>{{ decodeScope(scope.row.drillScope) }}</div>
          </template>
          <template #status="scope">
            <div>{{ decodeStatus(scope.row.status) }}</div>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton text="查看" @click="handleViewDrillPlan(scope.row.id)" />
              <ActionButton
                v-if="scope.row.status > 0 && scope.row.status <= 3"
                text="演练执行"
                @click="handleToExecute(scope.row.id)"
              />
              <ActionButton v-else-if="scope.row.status < 7" text="演练记录" @click="handleToRecord(scope.row)" />
              <ActionButton
                text="删除"
                :popconfirm="{
                  title: '确定要删除?',
                }"
                @confirm="handleDeleteDrillPlan(scope.row.id)"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import { ElButton } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import { reactive, ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import BasicSearch from '@/components/BasicSearch.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { queryEnergencyDrillPlanList, deleteEmergencyDrillPlan } from '@/api/emergency-drill/emergency-drill';
  import { DRILL_PLAN_LIST_SEARCH_CONFIG } from './configs/plan/search';
  import { TABLE_OPTIONS, DRILL_PLAN_LIST_TABLE_COLUMNS } from './configs/plan/table';
  import { DrillPlanListSearch, DrillPlanItem } from './types';
  import { EMERGENCY_DRILL_STATUS_DICT } from './constants';
  import { useEmergencyDrillHook } from './hook';
  import { QueryPageRequest } from '@/types/basic-query';

  const router = useRouter();

  function handleDeleteDrillPlan(id: number) {
    deleteEmergencyDrillPlan(id).then(() => {
      getTableData();
    });
  }

  // 搜索栏
  const searchData = reactive<DrillPlanListSearch>({});
  function handleSearch() {
    tableQuery.queryParam = {};
    if (searchData.daterange) {
      tableQuery.queryParam.dueCompleteTimeStart = searchData.daterange[0];
      tableQuery.queryParam.dueCompleteTimeEnd = searchData.daterange[1];
    }
    if (searchData.drillScope) tableQuery.queryParam.drillScope = searchData.drillScope;
    if (searchData.drillContent) tableQuery.queryParam.drillContent = searchData.drillContent;
    if (searchData.responsibleDept) tableQuery.queryParam.responsibleDept = searchData.responsibleDept;
    if (searchData.status) tableQuery.queryParam.status = searchData.status;
    getTableData();
  }

  // 表格
  const { tableConfig, pagination } = useTableConfig(DRILL_PLAN_LIST_TABLE_COLUMNS, TABLE_OPTIONS);

  const tableQuery = reactive<QueryPageRequest<DrillPlanListSearch>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  });

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

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

  // 解析演练规模字典
  const { drillScopeDice, getDrillScopeDict } = useEmergencyDrillHook();
  function decodeScope(code: string) {
    return drillScopeDice.value.find((x) => x.itemCode === code)?.itemValue;
  }
  // 解析演练状态
  function decodeStatus(status: number) {
    return EMERGENCY_DRILL_STATUS_DICT[status];
  }

  async function getTableData() {
    tableConfig.loading = true;
    const res = await queryEnergencyDrillPlanList(tableQuery);
    res.records.forEach((item) => {
      item.responsibleDeptNameList = item.responsibleDeptNameList.replace(/^\[|\]$/g, '');
      item.coordinateDeptNameList = item.coordinateDeptNameList?.replace(/^\[|\]$/g, '');
    });
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  }

  // 初始化
  onMounted(async () => {
    await getDrillScopeDict();
    getTableData();
  });

  // 按钮操作
  function handleCreateDrillPlan() {
    router.push({
      name: 'emergency-drill-plan-item',
      query: {
        operate: 'create',
      },
    });
  }

  function handleViewDrillPlan(id: number) {
    router.push({
      name: 'emergency-drill-plan-view',
      query: {
        id: id,
      },
    });
  }

  function handleToExecute(id: number) {
    router.push({
      name: 'emergency-drill-plan-item',
      query: {
        id: id,
        operate: 'execute',
      },
    });
  }

  function handleToRecord(row: DrillPlanItem) {
    router.push({
      name: 'emergency-drill-plan-item',
      query: {
        planId: row.id,
        approvalId: row.approvalTemplateId,
        operate: 'record',
      },
    });
  }
</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 *;
</style>
