<template>
  <div class="search-table-container">
    <header>
      <!-- 按钮 -->
      <el-button
        v-if="trafficManagementPermission"
        type="primary"
        class="search-table-container--button"
        :icon="Plus"
        @click="handleCreateNotice"
      >
        新建管理通知
      </el-button>

      <div class="regulation-search">
        <el-input
          class="regulation-search-input"
          v-model="searchData.searchName"
          placeholder="输入通知标题或文件名称"
          :prefix-icon="Search"
          clearable
        >
        </el-input>
        <el-button type="primary" @click="handleSearch"> 查询 </el-button>
      </div>
    </header>
    <!-- 表格 -->
    <BasicTable
      :tableConfig="tableConfig"
      :tableData="tableData"
      @update:pageSize="handleSizeChange"
      @update:pageNumber="handleCurrentChange"
    >
      <template #attachment="scope">
        <div class="file-container--div" v-for="item in unformatAttachment(scope.row.attachment)" :key="item.fileId">
          <img
            class="file-container--div__icon"
            @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
            :src="FILE_TYPE_ICON[item.fileType]"
          />
          <span
            class="file-container--div__name"
            @click="previewOnline(item.fileUrl, item.fileType as keyof typeof FILE_TYPE_ICON)"
            >{{ item.fileName }}</span
          >
          <img
            class="file-container--div__download"
            :src="DownloadIcon"
            @click="downloadFile(item.fileUrl, item.fileName)"
          />
        </div>
      </template>
      <template #effectState="scope">
        <div class="effect-state" v-if="scope.row.effectState === 1">
          <div style="background-color: #52c41a; width: 5px; height: 5px; border-radius: 50%; margin-right: 5px"></div>
          <span>已生效</span>
        </div>
        <div class="effect-state" v-else-if="scope.row.effectState === 0">
          <div style="background-color: #ff4d4f; width: 5px; height: 5px; border-radius: 50%; margin-right: 5px"></div>
          <span>未生效</span>
        </div>
      </template>
      <template #action="scope">
        <div class="action-container--div" style="justify-content: left">
          <ActionButton text="查看" @click="handleViewNotice(scope.row.id)" />
          <ActionButton
            text="编辑"
            v-if="trafficManagementPermission && scope.row.effectState === 0"
            @click="handleEditNotice(scope.row.id)"
          />
          <ActionButton
            v-if="trafficManagementPermission && scope.row.effectState === 0"
            text="发布"
            :popconfirm="{
              title: '确定要发布吗?',
            }"
            @confirm="
              handleChangeNoticeState({
                id: scope.row.id,
                managementType: 2,
                name: scope.row.name,
                content: scope.row.content,
                attachment: scope.row.attachment,
                isPush: scope.row.isPush,
                effectState: 1,
              })
            "
          />
          <ActionButton
            v-if="trafficManagementPermission && scope.row.effectState === 1"
            text="撤回"
            :popconfirm="{
              title: '确定要撤回吗?',
            }"
            @confirm="
              handleChangeNoticeState({
                id: scope.row.id,
                managementType: 2,
                name: scope.row.name,
                content: scope.row.content,
                attachment: scope.row.attachment,
                isPush: scope.row.isPush,
                effectState: 0,
              })
            "
          />
          <ActionButton
            v-if="trafficManagementPermission"
            text="删除"
            :popconfirm="{
              title: '确定要删除?',
            }"
            @confirm="handleDelete(scope.row.id)"
          />
        </div>
      </template>
    </BasicTable>
    <PreviewOnline ref="previewOnlineRef" />
  </div>
</template>

<script setup lang="ts">
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import { ElMessage } from 'element-plus';
  import { TABLE_OPTIONS, NOTICE_TABLE_COLUMNS, NOTICE_TABLE_COLUMNS_CHECKONLY } from '../configs/tables';
  import { ref, reactive, onMounted } from 'vue';
  import { Search, Plus } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { UpdateNoticeQuery, RegulationDetailResponse, TableSearchQuery } from '../types';
  import { getNoticeList, updateNotice, deleteNotice } from '@/api/traffic-regulation/traffic-regulation';
  import DownloadIcon from '@/views/disaster/disaster-control/src/svg/download.svg';
  import { downloadFile } from '@/views/disaster/utils';
  import PreviewOnline from '@/views/disaster/components/PreviewOnline.vue';
  import { FILE_TYPE_ICON } from '@/components/UploadFiles/constants';
  import { unformatAttachment } from '@/components/UploadFiles/utils';

  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { TRAFFIC_MANAGEMENT_PERMISSION } from '../constants';

  const { permissions } = useUserInfoHook();

  const trafficManagementPermission = ref<Boolean>(
    Boolean(permissions.find((item: { code: string }) => item.code === TRAFFIC_MANAGEMENT_PERMISSION)),
  );

  const router = useRouter();

  // 搜索栏
  const searchData = reactive<TableSearchQuery>({
    searchName: null,
    managementType: 2, // 1-管理规定，2-管理通知
  });
  function handleSearch() {
    tableQuery.value.queryParam = searchData;
    getTableData();
  }

  // 表格
  const { tableConfig, pagination } = useTableConfig(
    trafficManagementPermission.value ? NOTICE_TABLE_COLUMNS : NOTICE_TABLE_COLUMNS_CHECKONLY,
    TABLE_OPTIONS,
  );

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

  const tableQuery = ref<QueryPageRequest<TableSearchQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: searchData,
  });

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

  async function getTableData() {
    const res = await getNoticeList(tableQuery.value);
    tableData.value = res.records;
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  }

  // 预览
  const previewOnlineRef = ref<InstanceType<typeof PreviewOnline>>();
  const previewOnline = (url: string | undefined, type: keyof typeof FILE_TYPE_ICON) => {
    if (url) {
      previewOnlineRef.value?.open(url, type);
    }
  };

  onMounted(async () => {
    getTableData();
  });

  function handleCreateNotice() {
    router.push({
      name: 'traffic-regulation-item',
      query: {
        operate: 'notice-create',
      },
    });
  }

  function handleViewNotice(id: number) {
    router.push({
      name: 'traffic-regulation-item',
      query: {
        id,
        operate: 'notice-view',
      },
    });
  }
  function handleEditNotice(id: number) {
    router.push({
      name: 'traffic-regulation-item',
      query: {
        id,
        operate: 'notice-edit',
      },
    });
  }
  async function handleChangeNoticeState(data: UpdateNoticeQuery) {
    tableConfig.loading = true;
    try {
      await updateNotice(data);
    } catch (e) {
      ElMessage.error('修改失败');
      return;
    } finally {
      tableConfig.loading = false;
    }
    getTableData();
  }
  async function handleDelete(id: number) {
    tableConfig.loading = true;
    try {
      await deleteNotice(id);
    } catch (e) {
      ElMessage.error('删除失败');
      return;
    } finally {
      tableConfig.loading = false;
    }
    getTableData();
  }
</script>

<style scoped lang="scss">
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;
  @use '@/styles/basic-table-file.scss' as *;
  .regulation-search-input {
    max-width: 500px;
  }
  .regulation-search {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .effect-state {
    display: flex;
    align-items: center;
    justify-self: center;
  }
</style>
