<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 { cdcmTemplateAPI } from '#/cdcm/api/api.js';
import req from '#/cdcm/api/req_code';

import AddPoint from './addPoint.vue';
import EditPoint from './editPoint.vue';

interface PointDataType {
  id: number;
  name: string;
  point_type: string;
  description: string;
  access: string;
  calculation: string;
  unit: string;
  protocol_config: string;
}

interface TemplateDateType {
  description: string;
  id: number;
  name: string;
  point_count: number;
  points: PointDataType[];
  type: string;
}

interface TemplateType {
  data: TemplateDateType;
}

// 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: 'point_type', title: '点位类型' },
    { field: 'description', title: '点位描述' },
    { field: 'access', title: '读写权限' },
    { field: 'calculation', title: '计算公式' },
    { field: 'unit', title: '单位' },
    { field: 'protocol_config', title: '扩展配置' },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '管理',
      width: 240,
    },
  ],
  proxyConfig: {
    ajax: {
      query: () => {
        return {
          items: getPointData(),
        };
      },
    },
  },
  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<TemplateType>();
      if (data) {
        getPointData();
      }
    }
  },
});
const [addPointModal, addApi] = useVbenModal({
  connectedComponent: AddPoint,
  onclose: () => {
    tableApi.reload();
  },
});
const [editPointModal, editApi] = useVbenModal({
  connectedComponent: EditPoint,
  onclose: () => {
    tableApi.reload();
  },
});

// 编辑
const btn_edit = (row: TemplateType) => {
  const list = {
    ...row,
    template_id: drawerApi.getData<TemplateType>().data.id,
    template_type: drawerApi.getData<TemplateType>().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 cdcmTemplateAPI({ id: rowId }, req.PointDelete);
      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<TemplateType>() }).open();
}

async function getPointData() {
  const templateId = drawerApi.getData<TemplateType>().data.id;
  const res = await cdcmTemplateAPI({ id: templateId }, req.TemplateQuery);
  tableApi.setGridOptions({
    data: res.data.data.points,
  });
}
</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>
    <addPointModal />
    <editPointModal />
  </Drawer>
</template>
