<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>
          <div v-if="actManagementPermission" style="position: relative">
            <el-button type="primary" class="search-table-container--button" :icon="Plus" @click="handleCreateAct">
              新建记录
            </el-button>
            <el-button plain class="search-table-container--button" @click="batchImportVisible = true">
              批量导入
            </el-button>
            <RealtimeNotice />
          </div>

          <div class="act-search">
            <section class="select-box">
              <SelectableInput ref="selectableInputRef" :options="ACT_TABLE_SEARCH_OPTIONS" />
              <div class="select-box--item">
                <span>违规类型：</span>
                <el-select
                  v-model="searchData.violateType"
                  placeholder="请选择违规类型"
                  class="select-box--select"
                  clearable
                >
                  <el-option
                    v-for="item in ACT_VIOLATION_TYPE_OPTIONS"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                    :disabled="item.disabled"
                  />
                </el-select>
              </div>
              <div class="select-box--item">
                <span>通知状态：</span>
                <el-select
                  v-model="searchData.isNotice"
                  placeholder="请选择通知状态"
                  class="select-box--select"
                  clearable
                >
                  <el-option
                    v-for="item in ACT_NOTICE_STATE_OPTIONS"
                    :key="item.value"
                    :value="item.value"
                    :label="item.label"
                    :disabled="item.disabled"
                  />
                </el-select>
              </div>
              <div>
                <span>时间：</span>
                <el-date-picker
                  v-model="searchData.searchTime"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                />
              </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>
        <!-- 表格 -->
        <div class="batch-table">
          <div class="batch-operation--div" v-show="actManagementPermission && 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="handleBatchNotice">批量通知</el-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-size="handleSizeChange"
            @update:page-number="handleCurrentChange"
            @update:selection="handleSelectionChange"
          >
            <template #violateName="scope">
              <span>{{ scope.row.violateName ? scope.row.violateName + '(' + scope.row.staffNo + ')' : '-' }}</span>
            </template>
            <template #deptName="scope">
              <span>{{ scope.row.deptName || '-' }}</span>
            </template>
            <template #violateType="scope">
              <span>{{ ACT_VIOLATION_TYPE_LABEL[scope.row.violateType] }}</span>
            </template>
            <template #speed="scope">
              <span>{{ scope.row.speed ? scope.row.speed + ' km/h' : '-' }}</span>
            </template>
            <template #capturePhotos="scope">
              <ImageViewer :file-list="scope.row.capturePhotos" />
            </template>
            <template #violateLocation="scope">
              <span>{{ scope.row.violateLocation || '-' }}</span>
            </template>
            <template #createSource="scope">
              <span>{{ ACT_NOTICE_DATA_SOURCE_LABEL[scope.row.createSource] }}</span>
            </template>
            <template #isNotice="scope">
              <div class="notice-state">
                <div
                  :style="{
                    backgroundColor: ACT_NOTICE_STATE_COLOR[scope.row.isNotice],
                    width: '6px',
                    height: '6px',
                    borderRadius: '50%',
                    marginRight: '5px',
                  }"
                ></div>
                <span>{{ ACT_NOTICE_STATE_LABEL[scope.row.isNotice] }}</span>
              </div>
            </template>
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <ActionButton
                  v-if="scope.row.isNotice === ACT_NOTICE_STATE.INACTIVE"
                  text="编辑"
                  @click="handleEditAct(scope.row.id)"
                />
                <ActionButton
                  v-if="scope.row.isNotice === ACT_NOTICE_STATE.INACTIVE"
                  text="通知"
                  @click="handleNoticeAct(scope.row.id)"
                />
                <ActionButton
                  text="删除"
                  :popconfirm="{
                    title: '确定要删除?',
                  }"
                  @confirm="handleDeleteAct(scope.row.id)"
                />
              </div>
            </template>
          </BasicTable>
        </div>
      </div>
    </main>
    <BatchImport
      :visible="batchImportVisible"
      :importApiUrl="importApiUrl"
      :templateUrl="templateUrl"
      :templateName="'违规行为记录-批量导入模版'"
      @close="handleClose"
      @update="handleUpdate"
    />
  </div>
</template>

<script setup lang="ts">
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import SelectableInput from '@/components/formItems/selectableInput/SelectableInput.vue';
  import ActionButton from '@/components/ActionButton.vue';
  import RealtimeNotice from './components/RealtimeNotice.vue';
  import { ElMessage } from 'element-plus';
  import { TABLE_OPTIONS, VIOLATION_ACT_TABLE_COLUMNS, VIOLATION_ACT_TABLE_COLUMNS_CHECKONLY } from './configs/tables';
  import {
    ACT_NOTICE_DATA_SOURCE_LABEL,
    ACT_VIOLATION_TYPE_LABEL,
    ACT_TABLE_SEARCH_OPTIONS,
    ACT_VIOLATION_TYPE_OPTIONS,
    ACT_NOTICE_STATE_OPTIONS,
    ACT_NOTICE_STATE,
    ACT_NOTICE_STATE_LABEL,
    ACT_NOTICE_STATE_COLOR,
    ACT_MANAGEMENT_PROMISSION_CODE,
  } from './constants';
  import { ref, reactive, onMounted } from 'vue';
  import { Close, Plus } from '@element-plus/icons-vue';
  import { useRouter } from 'vue-router';
  import { openMessageBox } from '@/utils/element-plus/messageBox';
  import type { QueryPageRequest } from '@/types/basic-query';
  import type { ActTableSearch, ActTableQuery, ActTableData } from './types';
  import {
    getActTableList,
    noticeActData,
    deleteActData,
    exportActViolation,
  } from '@/api/traffic-violation/traffic-act';
  import { downloadFile } from '@/views/disaster/utils/download';
  import ImageViewer from './components/ImageViewer.vue';
  import { BatchImport } from '@/components/batch-import';
  import { useGlobSetting } from '@/hooks/setting';
  import urlJoin from 'url-join';
  import { useUserInfoHook } from '@/hooks/useUserInfoHook';

  const router = useRouter();

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

  // 搜索栏
  const selectableInputRef = ref<InstanceType<typeof SelectableInput>>();
  const searchData = reactive<ActTableSearch>({});

  function getQuery() {
    if (!selectableInputRef.value) return;
    tableQuery.queryParam = {
      pageType: 1,
    };
    const selectableSearch = selectableInputRef.value.getValue();
    if (selectableSearch) {
      tableQuery.queryParam[selectableSearch.key as string] = selectableSearch.value;
    }
    if (searchData.isNotice != null) {
      tableQuery.queryParam.isNotice = searchData.isNotice;
    }
    if (searchData.violateType != null) {
      tableQuery.queryParam.violateType = searchData.violateType;
    }
    if (searchData.searchTime) {
      tableQuery.queryParam.startTime = searchData.searchTime[0];
      tableQuery.queryParam.endTime = searchData.searchTime[1];
    }
  }

  function handleSearch() {
    getQuery();
    getTableData();
  }

  function handleReset() {
    selectableInputRef.value?.clearValue();
    searchData.carNumber = undefined;
    searchData.violateName = undefined;
    searchData.deptName = undefined;
    searchData.isNotice = undefined;
    searchData.violateType = undefined;
    searchData.searchTime = undefined;
    handleSearch();
  }

  async function handleDownload() {
    getQuery();
    try {
      const res = await exportActViolation(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 basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(
    actManagementPermission.value ? VIOLATION_ACT_TABLE_COLUMNS : VIOLATION_ACT_TABLE_COLUMNS_CHECKONLY,
    TABLE_OPTIONS,
  );

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

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

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

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

  const handleSelectionChange = (selection: any[]) => {
    selectionItems.value = selection;
  };

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

  const handleBatchNotice = async () => {
    const confirmed = await openMessageBox('', '确认通知任务吗？', 'warning');
    if (!confirmed) return;
    const unNoticeItem = selectionItems.value.filter((item) => item.isNotice === ACT_NOTICE_STATE.INACTIVE);
    if (!unNoticeItem.length) {
      ElMessage.warning('通知成功！共通知0条记录');
    } else {
      const noticeIds = unNoticeItem.map((item) => item.id);
      try {
        await noticeActData(noticeIds);
        ElMessage.success(`通知成功！共通知${noticeIds.length}条记录`);
      } catch (e) {
        ElMessage.error('批量通知失败');
      }
      getTableData();
    }
  };
  const handleBatchDelete = async () => {
    const confirmed = await openMessageBox('', '删除后任务不可恢复，确认删除吗？', 'warning');
    if (!confirmed) return;
    const deleteIds = selectionItems.value.map((item) => item.id);
    try {
      await deleteActData(deleteIds);
      ElMessage.success('批量删除成功');
    } catch (e) {
      ElMessage.error('批量删除失败');
    }
    getTableData();
  };

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

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

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

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

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

  function handleCreateAct() {
    router.push({
      name: 'traffic-violation-act-item',
      query: {
        operate: 'act-create',
      },
    });
  }

  function handleEditAct(id: number) {
    router.push({
      name: 'traffic-violation-act-item',
      query: {
        id,
        operate: 'act-edit',
      },
    });
  }
  async function handleNoticeAct(id: number) {
    tableConfig.loading = true;
    try {
      await noticeActData(id);
      ElMessage.success('通知成功');
    } catch (e) {
      ElMessage.error('通知失败');
      return;
    } finally {
      tableConfig.loading = false;
    }
    getTableData();
  }

  async function handleDeleteAct(id: number) {
    tableConfig.loading = true;
    try {
      await deleteActData(id);
    } catch (e) {
      ElMessage.error('删除失败');
      return;
    } finally {
      tableConfig.loading = false;
    }
    getTableData();
  }
</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 *;
  @use '../style/act-search-table.scss' as *;
</style>
