<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="handleCreateWarningInfo"
            v-if="warningInfoPermissions"
          >
            创建灾害预警信息
          </el-button>
          <Search
            :searchConfig="WARNING_INFO_SEARCH_CONFIG"
            :searchData="searchData"
            @update:searchData="handleSearch"
          />
        </header>
        <BasicTable
          :tableConfig="tableConfig"
          :tableData="tableData"
          @update:pageSize="handleSizeChange"
          @update:pageNumber="handleCurrentChange"
        >
          <template #warningIcon="scope">
            <img :src="getWarningIcon(scope.row.disasterType)" alt="预警图标" class="weather-warning-icon" />
          </template>
          <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="编辑"
              @click="handleEditWarningInfo(scope.row.id)"
              v-if="scope.row.effectState === ACTIVE_STATUS.NOT_EFFECTIVE"
            />
            <ActionButton
              text="发布"
              :popconfirm="{
                title: '确定要发布?',
              }"
              v-if="scope.row.effectState === ACTIVE_STATUS.NOT_EFFECTIVE"
              @confirm="handlePublishWarningInfo(scope.row.id, scope.row.effectState)"
            />
            <ActionButton
              text="撤回"
              :popconfirm="{
                title: '确定要撤回?',
              }"
              v-else-if="scope.row.effectState === ACTIVE_STATUS.ACTIVE"
              @confirm="handlePublishWarningInfo(scope.row.id, scope.row.effectState)"
            />
            <ActionButton
              text="删除"
              :popconfirm="{
                title: '确定要删除?',
              }"
              @confirm="handleDeleteWarningInfo(scope.row.id)"
            />
          </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 { getWarningInfoList } from '@/api/disaster-warning';
  import type { WarningInfoListResponse } from '@/types/disaster-warning';
  import {
    ACTIVE_STATUS,
    ACTIVE_STATUS_COLOR,
    ACTIVE_STATUS_MAP,
    DISASTER_PERMISSIONS,
  } from '@/views/disaster/constant';
  import PlaceHolderWeather from './src/images/placeholder-weather@1X.png';
  import { PUSH_STATUS_MAP, PUSH_STATUS, WEATHER_DISASTER_ALERT_TYPE } from './src/constant';
  import {
    WARNING_INFO_SEARCH_CONFIG,
    TABLE_OPTIONS,
    WARNING_INFO_TABLE_COLUMNS_DEFAULT,
    WARNING_INFO_TABLE_COLUMNS_PERMISSION,
    TABLE_HEIGHT_DEFAULT,
    TABLE_HEIGHT_PREMISSION,
  } from './src/config';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/disaster';
  import type { WarningInfoListQuery } from '@/types/disaster-warning';
  import { formatDisasterLevel } from '@/views/disaster/utils/formatTable';
  import { formatDisasterType } from './src/util';
  import { deleteWarningInfoItem, publishWarningInfoItem } from '@/api/disaster-warning';
  import { ElMessage } from 'element-plus';
  import { useUserInfoHook } from '@/views/disaster/hooks/userInfo';

  const { permissions } = useUserInfoHook();

  const router = useRouter();
  const searchData = reactive({
    disasterType: '',
    disasterLevel: '',
  });
  const getWarningIcon = (disasterType: string) => {
    const icon = WEATHER_DISASTER_ALERT_TYPE.find((item) => item.label === disasterType)?.icon;
    return icon ?? PlaceHolderWeather;
  };
  const defaultPath = '/disaster-prevention/disaster-warning/warning-info-item';
  const handleCreateWarningInfo = () => {
    router.push({
      path: defaultPath,
      query: {
        operate: 'create',
      },
    });
  };
  const handleEditWarningInfo = (id: number) => {
    router.push({
      path: defaultPath,
      query: {
        operate: 'edit',
        id,
      },
    });
  };
  const handlePublishWarningInfo = 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 publishWarningInfoItem({ id, effectState: effectStateStatus });
    await getTableData();
    ElMessage.success(message);
  };
  const handleDeleteWarningInfo = async (id: number) => {
    await deleteWarningInfoItem(id);
    getTableData();
    ElMessage.success('删除成功');
  };
  const tableData = ref<WarningInfoListResponse[]>([]);
  const warningInfoPermissions = ref<Boolean>(false);
  const { tableConfig, pagination } = useTableConfig(WARNING_INFO_TABLE_COLUMNS_DEFAULT, TABLE_OPTIONS);
  let wanrningInfoListQuery: QueryPageRequest<WarningInfoListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };
  const handleSearch = () => {
    wanrningInfoListQuery.queryParam = {};
    if (searchData.disasterLevel !== '') {
      wanrningInfoListQuery.queryParam.disasterLevel = searchData.disasterLevel;
    }
    if (searchData.disasterType !== '') {
      wanrningInfoListQuery.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 getWarningInfoList(wanrningInfoListQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  };
  onMounted(() => {
    getTableData();
    warningInfoPermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.WARNING_INFO),
    );
    tableConfig.height = warningInfoPermissions.value ? TABLE_HEIGHT_PREMISSION : TABLE_HEIGHT_DEFAULT;
    if (warningInfoPermissions.value) {
      tableConfig.columns = WARNING_INFO_TABLE_COLUMNS_PERMISSION;
    }
  });
</script>

<style lang="scss" scoped>
  @use '../style/disaster.scss' as *;
  @use './src/common.scss' as *;
  .weather-warning-icon {
    width: 50cpx;
    height: 50cpx;
  }
</style>
