<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]  }}
        </template>
      </BasicForm>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick, onMounted, reactive } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { uploadApi, AddAndUpload } from '/@/api/product/index';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const fileFlow = reactive({
        file:null
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'type',
          component: 'Input',
          label: t('routes.product.types'),
          slot: 'text',
          colProps: {
            span: 24,
          },
          // required: true,
        },
        {
          field: 'version',
          component: 'Input',
          label: t('routes.product.version'),
          required: true,
          colProps: {
            span: 24,
          },
          componentProps:{
            maxLength: 15,
            placeholder:t('common.inputText')+t('routes.product.versionPlaceholder'),
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value) {
                  return Promise.reject(t('common.inputText')+t('routes.product.version'));
                }
                if(/.*[\u4e00-\u9fa5]+.*$/.test(value)){
                  /* eslint-disable-next-line */
                  return Promise.reject('不支持中文字符');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          componentProps: {
            maxLength: 15,
            onChange: (data) => {
              console.log('data', data);
            },
          },
        },
        {
          field: 'minVersion',
          component: 'Input',
          label: t('routes.product.minVersion'),
          componentProps:{
            maxLength: 15,
            placeholder:t('common.inputText')+t('routes.product.minVersion')+t('routes.product.versionTips'),
          },
          rules: [
            {
              // required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                const regPos = /.*[\u4e00-\u9fa5]+.*$/; // 非中文
                if (!value) {
                  return Promise.reject(t('common.inputText')+t('routes.product.minVersion'));
                }
                if (regPos.test(value)) {
                  /* eslint-disable-next-line */
                  return Promise.reject('不支持中文字符');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 24,
          },
        },
        {
          field: 'description',
          component: 'InputTextArea',
          // required: true,
          label: t('routes.product.description'),
          colProps: {
            span: 24,
          },
          componentProps:{
            placeholder:t('common.inputText')+t('routes.product.description'),
            rows:4,
            maxLength: 200,
          },
        },
        {
          field: 'file',
          component: 'Upload',
          label: t('routes.product.file'),
          required: true,
          rules: [{ required: true, message: t('common.uploadMessge') }],
          // helpMessage: t('routes.corporation.uploadHelp'),
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            maxSize: 1000,
            fileFlow:true,
            accept: ['zip'],
            afterFetch: function (data) {
              console.log('uploadApi',data)
              // Reflect.set(data, 'url', data.file);
              fileFlow.file = data.file
              return data;
            },
          },

          colProps: {
            span: 22,
          },
        },
        // {
        //   field: 'orderSn',
        //   component: 'Input',
        //   label: t('routes.devices.orderSn'),
        //   colProps: {
        //     span: 24,
        //   },
        // },
        // {
        //   field: 'companyId',
        //   component: 'ApiSelect',
        //   label: t('routes.devices.companyId'),
        //   itemProps: {
        //     validateTrigger: 'blur',
        //   },
        //   componentProps: {
        //     api: allCompanyApi,
        //     numberToString: true,
        //     labelField: 'name',
        //     valueField: 'id',
        //     immediate: true,
        //     params: {
        //       page: 1,
        //       limit: 1000,
        //     },
        //   },
        //   colProps: {
        //     span: 24,
        //   },
        // },
      ];
      const [registerForm, { validate, resetFields, setFieldsValue }] = useForm({
        labelWidth: 120,
        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 2:
            return t('routes.product.type.2');
          case 1:
            return t('routes.product.type.1');
          case 3:
            return t('routes.product.type.3');
          default:
            return '';
        }
      }
      function rendercameraTypeLabel(cameraType: number): string {
        switch (cameraType) {
          case 4:
            return t('routes.devices.cameraName.4');
          case 1:
            return t('routes.devices.cameraName.1');
          case 9:
            return t('routes.devices.cameraName.9');
          case 10:
            return t('routes.devices.cameraName.10');
          case 6:
            return t('routes.devices.cameraName.6');
          default:
            return '';
        }
      }
      function onDataReceive(data) {
        modelRef.value = data
        console.log('renderOwnTypeLabel',data)
        resetFields();
        setFieldsValue({
          type:renderOwnTypeLabel(Number(data)),
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          const apiData = {
            data:{
            ...params as any,
            type:modelRef.value,
            file:fileFlow.file,
            }
          }
          console.log('res', apiData);
          const res = await AddAndUpload(apiData);
          console.log('res', res);
          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,
        rendercameraTypeLabel,
        renderOwnTypeLabel,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        t,
      };
    },
  });
</script>
