<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="fileFlow.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 } 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 { currencyList, dincrementList, AddUserIncrementApi, AddDownNumApi } from '/@/api/account';
  import dayjs from 'dayjs';
  import { remarkschemas, Addschemas } from "./data";
  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 fileFlow = reactive({
        file: null,
        id: '',
        type: 'down', //down-下载，equity-权益
        title: '新增下载',
      });
      const { createMessage, createConfirm } = useMessage();
      const schemas: FormSchema[] = [
        ...Addschemas,
        // {
        //   field: 'id',
        //   component: 'Input',
        //   show: false,
        //   label: 'id',
        // },
        {
          field: 'count',
          component: 'InputNumber',
          label: '新增次数',
          required: true,
          componentProps: {
            min: 1,
          },
          colProps: {
            span: 22,
          },
        },
        {
          field: 'amount',
          component: 'InputNumber',
          label: '订单金额',
          required: true,
          colProps: {
            span: 16,
          },
          componentProps: {
            precision: 2,
            min: 0,
            step: 1
          },
        },
        {
          field: 'currencySymbol',
          component: 'ApiSelect',
          required: true,
          label: '币种',
          defaultValue: userStore.isEnv ? '' : 'CNY',
          componentProps: {
            // filterOption: onFilterOption,
            // showSearch: true,
            api: currencyList,
            labelField: 'name',
            valueField: 'symbol',
            immediate: true,
          },
          colProps: {
            span: 20,
          },
        },
        ...remarkschemas,
      ];

      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);
        updateSchema([
          {
            field: 'useType',
            componentProps: {
              onChange: useTypeChange,
            },
          },
          {
            field: 'projectNum',
            ifShow: false,
          },
        ]);
        useTypeChange(0)
      });
      async function onDataReceive(data) {
        const res = await dincrementList();
        console.log('onDataReceive', data, res);
        resetFields();
        fileFlow.type = data.type;
        fileFlow.id = data.id;
        // fileFlow.title = data.type == '1' ? '新增下载（四维深时）' : '新增下载（四维看看）';
        // setFieldsValue(data);
      }
      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' },
        ]);
      };
      async function handleConfirm() {
        await validate();
        createConfirm({
          iconType: 'warning',
          title: () => h('span', '温馨提示'),
          content: () => h('span', `确定要新增下载次数吗？`),
          onOk: async () => {
            handleSubmit();
          },
        });
      }
      const handleSubmit = async () => {
        const submitUrl = AddDownNumApi;
        try {
          const params = await validate();
          console.log('validate', params);
          const res = await submitUrl({ userId: fileFlow.id, ...params }); //downType:fileFlow.type,
          overviewInfo.value.surDownNum = overviewInfo.value.surDownNum + params.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,
        handleConfirm,
        t,
      };
    },
  });
</script>

<style lang="less">
  .zdysrk {
    .ant-calendar-picker {
      min-width: 285px;
    }
  }
</style>
