<template>
  <BasicModal v-bind="$attrs" @register="register" title="发货" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, reactive } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form/index';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { ShippingListApi, sendGoods, GetOrderInfoApi } from '/@/api/order/list'; //GetOrderInfoApi

  export default defineComponent({
    name: 'ConfirmModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register', 'reload'],
    setup(_, { emit }) {
      // const isUpdate = ref(true);
      let modalRecord = reactive({
        id: 0,
        brandId: 0,
      });
      const formSchema: FormSchema[] = [
        {
          field: 'shippingId',
          label: '快递公司',
          component: 'ApiSelect',
          componentProps: {
            api: ShippingListApi,
            resultField: 'list',
            labelField: 'name',
            valueField: 'id',
            immediate: true,
            onChange: function (_, opt) {
              Reflect.set(modalRecord, 'shippingName', opt.label);
            },
            params: {
              page: 1,
              limit: 1000,
            },
            required: true,
          },
        },
        {
          field: 'orderSn',
          label: '快递单号',
          component: 'Input',
          required: true,
          componentProps: {
            maxLength: 100,
          },
        },
      ];
      const [registerForm, { validate, resetFields }] = useForm({
        labelWidth: 120,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 20, md: 20, offset: 1 },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      function onDataReceive(data) {
        console.log('data', data);
        modalRecord = { ...data };
        // modalRecord.brandId = data.brandId;
      }
      async function handleSubmit() {
        console.log('handleSubmit');
        try {
          const values = await validate();
          const orderInfo = await GetOrderInfoApi({
            id: modalRecord.id,
            brandId: modalRecord.brandId,
          });
          Reflect.set(modalRecord, 'shippingNo', values.orderSn);
          Reflect.set(modalRecord, 'shippingId', values.shippingId);
          await sendGoods({ ...orderInfo, ...modalRecord });
          resetFields();
          closeModal();
          emit('reload');
        } catch (error) {}
      }

      return {
        register,
        registerForm,
        handleSubmit,
        closeModal,
      };
    },
  });
</script>
