<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="新增"
    :confirmLoading="loading"
    @visible-change="handleVisibleChange"
    @cancel="resetFields"
    :width="550"
    :min-height="680"
    @ok="handleSubmit"
  >
    <div class="pt-2px pr-3px" style="width:600px">
      <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 { uploadApi, tipUpdata } from '/@/api/product/index';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isEmojiCharacter } from '/@/utils';
  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({
        type:null
      })
      const { createMessage } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'typeText',
          component: 'Input',
          label: '设备类型',
          required: true,
          slot:'text',
          componentProps: {
            maxLength: 15,
          },
          colProps: {
            span: 20,
          },
        },{
          field: 'version',
          component: 'Input',
          label: '版本号',
          required: true,
          componentProps: {
            maxLength: 15,
          },
          colProps: {
            span: 20,
          },
        },{
          field: 'timeList',
          label: '提示时段',
          component: 'RangePicker',
          required: true,
          componentProps: {
            format: 'YYYY-MM-DD',
            valueFormat:'YYYY-MM-DD',
            width:100,
          },
          colProps: {            
            span: 20,
          },
        },
        {
          field: 'title',
          component: 'Input',
          label: '中文标题',
          required: true,
          colProps: {
            span: 20,
          },
          componentProps: {
            maxLength: 50,
          },
        },
        {
          field: 'description',
          component: 'InputTextArea',
          required: true,
          label: t('routes.product.description_zh'),
          componentProps: {
            maxLength:500,
            rows:4,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'imageUrl',
          component: 'Upload',
          label: '中文图片/视频',
          // helpMessage: t('routes.corporation.uploadHelp'),
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            maxSize: 1000,
            accept: ['jpeg','jpg','png','mp4'],
          },

          colProps: {
            span: 20,
          },
        },
        {
          field: 'infoUrl',
          component: 'Input',
          label: '中文详情链接',
          rules: [
            {
              required: false,
              // @ts-ignore
              validator: async (rule, value) => {
                var reg=/(http|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#\u4e00-\u9fa5]*[\w\-\@?^=%&/~\+#])/;
                if (value && !reg.test(value)) {
                  return Promise.reject(t('common.inputText')+'正确的地址');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 20,
          },
        },{
          field: 'titleEn',
          component: 'Input',
          label: '英文标题',
          required: true,
          colProps: {
            span: 20,
          },
          componentProps: {
            maxLength: 50,
          },
        },
        {
          field: 'descriptionEn',
          component: 'InputTextArea',
          required: true,
          label: t('routes.product.description_en'),
          componentProps: {
            maxLength:500,
            rows:4,
          },
          colProps: {
            span: 20,
          },
        },
        {
          field: 'imageUrlEn',
          component: 'Upload',
          label: '英文图片/视频',
          // helpMessage: t('routes.corporation.uploadHelp'),
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: uploadApi,
            maxNumber: 1,
            maxSize: 1000,
            accept: ['jpeg','jpg','png','mp4'],
          },

          colProps: {
            span: 20,
          },
        },
        {
          field: 'infoUrlEn',
          component: 'Input',
          label: '英文详情链接',
          rules: [
            {
              required: false,
              // @ts-ignore
              validator: async (rule, value) => {
                var reg=/(http|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&:/~\+#\u4e00-\u9fa5]*[\w\-\@?^=%&/~\+#])/;
                if (value && !reg.test(value)) {
                  return Promise.reject(t('common.inputText')+'正确的地址');
                }
                return Promise.resolve();
              },
              trigger: 'change',
            },
          ],
          colProps: {
            span: 20,
          },
        },
      ];
      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 0:
            return '四维看看';
          case 1:
            return '四维深时'
          case 2:
            return '四维全景';
          case 3:
            return '四维带看';
          case 4:
            return '四维深光';
          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
        fileFlow.type = data
        resetFields();
        setFieldsValue({
          type:data,
          typeText:renderOwnTypeLabel(Number(data)),
        });
      }
      const handleSubmit = async () => {
        loading.value = true
        try {
          const params = await validate();
          const apiData = {
            ...params,
            type:fileFlow.type,
            imageUrl:params.imageUrl?.[0],
            imageUrlEn:params.imageUrlEn?.[0],
          }
          console.log('res', apiData);
          const res = await tipUpdata(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));
      }
      function IsURL(str_url){
        var strRegex = "^((https|http|ftp|rtsp|mms)?://)" 
        + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp的user@ 
          + "(([0-9]{1,3}.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184 
          + "|" // 允许IP和DOMAIN（域名）
          + "([0-9a-z_!~*'()-]+.)*" // 域名- www. 
          + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." // 二级域名 
          + "[a-z]{2,6})" // first level domain- .com or .museum 
          + "(:[0-9]{1,4})?" // 端口- :80 
          + "((/?)|" // a slash isn't required if there is no file name 
          + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; 
          var re=new RegExp(strRegex); 
        //re.test()
          if (re.test(str_url)){
          return (true); 
          }else{ 
          return (false); 
          }
        }
      return {
        register,
        rendercameraTypeLabel,
        renderOwnTypeLabel,
        schemas,
        registerForm,
        model: modelRef,
        fileFlow,
        handleVisibleChange,
        handleSubmit,
        loading,
        addListFunc,
        resetFields,
        t,
      };
    },
  });
</script>
<style lang="less">
.ant-calendar-picker-input.ant-input{
  width: 300px;
}
</style>
