<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :confirmLoading="loading"
    title="编辑版本"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px">
      <BasicForm @register="registerForm" :model="model" >
        <template #text="{ model, field }">
          {{ model[field]  }}
        </template>
        <template #Checkbox="{ model, field }">
          <div>
            <Checkbox v-model:checked="model[field]">(勾选此项，将在四维看看官网置顶)</Checkbox>
          </div>
        </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 { Checkbox  } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { uploadApi, SpaceSdkUpdate } from '/@/api/product/index';
  import { isEmojiCharacter } from '/@/utils';

  const { t } = useI18n();
  export default defineComponent({
    components: { BasicModal, BasicForm, Checkbox },
    props: {
      userData: { type: Object },
    },
    emits: ['update', 'register'],
    setup(props, { emit }) {
      const modelRef = ref({});
      const loading = ref(false)
      const fileFlow = reactive({
        file:null
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'fileUrl',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },{
          field: 'id',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },{
          field: 'platformType',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },{
          field: 'type',
          component: 'Input',
          label: t('routes.product.types'),
          slot: 'text',
          colProps: {
            span: 24,
          },
        },
        {
          field: 'version',
          component: 'Input',
          label: t('routes.product.version'),
          required: true,
          colProps: {
            span: 24,
          },
          rules: [
            {
              required: true,
              // @ts-ignore
              validator: async (rule, value) => {
                if (!value?.trim()) {
                  return Promise.reject(t('common.inputText')+t('routes.product.version'));
                }
                if(/.*[\u4e00-\u9fa5]+.*$/.test(value)){
                  /* eslint-disable-next-line */
                  return Promise.reject('不支持中文字符');
                }
                if(isEmojiCharacter(value)){
                  /* eslint-disable-next-line */
                  return Promise.reject('不支持emoji表情');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          componentProps: {
            disabled:true,
            maxLength: 15,
            onChange: (data) => {
              console.log('data', data);
            },
          },
        },
        {
          field: 'imprintCh',
          component: 'InputTextArea',
          // required: true,
          label: t('routes.product.description_zh'),
          componentProps: {
            rows:4,
          },
          colProps: {
            span: 24,
          },
        },
        {
          field: 'imprintEn',
          component: 'InputTextArea',
          // required: true,
          label: t('routes.product.description_en'),
          componentProps: {
            rows:4,
          },
          colProps: {
            span: 24,
          },
        },
        {
          field: 'isTop',
          component: 'CheckboxGroup',
          label: '官网置顶',
          slot:'Checkbox',
          componentProps: {
            options: [
              { label: '(勾选此项，将在四维看看官网置顶)', value: 1 },
            ],
          },
          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) => {
        console.log('useModalInner',data)
        data && onDataReceive(data);
      });
      function renderOwnTypeLabel(type: number): string {
        switch (type) {
          case 2:
            return t('routes.product.sdkType.2');
          case 1:
            return t('routes.product.sdkType.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
        let setData = {
          ...data,
          type:renderOwnTypeLabel(Number(data.type)),
        }
        console.log('onDataReceive',data,setData)
        resetFields();
        setFieldsValue(setData);
      }
      const handleSubmit = async () => {
        loading.value = true
        try {
          const params = await validate();
          console.log('modelRef',params)
          const apiData = {
            // ...modelRef.value,
            ...params as any,
            isTop:params.isTop?1:0
          }
          console.log('res', apiData);
          const res = await SpaceSdkUpdate(apiData);
          console.log('res', res);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          emit('update');
          loading.value = false
        } catch (error) {
          loading.value = false
          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,
        loading,
        t,
      };
    },
  });
</script>
