<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="开票登记"
    :okText="okText"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    :confirmLoading="loading"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field]  }}{{fileFlow.type}}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { InvoiceRegister } from '/@/api/order';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';
  import { ResultEnum } from '/@/enums/httpEnum';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const fileFlow = reactive({
        file:null,
        type:2,//2-普通发票，3-专用发票
      })
      const okText = ref('发送')
      const loading = ref(false)
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
          {
            field: 'id',
            component: 'Input',
            show:false,
            label: '发票编号',
            required: true,
          },
          {
            field: 'email',
            component: 'Input',
            label: '邮箱',
            slot: 'text',
            ifShow:fileFlow.type == 2,
            componentProps: {
              maxLength: 50,
            },
            colProps: {
              span: 24,
            },
          },{
            field: 'invoiceNum',
            component: 'Input',
            label: '发票编号',
            required: true,
            componentProps: {
              maxLength: 50,
            },
            colProps: {
              span: 24,
            },
          },{
            field: 'file',
            component: 'Upload',
            label: '电子发票',
            ifShow:fileFlow.type == 2,
            required: true,
            rules: [{ required: true, message: t('common.uploadMessge') }],
            itemProps: {
              validateTrigger: 'blur',
            },
            componentProps: {
              api: uploadApi,
              fileFlow:true,
              maxNumber: 1,
              maxSize: 1000,
              accept: ['jpeg','jpg','png'],
              afterFetch: function (data) {
                console.log('url',data)
                // Reflect.set(data, 'url', data.file);
                fileFlow.file = data.file
                return data;
              },
            },

            colProps: {
              span: 22,
            },
          },{
            field: 'invoiceNum',
            component: 'Input',
            label: '发票编号',
            required: true,
            componentProps: {
              maxLength: 50,
            },
            colProps: {
              span: 24,
            },
          },{
            field: 'shipNum',
            component: 'Input',
            ifShow:fileFlow.type == 3,
            label: '快递单号',
            componentProps: {
              maxLength: 50,
            },
            required: true,
            colProps: {
              span: 24,
            },
          },
      ];

      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 120,
        schemas:schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      function onDataReceive(data) {
        resetFields();
        fileFlow.type = data.type
        setFieldsValue(data);
        okText.value = fileFlow.type == 2?'发送':'确认'
        updateSchema([
          {field: 'shipNum',ifShow:fileFlow.type == 3,},
          {field: 'email',ifShow:fileFlow.type == 2,},
          {field: 'file',ifShow:fileFlow.type == 2,},
        ])
      }
      const handleSubmit = async () => {
        loading.value = true
        try {
          const params = await validate();
          const apiData = {
            data:fileFlow.type == 3?{
              id:params.id,
              invoiceNum:params.invoiceNum,
              shipNum:params.shipNum,
            }:{
              id:params.id,
              invoiceNum:params.invoiceNum,
              file:fileFlow.file,
            // file:params.file[0],
            }
          }
          console.log('res', apiData,params);
          await InvoiceRegister(apiData);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
          loading.value = false
        } catch (error) {
          loading.value = false
          console.log('not passing', error);
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        registerForm,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        okText,
        loading,
        t,
      };
    },
  });
</script>
