<script lang="ts" setup>
import { useVbenModal } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenForm } from '#/adapter/form';
import { cdcmDriverAPI } from '#/cdcm/api/api.js';
import req from '#/cdcm/api/req_code';
import { deviceTemplate } from '#/store';

const [Modal, modalApi] = useVbenModal({
  onCancel() {
    modalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = modalApi.getData<any>();
      console.warn(13, data.data.data.type);
    }
  },
});

const [TemplateForm] = useVbenForm({
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  // 提交函数
  handleSubmit: onSubmit,
  // 垂直布局，label和input在不同行，值为vertical
  // 水平布局，label和input在同一行
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',

      componentProps: {
        placeholder: '设备名称',
      },

      fieldName: 'name',
      label: '设备名称',
      rules: 'required',
    },
    {
      component: 'InputNumber',

      componentProps: {
        placeholder: '设备ID',
      },

      fieldName: 'salve_id',

      label: '设备ID',
      rules: 'required',
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        filterOption: true,
        options: deviceTemplate().support_device_template,
        placeholder: '模板ID',
        showSearch: true,
      },
      dependencies: {
        componentProps() {
          return {
            options: deviceTemplate().support_device_template,
          };
        },
        triggerFields: ['template_id'],
      },
      fieldName: 'template_id',
      label: '模板ID',
      rules: 'required',
    },
    {
      component: 'Input',

      componentProps: {
        placeholder: '设备描述',
      },
      fieldName: 'description',
      label: '设备描述',
    },
  ],
  wrapperClass: 'grid-cols-1',
});

async function onSubmit(values: Record<string, any>) {
  const data = modalApi.getData<any>();
  const param = {
    driver_id: data.data.data.id,
    template_id: values.template_id,
    driver_type: data.data.data.type,
    name: values.name,
    description: values.description,
    protocol_ext: {
      salve_id: values.salve_id,
    },
  };
  const ret = await cdcmDriverAPI(param, req.DeviceCreate);
  if (ret.data.code === 0) {
    ElMessage.success(ret.data.data);
    modalApi.close();
  } else {
    ElMessage.error(ret.data.data || ret.data.msg);
  }
}
</script>

<template>
  <Modal title="新增设备" :footer="false">
    <TemplateForm />
  </Modal>
</template>
