<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="handleCreateWarningInfo"
            v-if="warningInfoPermissions"
          >
            创建灾害预警信息
          </el-button>
          <BasicSearch
            :searchConfig="
              warningInfoPermissions ? WARNING_INFO_SEARCH_CONFIG_PERMISSION : WARNING_INFO_SEARCH_CONFIG_DEFAULT
            "
            :searchData="searchData"
            @update:searchData="handleSearch"
          >
            <template #disasterType>
              <el-select v-model="searchData.disasterType" placeholder="请选择预警类型" filterable>
                <el-option
                  v-for="item in warningTypeDice"
                  :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 #warningIcon="scope">
            <img :src="getWarningIcon(scope.row.disasterType)" alt="预警图标" class="weather-warning-icon" />
          </template>
          <template #disasterType="scope">
            <span>{{ getWarningType(scope.row.disasterType) }}</span>
          </template>
          <template #disasterLevel="scope">
            <span>{{ getDisasterLevel(scope.row.disasterLevel) }}</span>
          </template>
          <template #content="scope">
            <div class="content--div" :style="{ maxHeight: contentMaxHeight + 'px' }">
              <el-tooltip
                :content="scope.row.content"
                placement="top"
                popper-class="custom-tooltip"
                effect="light"
                :hide-after="0"
                v-if="scope.row.contentEltooptip"
              >
                <span>{{ scope.row.content }}</span>
              </el-tooltip>
              <span v-else>{{ scope.row.content }}</span>
            </div>
          </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="编辑"
                @click="handleEditWarningInfo(scope.row.id)"
                v-if="scope.row.effectState === ACTIVE_STATUS.NOT_EFFECTIVE"
              />
              <ActionButton text="查看" @click="handleViewWarningInfo(scope.row.id)" />
              <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)"
              />
            </div>
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script lang="ts" setup>
  import { useRouter } from 'vue-router';
  import { ref, onMounted, reactive, nextTick } 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 { WarningInfoListResponse, WarningInfoListQuery } from '@/types/disaster-warning';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { getWarningInfoList, deleteWarningInfoItem, publishWarningInfoItem } from '@/api/disaster-warning';
  import {
    ACTIVE_STATUS,
    ACTIVE_STATUS_COLOR,
    ACTIVE_STATUS_MAP,
    DISASTER_PERMISSIONS,
  } from '@/views/disaster/constant';
  import {
    WARNING_INFO_SEARCH_CONFIG_DEFAULT,
    WARNING_INFO_SEARCH_CONFIG_PERMISSION,
    TABLE_OPTIONS,
    WARNING_INFO_TABLE_COLUMNS_DEFAULT,
    WARNING_INFO_TABLE_COLUMNS_PERMISSION,
    TABLE_HEIGHT_DEFAULT,
    TABLE_HEIGHT_PREMISSION,
  } from './src/config';

  const { permissions } = useUserInfoHook();
  const {
    warningTypeDice,
    disasterLevelDice,
    getWarningInfoDict,
    getWarningType,
    getWarningIcon,
    getDisasterLevelDict,
    getDisasterLevel,
  } = useDisasterWarningHook();

  const router = useRouter();
  const contentMaxHeight = 50;
  const searchData = reactive({
    disasterType: null,
    disasterLevel: null,
    effectState: null,
  });
  const defaultName = 'warning-info-item';
  const handleCreateWarningInfo = () => {
    router.push({
      name: defaultName,
      query: {
        operate: 'create',
      },
    });
  };
  const handleEditWarningInfo = (id: number) => {
    router.push({
      name: defaultName,
      query: {
        operate: 'edit',
        id,
      },
    });
  };
  const handleViewWarningInfo = (id: number) => {
    router.push({
      name: defaultName,
      query: {
        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;
    }
    if (searchData.effectState) {
      wanrningInfoListQuery.queryParam.effectState = searchData.effectState;
    }
    getTableData();
  };
  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    wanrningInfoListQuery.pageSize = value;
    getTableData();
  };
  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    wanrningInfoListQuery.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;

    nextTick(() => {
      const contentDivs = document.querySelectorAll('.content--div');
      contentDivs.forEach((div, index) => {
        if (div.scrollHeight > contentMaxHeight) {
          tableData.value[index - 1].contentEltooptip = true;
        }
      });
    });
  };
  onMounted(() => {
    getTableData();
    getWarningInfoDict();
    getDisasterLevelDict();
    warningInfoPermissions.value = Boolean(
      permissions.find((item: { code: string }) => item.code === DISASTER_PERMISSIONS.WARNING_INFO),
    );
    tableConfig.maxHeight = warningInfoPermissions.value ? TABLE_HEIGHT_PREMISSION : TABLE_HEIGHT_DEFAULT;
    if (warningInfoPermissions.value) {
      tableConfig.columns = WARNING_INFO_TABLE_COLUMNS_PERMISSION;
    }
  });
</script>

<style lang="scss" scoped>
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use './src/style/common.scss' as *;
  @use '@/views/disaster/style/disaster.scss' as *;
  .weather-warning-icon {
    width: 50px;
    height: 50px;
  }
  .content--div {
    width: 100%;
    overflow-y: hidden;
  }
</style>
