<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.equity.renew')"
    height="500"
    @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 { useUserStore } from '/@/store/modules/user';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { renewApi } from '/@/api/equity/index';
  import dayjs from 'dayjs';

  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-专用发票
        validTimeType: 0,
        incrementEndTime:'',
      })
      const { createMessage } = useMessage();
      const userStore = useUserStore();
      const agent = computed(() => userStore.getAgent);
      const schemas: FormSchema[] = [
          {
            field: 'userName',
            component: 'Input',
            label: t('routes.equity.userName'),
            slot: 'text',
            colProps: {
              span: 24,
            },
          },{
            field: 'id',
            component: 'Input',
            label: t('routes.equity.id'),
            slot: 'text',
            colProps: {
              span: 24,
            },
          },{
            field: 'totalTime',            
            component: 'Select',
            label: t('routes.equity.totalTime'),
            required: true,
            suffix:`${t('routes.equity.syks')} ${agent.value.majorSubNum} ${t('routes.equity.unit.1')}`,
            defaultValue:1,
            itemProps: {
              validateTrigger: 'onBlur',
            },
            componentProps: {
              options:[],
              listHeight: 150,
              onChange:(value)=>{
                setFieldsValue({
                  incrementEndTime:dayjs(fileFlow.incrementEndTime || new Date()).add(value,fileFlow.validTimeType == 0?'year':'month').format('YYYY-MM-DD')
                });
              }
            },
            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: 22,
            },
          }
      ];

      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);
      });
      async function onDataReceive(data) {
        resetFields();
        // let detail = await InvoiceDetail({id:data.id})
        console.log('data',data)
        fileFlow.type = data.type
        fileFlow.validTimeType = data.validTimeType
        fileFlow.incrementEndTime = data.incrementEndTime
        updateSchema([{
                  field: 'totalTime',
                  suffix:`${t('routes.equity.syks')} ${data.validTimeType == 1?agent.value.highSubNum:agent.value.majorSubNum} ${data.validTimeType == 1?t('routes.equity.unit.-2'):t('routes.equity.unit.-1')}`, 
                  componentProps: {
                    options: timeOption(data.validTimeType)
                  },
                }])
        setFieldsValue({
          ...data,
          incrementEndTime:dayjs(data.isExpired == 1?new Date():data.incrementEndTime).add(1,data.validTimeType == 0?'year':'month').format('YYYY-MM-DD')
        });
      }
      function timeOption(incrementTypeId) {
        let list = []
        let timeVal = incrementTypeId == 1?agent.value.highSubNum:agent.value.majorSubNum
        let value = 10, unit = t('routes.equity.unit.-1')
        if(incrementTypeId == 1){//高级会员月
          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
      }
      const handleSubmit = async () => {
          const params = await validate();
          await renewApi(params);
          createMessage.success(t('common.optSuccess'));
          closeModal();
          emit('update',true);
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        registerForm,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
      };
    },
  });
</script>
