<template>
  <!--引用表格-->
  <BasicTable @register="registerTable" :rowSelection="rowSelection" @selection-change="handleRowSelectionChange">
    <!--插槽:table标题-->
    <template #tableTitle>
      <a-button type="primary" v-auth="'deviceInfo:device_base_info:add'" v-if="!noOperate" @click="handleAdd" preIcon="ant-design:plus-outlined">
        新增
      </a-button>
      <a-button
        type="primary"
        v-auth="'deviceInfo:device_base_info:exportXls'"
        v-if="!noOperate"
        preIcon="ant-design:export-outlined"
        @click="onExportXls"
      >
        导出
      </a-button>
      <j-upload-button
        type="primary"
        v-auth="'deviceInfo:device_base_info:importExcel'"
        v-if="!noOperate"
        preIcon="ant-design:import-outlined"
        @click="onImportXls"
      >
        导入
      </j-upload-button>
      <a-dropdown v-if="selectedRowKeys.length > 0 && !noOperate">
        <template #overlay>
          <a-menu>
            <a-menu-item key="1" @click="batchHandleDelete">
              <Icon icon="ant-design:delete-outlined" />
              删除
            </a-menu-item>
          </a-menu>
        </template>
        <a-button v-auth="'deviceInfo:device_base_info:deleteBatch'">
          批量操作
          <Icon icon="mdi:chevron-down" />
        </a-button>
      </a-dropdown>
      <!-- 高级查询 -->
      <super-query :config="superQueryConfig" @search="handleSuperQuery" />
    </template>
    <!--操作栏-->
    <template #action="{ record }">
      <TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
    </template>
    <!--字段回显插槽-->
    <!-- <template v-slot:bodyCell="{ column, record, index, text }"> </template> -->
    <template #imageUrl="{ text }">
      <TableImg :size="60" :simpleShow="true" :imgList="text ? [getFileAccessHttpUrl(text.split(',')[0])] : []" />
    </template>
    <template #deviceNumber="{ record }">
      <a-badge-ribbon style="top: -20px" v-if="record.isSpecialEquip === true" color="red" text="特">
        <div>
          <a-button type="link" @click="handleRowClick(record)">{{ record.deviceNumber }}</a-button>
        </div>
      </a-badge-ribbon>
      <div v-else>
        <a-button type="link" @click="handleRowClick(record)">{{ record.deviceNumber }}</a-button>
      </div>
    </template>
    <template #isMeteringDevice="{ record }">
      <Icon icon="ant-design:check-outlined" class="zgztel-check-icon checked" v-if="record.isMeteringDevice === true" />
      <Icon icon="ant-design:close-outlined" class="zgztel-check-icon no-checked" v-else />
    </template>
    <template #isDepreciation="{ record }">
      <Icon icon="ant-design:check-outlined" class="zgztel-check-icon checked" v-if="record.isDepreciation === true" />
      <Icon icon="ant-design:close-outlined" class="zgztel-check-icon no-checked" v-else />
    </template>
  </BasicTable>
  <!-- 表单区域 -->
  <DeviceBaseInfoModal @register="registerModal" @success="handleSuccess" />
  <!-- 添加父、子级设备 -->
  <AddDeviceModal @register="registerParentDeviceModal" @success="handleSuccess" />
  <!-- 详情 -->
  <DeviceBaseInfoDetailDrawer @register="registerDetailDrawer" @success="handleSuccess" />
</template>

<script lang="ts" name="deviceInfo-deviceBaseInfo" setup>
  import { reactive } from 'vue';
  import { BasicTable, TableAction, TableImg } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import DeviceBaseInfoModal from './components/DeviceBaseInfoModal.vue';
  import { columns, searchFormSchema, superQuerySchema } from './DeviceBaseInfo.data';
  import { list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './DeviceBaseInfo.api';
  import AddDeviceModal from './components/AddDeviceModal.vue';
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
  import DeviceBaseInfoDetailDrawer from './components/DeviceBaseInfoDetailDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';

  const queryParam = reactive<any>({});

  const emits = defineEmits(['selection-change']);
  const props = defineProps<{
    noOperate?: boolean;
    superQueryParams?: any[];
  }>();

  //注册model
  const [registerModal, { openModal }] = useModal();
  // 添加父、子级设备
  const [registerParentDeviceModal, { openModal: openAddDeviceModal }] = useModal();
  // 注册详情抽屉
  const [registerDetailDrawer, detailDrawer] = useDrawer();
  //注册table数据
  const { tableContext, onExportXls, onImportXls } = useListPage({
    tableProps: {
      title: '设备基本信息',
      api: list,
      columns,
      canResize: false,
      formConfig: {
        // labelWidth: 100,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: true,
        fieldMapToNumber: [],
        fieldMapToTime: [],
      },
      showActionColumn: !props.noOperate,
      actionColumn: {
        width: 120,
        fixed: 'right',
      },
      beforeFetch: (params) => {
        if (props.noOperate === true) {
          let superQueryParamsArr: any[] = [];
          if (queryParam['superQueryParams']) {
            superQueryParamsArr = JSON.parse(decodeURIComponent(queryParam['superQueryParams']));
          }

          if (!queryParam['superQueryMatchType']) {
            queryParam['superQueryMatchType'] = 'and';
          }

          (props.superQueryParams || []).forEach((ele) => {
            const parentDeviceIdsIndex = superQueryParamsArr.findIndex((item) => {
              return item.field === ele.field;
            });
            if (parentDeviceIdsIndex !== -1) {
              superQueryParamsArr.splice(parentDeviceIdsIndex, 1, ele);
            } else {
              superQueryParamsArr.push(ele);
            }
          });

          queryParam['superQueryParams'] = encodeURIComponent(JSON.stringify(superQueryParamsArr));
        }
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: '设备基本信息',
      url: getExportUrl,
      params: queryParam,
    },
    importConfig: {
      url: getImportUrl,
      success: handleSuccess,
    },
  });

  const [registerTable, { reload, setSelectedRowKeys }, { rowSelection, selectedRowKeys }] = tableContext;

  // 高级查询配置
  const superQueryConfig = reactive(superQuerySchema);

  /**
   * 高级查询事件
   */
  function handleSuperQuery(params) {
    Object.keys(params).map((k) => {
      queryParam[k] = params[k];
    });
    reload();
  }
  /**
   * 新增事件
   */
  function handleAdd() {
    openModal(true, {
      isUpdate: false,
      showFooter: true,
    });
  }
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
      showFooter: true,
    });
  }
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    detailDrawer.openDrawer(true, record);
  }
  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '编辑',
        onClick: handleEdit.bind(null, record),
        auth: 'deviceInfo:device_base_info:edit',
      },
    ];
  }
  /**
   * 下拉操作栏
   */
  function getDropDownAction(record) {
    return [
      {
        label: '添加父设备',
        onClick: () => {
          openAddDeviceModal(true, {
            device: record,
            isUpdate: false,
            showFooter: true,
            addType: 1, // 父设备
          });
        },
        auth: 'deviceInfo:parent_device_info:add',
      },
      {
        label: '添加子设备',
        onClick: () => {
          openAddDeviceModal(true, {
            device: record,
            isUpdate: false,
            showFooter: true,
            addType: 2, // 子设备
          });
        },
        auth: 'deviceInfo:sub_device_info:add',
      },
      {
        label: '详情',
        onClick: handleDetail.bind(null, record),
      },
      {
        label: '删除',
        popConfirm: {
          title: '是否确认删除',
          confirm: handleDelete.bind(null, record),
          placement: 'topLeft',
        },
        auth: 'deviceInfo:device_base_info:delete',
      },
    ];
  }

  // 点击行
  const handleRowClick = (record) => {
    if (!props.noOperate) {
      detailDrawer.openDrawer(true, record);
    }
  };

  // 选择行
  const handleRowSelectionChange = (selectedInfo) => {
    if (props.noOperate) {
      emits('selection-change', selectedInfo);
    }
  };

  // 暴露方法
  defineExpose({
    setSelectedRowKeys,
  });
</script>

<style lang="less" scoped>
  :deep(.ant-picker),
  :deep(.ant-input-number) {
    width: 100%;
  }
</style>
