<template>
  <div class="safety-platform-container">
    <div class="safety-platform-container__header">
      <div class="breadcrumb-title">监控调阅记录管理</div>
    </div>
    <div class="safety-platform-container__main">
      <div class="search-table-container">
        <header class="disaster-precaution__header">
          <el-button
            v-if="surveillanceManagePermission"
            class="search-table-container--button"
            type="primary"
            :icon="Plus"
            @click="handleAddSurveillanceInfo"
          >
            添加监控调阅记录
          </el-button>
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              :placeholder="`请输入${curSearchTypeLabel}进行搜索`"
              clearable
              @input="handleSearch"
              @clear="handleClear"
              @keyup.enter="handleSearch"
              style="width: 340px"
            >
              <template #prefix>
                <el-icon color="#1777ff"><Search /></el-icon>
              </template>
              <template #prepend>
                <el-select
                  v-model="searchSelectedType"
                  placeholder="选择搜索项"
                  @change="handleSelectedTypeChange"
                  style="width: 100px"
                >
                  <el-option
                    v-for="item in surveillanceQueryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-input>
            <div class="search-item">
              <label>是否拷贝：</label>
              <el-select v-model="searchIsCopy" placeholder="请选择" clearable style="width: 120px">
                <el-option v-for="item in COPY_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
            <div class="search-item">
              <label>调阅状态：</label>
              <el-select v-model="searchAccessStatus" placeholder="请选择" clearable style="width: 120px">
                <el-option
                  v-for="item in ACCESS_STATUS_OPTIONS"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="search-item">
              <label>调阅时段：</label>
              <el-date-picker
                v-model="searchTimeRange"
                type="datetimerange"
                range-separator="~"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 300px"
              />
            </div>
            <div class="search-container-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button @click="handleExport">导出</el-button>
            </div>
          </div>
        </header>
        <div class="table-container">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:page-number="handleCurrentPageChange"
            @update:page-size="handlePageSizeChange"
          >
            <template #accessTimePeriod="scope">
              <span v-if="scope.row.accessStartTime && scope.row.accessEndTime">
                {{ scope.row.accessStartTime }} ~ {{ scope.row.accessEndTime }}
              </span>
              <span v-else>-</span>
            </template>
            <template #isCopy="scope">
              <el-tag :type="scope.row.isCopy === 1 ? 'success' : 'info'">
                {{ scope.row.isCopy === 1 ? '是' : '否' }}
              </el-tag>
            </template>
            <template #approvalForm="scope">
              <ImageViewer :file-list="scope.row.approvalFormUrl" />
            </template>
            <template #accessStatus="scope">
              <el-tag :type="scope.row.accessStatus === 1 ? 'success' : 'warning'">
                {{ scope.row.accessStatus === 1 ? '已调阅' : '待调阅' }}
              </el-tag>
            </template>
            <template #action="scope">
              <div class="action-container--div">
                <ActionButton text="编辑" @click="handleEditSurveillanceInfo(scope.row)" />
                <ActionButton
                  text="删除"
                  :popconfirm="{
                    title: '是否删除该监控调阅记录？',
                  }"
                  @confirm="handleDeleteSurveillanceInfo(scope.row)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </div>
  </div>
  <ManageDrawer v-if="drawerVisible" :type="drawerType" :initial-data="initialData" @close="handleCloseDrawer" />
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import { ElMessage } from 'element-plus';
  import { Plus, Search } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import ManageDrawer from './components/ManageDrawer.vue';
  import ImageViewer from '@/views/traffic/violation/act/components/ImageViewer.vue';
  import { downloadByData } from '@/utils/file/download';
  import { msgConfirm } from '@/utils/element-plus/messageBox';
  import { getCurrentDateTimeString } from '@/utils/dateUtil';
  import type { QueryPageRequest } from '@/types/basic-query';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { SECURITY_CONFIDENTIALITY_PERMISSIONS } from '@/views/security-confidentiality/constant';
  import {
    SURVEILLANCE_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    SURVEILLANCE_LIST_TABLE_MAX_HEIGHT_PERMISSION,
    SURVEILLANCE_LIST_TABLE_OPTIONS,
    SURVEILLANCE_LIST_TABLE_COLUMNS,
  } from './config';
  import { FIELDTYPE, FIELD_CONTENT, surveillanceQueryOptions, COPY_OPTIONS, ACCESS_STATUS_OPTIONS } from './constant';
  import {
    SurveillanceListQuery,
    SurveillanceInfoStruct,
    getSurveillanceInfoList,
    deleteSurveillanceInfo,
    exportSurveillanceInfo,
  } from '@/api/security-confidentiality-surveillance';

  const { tableConfig, pagination } = useTableConfig(SURVEILLANCE_LIST_TABLE_COLUMNS, SURVEILLANCE_LIST_TABLE_OPTIONS);

  const { permissions } = useUserInfoHook();
  const surveillanceManagePermission = ref<boolean>(false);

  const searchSelectedType = ref(FIELDTYPE.NAME);
  const searchKeyword = ref('');
  const searchIsCopy = ref<number | undefined>(undefined);
  const searchAccessStatus = ref<number | undefined>(undefined);
  const searchTimeRange = ref<[string, string] | undefined>(undefined);

  const curSearchTypeLabel = computed(() => {
    const option = surveillanceQueryOptions.find((item) => item.value === searchSelectedType.value);
    return option ? option.label : FIELD_CONTENT[searchSelectedType.value];
  });

  const surveillanceTableQuery: QueryPageRequest<SurveillanceListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };

  const basicTableRef = ref<InstanceType<typeof BasicTable>>();
  const tableData = ref<SurveillanceInfoStruct[]>([]);

  // add or edit
  const drawerVisible = ref(false);
  const drawerType = ref('');
  const initialData = ref<SurveillanceInfoStruct>({});

  const handleSelectedTypeChange = () => {
    searchKeyword.value = '';
  };

  const handleSearch = () => {
    if (!searchKeyword.value.trim()) {
      handleClear();
      return;
    }
    getTableData();
  };

  const handleClear = () => {
    searchKeyword.value = '';
    getTableData();
  };

  const handleReset = () => {
    searchSelectedType.value = FIELDTYPE.NAME;
    searchKeyword.value = '';
    searchIsCopy.value = undefined;
    searchAccessStatus.value = undefined;
    searchTimeRange.value = undefined;
    getTableData();
  };

  // 导出
  const handleExport = () => {
    msgConfirm('确定导出所查询数据？', '导出', {
      confirmButtonText: '确定',
      showCancelButton: true,
      type: 'warning',
    })
      .then(() => {
        exportSurveillanceInfo(surveillanceTableQuery.queryParam).then(async (responnse) => {
          if (!responnse) {
            throw new Error('下载文件失败');
          }
          downloadByData(responnse, `监控调阅记录_${getCurrentDateTimeString()}.xlsx`);
          ElMessage.success('下载文件成功');
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消导出',
        });
      });
  };

  const handleCurrentPageChange = (pageNumber: number) => {
    pagination.pageNumber = pageNumber;
    surveillanceTableQuery.pageNumber = pageNumber;
    getTableData();
  };

  const handlePageSizeChange = (pageSize: number) => {
    pagination.pageSize = pageSize;
    surveillanceTableQuery.pageSize = pageSize;
    getTableData();
  };

  const handleAddSurveillanceInfo = () => {
    drawerVisible.value = true;
    drawerType.value = 'add';
    initialData.value = {};
  };

  const handleEditSurveillanceInfo = (row: SurveillanceInfoStruct) => {
    drawerVisible.value = true;
    drawerType.value = 'edit';
    initialData.value = row;
  };

  const handleCloseDrawer = () => {
    drawerVisible.value = false;
    getTableData();
  };

  const handleDeleteSurveillanceInfo = (row: SurveillanceInfoStruct) => {
    if (!row.id) return;
    deleteSurveillanceInfo(row.id).then(() => {
      ElMessage.success('删除成功');
      getTableData();
    });
  };

  const getTableData = () => {
    tableConfig.loading = true;
    surveillanceTableQuery.queryParam = {
      fieldType: searchSelectedType.value,
      fieldContent: searchKeyword.value,
      isCopy: searchIsCopy.value,
      accessStatus: searchAccessStatus.value,
      startTime: searchTimeRange.value?.[0],
      endTime: searchTimeRange.value?.[1],
    };
    getSurveillanceInfoList(surveillanceTableQuery).then((res) => {
      tableData.value = res?.records || [];
      pagination.total = res?.totalRow || 0;
    });
    tableConfig.loading = false;
  };

  // 动态生成表格列配置
  const getTableColumns = () => {
    if (surveillanceManagePermission.value) {
      return SURVEILLANCE_LIST_TABLE_COLUMNS;
    } else {
      // 过滤掉操作列
      return SURVEILLANCE_LIST_TABLE_COLUMNS.filter((column) => column.prop !== 'action');
    }
  };

  onMounted(() => {
    surveillanceManagePermission.value = Boolean(
      permissions.find(
        (item: { code: string }) => item.code === SECURITY_CONFIDENTIALITY_PERMISSIONS.SURVEILLANCE_MANAGEMENT,
      ),
    );
    getTableData();
    tableConfig.maxHeight = surveillanceManagePermission.value
      ? SURVEILLANCE_LIST_TABLE_MAX_HEIGHT_PERMISSION
      : SURVEILLANCE_LIST_TABLE_MAX_HEIGHT_DEFAULT;
    tableConfig.columns = getTableColumns();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-main-layout.scss' as *;
  @use '@/styles/page-details-layout.scss' as *;
  @use '@/styles/basic-table-action.scss' as *;

  .search-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 16px;

    .search-container-btn {
      margin-left: auto;
    }

    .search-item {
      display: flex;
      align-items: center;
      gap: 8px;

      label {
        white-space: nowrap;
        font-size: 14px;
        color: #606266;
      }
    }
  }

  .table-container {
    position: relative;
    width: 100%;
    height: 100%;
  }
</style>
