<template>
  <div class="card">
    <Card :bordered="false" class="card">
      <BasicForm @register="registerForm">
        <template #logoUpload>
          <Upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="customUploadLogoPic"
            :before-upload="beforeUploadLogoPic"
          >
            <img v-if="logoPic" :src="logoPic" />
            <div v-else>
              <div style="margin-top: 1.875rem">
                <PlusOutlined style="font-size: 2.5rem" />
              </div>
              <div
                class="ant-upload-text flex"
                style="width: 180px; height: 100px; align-items: center; font-size: 0.5625rem"
              >
                支持.PNG、.JPG格式，建议尺寸为32*32px，大小不超过500KB</div
              >
            </div>
          </Upload>
        </template>
        <template #iconUpload>
          <Upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="customUploadIconPic"
            :before-upload="beforeUploadIconPic"
          >
            <div v-if="iconPic">
              <img :src="iconPic" class="m-auto" />
              <div style="background-color: #ccc; margin-top: 20px">重新上传</div>
            </div>
            <div v-else>
              <div style="margin-top: 20px">
                <PlusOutlined style="font-size: 30px" />
              </div>
              <div
                class="ant-upload-text flex"
                style="width: 130px; height: 70px; align-items: center; font-size: 0.5625rem"
              >
                支持.ICON格式，建议尺寸为16*16px</div
              >
            </div>
          </Upload>
        </template>
        <template #bgUpload>
          <Upload
            name="avatar"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="customUploadBgPic"
            :before-upload="beforeUploadBgPic"
          >
            <img v-if="bgPic" :src="bgPic" alt="avatar" />
            <div v-else>
              <div style="margin-top: 1.875rem">
                <PlusOutlined style="font-size: 2.5rem" />
              </div>
              <div
                class="ant-upload-text flex"
                style="width: 280px; height: 130px; align-items: center; font-size: 0.5625rem"
              >
                支持.PNG、.JPG格式，建议尺寸为1920*1080px以上，大小不超过5M</div
              >
            </div>
          </Upload>
        </template>

        <template #colorInput="{ model, field }"
          ><Input disabled v-model:value="model[field]">
            <template #prefix> <input type="color" v-model="model[field]" /> </template
          ></Input>
        </template>
      </BasicForm>
    </Card>
    <Loading v-bind="compState" />
    <a-button @click="handleUpdateInfo" type="primary" class="mt-4">保存信息</a-button>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, onMounted, unref } from 'vue';
  import { Card, Upload, Input } from 'ant-design-vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { schemas } from '../config/CVIDraw.config';
  import { Loading } from '/@/components/Loading/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import type { FileItem } from '/@/components/Upload/src/typing';
  import { logoUpload, iconUpload, bgUpload, getPlatForm, updatePlatForm } from '/@/api/oem/index';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { createLocalStorage } from '/@/utils/cache/index';
  import { useTitle } from '@vueuse/core';
  import { useGlobSetting } from '/@/hooks/setting';
  export default defineComponent({
    components: {
      BasicForm,
      Card,
      Loading,
      Upload,
      Input,
      PlusOutlined,
    },
    setup() {
      const compState = ref({
        absolute: false,
        loading: false,
        tip: '拼命加载中...',
      });
      const { createMessage } = useMessage();
      const userStore = useUserStore();
      const storage = createLocalStorage();
      const [registerForm, { getFieldsValue, setFieldsValue }] = useForm({
        schemas,
        showSubmitButton: false,
        showResetButton: false,
        labelWidth: 150,
        wrapperCol: {
          span: 10,
        },
      });

      const logoPic = ref();
      const iconPic = ref();
      const bgPic = ref();
      // logo图片上传
      async function customUploadLogoPic({ file }) {
        if (beforeUploadLogoPic(file)) {
          const formData = new FormData();
          formData.append('file', file);
          const response = await logoUpload(formData);
          if (response.fileStaticUri) {
            logoPic.value = response.fileStaticUri;
          }
        }
      }
      const beforeUploadLogoPic = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          createMessage.error('只能上传图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 < 500;
        if (!isLt2M) {
          createMessage.error('图片大小不能超过500KB!');
        }
        return isJpgOrPng && isLt2M;
      };
      // Icon上传
      async function customUploadIconPic({ file }) {
        if (beforeUploadIconPic(file)) {
          const formData = new FormData();
          formData.append('file', file);
          const response = await iconUpload(formData);
          if (response.fileStaticUri) {
            iconPic.value = response.fileStaticUri;
          }
        }
      }
      const beforeUploadIconPic = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/x-icon';
        if (!isJpgOrPng) {
          createMessage.error('只能上传.icon图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 < 500;
        if (!isLt2M) {
          createMessage.error('图片大小不能超过500KB!');
        }
        return isJpgOrPng && isLt2M;
      };
      // 登录页背景上传
      async function customUploadBgPic({ file }) {
        if (beforeUploadBgPic(file)) {
          const formData = new FormData();
          formData.append('file', file);
          const response = await bgUpload(formData);
          if (response.fileStaticUri) {
            bgPic.value = response.fileStaticUri;
          }
        }
      }
      const beforeUploadBgPic = (file: FileItem) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          createMessage.error('只能上传图片文件!');
        }
        const isLt2M = (file.size as number) / 1024 / 1024 < 5;
        if (!isLt2M) {
          createMessage.error('图片大小不能超过5MB!');
        }
        return isJpgOrPng && isLt2M;
      };

      // 更新
      const handleUpdateInfo = async () => {
        try {
          const fieldValue = getFieldsValue();
          compState.value.loading = true;
          const newFieldValue = {
            ...fieldValue,
            logo: unref(logoPic),
            icon: unref(iconPic),
            background: unref(bgPic),
          };
          await updatePlatForm(newFieldValue);
          compState.value.loading = false;
          createMessage.success('保存信息成功');

          setPlatFormInfo(newFieldValue);
        } catch (e) {
          createMessage.error('保存信息失败');
        }
      };
      // 设置平台信息
      function setPlatFormInfo(newFieldValue) {
        // 保存store
        userStore.setPlatInfo(newFieldValue);
        // 保存本地缓存
        storage.set('platformInfo', newFieldValue);
      }

      onMounted(async () => {
        const res = await getPlatForm();
        setFieldsValue(res);
        logoPic.value = res.logo;
        iconPic.value = res.icon;
        bgPic.value = res.background;
      });
      return {
        registerForm,
        logoPic,
        iconPic,
        bgPic,
        customUploadLogoPic,
        beforeUploadLogoPic,
        customUploadIconPic,
        beforeUploadIconPic,
        customUploadBgPic,
        beforeUploadBgPic,
        compState,
        handleUpdateInfo,
      };
    },
  });
</script>

<style lang="less" scoped></style>
