<template>
  <BasicForm @register="registerForm"> </BasicForm>
</template>
<script setup lang="ts">
  import { watch, nextTick } from 'vue';
  import { FormSchema } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { searDkbm } from '../api';

  const props = defineProps({
    data: {
      type: Object,
      default: {},
    },
    showFooter: {
      type: Boolean,
      default: true,
    },
  });
  const formSchema: FormSchema[] = [
    {
      label: '地块名称',
      field: 'dkmc',
      required: true,
      component: 'Input',
      componentProps: {
        disabled: true,
      },
    },
    {
      label: '地块编码',
      field: 'dkbm',
      required: true,
      component: 'ApiSelect',
      dynamicDisabled: () => {
        return !props.showFooter;
      },
      componentProps: ({ formModel, formActionType }) => {
        return {
          showSearch: true,
          api: searDkbm,
          params: { wrdkbm: '' },
          labelField: 'remark',
          valueField: 'wrdkbm',
          onChange: async (val) => {
            const { updateSchema } = formActionType;
            formModel.dkmc = undefined;
            if (val) {
              formModel.dkmc = await getDkbm(val);
              updateSchema({
                label: '地块名称',
                field: 'dkmc',
                required: true,
                component: 'Input',
                componentProps: {
                  disabled: true,
                },
              });
            }
          },
        };
      },
    },
  ];
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
    labelWidth: 220,
    schemas: formSchema,
    showActionButtonGroup: false,
    //默认row行配置,当 layout 为 horizontal 生效
    rowProps: { gutter: 24, justify: 'start', align: 'middle' },
    //全局col列占比(每列显示多少位)，和schemas中的colProps属性一致
    baseColProps: { span: 12 },
    //使用labelCol的样式参数来控制标题宽度
    labelCol: { style: { width: '150px' } },
    //row行的样式
    baseRowStyle: { width: '100%' },
    //表单布局属性，支持（vertical,horizontal），默认为horizontal
    layout: 'horizontal',
  });
  //表单赋值
  watch(
    () => props.data,
    async (val: any) => {
      if (val) {
        //重置表单
        await nextTick();
        await resetFields();

        await setFieldsValue({
          ...val,
        });
      }
    },
    { deep: true, immediate: true }
  );
  // 获取地块编码

  async function getDkbm(val) {
    const res = await searDkbm({ wrdkbm: val });
    let dkmc = '';

    res.forEach((v) => {
      if (v.wrdkbm == val) dkmc = v.wrdkmc;
    });
    return dkmc;
  }

  // 获取子组件 列表
  async function getFormValue() {
    //获取所有值
    let fieldsValue = await getFieldsValue();
    fieldsValue = await validate();
    return fieldsValue;
  }

  // 通过ref必须把在父组件里面的方法导出
  defineExpose({
    getFormValue,
  });
</script>
