<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
    wrapClassName="custom-modal-box"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addIotDic, getIotLinkList, updateIotDic } from '/@/api/iot';
  import { getDatabaselinkTree, getDatabaselinkTable } from '/@/api/system/databaselink';
  const { t } = useI18n();

  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: t('字典名称'),
      required: true,
      component: 'Input',
      componentProps: {
        placeholder: t('请输入字典名称'),
      },
      colProps: { span: 24 },
    },
    {
      field: 'linkId',
      label: t('链接'),
      required: true,
      component: 'ApiSelect',
      componentProps: {
        api: getIotLinkList,
        // use name as label
        labelField: 'name',
        // use id as value
        valueField: 'id',
        getPopupContainer: () => document.body,
      },
      colProps: { span: 24 },
    },

    // {
    //   field: 'getStr',
    //   label: t('取值方式'),
    //   required: true,
    //   component: 'Input',
    //   componentProps: {
    //     placeholder: t('请输入取值方式'),
    //   },
    //   colProps: { span: 24 },
    // },
    {
      field: 'trans',
      label: t('转换'),
      component: 'RadioButtonGroup',
      defaultValue: 0,
      componentProps: {
        options: [
          { label: '无', value: 0 },
          { label: '过滤', value: 1 },
          { label: '开方', value: 2 },
          { label: '线性', value: 3 },
          { label: '偏移', value: 4 },
        ],
      },
      colProps: { span: 24 },
    },
    {
      field: 'transValue',
      label: () => {
        return getFieldsValue().trans === 1 ? '死区' : '转换对应值';
      },
      component: 'Input',
      helpMessage: `如果转换类型选择为 线性
      填写 格式为 1-20:5-100 代表
      原始最小值为    1
      原始最大值为    20
      工程最小值为    5
      工程最大值为    100 `,
      dynamicDisabled: ({ values }) => {
        return values.trans === 0;
      },
      componentProps: {
        style: { width: '100%' },
      },
      colProps: { span: 24 },
    },
    {
      field: 'saveType',
      label: t('保存类型'),
      component: 'RadioButtonGroup',
      defaultValue: 0,
      componentProps: {
        options: [
          { label: '无', value: 0 },
          { label: '改变', value: 1 },
          { label: '间隔', value: 2 },
          { label: '每次采集记录', value: 3 },
        ],
      },
      colProps: { span: 24 },
    },
    {
      field: 'saveValue',
      label: () => {
        const saveType = getFieldsValue().saveType;
        return saveType === 1 ? '死区' : saveType === 2 ? '每' : t('对应值');
      },
      component: 'Input',
      dynamicDisabled: ({ values }) => {
        return values.saveType === 0;
      },
      ifShow: ({ values }) => {
        return values.saveType !== 3;
      },
      componentProps: ({ formModel }) => {
        return {
          style: { width: '100%' },
          addonAfter: formModel.saveType === 2 ? '毫秒' : '',
        };
      },
      colProps: { span: 24 },
    },
    {
      field: 'saveDb',
      label: t('存储库'),
      required: true,
      component: 'ApiSelect',
      componentProps: {
        api: getDatabaselinkTree,
        // use name as label
        labelField: 'dbName',
        // use id as value
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: (val) => {
          updateSchema({
            field: 'saveTable',
            componentProps: {
              api: getDatabaselinkTable,
              params: { id: val },
            },
          });
        },
      },
      colProps: { span: 24 },
    },
    {
      field: 'saveTable',
      label: t('存储表'),
      component: 'ApiSelect',
      required: true,
      componentProps: {
        labelField: 'tableName',
        valueField: 'tableName',
        getPopupContainer: () => document.body,
      },
      colProps: { span: 24 },
    },
  ];
  const emit = defineEmits(['success']);
  const isUpdate = ref(true);
  const { notification } = useMessage();
  const rowId = ref('');
  const groupId = ref('');

  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, getFieldsValue }] =
    useForm({
      layout: 'vertical',
      schemas: formSchema,
      showActionButtonGroup: false,
    });

  const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, width: '600px', destroyOnClose: true });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      groupId.value = data.record.groupId;

      updateSchema([
        {
          field: 'saveTable',
          componentProps: {
            api: getDatabaselinkTable,
            params: { id: data.record.saveDb },
          },
        },
      ]);
      setFieldsValue({
        ...data.record,
      });
    } else {
      groupId.value = data.groupId;
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? t('新增数据字典') : t('编辑数据字典')));

  async function handleSubmit() {
    try {
      const values = await validate();

      setModalProps({ confirmLoading: true });
      values.groupId = groupId.value;
      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增

        await addIotDic(values);
        notification.success({
          message: t('提示'),
          description: t('新增数据字典成功'),
        }); //提示消息
      } else {
        values.id = rowId.value;
        await updateIotDic(values);
        notification.success({
          message: t('提示'),
          description: t('编辑数据字典成功'),
        }); //提示消息
      }
      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
<style lang="less" scoped>
  :deep(.ant-radio-group) {
    display: flex;

    .ant-radio-button-wrapper {
      flex: 1;
      text-align: center;
      padding: 0;
    }
  }
</style>
