<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    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>
      </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 { EditAndUpload, } 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: 'id',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },{
          field: 'type',
          component: 'Input',
          label: t('routes.product.types'),
          show: false,
          colProps: {
            span: 24,
          },
        },{
          field: 'name',
          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,
          },
          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'),
          required: true,
          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'),
          componentProps: {
            rows:4,
          },
          colProps: {
            span: 24,
          },
        },
        // {
        //   field: 'file',
        //   component: 'Upload',
        //   label: t('routes.product.file'),
        //   required: true,
        //   rules: [{ required: true, message: t('common.uploadMessge') }],
        //   itemProps: {
        //     validateTrigger: 'onBlur',
        //   },
        //   componentProps: {
        //     api: uploadApi,
        //     maxNumber: 1,
        //     maxSize: 1000,
        //     fileFlow:true,
        //     accept: ['4dage'],
        //     afterFetch: function (data) {
        //       console.log('uploadApi',data)
        //       Reflect.set(data, 'url', data.file);
        //       fileFlow.file = data.file
        //       return data;
        //     },
        //   },
      ];
      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('onDataReceive',data)
        resetFields();
        setFieldsValue({
          ...data,
          type:renderOwnTypeLabel(Number(data.type)),
        });
      }
      const handleSubmit = async () => {
        try {
          const params = await validate();
          console.log('modelRef',params)
          const apiData = {
            // ...modelRef.value,
            ...params as any,
          }
          console.log('res', apiData);
          const res = await EditAndUpload(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>
