<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="新增权益"
    @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 { InvoiceRegister } from '/@/api/order';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi } from '/@/api/product/index';
  import { ResultEnum } from '/@/enums/httpEnum';
  import { DetailsApi, dincrementList, AddUserIncrementApi, AddDownNumApi } from '/@/api/account';
  import dayjs from 'dayjs';
  import { otherInfoStore } from '/@/store/modules/other'

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const otherInfo = otherInfoStore();
      const overviewInfo = computed(() => otherInfo.getOverviewInfo);
      // const overviewInfo = getOverviewInfo() || {}
      const fileFlow = reactive({
        file:null,
        id:'',
        type:'down',//down-下载，equity-权益
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
          {
            field: 'id',
            component: 'Input',
            show:false,
            label: 'id',
          },
          {
            field: 'incrementTypeId',
            component: 'ApiSelect',
            label: '权益类型',
            required: true,
            componentProps: {
            api: async function () {
              const res = await dincrementList();
              return res.map(ele => {
                return {name:ele.name,value:ele.id}
              });
            },
            numberToString: true,
            labelField: 'name',
            valueField: 'value',
            immediate: true,
            params: {
              agentName: '',
            },
            onChange:(value)=>{
              console.log('onChange',value)
              updateSchema([{field: 'monthQy',ifShow:value=='3',},
                            {field: 'incrementEndTime',componentProps: { disabled:value=='3',}}])
              setFieldsValue({
                monthQy:1,
                incrementEndTime: dayjs().add(1,value=='3'?'month':'year').format('YYYY-MM-DD'),
              });
            }
          },
            // componentProps: {
            //   options: [
            //     {
            //       label: '专业会员',
            //       value: 'PR',
            //       key: '0',
            //     },
            //     {
            //       label: '高级会员',
            //       value: 'SE',
            //       key: '1',
            //     },
            //   ],
            //   onChange: (incrementTypeId) => {
            //     updateSchema([{field: 'monthQy',ifShow:incrementTypeId=='SE',},
            //                   {field: 'incrementEndTime',componentProps: { disabled:incrementTypeId=='SE',}}])
            //     setFieldsValue({
            //       monthQy:1,
            //       incrementEndTime: dayjs().add(1,incrementTypeId=='SE'?'month':'year').format('YYYY-MM-DD'),
            //     });
            //   },
            // },
            colProps: {
              span: 20,
            },
          },
          {
            field: 'counts',
            component: 'InputNumber',
            label: '新增权益数',
            required: true,
            defaultValue:1,
            componentProps: {
              min:1,
            },
            colProps: {
              span: 20,
            },
          },
          {
            field: 'monthQy',
            component: 'Select',
            label: '会员期限',
            required: true,
            defaultValue:1,
            componentProps: {
              options: [
                {
                  label: '1个月',
                  value: 1,
                  key: '1',
                },{
                  label: '2个月',
                  value: 2,
                  key: '2',
                },{
                  label: '3个月',
                  value: 3,
                  key: '3',
                },{
                  label: '4个月',
                  value: 4,
                  key: '4',
                },{
                  label: '5个月',
                  value: 5,
                  key: '5',
                },{
                  label: '6个月',
                  value: 6,
                  key: '6',
                },
              ],
              onChange: (data) => {
                setFieldsValue({
                  incrementEndTime: dayjs().add(data,'month').format('YYYY-MM-DD'),
                });
              },
            },
            colProps: {
              span: 20,
            },
          },
          {
            field: 'incrementEndTime',
            component: 'DatePicker',
            label: '到期日期',
            required: true,
            defaultValue:dayjs().add(1,'month').format('YYYY-MM-DD'),
            componentProps: {
              disabled:false,
              valueFormat: 'YYYY-MM-DD',
              format: 'YYYY-MM-DD',
              disabledDate: (current) => {
                return current && current < dayjs().endOf('day');
              },
            },
          }
      ];

      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) {
        const res = await dincrementList();
        console.log('onDataReceive',data,res)
        resetFields();
        fileFlow.type = data.type
        fileFlow.id = data.id
        setFieldsValue(data);
      }
      const handleSubmit = async () => {
        const submitUrl = AddUserIncrementApi
        try {
          const params = await validate();
          console.log('validate',params)
          const apiData = {
              ...params,
              userId:params.id,
              incrementEndTime:params.incrementEndTime,
              count:params.counts,
            }
          const res = await submitUrl(apiData);
          overviewInfo.value.incrementCount = overviewInfo.value.incrementCount + apiData.count
          console.log('res', res);
          otherInfo.updateOverviewInfo()
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
        } 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>
