<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleConfirm"
  >
    <div class="pt-2px pr-3px zdysrk">
      <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, h, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { remarkschemas, Addschemas } from "./data";
  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 title = ref('新增权益')
      const fileFlow = reactive({
        file: null,
        id: '',
        type: 'down', //down-下载，equity-权益
      });
      const { createMessage, createConfirm } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          show: false,
          label: 'id',
        },
        {
          field: 'userId',
          component: 'Input',
          show: false,
          label: 'userId',
        },
        {
          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);
              let { monthQy = 1, count = 1 } = getFieldsValue()
              let unitStr = value == '3' ? '个月' : '年';
              updateSchema([
                { field: 'monthQy', ifShow: true, componentProps: { options: showOptions( value == '3' ? 12 : 5), } },
                { field: 'count', suffix: ( count * monthQy ) + unitStr }
              ]);
              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: 'monthQy',
          component: 'Select',
          label: '会员期限',
          ifShow: false,
          required: true,
          defaultValue: 1,
          componentProps: {
            options: showOptions(5),
            onChange: (data) => {
              let { incrementTypeId, count = 1 } = getFieldsValue()
              let unit = incrementTypeId == '3' ? 'month' : 'year'
              let unitStr = incrementTypeId == '3' ? '个月' : '年';
              updateSchema({ field: 'count', suffix: ( count * data ) + unitStr });
              setFieldsValue({
                incrementEndTime: dayjs().add(data, unit).format('YYYY-MM-DD'),
              });
            },
          },
          colProps: {
            span: 16,
          },
        },
        {
          field: 'count',
          component: 'InputNumber',
          label: '新增权益数',
          required: true,
          defaultValue: 1,
          componentProps: {
            min: 1,
            onChange: (data = 1) => {
              let { incrementTypeId, monthQy = 1 } = getFieldsValue();
              let unit = incrementTypeId == '3' ? '个月' : '年';
              updateSchema({ field: 'count', suffix: ( monthQy * data ) + unit });
            },
          },
          colProps: {
            span: 18,
          },
        },
        {
          field: 'incrementEndTime',
          component: 'DatePicker',
          label: '到期日期',
          required: true,
          defaultValue: dayjs().add(1, 'month').format('YYYY-MM-DD'),
          colProps: {
            span: 16,
          },
          componentProps: {
            disabled: true,
            valueFormat: 'YYYY-MM-DD',
            format: 'YYYY-MM-DD',
            disabledDate: (current) => {
              return current && current < dayjs().endOf('day');
            },
          },
        },
      ];

      const [registerForm, { validate, getFieldsValue, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: 120,
        schemas: [...Addschemas, ...schemas, ...remarkschemas],
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
        updateSchema([
          {
            field: 'useType',
            componentProps: {
              onChange: (value) => {
                updateSchema({ field: 'projectNum', ifShow: value == '4' });
              },
            },
          },
          {
            field: 'projectNum',
            ifShow: data.useType == '4',
          },
        ]);
      });
      async function onDataReceive(data) {
        const res = await dincrementList();
        console.log('onDataReceive', data, res);
        title.value = data.id ? '续费权益' : '新增权益';
        resetFields();
        fileFlow.type = data.type;
        fileFlow.id = data.id;
        setFieldsValue(data);
      }
      function showOptions(type = 5){
        let uint = type == 5 ? '年' : '个月'
        let arr = []
        for (let index = 0; index < type; index++) {
          arr.push({
            label: (index+1) + uint,
            value: index+1,
            key: index+1,
          });
        }
        return arr || []
      }
      async function handleConfirm() {
        await validate();
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '温馨提示'),
          content: () => h('span', `确定要新增权益吗？`),
          onOk: async () => {
            handleSubmit();
          },
        });
      }
      const handleSubmit = async () => {
        const submitUrl = AddUserIncrementApi;
        try {
          const params = await validate();
          console.log('validate', params);
          const apiData = {
            ...params,
          };
          const res = await submitUrl(apiData);
          overviewInfo.value.incrementCount = overviewInfo.value.incrementCount + apiData.count;
          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,
        handleConfirm,
        t,
        title,
      };
    },
  });
</script>
<style lang="less">
  .zdysrk {
    .ant-calendar-picker {
      min-width: 285px;
    }
  }
</style>
