<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.equity.addDowm')"
    height="500"
    width="550px"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
        <template #img="{ model }">
          <TableImg
            v-if="model.invoiceUrl"
            :size="200"
            :adaptations="true"
            :simpleShow="true"
            :imgList="[model.invoiceUrl]"
          />
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, nextTick, onMounted, reactive, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { TableImg } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { InvoiceRegister, InvoiceDetail } from '/@/api/order';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';
  import { ResultEnum } from '/@/enums/httpEnum';
  import dayjs from 'dayjs';
  import { checkjxsUserName, addDowm } from '/@/api/equity';
  import { useUserStore } from '/@/store/modules/user';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, TableImg },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const fileFlow = reactive({
        file: null,
        type: 2, //2-普通发票，3-专用发票
      });
      const userStore = useUserStore();
      const agent = computed(() => userStore.getAgent);
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'userName',
          component: 'Input',
          label: t('routes.equity.userName'),
          required: true,
          itemProps: {
            autoLink: false, // 添加该属性即可解决多触发一次 validator，value 为空值 
          },
          componentProps: {
            autoComplete: 'off',
            // readonly:preventAutoFill.value
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                console.log('value', value);
                // const regEmail = /^(.+)@(.+)$/;
                // const regPos = /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/; // 非中文
                if (!value) {
                  return Promise.reject(t('routes.equity.rules.userName'));
                }
                // if (!(regPos.test(value) || regEmail.test(value))) {
                //   /* eslint-disable-next-line */
                //     return Promise.reject(t('routes.equity.rules.userName1'));
                // }
                const res = await checkjxsUserName({ userName: value });
                if (!res) {
                  return Promise.reject(t('routes.equity.rules.userName2'));
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 16,
          },
        },
        {
          field: 'count',
          component: 'InputNumber',
          label: t('routes.equity.addcount'),
          required: true,
          suffix: `${t('routes.equity.syks')} ${agent.value.downSubNum} ${t(
            'routes.equity.unit.2',
          )}`,
          // defaultValue:1,
          componentProps: {
            max: agent.value.downSubNum,
            min: 1,
          },
          colProps: {
            span: 23,
          },
        },
      ];

      const [registerForm, { validate, resetFields, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        resetFields();
        updateSchema([
          {
            field: 'count',
            suffix: `${t('routes.equity.syks')} ${agent.value.downSubNum} ${t(
              'routes.equity.unit.2',
            )}`,
            componentProps: {
              max: agent.value.downSubNum,
              min: 1,
            },
          },
        ]);
        // data && onDataReceive(data);
      });
      async function onDataReceive() {
        resetFields();
      }
      const handleSubmit = async () => {
        const values = await validate();
        const res = await addDowm(values);
        console.log('res', res);
        closeModal();
        emit('update', true);
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        registerForm,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
      };
    },
  });
</script>
