<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter/vxe-table';

import { confirm, useVbenDrawer, useVbenModal } from '@vben/common-ui';

import { ElButton, ElMessage } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { cdcmDriverAPI } from '#/cdcm/api/api.js';
import req from '#/cdcm/api/req_code';
import { deviceTemplate } from '#/store';

import AddDevice from './addDevice.vue';
import EditDevice from './editDevice.vue';

// const template_data = ref<TemplateDateType>();

const gridOptions: VxeGridProps<any> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name', // 修改为实际的字段名，原代码中是 productName 可能不正确
  },
  columns: [
    { title: '序号', type: 'seq', width: 100 },
    { field: 'Name', title: '设备名称' },
    { field: 'ProtocolExt.salve_id', title: '设备ID' },
    { field: 'Description', title: '设备描述' },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '管理',
      width: 240,
    },
  ],
  proxyConfig: {
    ajax: {
      query: () => {
        return {
          items: getDeviceData(),
        };
      },
    },
  },
  exportConfig: {},
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    zoom: true,
  },
  pagerConfig: {
    enabled: false,
  },
  round: true,
  showOverflow: true,
};

const [PointTable, tableApi] = useVbenVxeGrid({
  gridOptions,
});
const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = drawerApi.getData<any>();
      if (data) {
        getDeviceData();
        const type = data.data.type;
        get_template_types(type);
      }
    }
  },
});

const [addDeviceModal, addApi] = useVbenModal({
  connectedComponent: AddDevice,
});
const [editDeviceModal, editApi] = useVbenModal({
  connectedComponent: EditDevice,
});

async function get_template_types(type: String) {
  const res = await cdcmDriverAPI(
    { driver_type: type },
    req.DriverTemplateQuery,
  );
  const templateList = [];
  res.data.data.forEach((ele) => {
    const obj = {
      label: ele.Name,
      value: ele.ID,
    };
    templateList.push(obj);
  });
  console.warn(23, templateList);
  deviceTemplate().setData(templateList);
}

// 编辑
const btn_edit = (row: any) => {
  const list = {
    ...row,
    id: row.ID,
    driver_id: row.DriverID,
    driver_type: drawerApi.getData<any>().data.type,
  };
  editApi.setData({ data: list }).open();
};

// 删除
const btn_delete = (row: any) => {
  showConfirm(row.ID);
};

function showConfirm(rowId: Number) {
  confirm('确认删除该设备？')
    .then(async () => {
      const ret = await cdcmDriverAPI({ id: rowId }, req.DeviceDelete);
      if (ret.data.code === 0) {
        ElMessage.success(ret.data.data);
        tableApi.reload();
      } else {
        ElMessage.error(ret.data.data || ret.data.msg);
      }
    })
    .catch(() => {});
}
function btn_add() {
  // 这里添加新增设备的逻辑
  addApi.setData({ data: drawerApi.getData<any>() }).open();
}

async function getDeviceData() {
  const deviceId = drawerApi.getData<any>().data.id;
  const res = await cdcmDriverAPI({ id: deviceId }, req.DriverQuery);
  console.warn(res.data.data);
  tableApi.setGridOptions({
    data: res.data.data.Devices,
  });
}
</script>

<template>
  <Drawer title="设备管理" :footer="false" class="w-[1500px]">
    <div class="vp-raw w-full" style="height: 600px">
      <PointTable>
        <template #toolbar-tools>
          <ElButton class="mr-2" type="success" @click="btn_add">
            新增
          </ElButton>
          <ElButton
            class="mr-2"
            type="primary"
            @click="() => tableApi.reload()"
          >
            刷新当前页面
          </ElButton>
        </template>
        <template #action="{ row }">
          <ElButton size="small" type="primary" round @click="btn_edit(row)">
            编辑
          </ElButton>
          <ElButton size="small" type="danger" round @click="btn_delete(row)">
            删除
          </ElButton>
        </template>
      </PointTable>
    </div>
    <addDeviceModal />
    <editDeviceModal />
  </Drawer>
</template>
