<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:searchData="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:pageSize="handleSizeChange"
          @update:pageNumber="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>
              <ActionButton
                v-if="scope.row.status > 0 && scope.row.status <= 3"
                text="演练执行"
                @click="handleToExecute(scope.row.id)"
              ></ActionButton>
              <ActionButton
                v-else-if="scope.row.status < 7"
                text="演练记录"
                @click="handleToRecord(scope.row)"
              ></ActionButton>
              <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';

  const router = useRouter();

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

  // 搜索栏
  const searchData = reactive<DrillPlanListSearch>({});
  function handleSearch() {
    tabelQuery.value.queryParam = searchData;
    getTabelData();
  }

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

  const tabelQuery = ref({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  });

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

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

  // 解析演练规模字典
  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 getTabelData() {
    tableConfig.loading = true;
    const res = await queryEnergencyDrillPlanList(tabelQuery.value);
    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();
    getTabelData();
  });

  // 按钮操作
  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>
