<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.equity.add')"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @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, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { dincrementList, checkUserName, addApi } from '/@/api/equity'
  import { useUserStore } from '/@/store/modules/user';
  import dayjs from 'dayjs';

  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 userStore = useUserStore();
      const { createMessage } = useMessage();
      const agent = computed(() => userStore.getAgent);
      const schemas: FormSchema[] = [
          {
            field: 'userName',
            component: 'Input',
            label: t('routes.equity.userName'),
            required: true,
            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'));
                  }
                  // useThrottleFn(handleSplitLeftMenu, 50);
                  let res = await checkUserName({userName:value})
                  //await checkUserName({userName:value})
                  // useThrottleFn(,50)()
                  if(!res){
                    return Promise.reject(t('routes.equity.rules.userName2'));
                  }
                  return Promise.resolve();
                },
                trigger: 'blur',
              },
            ],
            colProps: {
              span: 16,
            },
        },{
            field: 'incrementTypeId',
            component: 'ApiSelect',
            label: t('routes.equity.Type'),
            required: true,
            componentProps: {
              maxLength: 50,
              api: async function () {
                const list = await dincrementList();
                return list.map(ele => {
                  return {name:t(`routes.finance.equityType.${ele.validTimeType}`),value:ele.id}
                });
              },
              numberToString: true,
              labelField: 'name',
              valueField: 'value',
              immediate: true,
              params: {
                agentName: '',
              },
              onChange:(value)=>{
                updateSchema([{
                  field: 'count',
                  suffix:`${t('routes.equity.syks')} ${value == 3?agent.value.highSubNum:agent.value.majorSubNum} ${t('routes.equity.unit.1')}`, 
                  componentProps: {
                    max:value == 3?agent.value.highSubNum:agent.value.majorSubNum,
                    min:1,
                  },
                }])
                setFieldsValue({
                  count:1,
                  incrementEndTime: dayjs().add(1,value!='3'?'year':'month').format('YYYY-MM-DD'),
                });
              }
              },
            colProps: {
              span: 16,
            },
          },{
            field: 'count',
            component: 'InputNumber',
            label: t('routes.equity.countNumber'),
            required: true,
            suffix:`${t('routes.equity.syks')} ${agent.value.majorSubNum} ${t('routes.equity.unit.1')}`,
            defaultValue:1,
            itemProps: {
              validateTrigger: 'onBlur',
            },
            componentProps: {
              max:agent.value.majorSubNum,
              min:1,
            },
            colProps: {
              span: 19,
            },
          },{
            field: 'incrementEndTime',
            component: 'DatePicker',
            label: t('routes.equity.expiryTime'),
            required: true,
            defaultValue:dayjs().add(1,'year').format('YYYY-MM-DD'),
            componentProps: {
              disabled:true,
              valueFormat: 'YYYY-MM-DD',
              format: 'YYYY-MM-DD',
              disabledDate: (current) => {
                return current && current < dayjs().endOf('day');
              },
            },
            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);
        updateSchema([
          {field: 'shipNum',ifShow:fileFlow.type == 3,},
          {field: 'email',ifShow:fileFlow.type == 2,},
          {field: 'file',ifShow:fileFlow.type == 2,},
          {field: 'count',suffix:`${t('routes.equity.syks')} ${agent.value.majorSubNum} ${t('routes.equity.unit.1')}`,componentProps:{
              max:agent.value.majorSubNum,
              min:1,
            }},
        ])
      }
      const handleSubmit = async () => {
        // try {
          const params = await validate();
          await addApi(params);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update',true);
        // } catch (error) {
        //   console.log('not passing', error);
        // }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        registerForm,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
      };
    },
  });
</script>
