<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="t('routes.retailer.setName')"
    @visible-change="handleVisibleChange"
    :confirmLoading="loading"
    @cancel="resetFields"
    width="650px"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <div class="name" style="line-height: 43px;">{{t('routes.retailer.form.dqname')}}：{{ modelRef.name }}</div>
      <BasicForm @register="registerForm">
        <template #text="{ model, field }">
          {{ model[field] }}
        </template>
        <template #type="{ model, field }">
          {{ renderOwnTypeLabel(Number(model[field])) }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, 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 { useI18n } from '/@/hooks/web/useI18n';
  import { isEmojiCharacter } from '/@/utils';
  import { useUserStore } from '/@/store/modules/user';
  import { addIncrementNum } from '/@/api/retailer';
  import { useLocaleStore } from '/@/store/modules/locale';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const loading = ref(false);
      const fileFlow = reactive({
        file: null,
      });
      const userStore = useUserStore();
      const { getUserInfoAction } = userStore
      const isDev = computed(() => userStore.getSystemEnv);
      const localeStore = useLocaleStore();
      const isEn = computed(() => localeStore.getLocale === 'en');
      const agent = computed(() => userStore.getAgent);
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'id',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },
        // {
        //   field: 'name',
        //   component: 'Input',
        //   label: t('routes.retailer.form.dqname'),
        //   slot: 'text',
        //   colProps: {
        //     span: 24,
        //   },
        // },
        {
          field: 'majorAddNum',
          component: 'InputNumber',
          label: t('routes.retailer.majorAddNum', {value: agent.value.majorSubNum}),
          defaultValue: 0,
          colProps: {
            span: 22,
          },
        },
        {
          field: 'highAddNum',
          component: 'InputNumber',
          label: t('routes.retailer.highAddNum', {value: agent.value.highSubNum}),
          defaultValue: 0,
          ifShow: isDev.value,
          colProps: {
            span: 22,
          },
        },
        {
          field: 'downAddNum',
          component: 'InputNumber',
          label: t('routes.retailer.downAddNum', {value: agent.value.downSubNum}),
          defaultValue: 0,
          colProps: {
            span: 22,
          },
        },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue, updateSchema }] = useForm({
        labelWidth: isEn.value ? 470 : 330,
        labelAlign: 'left',
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });
      onMounted(() => {});
      let addListFunc = () => {};
      const [register, { closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });
      function renderOwnTypeLabel(type: number): string {
        switch (type) {
          case 9:
            return t('routes.product.type.2');
          case 1:
            return t('routes.product.type.1');
          case 10:
            return t('routes.product.type.3');
          case 11:
            return t('routes.product.type.11');
          default:
            return '';
        }
      }
      function onDataReceive(data) {
        modelRef.value = data;
        console.log('onDataReceive', data);
        resetFields();
        setTimeout(() => {
          updateSchema([
            {
              field: 'majorAddNum',
              label: t('routes.retailer.majorAddNum', {value: agent.value.majorSubNum}),
              componentProps: {
                max: agent.value.majorSubNum,
                min: 0,
              },
            },
            {
              field: 'highAddNum',
              label: t('routes.retailer.highAddNum', {value: agent.value.highSubNum}),
              componentProps: {
                max: agent.value.highSubNum,
                min: 0,
              },
              ifShow: isDev.value,
            },
            {
              field: 'downAddNum',
              label: t('routes.retailer.downAddNum', {value: agent.value.downSubNum}),
              componentProps: {
                max: agent.value.downSubNum,
                min: 0,
              },
            },
          ]);
        }, 500);
        setFieldsValue({
          ...data,
          downAddNum: 0,
          majorAddNum: 0,
          highAddNum: 0,
        });
      }
      const handleSubmit = async () => {
        loading.value = true;
        try {
          const params = await validate();
          console.log('modelRef', params);
          const apiData = {
            // ...modelRef.value,
            ...(params as any),
          };
          console.log('res', apiData);
          const res = await addIncrementNum(apiData);
          console.log('res', res);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
          getUserInfoAction();
          loading.value = false;
        } catch (error) {
          console.log('not passing', error);
          loading.value = false;
        }
      };
      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }
      return {
        register,
        renderOwnTypeLabel,
        schemas,
        loading,
        registerForm,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
        modelRef,
      };
    },
  });
</script>
