<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="新增APP"
    @visible-change="handleVisibleChange"
    :confirmLoading="loading"
    @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, reactive, nextTick, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { AppFileAdd, AppFileUpload } from '/@/api/product/index';
  import { TreeNode } from '/@/utils/treeUtils';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { AppFileAgentList } from '/@/api/product'

  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 uploadData = reactive({
        md5:'',
        name:'',
        versionName:'',
      })
      const { createMessage,mes } = useMessage();
      const schemas: FormSchema[] = [
        {
          field: 'fileServerType',
          label: '上传服务器',
          component: 'RadioButtonGroup',
          defaultValue: 'oss',
          required: true,
          componentProps: {
            options: [
              { label: '阿里云', value: 'oss' },
              { label: '亚马逊', value: 'aws' },
            ],
          },
        },{
          field: 'agent',
          component: 'ApiSelect',
          required: true,
          label: '代理商标识',
          componentProps: {
            api: async function (params) {
              const res = (await AppFileAgentList(params)) as any as TreeNode[];
              return res.map(ele => {
                return {name:ele,value:ele}
              });
            },
            numberToString: true,
            labelField: 'name',
            valueField: 'value',
            immediate: true,
            params: {
              agentName: '',
            },
          },
          colProps: {
            span: 22,
          },
        },{
          field: 'appType',
          label: 'APP类型',
          component: 'RadioButtonGroup',
          defaultValue: 'Android',
          required: true,
          componentProps: {
            options: [
              { label: 'Android', value: 'Android' },
              { label: 'IOS', value: 'IOS' },
            ],
          },
        },
        {
          field: 'file',
          component: 'Upload',
          label: 'APP包',
          required: true,
          rules: [{ required: true, message: t('common.uploadMessge') }],
          helpMessage: ['1、支持 .ipa、.apk文件，大小不超过1G','2、文件格式以4DKanKan+_版本号组成'],
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: AppFileUpload,
            maxNumber: 1,
            maxSize: 1000,
            accept: ['ipa','apk'],
            afterFetch: function (data) {
              console.log('uploadApi',data)
              const {fileName,md5} = data
              uploadData.md5 = md5
              uploadData.name = fileName
              setFieldsValue({
                md5:md5
              })
              return fileName;
            },
          },
          colProps: {
            span: 22,
          },
        },{
          field: 'md5',
          component: 'Input',
          label: 'md5',
          colProps: {
            span: 22,
          },
          componentProps: {
            disabled:true,
          },
          rules: [
            {
            required: true,
            // @ts-ignore
            validator: async (rule, value) => {
              if (!value) {
                return Promise.reject('请输入md5!');
              }
              console.log('value',value)
              if (value !== uploadData.md5) {
              //   /* eslint-disable-next-line */
                return Promise.reject('MD5输入有误!');
              }
              return Promise.resolve();
            },
            trigger: 'change',
          },
          ],
          required: true,
        },
        {
          field: 'version',
          component: 'Upload',
          label: '版本信息',
          required: true,
          rules: [
            {
            required: true,
            // @ts-ignore
            validator: async (rule, value) => {
              if (!value) {
                /* eslint-disable-next-line */

                return Promise.reject(t('common.uploadMessge'));
              }
              console.log('value',value)
              if (value && value[0] !== 'version.json') {
              //   /* eslint-disable-next-line */
                return Promise.reject('仅能上传version.json文件');
              }
              return Promise.resolve();
            },
            trigger: 'change',
          },
          ],
          helpMessage: ['仅能上传version.json文件，且不超过10 M'],
          itemProps: {
            validateTrigger: 'onBlur',
          },
          componentProps: {
            api: AppFileUpload,
            maxNumber: 1,
            maxSize: 10,
            accept: ['json'],
            afterFetch: function (data) {
              uploadData.versionName = data.fileName
              Reflect.set(data, 'url', data &&data.fileName);
              return data.fileName;
            },
          },
          colProps: {
            span: 22,
          },
        },
      ];
      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.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
        resetFields();
        setFieldsValue({
          type:renderOwnTypeLabel(Number(data)),
        });
      }
      const handleSubmit = async () => {
        loading.value = true
        try {
          const params = await validate();
          if('version.json' != uploadData.versionName ){
            return  createMessage.error('仅能上传version.json文件')
          }
          
          if(params.md5 != uploadData.md5 ){
            return  createMessage.error('您输入的MD5错误！')
          }
          const apiData = {
            ...params as any,
            md5:uploadData.md5,
            version:params.version[0],
            name:uploadData.name,
          }
          console.log('res', apiData);
          const res = await AppFileAdd(apiData);
          console.log('res', res);
          closeModal();
          resetFields();
          createMessage.success(t('common.optSuccess'));
          loading.value = false
          emit('update');
        } 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,
        handleVisibleChange,
        handleSubmit,
        addListFunc,
        resetFields,
        uploadData,
        loading,
        t,
      };
    },
  });
</script>
