<template>
  <div class="p-4">
    <div class="btm-group vent-flex-row-between">
      <div class="mb-10px">
        <JDictSelectTag v-model:value="deviceKind" placeholder="请输入设备类型" dictCode="analyReportType" />
        <a-button class="ml-5px mr-5px" type="primary" @click="handleAddDevices"> 新增 </a-button>
        <a-button type="primary" @click="handleAssoicate"> 自动关联 </a-button>
      </div>
      <!-- <a-button class="vent-margin-l-10" type="primary" @click="handleSave()"> 批量保存 </a-button> -->
    </div>
    <BasicTable ref="editTable" @register="registerTable">
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '查看报表数据',
              onClick: () => handlePreview(record),
            },
            {
              label: '删除',
              popConfirm: {
                title: '确认删除？',
                confirm: () => handleDelete(record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <BasicModal title="手动关联报表数据" width="800px" @register="registerModal">
      <a-button type="primary" @click="handleSaveSelection"> 批量保存 </a-button>
      <BasicTable @register="registerTable2">
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                label: '保存',
                onClick: () => handleSave(record),
              },
            ]"
          />
        </template>
      </BasicTable>
    </BasicModal>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, watch } from 'vue';
  import { BasicModal, useModal } from '/@/components/Modal';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    deviceList,
    sceneReportAssociationList,
    sceneReportAssociationDelete,
    findPotentialAssociations,
    autoAssociate,
    manualAssociate,
  } from './point.api';
  import { reportColumns } from './point.data';
  import { message, Modal } from 'ant-design-vue';
  import { JDictSelectTag } from '/@/components/Form';
  import { JsonPreview } from '/@/components/CodeEditor';
  import { h } from 'vue';

  export default defineComponent({
    components: { BasicTable, TableAction, BasicModal, JDictSelectTag },
    props: {
      columns: {
        type: Array<any>,
        requried: true,
      },
      device: {
        type: Object,
        requried: true,
        default: () => ({}),
      },
    },
    emits: ['save', 'delete'],
    setup(props) {
      const deviceKind = ref('');

      const [registerModal, { openModal }] = useModal();

      const [registerTable, tableCtx] = useTable({
        columns: props.columns,
        title: '',
        api: ({ pageNo, pageSize }) => {
          return sceneReportAssociationList({
            pageNo,
            pageSize,
            sceneId: props.device.id,
          });
        },
        showIndexColumn: true,
        showTableSetting: false,
        tableSetting: { fullScreen: true },
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      const [registerTable2, tableCtx2] = useTable({
        columns: reportColumns,
        api() {
          return findPotentialAssociations({ sceneName: props.device.systemname, reportType: deviceKind.value });
        },
        pagination: false,
        rowSelection: { type: 'checkbox' },
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      function handleSave(record) {
        return manualAssociate([
          {
            ...record,
            sceneId: props.device.id,
          },
        ])
          .then((res) => {
            message.success(res);
            tableCtx.reload();
            tableCtx2.reload();
          })
          .catch((res) => {
            message.error(res.message);
          });
      }
      function handleSaveSelection() {
        return manualAssociate(
          tableCtx2.getSelectRows().map((e) => ({
            ...e,
            sceneId: props.device.id,
          }))
        )
          .then((res) => {
            message.success(res);
            tableCtx.reload();
            tableCtx2.reload();
          })
          .catch((res) => {
            message.error(res.message);
          });
      }
      function handleDelete(record) {
        return sceneReportAssociationDelete({
          id: record.id,
        })
          .then((res) => {
            message.success(res);
            tableCtx.reload();
          })
          .catch((res) => {
            message.error(res.message);
          });
      }
      function handleAssoicate() {
        if (!deviceKind.value) return message.info('请选择设备类型');
        return autoAssociate({
          reportType: deviceKind.value,
        })
          .then((res) => {
            message.success(res);
            tableCtx.reload();
          })
          .catch((res) => {
            message.error(res.message);
          });
      }
      function handlePreview(record) {
        Modal.info({
          title: record.reportPointName,
          width: 700,
          content: h(JsonPreview, {
            data: record.reportJsonData,
            style: { backgroundColor: '#333', marginRight: '38px' },
          }),
        });
      }

      function handleAddDevices() {
        if (!deviceKind.value) return message.info('请选择设备类型');
        openModal();
        nextTick(() => tableCtx2.reload());
      }

      watch(
        () => props.columns,
        (columns = []) => {
          // linkColumns.value = columns
          // reload()
          tableCtx.setColumns(columns);
        }
      );

      return {
        registerTable,
        registerTable2,
        deviceKind,
        deviceList,
        registerModal,
        handleAddDevices,
        handleSave,
        handleAssoicate,
        handleDelete,
        handleSaveSelection,
        handlePreview,
      };
    },
  });
</script>
<style scoped lang="less">
  @ventSpace: zxm;

  :deep(.@{ventSpace}-table-body) {
    height: auto !important;
  }
  .btm-group {
    padding-bottom: 2px;
  }
  .device-button-group {
    // margin: 0 20px;
    display: flex;
    flex-wrap: wrap;
    pointer-events: auto;
    position: relative;
    margin-top: 10px;
    margin-bottom: 5px;
    &::after {
      position: absolute;
      content: '';
      width: calc(100% + 10px);
      height: 2px;
      top: 30px;
      left: -10px;
      border-bottom: 1px solid #0efcff;
    }
    .device-button {
      padding: 4px 10px;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;

      color: #fff;
      cursor: pointer;
      margin: 0 1px;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        border: 1px solid #6176af;
        // transform: skewX(-38deg);
        background-color: rgba(0, 77, 103, 85%);
        z-index: -1;
      }
    }
    .device-active {
      // color: #0efcff;
      &::before {
        border-color: #0efcff;
        box-shadow: 1px 1px 3px 1px #0efcff inset;
      }
    }
  }
</style>
