<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <span class="breadcrumb-title">管理规定与通知</span>
    </header>
    <main 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"
            @click="handleCreateDefenseNotice"
            v-if="defenseNoticePermissions"
            >创建规定与通知
          </el-button>
          <BasicSearch
            :searchConfig="
              defenseNoticePermissions ? DEFENSE_NOTICE_SEARCH_CONFIG_PERMISSION : DEFENSE_NOTICE_SEARCH_CONFIG_DEFAULT
            "
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #disasterType>
              <el-select v-model="searchData.disasterType" placeholder="请选择灾害类型" filterable>
                <el-option
                  v-for="item in disasterTypeDice"
                  :key="item.itemCode"
                  :label="item.itemValue"
                  :value="item.itemCode"
                />
              </el-select>
            </template>
            <template #disasterLevel>
              <el-select v-model="searchData.disasterLevel" placeholder="请选择灾害等级">
                <el-option
                  v-for="item in disasterLevelDice"
                  :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 #disasterType="scope">
            <span>{{ getDisasterType(scope.row.disasterType) }}</span>
          </template>
          <template #disasterLevel="scope">
            <span>{{ getDisasterLevel(scope.row.disasterLevel) }}</span>
          </template>
          <template #effectState="scope">
            <div class="active-status--div">
              <div
                class="dot"
                :style="{ backgroundColor: ACTIVE_STATUS_COLOR[scope.row.effectState as ACTIVE_STATUS] }"
              />
              <span>{{ ACTIVE_STATUS_MAP[scope.row.effectState] }}</span>
            </div>
          </template>
          <template #action="scope">
            <div class="action-container--div">
              <ActionButton
                text="编辑"
                v-if="scope.row.effectState === ACTIVE_STATUS.NOT_EFFECTIVE && defenseNoticePermissions"
                @click="handleEditDefenseNotice(scope.row.id)"
              />
              <ActionButton text="查看" @click="handleViewDefenseNotice(scope.row.id)" />
              <ActionButton
                text="发布"
                :popconfirm="{
                  title: '确定要发布?',
                }"
                v-if="scope.row.effectState === ACTIVE_STATUS.NOT_EFFECTIVE && defenseNoticePermissions"
                @confirm="handlePublishDefenseNotice(scope.row.id, scope.row.effectState)"
              />
              <ActionButton
                text="撤回"
                :popconfirm="{
                  title: '确定要撤回?',
                }"
                v-else-if="scope.row.effectState === ACTIVE_STATUS.ACTIVE && defenseNoticePermissions"
                @confirm="handlePublishDefenseNotice(scope.row.id, scope.row.effectState)"
              />
              <ActionButton
                text="删除"
                :popconfirm="{
                  title: '确定要删除?',
                }"
                @confirm="handleDeleteDefenseNotice(scope.row.id)"
                v-if="defenseNoticePermissions"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { ref, onMounted, reactive } 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 ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useDisasterWarningHook } from './src/hook';
  import { useUserInfoHook } from '@/views/disaster/hooks';
  import type { DefenseNoticeListResponse, DefenseNoticeListQuery } from '@/types/disaster-warning';
  import type { QueryPageRequest } from '@/types/disaster';
  import { getDefenseNoticeList, deleteDefenseNoticeItem, publishDefenseNoticeItem } from '@/api/disaster-warning';
  import {
    ACTIVE_STATUS,
    ACTIVE_STATUS_COLOR,
    ACTIVE_STATUS_MAP,
    DISASTER_PERMISSIONS,
  } from '@/views/disaster/constant';
  import {
    DEFENSE_NOTICE_SEARCH_CONFIG_DEFAULT,
    DEFENSE_NOTICE_SEARCH_CONFIG_PERMISSION,
    TABLE_OPTIONS,
    DEFENSE_NOTICE_TABLE_COLUMNS_DEFAULT,
    DEFENSE_NOTICE_TABLE_COLUMNS_PERMISSION,
    TABLE_HEIGHT_DEFAULT,
    TABLE_HEIGHT_PREMISSION,
  } from './src/config';

  const { permissions } = useUserInfoHook();
  const {
    disasterTypeDice,
    disasterLevelDice,
    getDisasterTypeDict,
    getDisasterLevelDict,
    getDisasterType,
    getDisasterLevel,
  } = useDisasterWarningHook();

  const defenseNoticePermissions = ref<Boolean>(false);

  const tableData = ref<DefenseNoticeListResponse[]>([]);
  const router = useRouter();
  const defaultName = 'defense-notice-item';
  const handleEditDefenseNotice = (id: number) => {
    router.push({
      name: defaultName,
      query: { id, operate: 'edit' },
    });
  };
  const handleCreateDefenseNotice = () => {
    router.push({
      name: defaultName,
      query: {
        operate: 'create',
      },
    });
  };
  const handleViewDefenseNotice = (id: number) => {
    router.push({
      name: defaultName,
      query: { id },
    });
  };
  const handlePublishDefenseNotice = async (id: number, effectState: number) => {
    const message = effectState === ACTIVE_STATUS.ACTIVE ? '已取消发布' : '发布成功';
    const effectStateStatus = effectState === ACTIVE_STATUS.ACTIVE ? ACTIVE_STATUS.NOT_EFFECTIVE : ACTIVE_STATUS.ACTIVE;
    await publishDefenseNoticeItem({ id, effectState: effectStateStatus });
    await getTableData();
    ElMessage.success(message);
  };
  const handleDeleteDefenseNotice = async (id: number) => {
    await deleteDefenseNoticeItem(id);
    await getTableData();
    ElMessage.success('删除成功');
  };
  const searchData = reactive({
    disasterType: null,
    disasterLevel: null,
    effectState: null,
  });
  const { tableConfig, pagination } = useTableConfig(DEFENSE_NOTICE_TABLE_COLUMNS_DEFAULT, TABLE_OPTIONS);
  let defenseNoticeListQuery: QueryPageRequest<DefenseNoticeListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const handleSearch = () => {
    defenseNoticeListQuery.queryParam = {};
    if (searchData.disasterLevel) {
      defenseNoticeListQuery.queryParam.disasterLevel = searchData.disasterLevel;
    }
    if (searchData.effectState) {
      defenseNoticeListQuery.queryParam.effectState = searchData.effectState;
    }
    if (searchData.disasterType) {
      defenseNoticeListQuery.queryParam.disasterType = searchData.disasterType;
    }
    getTableData();
  };
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    defenseNoticeListQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    defenseNoticeListQuery.pageNumber = value;
    getTableData();
  };
  const getTableData = async () => {
    tableConfig.loading = true;
    const res = await getDefenseNoticeList(defenseNoticeListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  onMounted(() => {
    getTableData();
    getDisasterTypeDict();
    getDisasterLevelDict();
    defenseNoticePermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.DEFENSE_NOTICE),
    );
    tableConfig.maxHeight = defenseNoticePermissions.value ? TABLE_HEIGHT_PREMISSION : TABLE_HEIGHT_DEFAULT;
    if (defenseNoticePermissions.value) {
      tableConfig.columns = DEFENSE_NOTICE_TABLE_COLUMNS_PERMISSION;
    }
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use './src/style/common.scss' as *;
  @use '@/views/disaster/style/disaster.scss' as *;
</style>
