<template>
  <div class="search-table-container">
    <header>
      <!-- 按钮 -->
      <el-button
        v-if="trafficManagementPermission"
        type="primary"
        class="search-table-container--button"
        :icon="Plus"
        @click="handleCreateRegulation"
      >
        新建管理规定
      </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: 6px; height: 6px; 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: 6px; height: 6px; border-radius: 50%; margin-right: 5px"></div>
          <span>未生效</span>
        </div>
      </template>
      <template #action="scope">
        <div class="action-container--div" style="justify-content: left">
          <ActionButton v-if="scope.row.effectState === 0" text="编辑" @click="handleEditRegulation(scope.row.id)" />
          <ActionButton
            v-if="scope.row.effectState === 0"
            text="发布"
            :popconfirm="{
              title: '确定要发布吗?',
            }"
            @confirm="
              handleChangeRegulationState({
                id: scope.row.id,
                managementType: 1,
                name: scope.row.name,
                attachment: scope.row.attachment,
                isPush: scope.row.isPush,
                effectState: 1,
              })
            "
          />
          <ActionButton
            v-if="scope.row.effectState === 1"
            text="撤回"
            :popconfirm="{
              title: '确定要撤回吗?',
            }"
            @confirm="
              handleChangeRegulationState({
                id: scope.row.id,
                managementType: 1,
                name: scope.row.name,
                attachment: scope.row.attachment,
                isPush: scope.row.isPush,
                effectState: 0,
              })
            "
          />
          <ActionButton
            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 { ref, reactive, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { Search, Plus } from '@element-plus/icons-vue';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { getRegulationList, updateRegulation, deleteRegulation } from '@/api/traffic-regulation/traffic-regulation';
  import { TABLE_OPTIONS, REGULATION_TABLE_COLUMNS, REGULATION_TABLE_COLUMNS_CHECKONLY } from '../configs/tables';
  import type { UpdateRegulationQuery, RegulationDetailResponse, TableSearchQuery } from '../types';
  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 '@/views/disaster/constant';
  import { unformatAttachment } from '../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: 1,
  });
  function handleSearch() {
    tableQuery.value.queryParam = searchData;
    getTableData();
  }

  // 表格
  const { tableConfig, pagination } = useTableConfig(
    trafficManagementPermission.value ? REGULATION_TABLE_COLUMNS : REGULATION_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() {
    tableConfig.loading = true;
    const res = await getRegulationList(tableQuery.value);
    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 handleCreateRegulation() {
    router.push({
      name: 'traffic-regulation-item',
      query: {
        operate: 'regulation-create',
      },
    });
  }
  function handleEditRegulation(id: number) {
    router.push({
      name: 'traffic-regulation-item',
      query: {
        id,
        operate: 'regulation-edit',
      },
    });
  }
  async function handleChangeRegulationState(data: UpdateRegulationQuery) {
    tableConfig.loading = true;
    try {
      await updateRegulation(data);
    } catch (e) {
      ElMessage.error('修改失败');
      return;
    } finally {
      tableConfig.loading = false;
    }
    getTableData();
  }
  async function handleDelete(id: number) {
    tableConfig.loading = true;
    try {
      await deleteRegulation(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>
