<template>
  <div class="transfer-config-mode">
    <BasicForm :showSubmitButton="false" @register="register">
      <template #uploadAdd1="{ field }">
        <span style="display: none">{{ field }}</span>
        <a-upload-dragger
          v-model:fileList="fileList1"
          name="file"
          :key="1"
          :multiple="false"
          @change="handleChange('T', $event)"
          :before-upload="() => false"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
          <p class="ant-upload-hint">
            支持扩展名：.jpeg .png .jpg ...
            <br />
            文件大小：最大支持5M
          </p>
        </a-upload-dragger>
      </template>
      <template #showImg1="{ field }">
        <span style="display: none">{{ field }}</span>
        <img
          v-if="showImg1"
          :src="showImg1Pic"
          alt="avatar"
          style="width: 6.25rem; height: 6.25rem"
        />
      </template>
      <div style="margin-top: 50px"></div>
      <template #uploadAdd2="{ field }">
        <span style="display: none">{{ field }}</span>
        <a-upload-dragger
          v-model:fileList="fileList2"
          name="file"
          :key="2"
          :multiple="false"
          @change="handleChange('F', $event)"
          :before-upload="() => false"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
          <p class="ant-upload-hint">
            支持扩展名：.jpeg .png .jpg ...
            <br />
            文件大小：最大支持5M
          </p>
        </a-upload-dragger>
      </template>
      <template #showImg2="{ field }">
        <span style="display: none">{{ field }}</span>
        <img
          v-if="showImg2"
          :src="showImg2Pic"
          alt="avatar"
          style="width: 6.25rem; height: 6.25rem"
        />
      </template>
      <div style="margin-top: 50px"></div>
      <template #uploadAdd3="{ field }">
        <span style="display: none">{{ field }}</span>
        <a-upload-dragger
          v-model:fileList="fileList3"
          name="file"
          :key="3"
          :multiple="false"
          @change="handleChange('C', $event)"
          :before-upload="() => false"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
          <p class="ant-upload-hint">
            支持扩展名：.jpeg .png .jpg ...
            <br />
            文件大小：最大支持5M
          </p>
        </a-upload-dragger>
      </template>
      <template #showImg3="{ field }">
        <span style="display: none">{{ field }}</span>
        <img
          v-if="showImg3"
          :src="showImg3Pic"
          alt="avatar"
          style="width: 6.25rem; height: 6.25rem"
        />
      </template>
    </BasicForm>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, nextTick } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form';
  import { CredentialsEnum, modeMqttForm } from '../config';
  import { InboxOutlined } from '@ant-design/icons-vue';
  import { Alert, Divider, Descriptions, Upload } from 'ant-design-vue';
  import { uploadApi } from '/@/api/personal/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { buildUUID } from '/@/utils/uuid';

  export default defineComponent({
    components: {
      BasicForm,
      [Alert.name]: Alert,
      [Divider.name]: Divider,
      [Descriptions.name]: Descriptions,
      [Descriptions.Item.name]: Descriptions.Item,
      InboxOutlined,
      [Upload.Dragger.name]: Upload.Dragger,
    },
    emits: ['next', 'prev', 'register'],
    setup(_, { emit }) {
      const showImg1 = ref(false);
      const showImg1Pic = ref('');
      const showImg2 = ref(false);
      const showImg2Pic = ref('');
      const showImg3 = ref(false);
      const showImg3Pic = ref('');
      const { createMessage } = useMessage();
      let caCertFileName = ref('');
      let privateKeyFileName = ref('');
      let certFileName = ref('');
      let fileList1: any = ref<[]>([]);
      let fileList2: any = ref<[]>([]);
      let fileList3: any = ref<[]>([]);
      const credentialsV: any = reactive({
        credentials: {
          type: '',
        },
      });
      const sonValues: any = reactive({
        configuration: {},
      });
      const [register, { validate, setFieldsValue, resetFields: defineClearFunc }] = useForm({
        labelWidth: 120,
        schemas: modeMqttForm,
        actionColOptions: {
          span: 14,
        },
        resetButtonOptions: {
          text: '上一步',
        },
        resetFunc: customResetFunc,
        submitFunc: customSubmitFunc,
      });

      /**
       * 上传图片
       */
      const handleChange = async (e, { file }) => {
        if (file.status === 'removed') {
          if (e == 'T') {
            fileList1.value = [];
            showImg1.value = false;
            showImg1Pic.value = '';
            caCertFileName.value = '';
          } else if (e == 'F') {
            fileList2.value = [];
            showImg2.value = false;
            showImg2Pic.value = '';
            certFileName.value = '';
          } else {
            fileList3.value = [];
            showImg3.value = false;
            showImg3Pic.value = '';
            privateKeyFileName.value = '';
          }
        } else {
          const isLt5M = file.size / 1024 / 1024 < 5;
          if (!isLt5M) {
            createMessage.error('图片大小不能超过5MB!');
          } else {
            e == 'T'
              ? (fileList1.value = [file])
              : e == 'F'
              ? (fileList2.value = [file])
              : (fileList3.value = [file]);
            const formData = new FormData();
            formData.append('file', file);
            const response = await uploadApi(formData);
            if (response.fileStaticUri) {
              if (e == 'T') {
                caCertFileName.value = response.fileStaticUri;
                const iscaCertFileNamePic = caCertFileName.value.split('.').pop();
                if (
                  iscaCertFileNamePic == 'jpg' ||
                  iscaCertFileNamePic == 'png' ||
                  iscaCertFileNamePic == 'jpeg' ||
                  iscaCertFileNamePic == 'gif'
                ) {
                  showImg1.value = true;
                  showImg1Pic.value = response.fileStaticUri;
                } else {
                  showImg1.value = false;
                }
              } else if (e == 'F') {
                certFileName.value = response.fileStaticUri;
                const iscertFileNamePic = certFileName.value.split('.').pop();
                if (
                  iscertFileNamePic == 'jpg' ||
                  iscertFileNamePic == 'png' ||
                  iscertFileNamePic == 'jpeg' ||
                  iscertFileNamePic == 'gif'
                ) {
                  showImg2.value = true;
                  showImg2Pic.value = response.fileStaticUri;
                } else {
                  showImg2.value = false;
                }
              } else {
                privateKeyFileName.value = response.fileStaticUri;
                const isprivateKeyFileNamePic = privateKeyFileName.value.split('.').pop();
                if (
                  isprivateKeyFileNamePic == 'jpg' ||
                  isprivateKeyFileNamePic == 'png' ||
                  isprivateKeyFileNamePic == 'jpeg' ||
                  isprivateKeyFileNamePic == 'gif'
                ) {
                  showImg3.value = true;
                  showImg3Pic.value = response.fileStaticUri;
                } else {
                  showImg3.value = false;
                }
              }
            }
          }
        }
      };
      const setStepTwoFieldsValueFunc = (v, v1, v2) => {
        setFieldsValue(v);
        setFieldsValue({
          name: v1,
          description: v2,
        });
        setFieldsValue({
          password: v.credentials?.password,
          username: v.credentials?.username,
          type: v.credentials?.type,
        });
        fileList1.value = [
          {
            name: v.credentials?.caCertFileName.slice(39),
            uid: '1',
          },
        ];
        fileList2.value = [
          {
            name: v.credentials?.certFileName.slice(39),
            uid: '2',
          },
        ];
        fileList3.value = [
          {
            name: v.credentials?.privateKeyFileName.slice(39),
            uid: '3',
          },
        ];
        caCertFileName.value = v.credentials?.caCertFileName;
        certFileName.value = v.credentials?.certFileName;
        privateKeyFileName.value = v.credentials?.privateKeyFileName;
        const iscaCertFileNamePic = v.credentials?.caCertFileName.split('.').pop();
        const iscertFileNamePic = v.credentials?.certFileName.split('.').pop();
        const isprivateKeyFileNamePic = v.credentials?.privateKeyFileName.split('.').pop();
        if (
          iscaCertFileNamePic == 'jpg' ||
          iscaCertFileNamePic == 'png' ||
          iscaCertFileNamePic == 'jpeg' ||
          iscaCertFileNamePic == 'gif'
        ) {
          showImg1.value = true;
          showImg1Pic.value = v.credentials?.caCertFileName;
        } else {
          showImg1.value = false;
        }
        if (
          iscertFileNamePic == 'jpg' ||
          iscertFileNamePic == 'png' ||
          iscertFileNamePic == 'jpeg' ||
          iscertFileNamePic == 'gif'
        ) {
          showImg2.value = true;
          showImg2Pic.value = v.credentials?.certFileName;
        } else {
          showImg2.value = false;
        }
        if (
          isprivateKeyFileNamePic == 'jpg' ||
          isprivateKeyFileNamePic == 'png' ||
          isprivateKeyFileNamePic == 'jpeg' ||
          isprivateKeyFileNamePic == 'gif'
        ) {
          showImg3.value = true;
          showImg3Pic.value = v.credentials?.privateKeyFileName;
        } else {
          showImg3.value = false;
        }
      };
      const customClearStepTwoValueFunc = async () => {
        nextTick(() => {
          defineClearFunc();
          fileList1.value = [];
          fileList2.value = [];
          fileList3.value = [];
          caCertFileName.value = '';
          privateKeyFileName.value = '';
          certFileName.value = '';
          showImg1.value = false;
          showImg1Pic.value = '';
          showImg2.value = false;
          showImg2Pic.value = '';
          showImg3.value = false;
          showImg3Pic.value = '';
        });
      };
      async function customResetFunc() {
        emit('prev');
      }
      async function customSubmitFunc() {
        try {
          const values = await validate();
          emit('next', values);
        } catch (error) {
        } finally {
        }
      }
      const getSonValueFunc = async () => {
        sonValues.configuration = await validate();
        credentialsV.credentials.type = sonValues.configuration.type;
        if (credentialsV.credentials.type == CredentialsEnum.IS_BASIC) {
          credentialsV.credentials.username = sonValues.configuration.username;
          credentialsV.credentials.password = sonValues.configuration.password;
          sonValues.configuration.username = undefined;
          sonValues.configuration.password = undefined;
        } else if (credentialsV.credentials.type == CredentialsEnum.IS_PEM) {
          credentialsV.credentials.caCertFileName = caCertFileName.value;
          credentialsV.credentials.certFileName = certFileName.value;
          credentialsV.credentials.privateKeyFileName = privateKeyFileName.value;
        }
        //clientId 从uuid里切片8位
        sonValues.configuration.clientId = buildUUID().slice(0, 8);
        Object.assign(sonValues.configuration, credentialsV);
        return sonValues;
      };
      return {
        getSonValueFunc,
        register,
        setStepTwoFieldsValueFunc,
        customClearStepTwoValueFunc,
        fileList1,
        fileList2,
        fileList3,
        handleChange,
        caCertFileName,
        privateKeyFileName,
        certFileName,
        showImg1,
        showImg1Pic,
        showImg2,
        showImg2Pic,
        showImg3,
        showImg3Pic,
      };
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ant-col-24) {
    margin-bottom: 20px !important;
  }
  :deep(.ant-btn-default) {
    color: white;
    background: #377dff;
  }
</style>
