<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-专用发票
      validTimeType: 0,
    });
    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',
          style: 'width:200px',
          // 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);
              const res = await checkUserName({ userName: value });
              //await checkUserName({userName:value})
              // useThrottleFn(,50)()
              console.log('validator', res);
              if (!res) {
                return Promise.reject(t('routes.equity.rules.userName2'));
              }
              return Promise.resolve();
            },
            trigger: 'blur',
          },
        ],
        colProps: {
          span: 19,
        },
      },
      {
        field: 'incrementTypeId',
        component: 'ApiSelect',
        label: t('routes.equity.Type'),
        required: true,
        componentProps: {
          maxLength: 50,
          style: 'width:200px',
          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) => {
            let { totalTime, count = 1 } = getFieldsValue();
            updateSchema([
              {
                field: 'incrementTypeId',
                suffix: `${t('routes.equity.syks')} ${
                  value == 3 ? agent.value.highSubNum : agent.value.majorSubNum
                } ${value == 3 ? t('routes.equity.unit.-2') : t('routes.equity.unit.-1')}`,
              },
              {
                field: 'count',
                componentProps: {
                  max: value == 3 ? agent.value.highSubNum : agent.value.majorSubNum,
                  min: 1,
                },
              },
              {
                field: 'totalTime',
                suffix:
                  totalTime && count
                    ? `${t('routes.equity.jjxs')} ${totalTime * count} ${
                        value == 3 ? t('routes.equity.unit.-2') : t('routes.equity.unit.-1')
                      }`
                    : '',
                componentProps: {
                  options: timeOption(value),
                },
              },
            ]);
            setFieldsValue({
              count: 1,
              incrementEndTime: dayjs()
                .add(totalTime ? totalTime : 1, value != '3' ? 'year' : 'month')
                .format('YYYY-MM-DD'),
            });
          },
        },
        colProps: {
          span: 23,
        },
      },
      {
        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: 'change',
        },
        componentProps: {
          max: agent.value.majorSubNum,
          min: 1,
          onChange: (value) => {
            let { incrementTypeId, totalTime } = getFieldsValue();
            console.log('totalTime', totalTime);
            updateSchema([
              {
                field: 'totalTime',
                suffix:
                  totalTime && value
                    ? `${t('routes.equity.jjxs')} ${value * totalTime} ${
                        incrementTypeId == 3
                          ? t('routes.equity.unit.-2')
                          : t('routes.equity.unit.-1')
                      }`
                    : '',
              },
            ]);
          },
        },
        colProps: {
          span: 24,
        },
      },
      {
        field: 'totalTime',
        component: 'Select',
        label: t('routes.equity.totalTime'),
        required: true,
        itemProps: {
          validateTrigger: 'change',
        },
        componentProps: {
          options: [],
          listHeight: 150,
          style: 'width:200px',
          onChange: (value) => {
            let { incrementTypeId, count = 1 } = getFieldsValue();

            updateSchema([
              {
                field: 'totalTime',
                suffix:
                  value && count
                    ? `${t('routes.equity.jjxs')} ${value * count} ${
                        incrementTypeId == 3
                          ? t('routes.equity.unit.-2')
                          : t('routes.equity.unit.-1')
                      }`
                    : '',
              },
            ]);
            setFieldsValue({
              incrementEndTime: dayjs(fileFlow.incrementEndTime || new Date())
                .add(value, incrementTypeId != 3 ? 'year' : 'month')
                .format('YYYY-MM-DD'),
            });
          },
        },
        colProps: {
          span: 23,
        },
      },
      {
        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, getFieldsValue }] =
      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();
      console.log('validTimeType', data);
      fileFlow.type = data.type;
      fileFlow.validTimeType = data.validTimeType;
      setFieldsValue(data);
      updateSchema([
        { field: 'shipNum', ifShow: fileFlow.type == 3 },
        { field: 'email', ifShow: fileFlow.type == 2 },
        { field: 'file', ifShow: fileFlow.type == 2 },
        { field: 'incrementTypeId', suffix: '' },
        { field: 'totalTime', suffix: '' },
        {
          field: 'count',
          componentProps: {
            max: agent.value.majorSubNum,
            min: 1,
          },
        },
      ]);
    }
    const handleSubmit = async () => {
      // try {
      const params = await validate();
      console.log('params', params);
      let timeVal = params.incrementTypeId == 3 ? agent.value.highSubNum : agent.value.majorSubNum;
      if (params.count * params.totalTime > timeVal) {
        createMessage.error(t('routes.equity.totalMessge'));
        return;
      }
      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));
    }
    function timeOption(incrementTypeId) {
      let list = [];
      let timeVal = incrementTypeId == 3 ? agent.value.highSubNum : agent.value.majorSubNum;
      let value = 10,
        unit = t('routes.equity.unit.-1');
      if (incrementTypeId == 3) {
        //高级会员月
        value = timeVal > 12 ? 12 : timeVal;
        unit = t('routes.equity.unit.-3');
      } else {
        value = timeVal > 10 ? 10 : timeVal;
      }
      for (let index = 1; index <= value; index++) {
        list.push({
          label: index + unit,
          value: index,
          key: index,
        });
      }
      return list;
    }
    return {
      register,
      registerForm,
      fileFlow,
      handleVisibleChange,
      handleSubmit,
      addListFunc,
      resetFields,
      timeOption,
      t,
    };
  },
});
</script>
