<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="accidentManagePermission"
            class="search-table-container--button"
            type="primary"
            :icon="Plus"
            @click="handleAddVehicleInfo"
          >
            添加交通事故记录
          </el-button>
          <el-button
            v-if="accidentManagePermission"
            class="search-table-container--button"
            @click="batchImportVisible = true"
          >
            批量导入
          </el-button>
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              :placeholder="`请输入${curSearchTypeLabel}进行搜索`"
              clearable
              @input="handleSearch"
              @clear="handleClear"
              @keyup.enter="handleSearch"
              style="width: 380px"
            >
              <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 accidentQueryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-input>
            <div class="search-time">
              <span>事故时间：</span>
              <el-date-picker
                v-model="queryTimes"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="handleSearch"
              />
            </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="batch-table">
          <div class="batch-operation--div" v-show="accidentManagePermission && selectionItems.length > 0">
            <span>已选{{ selectionItems.length }}项</span>
            <div class="batch-operation--div--close">
              <div class="batch-operation--div--button">
                <el-button class="custom-el-button" @click="handleBatchDelete">批量删除</el-button>
              </div>
              <el-icon class="close-icon" @click="handleCloseBatchOperation"><Close /></el-icon>
            </div>
          </div>
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:page-number="handleCurrentPageChange"
            @update:page-size="handlePageSizeChange"
            @update:selection="handleSelectionChange"
          >
            <template #action="scope">
              <div class="action-container--div">
                <ActionButton text="查看" @click="handleViewDetail(scope.row.id)" />
                <ActionButton
                  text="编辑"
                  v-if="accidentManagePermission"
                  @click="handleEditVehicleInfo(scope.row.id)"
                />
                <ActionButton
                  v-if="accidentManagePermission"
                  text="删除"
                  :popconfirm="{
                    title: '是否删除该交通事故记录？',
                  }"
                  @confirm="handleDeleteVehicleInfo(scope.row)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </div>
  </div>
  <BatchImport
    :visible="batchImportVisible"
    :importApiUrl="importApiUrl"
    :templateUrl="templateUrl"
    :templateName="'交通事故记录-批量导入模版'"
    @close="handleClose"
    @update="handleUpdate"
  />
</template>

<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import urlJoin from 'url-join';
  import { useRouter } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { Plus, Search, Close } from '@element-plus/icons-vue';
  import { openMessageBox } from '@/utils/element-plus/messageBox';
  import BasicTable from '@/components/BasicTable.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import { BatchImport } from '@/components/batch-import';
  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 { useGlobSetting } from '@/hooks/setting';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';
  import { TRAFFIC_PERMISSIONS } from '@/views/traffic/constant';
  import {
    ACCIDENT_LIST_TABLE_MAX_HEIGHT_DEFAULT,
    ACCIDENT_LIST_TABLE_MAX_HEIGHT_PERMISSION,
    ACCIDENT_LIST_TABLE_OPTIONS,
    ACCIDENT_LIST_TABLE_COLUMNS,
  } from './config';
  import { FIELDTYPE, FIELD_CONTENT, accidentQueryOptions } from './constant';
  import {
    AccidentListQuery,
    AccidentInfoStruct,
    getAccidentInfoList,
    deleteAccidentInfo,
    exportAccidentInfo,
  } from '@/api/traffic-accident';

  const { tableConfig, pagination } = useTableConfig(ACCIDENT_LIST_TABLE_COLUMNS, ACCIDENT_LIST_TABLE_OPTIONS);

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

  const router = useRouter();

  const searchSelectedType = ref(FIELDTYPE.LOCATION);
  const searchKeyword = ref('');
  const curSearchTypeLabel = computed(() => {
    const option = accidentQueryOptions.find((item) => item.value === searchSelectedType.value);
    return option ? option.label : FIELD_CONTENT[searchSelectedType.value];
  });
  const queryTimes = ref(['', '']);

  const accidentTableQuery: QueryPageRequest<AccidentListQuery> = {
    pageNumber: pagination.pageNumber,
    pageSize: pagination.pageSize,
    queryParam: {},
  };

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

  const selectionItems = ref<any[]>([]);

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

  const handleSearch = () => {
    if (!queryTimes.value) queryTimes.value = ['', ''];
    getTableData();
  };

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

  const handleReset = () => {
    searchSelectedType.value = FIELDTYPE.LOCATION;
    searchKeyword.value = '';
    queryTimes.value = ['', ''];
    getTableData();
  };

  // 导出
  const handleExport = () => {
    msgConfirm('确定导出所查询数据？', '导出', {
      confirmButtonText: '确定',
      showCancelButton: true,
      type: 'warning',
    })
      .then(() => {
        exportAccidentInfo(accidentTableQuery.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;
    accidentTableQuery.pageNumber = pageNumber;
    getTableData();
  };

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

  const handleAddVehicleInfo = () => {
    router.push({
      name: 'traffic-accident-item',
      query: { operate: 'create' },
    });
  };

  const handleEditVehicleInfo = (id: number) => {
    router.push({
      name: 'traffic-accident-item',
      query: { operate: 'edit', id },
    });
  };

  const handleViewDetail = (id: number) => {
    router.push({
      name: 'traffic-accident-item',
      query: { id },
    });
  };

  const handleDeleteVehicleInfo = (row: AccidentInfoStruct) => {
    if (!row.id) return;
    deleteAccidentInfo({ accidentRecordIds: [row.id] }).then(() => {
      ElMessage.success('删除成功');
      getTableData();
    });
  };

  // 批量删除
  const handleSelectionChange = (selection: any[]) => {
    selectionItems.value = selection;
  };

  const handleCloseBatchOperation = () => {
    if (!basicTableRef.value) return;
    basicTableRef.value.clearSelection();
  };

  const handleBatchDelete = async () => {
    const confirmed = await openMessageBox('', '删除后信息不可恢复，确认删除吗？', 'warning');
    if (!confirmed) return;
    const deleteIds = selectionItems.value.map((item) => item.id);
    if (!deleteIds.length) return;
    deleteAccidentInfo({ accidentRecordIds: deleteIds }).then(() => {
      ElMessage.success('批量删除成功');
      getTableData();
    });
  };

  // 批量导入
  const batchImportVisible = ref(false);
  const { urlPrefix } = useGlobSetting();
  const importApiUrl = ref(urlJoin(urlPrefix, '/trafficAccident/importTrafficAccidentRecord'));
  const templateUrl = ref('./skyeye-file-upload/sfysecurity/TEMPLATE/import-traffic-template.xlsx');

  const handleUpdate = () => {
    // update 事件只用于更新数据，不关闭弹窗
    getTableData();
  };

  const handleClose = () => {
    // close 事件用于关闭弹窗
    batchImportVisible.value = false;
  };

  const getTableData = () => {
    tableConfig.loading = true;
    accidentTableQuery.queryParam = {
      fieldType: searchSelectedType.value,
      fieldContent: searchKeyword.value,
      startTime: queryTimes.value[0] || '',
      endTime: queryTimes.value[1] || '',
    };
    getAccidentInfoList(accidentTableQuery).then((res) => {
      tableData.value = res?.records || [];
      pagination.total = res?.totalRow || 0;
    });
    tableConfig.loading = false;
  };

  onMounted(() => {
    getTableData();
    accidentManagePermission.value = Boolean(
      permissions.find((item: { code: string }) => item.code === TRAFFIC_PERMISSIONS.ACCIDENT_MANAGE),
    );
    tableConfig.maxHeight = accidentManagePermission.value
      ? ACCIDENT_LIST_TABLE_MAX_HEIGHT_PERMISSION
      : ACCIDENT_LIST_TABLE_MAX_HEIGHT_DEFAULT;
  });
</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;
    gap: 20px;

    .search-time {
      color: rgba(0, 0, 0, 0.85);
      font-size: 14px;
      display: flex;
      align-items: center;
    }

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

  .batch-table {
    position: relative;
    width: 100%;
    height: 100%;
  }
  .batch-operation--div {
    @include flex-center;
    justify-content: flex-start;
    position: absolute;
    top: 0;
    left: 0;
    gap: 60px;
    width: 100%;
    height: 48px;
    border: 4px;
    padding: 16px 25px;
    background-color: #ddefff;
    z-index: 100;
    &--close {
      @include flex-center;
      justify-content: space-between;
      flex: 1;
    }
    .close-icon {
      font-size: 20px;
      color: #ff4d4f;
      cursor: pointer;
    }
  }
</style>
