<template>
  <div class="disaster-precaution-container">
    <header class="disaster-precaution-container__header">
      <span class="disaster-precaution-container__title">防御通知管理列表</span>
    </header>
    <main class="disaster-precaution-container__main">
      <div class="disaster-precaution">
        <header class="disaster-precaution__header">
          <el-button
            type="primary"
            class="disaster-precaution__header--button"
            :icon="Plus"
            @click="handleCreateDefenseNotice"
            v-if="defenseNoticePermissions"
            >创建灾害防御通知
          </el-button>
          <Search
            :searchConfig="DEFENSE_NOTICE_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          />
        </header>
        <BasicTable
          :tableConfig="tableConfig"
          :tableData="tableData"
          @update:pageSize="handleSizeChange"
          @update:pageNumber="handleCurrentChange"
        >
          <template #disasterType="scope">
            <span>{{ formatDisasterType(scope.row.disasterType) }}</span>
          </template>
          <template #disasterLevel="scope">
            <span>{{ formatDisasterLevel(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 #isPush="scope">
            <span :style="{ color: scope.row.isPush === PUSH_STATUS.PUSHED ? '' : '#ff4d4f' }">
              {{ PUSH_STATUS_MAP[scope.row.isPush as PUSH_STATUS] }}
            </span>
          </template>
          <template #action="scope">
            <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"
            />
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import Search from '@/views/disaster/components/Search.vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { getDefenseNoticeList, deleteDefenseNoticeItem } from '@/api/disaster-warning';
  import type { DefenseNoticeListResponse, DefenseNoticeListQuery } from '@/types/disaster-warning';
  import type { QueryPageRequest } from '@/types/disaster';
  import {
    ACTIVE_STATUS,
    ACTIVE_STATUS_COLOR,
    ACTIVE_STATUS_MAP,
    DISASTER_PERMISSIONS,
  } from '@/views/disaster/constant';
  import { PUSH_STATUS_MAP, PUSH_STATUS } from './src/constant';
  import {
    DEFENSE_NOTICE_SEARCH_CONFIG,
    TABLE_OPTIONS,
    DEFENSE_NOTICE_TABLE_COLUMNS,
    TABLE_HEIGHT_DEFAULT,
    TABLE_HEIGHT_PREMISSION,
  } from './src/config';
  import { formatDisasterLevel, formatDisasterType } from '@/views/disaster/utils/formatTable';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { publishDefenseNoticeItem } from '@/api/disaster-warning';
  import { useUserInfoHook } from '@/views/disaster/hooks/userInfo';

  const { permissions } = useUserInfoHook();
  const defenseNoticePermissions = ref<Boolean>(false);

  const tableData = ref<DefenseNoticeListResponse[]>([]);
  const router = useRouter();
  const defaultPath = '/disaster-prevention/disaster-warning/defense-notice-item';
  const handleEditDefenseNotice = (id: number) => {
    router.push({
      path: defaultPath,
      query: { id, operate: 'edit' },
    });
  };
  const handleCreateDefenseNotice = () => {
    router.push({
      path: defaultPath,
      query: {
        operate: 'create',
      },
    });
  };
  const handleViewDefenseNotice = (id: number) => {
    router.push({
      path: defaultPath,
      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: '',
    disasterLevel: '',
    effectState: '',
  });
  const { tableConfig, pagination } = useTableConfig(DEFENSE_NOTICE_TABLE_COLUMNS, 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;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.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();
    defenseNoticePermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.DEFENSE_NOTICE),
    );
    tableConfig.height = defenseNoticePermissions.value ? TABLE_HEIGHT_PREMISSION : TABLE_HEIGHT_DEFAULT;
  });
</script>

<style lang="scss" scoped>
  @use '../style/disaster.scss' as *;
  @use './src/common.scss' as *;
</style>
