<template>
  <div>
    <el-upload
      v-if="containerType == 'font'"
      :on-success="handleFontUploadSuccess"
      :before-upload="handleBeforeFontUpload"
      class="upload-demo"
      :headers="{ Authorization: 'Bearer' + getZHToken() }"
      :data="font_option"
      :show-file-list="false"
      action="https://zhihui.qq.com/middle-material/font/upload"
    >
      <el-button type="primary">上传字体</el-button>
    </el-upload>
    <el-popover v-else placement="bottom-start" trigger="hover" :width="200">
      <div>
        <div class="popover-btn" style="font-size: 14px; font-weight: 500; line-height: 16px; color: #33383e" @click="openDialog">上传模板</div>
        <div class="popover-btn" style="font-size: 14px; font-weight: 500; line-height: 16px; color: #33383e">
          <el-upload
            :headers="{ Authorization: 'Bearer' + getZHToken() }"
            :show-file-list="false"
            class="upload-demo"
            :on-success="handleUploadSuccess"
            :accept="'image/*'"
            action="https://zhihui.qq.com/bll-apollo/common/upload"
          >
            <div type="primary">上传素材</div>
          </el-upload>
        </div>
      </div>
      <template #reference>
        <el-button type="primary">添加资源</el-button>
      </template>
    </el-popover>
    <fileUpload v-model:upLoadDialog="upLoadDialog" :type="uploader_type" :belong="belong" :name="userName" @updateEnd="getUploaderFiles" />
    <ClaSelect v-model:pushDialog="pushDialog" :belong="belong" :pushFiles="push_files" :name="userName" :type="uploader_type" @dialogClose="handleDialogClose" @updateEnd="uploadSubmit" />
  </div>
</template>
<script setup>
import fileUpload from '@/components/TemplateUpload/index.vue';
import ClaSelect from '@/components/ClaSelect/index.vue';
import useUserStore from '@/store/modules/user';
import { getZHToken } from '@/utils/auth';
import { ElMessage } from 'element-plus';
import { templateUpload, addGroupMraw, updateUserInfo, listApolloByTeam, getGroupMraw, getGroupFront, getTemplate } from '@/api/zhihui/index.js';

const { proxy } = getCurrentInstance();

const emits = defineEmits(['update:pushDialog', 'updateEnd']);
const props = defineProps({
  belong: {
    type: String,
  },
  containerType: {
    type: String,
    default: 'template',
  },
});
const userName = ref(useUserStore().name);
const { belong, containerType } = toRefs(props);
const upLoadDialog = ref(false); //上传弹窗
const pushDialog = ref(false); //推弹窗
const uploader_type = ref('template'); //上传类型
const push_files = ref([]); //待推送文件

const font_option = ref({});

//获取上传后的文件信息
function getUploaderFiles(files) {
  push_files.value = files;
  upLoadDialog.value = false;
  pushDialog.value = true;
}
function pushFilesEnd() {
  push_files.value = [];
  pushDialog.value = false;
  emits('updateEnd');
}
function openDialog() {
  upLoadDialog.value = true;
  uploader_type.value = 'template';
}
async function handleUploadSuccess(res, file, uploadFiles) {
  if (res.statusCode == 201) {
    let data = res.data;
    push_files.value.push({ ...data, file_name: file.name, thumb: data.thumbUrl });
    let uploading_list = uploadFiles.filter(item => item.status !== 'success');
    if (uploading_list.length == 0) {
      uploader_type.value = 'mraw';
      upLoadDialog.value = false;
      pushDialog.value = true;
    }
  }
}
function handleDialogClose() {
  push_files.value = [];
}
function handleFontUploadSuccess(response, uploadFile, uploadFiles) {
  ElMessage.closeAll();
  if (response.statusCode != 201) {
    return proxy.$modal.msgError('创建失败-' + response.message);
  }
  emits('updateEnd');
}
function handleBeforeFontUpload(rawFile) {
  font_option.value = {
    type: 'team',
    teamId: belong.value,
    creator: userName,
    fileName: rawFile.name.split('.')[0],
  };
  ElMessage({
    message: '上传中...',
    duration: 0,
  });
  return true;
}

//推送上传文件
async function uploadSubmit(cla_ids) {
  let list = [];

  push_files?.value.map(item => {
    let option = {};
    if (uploader_type.value == 'mraw') {
      option = {
        belong: belong.value, // 团队ID
        creator: name.value, // 创建者名称
        height: item.height, // 模版高度
        name: item.file_name, // 模版名称
        status: 1, // 模版状态，默认为1
        thumb: item.thumb, // 模版缩略图
        type: 'image', // 类型，默认为template
        url: item.url, // 模版的实际图片
        width: item.width, // 模版宽度
      };
    }
    if (uploader_type.value == 'template') {
      option = {
        belong: belong.value, // 团队ID
        creator: name.value, // 创建者名称
        height: item.height, // 模版高度
        name: item.file_name, // 模版名称
        status: 1, // 模版状态，默认为1
        thumb: item.thumb, // 模版缩略图
        type: 'template', // 类型，默认为template
        url: item.thumb, // 模版的实际图片
        width: item.width, // 模版宽度
      };
      delete item.file_name;
      option.content = item;
    }
    if (cla_ids.length > 0) {
      option.categoryIds = cla_ids;
    }
    console.log("🚀 ~ file: index.vue:156 ~ uploadSubmit ~ option:", option)
    list.push(option);
  });
  if (list.length <= 0) {
    return;
  }
  let result = {};
  if (uploader_type.value == 'template') {
    result = await templateUpload(list);
  }
  if (uploader_type.value == 'mraw') {
    result = await addGroupMraw(list);
  }
  if (result.statusCode != 201) {
    return proxy.$modal.msgError('创建失败-' + result.message);
  }
  pushFilesEnd();
}
</script>
<style scoped lang="scss">
.popover-btn {
  border-radius: 8px;
  width: 170px;
  padding: 8px;
  color: #33383e;
  font-weight: 400;
  font-size: 14px;
  line-height: 20px;
  cursor: pointer;
  text-align: center;
  &:hover {
    background-color: #f4f3ff;
  }
}
</style>
