<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="title"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    minHeight="900px"
    @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,
    getAddUserIncrementTime,
    currencyList,
  } from '/@/api/account';
  import dayjs from 'dayjs';
  import { otherInfoStore } from '/@/store/modules/other';
  import { useUserStore } from '/@/store/modules/user';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const otherInfo = otherInfoStore();
      const userStore = useUserStore();
      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,
          itemProps: {
            autoLink: false,
          },
          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' ? '个月' : '年';
              let incrementEndTime = dayjs()
                .add(1, value == '3' ? 'month' : 'year')
                .format('YYYY-MM-DD');
              updateSchema([
                {
                  field: 'monthQy',
                  ifShow: true,
                  componentProps: { options: showOptions(value == '3' ? 12 : 5) },
                },
                { field: 'count', suffix: count * monthQy + unitStr },
                {
                  field: 'incrementEndTime',
                  componentProps: {
                    // disabledDate: (current) => {
                    //   return current && current < dayjs().subtract(1, 'day').add(1, value == '3' ? 'month' : 'year');
                    // },
                  },
                },
              ]);
              setFieldsValue({
                monthQy: 1,
                incrementEndTime: incrementEndTime,
              });
            },
          },
          // 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 = 1) => {
              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');
            },
          },
        },
        {
          field: 'amount',
          component: 'InputNumber',
          label: '订单金额',
          required: true,
          colProps: {
            span: 16,
          },
          componentProps: {
            precision: 2,
            min: 0,
            step: 1,
          },
        },
        {
          field: 'currencySymbol',
          component: 'ApiSelect',
          required: true,
          defaultValue: userStore.isEnv ? '' : 'CNY',
          label: '币种',
          componentProps: {
            // filterOption: onFilterOption,
            // showSearch: true,
            api: currencyList,
            labelField: 'name',
            valueField: 'symbol',
            immediate: true,
          },
          colProps: {
            span: 20,
          },
        },
      ];

      const [
        registerForm,
        { validate, getFieldsValue, resetFields, setFieldsValue, updateSchema, validateFields, scrollToField },
      ] = 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: useTypeChange,
            },
          },
          {
            field: 'incrementTypeId',
            componentProps: {
              disabled: data.id ? true : false,
            },
          },
          {
            field: 'projectNum',
            ifShow: data.useType == '4',
          },
          {
            field: 'count',
            ifShow: !data.id,
          },
          {
            field: 'incrementEndTime',
            componentProps: {
              disabled: data.id,
              valueFormat: 'YYYY-MM-DD',
              format: 'YYYY-MM-DD',
              disabledDate: (current) => {
                return current && current < dayjs(data.incrementEndTime).subtract(1, 'day');
              },
            },
          },
        ]);
        useTypeChange(data.useType || 0);
      });
      async function onDataReceive(data) {
        let incrementEndTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        if (data.incrementTypeId) {
          const res = await getAddUserIncrementTime({
            id: data.id,
            userId: data.userId,
            incrementTypeId: data.incrementTypeId,
          });
          incrementEndTime = dayjs(res.deadLine).format('YYYY-MM-DD HH:mm:ss');
        }
        title.value = data.id ? '续费权益' : '新增权益';
        resetFields();
        fileFlow.type = data.type;
        fileFlow.id = data.id;
        if(data.id){
          delete data.customerPayTime
        }
        setFieldsValue({
          ...data,
          incrementEndTime,
          // incrementEndTime: dayjs(incrementEndTime).add(1, data.incrementTypeId == '3' ? 'month' : 'year').format('YYYY-MM-DD'),
        });
      }
      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() {
        try {
          await validate();
          createConfirm({
            iconType: 'warning',
            title: () => h('span', '温馨提示'),
            content: () => h('span', `确定要${title.value}吗？`),
            onOk: async () => {
              handleSubmit();
            },
          });
        } catch (error) {
          console.log('validate', error);
          let errorFields = error?.errorFields[0];
          createMessage.error(errorFields?.errors[0]);
          // scrollToField(errorFields.name[0])
        }
        // let text = record.id ? `您确定给权益ID${record.id}续期${record.validTimeType == 1?'1月':'1年'}！`:`确定要${title.value}吗？`
        // createConfirm({
        //   iconType: 'warning',
        //   title: () => h('span', '续费提示'),
        //   content: () => h('span', `您确定给权益ID${record.id}续期${record.validTimeType == 1?'1月':'1年'}！`),
        //   onOk: async () => {
        //     await await IncrementDelayApi({id:record.id,year:1})
        //     createMessage.success(t('common.optSuccess'));
        //     otherInfo.updateOverviewInfo()
        //     reload()
        //   },
        // });
      }
      const useTypeChange = (value) => {
        updateSchema([
          { field: 'projectNum', ifShow: value == '4' },
          { field: 'companyName', ifShow: value != '3' },
          { field: 'businessDept', ifShow: value != '3' },
          { field: 'businessName', ifShow: value != '3' },
          { field: 'customerPayTime', ifShow: value != '3' },
          { field: 'customerName', ifShow: value != '3' },
          { field: 'customerType', ifShow: value != '3' },
          { field: 'endCustomer', ifShow: value != '3' },
        ]);
      };
      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>
