<template>
  <!---------- 查询表单form begin ----------->
  <a-form class="smart-query-form" ref="queryFormRef">
    <a-row class="smart-query-form-row" v-privilege="'aiAlarmRecord:query'">
      <a-form-item label="设备名称" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.hardwareName" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="预警类型" class="smart-query-form-item">
        <DictSelect key-code="AI_ALARM_TYPE" type="default" width="200px" v-model:value="queryForm.alarmType" />
      </a-form-item>

      <a-form-item label="预警时间" class="smart-query-form-item">
        <a-range-picker v-model:value="timeRange" @change="handleChangeTime" value-format="YYYY-MM-DD" />
      </a-form-item>

      <a-form-item class="smart-query-form-item">
        <a-button-group>
          <a-button type="primary" @click="onSearch" v-privilege="'aiAlarmRecord:query'">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>
          <a-button @click="resetQuery" v-privilege="'aiAlarmRecord:query'">
            <template #icon>
              <ReloadOutlined />
            </template>
            重置
          </a-button>
        </a-button-group>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true" class="smart-table-card">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block" ref="tableOperatorRef">
      <div class="smart-table-operate-block">
        <a-button @click="add" type="primary" v-privilege="'aiAlarmRecord:add'">
          <template #icon>
            <PlusOutlined />
          </template>
          新建
        </a-button>

        <a-button @click="confirmBatchDelete" danger :disabled="selectedRowKeyList.length === 0" v-privilege="'aiAlarmRecord:delete'">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>
      <div class="smart-table-setting-block">
        <TableOperator v-model="columns" :tableId="TABLE_ID_CONST.BUSINESS.ERP.AI_ALARM_RECORD" :refresh="queryData" />
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->
    <a-table
      size="small"
      :loading="tableLoading"
      :dataSource="tableData"
      :columns="columns"
      rowKey="id"
      bordered
      :pagination="false"
      :showSorterTooltip="false"
      :scroll="{ y: scrollY }"
      :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
    >
      <template #bodyCell="{ index, record, column }">
        <template v-if="column.dataIndex === 'index'">
          <span>{{ index + 1 }}</span>
        </template>
        <template v-if="column.dataIndex === 'imageUrl'">
          <a-image v-if="record.imageUrl" :src="record.imageUrl" :height="80" />
        </template>
        <template v-if="column.dataIndex === 'action'">
          <div class="smart-table-operate">
            <a-button @click="edit(record)" type="link" v-privilege="'aiAlarmRecord:update'">编辑</a-button>
            <a-button @click="deleteAiAlarmRecord(record)" danger type="link" v-privilege="'aiAlarmRecord:delete'">删除</a-button>
          </div>
        </template>
      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        ref="paginationRef"
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>

  <ai-alarm-modal ref="aiAlarmModal" @refresh="queryData" />
</template>
<script setup>
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { reactive, ref, onMounted, onUnmounted } from 'vue';
  import { message, Modal } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { monitorApi } from '/@/api/business/monitor/monitor-api';
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableOperator from '/@/components/support/table-operator/index.vue';
  import { TABLE_ID_CONST } from '/@/constants/support/table-id-const';
  import _ from 'lodash';
  import AiAlarmModal from './components/ai-alarm-modal.vue';
  import { calcTableHeight } from '/@/lib/table-auto-height';
  import { DeleteOutlined } from '@ant-design/icons-vue';

  // ---------------------------- 表格列 ----------------------------

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
    },
    {
      title: '设备名称',
      dataIndex: 'hardwareName',
    },
    {
      title: '设备编号',
      dataIndex: 'hardwareId',
    },
    {
      title: '预警时间',
      dataIndex: 'alarmTime',
    },
    {
      title: '预警类型',
      dataIndex: 'alarmTypeName',
    },
    {
      title: '图片',
      dataIndex: 'imageUrl',
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 180,
    },
  ]);

  // ---------------------------- 查询数据表单和方法 ----------------------------
  const queryFormState = {
    hardwareName: '',
    alarmType: [],
    pageNum: 1,
    pageSize: 10,
    sortItemList: [],
    alarmTimeBegin: '',
    alarmTimeEnd: '',
  };
  const timeRange = ref([]);
  // 查询表单form
  const queryForm = reactive(_.cloneDeep(queryFormState));
  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize;
    Object.assign(queryForm, _.cloneDeep(queryFormState));
    queryForm.pageSize = pageSize;
    timeRange.value = [];
    queryData();
  }

  // 搜索
  function onSearch() {
    queryForm.pageNum = 1;
    queryData();
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true;
    try {
      const param = {
        ...queryForm,
        alarmType: queryForm.alarmType.join(',') || undefined,
      };
      let queryResult = await monitorApi.queryAiAlarmRecordPage(param);

      tableData.value = queryResult.data.list;
      total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  function handleChangeTime(value) {
    queryForm.alarmTimeBegin = value[0] || undefined;
    queryForm.alarmTimeEnd = value[1] || undefined;
  }

  // ---------------------------- 添加/修改/详情 ----------------------------

  const aiAlarmModal = ref(null);

  function add() {
    aiAlarmModal.value.showModal();
  }

  function edit(data) {
    aiAlarmModal.value.showModal(data);
  }
  // ---------------------------- 单个删除 ----------------------------

  function deleteAiAlarmRecord(aiAlarmRecordData) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除【' + aiAlarmRecordData.hardwareName + '】吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        singleDelete(aiAlarmRecordData);
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function singleDelete(aiAlarmRecordData) {
    try {
      SmartLoading.show();
      await monitorApi.deleteAiAlarmRecord(aiAlarmRecordData.id);
      message.success('删除成功');
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ---------------------------- 批量删除 ----------------------------

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  // 批量删除
  function confirmBatchDelete() {
    Modal.confirm({
      title: '提示',
      content: '确定要删除选中告警记录吗?',
      okText: '删除',
      okType: 'danger',
      onOk() {
        batchDelete();
      },
      cancelText: '取消',
      onCancel() {},
    });
  }

  async function batchDelete() {
    try {
      SmartLoading.show();
      await monitorApi.batchDeleteAiAlarmRecord(selectedRowKeyList.value);
      message.success('删除成功');
      selectedRowKeyList.value = [];
      queryData();
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      SmartLoading.hide();
    }
  }

  // ----------------- 表格自适应高度 --------------------
  const scrollY = ref(100);
  const tableOperatorRef = ref();
  const queryFormRef = ref();
  const paginationRef = ref();

  function autoCalcTableHeight() {
    calcTableHeight(scrollY, [tableOperatorRef, queryFormRef, paginationRef], 25);
    console.log(scrollY.value);
  }

  window.addEventListener('resize', autoCalcTableHeight);

  onMounted(() => {
    queryData();
    autoCalcTableHeight();
  });

  onUnmounted(() => {
    window.removeEventListener('resize', autoCalcTableHeight);
  });
</script>
<style>
  .tag-icon {
    margin: -2px 4px -2px 0;
    display: inline-block;
    border-radius: 50%;
    width: 14px;
    height: 14px;
  }
</style>
