<template>
  <div class="safety-platform-container">
    <header class="safety-platform-container__header">
      <div class="breadcrumb-title"> 门禁事件记录 </div>
    </header>
    <main class="safety-platform-container__main">
      <div class="search-table-container">
        <header>
          <!-- 按钮 -->
          <el-button
            v-if="managementPermission"
            type="primary"
            class="search-table-container--button"
            :icon="Plus"
            @click="handleCreateRecord"
          >
            新建门禁事件
          </el-button>
          <div class="table-search">
            <section class="select-box">
              <SelectableInput ref="selectableInputRef" :options="ACCESS_TABLE_SEARCH_OPTIONS" />
              <div class="select-box--item">
                <span>时间：</span>
                <el-date-picker
                  v-model="searchTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </div>
            </section>
            <section class="search-btn">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
              <el-button @click="handleDownload">导出</el-button>
            </section>
          </div>
        </header>
        <!-- 表格 -->
        <BasicTable
          ref="basicTableRef"
          :tableData="tableData"
          :tableConfig="tableConfig"
          @update:pageSize="handleSizeChange"
          @update:pageNumber="handleCurrentChange"
        >
          <template #images="scope">
            <ImageViewer :file-list="scope.row.images" />
          </template>
          <template #actions="scope">
            <ActionButton text="编辑" @click="handleEditRecord(scope.row.id)" />
            <ActionButton
              text="删除"
              :popconfirm="{
                title: '确定要删除?',
              }"
              @confirm="handleDeleteRecord(scope.row.id)"
            />
          </template>
        </BasicTable>
      </div>
    </main>
  </div>
</template>

<script setup lang="ts">
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import ActionButton from '@/components/ActionButton.vue';
  import SelectableInput from '@/components/formItems/selectableInput/SelectableInput.vue';
  import ImageViewer from '@/views/traffic/violation/act/components/ImageViewer.vue';
  import { useRouter } from 'vue-router';
  import { ref, reactive, onMounted } from 'vue';
  import { Plus } from '@element-plus/icons-vue';
  import { ElMessage } from 'element-plus';
  import { downloadFile } from '@/views/disaster/utils';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import {
    getAccessRecordList,
    exportAccessRecordList,
    deleteAccessRecord,
  } from '@/api/security-confidentiality-access';
  import { ACCESS_MANAGEMENT_PERMISSION, ACCESS_TABLE_SEARCH_OPTIONS } from './constants';
  import { TABLE_OPTIONS, ACCESS_TABLE_COLUMNS, ACCESS_TABLE_COLUMNS_CHECKONLY } from './configs/tables';
  import type { AccessDetailResponse, AccessTableQuery } from './types';
  import type { QueryPageRequest } from '@/types/basic-query';
  import dayjs from 'dayjs';

  const { permissions } = useUserInfoHook();
  const managementPermission = ref<Boolean>(
    Boolean(permissions.find((item: { code: string }) => item.code === ACCESS_MANAGEMENT_PERMISSION)),
  );

  const router = useRouter();
  const handleCreateRecord = () => {
    router.push({
      name: 'security-confidentiality-access-control-item',
      query: {
        operate: 'access-create',
      },
    });
  };

  const searchTime = ref<string[]>();
  const selectableInputRef = ref<InstanceType<typeof SelectableInput>>();
  function getQuery() {
    const selectableSearch = selectableInputRef.value?.getValue();
    tableQuery.queryParam = {
      fieldType: selectableSearch?.key as number | null,
      fieldContent: selectableSearch?.value,
    };
    if (searchTime.value) {
      tableQuery.queryParam.startTime = searchTime.value[0];
      tableQuery.queryParam.endTime = searchTime.value[1];
    }
  }
  async function getTableData() {
    tableConfig.loading = true;
    const res = await getAccessRecordList(tableQuery);
    tableData.value = res.records;
    pagination.total = res.totalRow;
    tableConfig.loading = false;
  }
  function handleSearch() {
    getQuery();
    getTableData();
  }

  function handleReset() {
    selectableInputRef.value?.clearValue();
    for (const key in tableQuery.queryParam) {
      if (tableQuery.queryParam.hasOwnProperty(key)) {
        tableQuery.queryParam[key] = undefined;
      }
    }
    searchTime.value = [];
    handleSearch();
  }

  async function handleDownload() {
    getQuery();
    try {
      const res = await exportAccessRecordList(tableQuery.queryParam);
      if (res.size === 0) return;
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const url = window.URL.createObjectURL(blob);
      downloadFile(url, '门禁事件记录.xlsx');
    } catch (e) {
      ElMessage.error('下载失败');
      console.log(e);
    }
  }

  // 表格
  const { tableConfig, pagination } = useTableConfig(
    managementPermission.value ? ACCESS_TABLE_COLUMNS : ACCESS_TABLE_COLUMNS_CHECKONLY,
    TABLE_OPTIONS,
  );
  const tableData = ref<AccessDetailResponse[]>([]);

  const tableQuery = reactive<QueryPageRequest<AccessTableQuery>>({
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  });

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

  const handleEditRecord = (id: number) => {
    router.push({
      name: 'security-confidentiality-access-control-item',
      query: {
        operate: 'access-edit',
        id,
      },
    });
  };

  const handleDeleteRecord = async (id: number) => {
    try {
      await deleteAccessRecord(id);
      ElMessage.success('删除成功');
    } catch (e) {
      ElMessage.error('删除失败');
    }
    getTableData();
  };

  onMounted(() => {
    handleSearch();
  });
</script>

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

  .table-search {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    width: 100%;
  }
  .select-box {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 20px;
    &--item {
      @include flex-center;
      white-space: nowrap;
    }
    span {
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
    }
    .el-select {
      width: 200px;
    }
  }
  .search-btn {
    display: flex;
  }
</style>
