<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="tsx" setup>
  import { ref, computed, unref, h } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { addDemo, getDemo, updateDemo } from '/@/api/code/demo';
  import { Input } from 'ant-design-vue';
  import { getPostList } from '/@/api/system/post';

  const accountFormSchema: FormSchema[] = [
    {
      field: 'fieldString',
      label: '字符串',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
    },
    {
      label: '联动字符串',
      field: 'fieldString111',
      component: 'ApiSelect',
      required: true,
      componentProps: {
        api: getPostList,
        // use name as label
        labelField: 'name',
        // use id as value
        valueField: 'id',
        getPopupContainer: () => document.body,
        onChange: () => {
          console.log('sssssssssss');
        },
      },
      // width: 120,
    },
    {
      field: 'fieldInt',
      label: '整型',
      component: 'InputNumber',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'fieldDouble',
      label: '浮点',
      component: 'InputNumber',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'fieldLong',
      label: '长整型',
      component: 'InputNumber',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'sortCode',
      label: '排序',
      component: 'InputNumber',
      required: true,
      colProps: { span: 24 },
    },

    {
      label: '备注',
      field: 'remark',
      component: 'InputTextArea',
      colProps: { span: 24 },
    },
    {
      label: '部门',
      field: 'dept',
      component: 'Dept',
      required: true,
      colProps: { span: 24 },
    },
    {
      label: '用户',
      field: 'user',
      component: 'User',
      required: true,
      colProps: { span: 24 },
    },
    {
      label: '信息体',
      field: 'info',
      component: 'Info',
      required: true,
      colProps: { span: 24 },
      componentProps: { infoType: 0 },
    },
    {
      label: '区域',
      field: 'area',
      component: 'Area',
      required: true,
      colProps: { span: 24 },
      componentProps: { initFetchParams: { id: '0' } },
    },
    {
      label: '子表单',
      field: 'subform',
      component: 'SubForm',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        mainKey: 'subform',
        columns: [
          {
            title: '字符串',
            dataIndex: 'fieldString',
            componentType: 'Input',
            defaultValue: 111,
            rules: [
              {
                required: true,
                message: '子表单组件验证案例',
              },
            ],
            // width: 120,
          },
          {
            title: '整型',
            dataIndex: 'fieldInt',
            componentType: 'Switch',
            rules: [
              {
                required: true,
                message: '子表单组件验证案例',
              },
            ],
            defaultValue: true,
            componentProps: {
              checked: true,
              onChange: function () {
                console.log('子表单组件事件案例');
              },
            },
            // width: 120,
          },
          {
            title: '时间',
            dataIndex: 'fieldDatetimeStart,fieldDatetimeEnd',
            componentType: 'RangePicker',
            defaultValue: ['2022-06-15', '2022-06-18'],
            componentProps: {
              placeholder: ['开始时间', '结束时间'],
            },
            // width: 120,
          },
          {
            title: '合并',
            dataIndex: 'xxxx',
            children: [
              {
                title: '浮点',
                dataIndex: 'fieldDouble',
                componentType: 'Switch',
                // width: 120,
              },
              {
                title: '长整数',
                dataIndex: 'fieldLong',
                componentType: 'Render', //如果使用自定义渲染  必须设置componentType === 'Render'
                rules: [
                  {
                    required: true,
                    message: '子表单组件验证案例',
                  },
                ],
                componentProps: {
                  xxxx: ['xxxx', 'xxxx'],
                },
                render: ({ model, field, rules, componentProps }) => {
                  const handleChange = (e: ChangeEvent) => {
                    model[field] = e.target.value;
                    console.log('参数有', model, field, rules, componentProps);
                  };

                  // tsx写法

                  // return (
                  //   <Input
                  //     placeholder="请输入"
                  //     v-model:value={model[field]}
                  //     onChange={handleChange}
                  //   ></Input>
                  // );

                  //渲染函数写法
                  return h(Input, {
                    placeholder: '请输入11111111',
                    value: model[field],
                    onChange: handleChange,
                  });
                },
                // width: 180,
              },
              {
                title: '备注',
                dataIndex: 'remark',
                componentType: 'IconPicker',
              },
            ],
            // width: 120,
          },
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
          },
        ],
      },
    },
  ];

  const emit = defineEmits(['close', 'register']);

  const { notification } = useMessage();

  const isUpdate = ref(true);
  const rowId = ref('');
  const { t } = useI18n();

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });

    console.log('useModalInner', data);

    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getDemo(data.id);

      setFieldsValue({
        user: '1,2',
        dept: '1419276791701966848',
        info: '2',
        area: '130000,130100',
        ...record,
      });
    }

    if (data.id) {
      //ssss
      type.value = data.id;
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增用户' : '编辑用户'));

  async function handleSubmit() {
    try {
      const values = await validate();
      console.log('handleSubmit', values);
      return;
      setModalProps({ confirmLoading: true });

      // TODO custom api
      if (!unref(isUpdate)) {
        //false 新增
        await addDemo(values);
        notification.success({
          message: 'Tip',
          description: t('新增成功！'),
        }); //提示消息
      } else {
        values.id = rowId.value;
        await updateDemo(values);
        notification.success({
          message: 'Tip',
          description: t('修改成功！'),
        }); //提示消息
      }

      closeModal();
      emit('close');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
