// 单独写上传的处理函数
import { addOrUpdateDisplayTemp } from "@/api/display";
import fileUploadFuctions from "@/utils/bizUploadFunctions";
import bizTransform from "@/utils/bizTransform";
import { uploadV1 } from "@/utils/file";

const { getNeedUploadFormData, isFileRaw, isFormDataHasData } =
  fileUploadFuctions;
const { getDeptIdStr } = bizTransform;
const mediaKeys = ["faceImage", "images", "videos", "audios"];

const getUnitData = ($el) => {
  const units = $el.$refs["exhibitionUnits"].getUnitData();
  return units;
};
/**
 * 添加展览单元的媒体文件至formData
 * @param {*} $el 当前this对象
 * @param {FormData} formData 当前this对象
 * @returns {Object} form 表单对象
 */
const getFormDataUnits = ($el, formData) => {
  const units = getUnitData($el);
  appendUnitToForm(units, formData);
  return formData;
};

const appendUnitToForm = (arr, formData) => {
  arr.forEach((item) => {
    if (item.imagesVo && item.imagesVo.length > 0) {
      item.imagesVo.forEach((imgFile) => {
        if (isFileRaw(imgFile)) {
          const { euId } = item;
          const { raw } = imgFile;
          formData.append(`unit-images-${euId}`, raw);
        }
      });
    }
    if (item.children && item.children.length > 0) {
      appendUnitToForm(item.children, formData);
    }
  });
};

/**
 * 上传文件
 * @param {*} $el 当前this对象
 * @returns {Object} form 表单对象
 */
const uploadFile = ($el) => {
  return new Promise(async (resolve, reject) => {
    const formData = getNeedUploadFormData($el, mediaKeys);
    const formDataFull = getFormDataUnits($el, formData);
    try {
      if (isFormDataHasData(formDataFull)) {
        const res = await uploadV1(formDataFull);
        if (res.code == 0) {
          resolve(res);
        }
      } else {
        resolve({});
      }
    } catch (error) {
      reject(error);
    }
  });
};

const getUnitRemovedIds = ($el) => {
  return $el.$refs["exhibitionUnits"].getRemovedIds();
};

const getUnitExsitedObj = ($el, units) => {
  const obj = {};
  loopUnits(units, obj);
  return obj;
  function loopUnits(arr, obj) {
    arr.forEach((item) => {
      if (item.images) {
        const { euId } = item;
        const key = `unit-images-${euId}`;
        const removedIds = getUnitRemovedIds($el);
        const imgArr = item.images.split(",");
        // 筛选存在在images字符串中，并且没有被删除的id，这些是仍然要保留的
        const ids = imgArr.filter((id) => {
          return !removedIds.includes(id);
        });
        obj[key] = ids;
      }

      if (item.children && item.children.length > 0) {
        loopUnits(item.children, obj);
      }
    });
  }
};

const getUploadedIdByKey = (key, res) => {
  if (!res.data) {
    return [];
  }
  const items = res.data.filter((item) => {
    return item.fileKey == key;
  });
  if (items.length > 0) {
    return items.map((item) => {
      return item.fileId;
    });
  } else {
    return [];
  }
};
// 获取已经上传了的文件的id集合
const getUnitSuccessObj = ($el, units, res) => {
  const obj = {};
  loopUnits(units, obj, res);
  return obj;
  function loopUnits(arr, obj, res) {
    arr.forEach((item) => {
      // 只有图片长度大于0的才会有新上传的
      if (item.imagesVo && item.imagesVo.length) {
        // 通过key去查找res中的fileId
        const { euId } = item;
        const key = `unit-images-${euId}`;
        const idsArr = getUploadedIdByKey(key, res);
        obj[key] = idsArr;
      }
      if (item.children && item.children.length > 0) {
        loopUnits(item.children, obj, res);
      }
    });
  }
};

const mergeObjects = (objA, objB) => {
  let result = {};

  // 遍历对象A，复制键值对
  for (let key in objA) {
    if (objA.hasOwnProperty(key)) {
      result[key] = objA[key];
    }
  }

  // 遍历对象B，合并相同的键对应的值
  for (let key in objB) {
    if (objB.hasOwnProperty(key)) {
      if (result.hasOwnProperty(key)) {
        if (Array.isArray(result[key])) {
          result[key].push(...objB[key]);
        } else {
          console.log(
            `Warning: Key ${key} exists in both objA and objB, but the value is not an array in objA.`
          );
        }
      } else {
        result[key] = objB[key]; // 如果键在result中不存在，就创建一个新的键值对
      }
    }
  }
  return result;
};
// 获取最终的布展单元
const getUploadedUnits = ($el, res) => {
  const units = getUnitData($el);
  const exsitedObj = getUnitExsitedObj($el, units);
  const successObj = getUnitSuccessObj($el, units, res);
  //   将存在的和新上传的取交集，因为当key重复时，已存在的会被新上传的覆盖，因此需要再和已存在的进行取并集
  const mergeObj = mergeObjects(exsitedObj, successObj);
  loopUnits(units);
  return units;
  function loopUnits(arr) {
    arr.forEach((item) => {
      const { euId } = item;
      const key = `unit-images-${euId}`;
      if (mergeObj[key]) {
        item.images = mergeObj[key].join(",");
      }
      //   处理关联文物
      if (item.crIds && item.crIds instanceof Array) {
        item.crIds = item.crIds.join(",");
      }
      //   删除imagesVo不要传到后台
      delete item.imagesVo;
      if (item.children && item.length > 0) {
        loopUnits(item.children);
      }
    });
  }
};

const getFormExsitedObj = ($el) => {
  const obj = {};
  mediaKeys.forEach((key) => {
    // 已存在的不为空再继续
    if ($el.dialogForm[key]) {
      const removedIds = $el.getRemovedIds();
      const arr = $el.dialogForm[key].split(",");
      // 筛选存在在媒体字符串中，并且没有被删除的id，这些是仍然要保留的
      const ids = arr.filter((id) => {
        return !removedIds.includes(id);
      });
      obj[key] = ids;
    }
  });
  return obj;
};

// 获取已经上传了的文件的id集合
const getFormSuccessObj = ($el, res) => {
  const obj = {};
  mediaKeys.forEach((key) => {
    // 通过key去查找res中的fileId
    const idsArr = getUploadedIdByKey(key, res);
    obj[key] = idsArr;
  });
  return obj;
};

const getLtStrByArr = (arr) => {
  if (arr.length == 0) {
    return "";
  }
  return arr.join(",");
};

const getStatusNumByBool = (bool) => {
  if (!bool instanceof Boolean) {
    return;
  }
  return bool ? 1 : 0;
};

// 获取最终的展览表单
const getUploadedForm = ($el, res, submitFlag) => {
  const form = JSON.parse(JSON.stringify($el.dialogForm));
  const exsitedObj = getFormExsitedObj($el);
  const successObj = getFormSuccessObj($el, res);
  //   将存在的和新上传的取交集，因为当key重复时，已存在的会被新上传的覆盖，因此需要再和已存在的进行取并集
  const mergeObj = mergeObjects(exsitedObj, successObj);
  mediaKeys.forEach((key) => {
    if (mergeObj[key] && mergeObj[key].length > 0) {
      form[key] = mergeObj[key].join(",");
    }
  });
  form.literature = getLtStrByArr($el.literatureIdArr); //文献
  form.status = getStatusNumByBool($el.dialogForm.status);
  form.crIds = $el.crIds?.join(",");
  form.bvIds = $el.vrIds?.join(",");
  form.displayCharacter = 1; //传布展
  form.submitFlag = submitFlag;
  form.deptId = getDeptIdStr(form.deptId);
  return form;
};

/**
 *
 * @param {Boolean} submitFlag 上传的类别，是仅保存还是
 * @param {*} $el 当前this对象
 */
const submit = (submitFlag, $el) => {
  // this.loading = true;
  $el.$refs.form.validate(async (valid) => {
    if (valid) {
      const res = await uploadFile($el);

      const unitsUploaded = getUploadedUnits($el, res);
      const formUploaded = getUploadedForm($el, res, submitFlag);
      const params = {
        ...formUploaded,
        exhibitionUnits: unitsUploaded,
      };
      //   console.log("unitsUploaded", unitsUploaded);
      //   console.log("formUploaded", formUploaded);
      addOrUpdateDisplayTemp(params)
        .then((res) => {
          if (res.code == 0) {
            setTimeout(() => {
              $el.$emit("refresh");
              $el.reload();
              $el.submitLoading = false;
              $el.$message.success("提交成功！");
              $el.visible = false;
              //   TODO:删除文件
            }, 1000);
          }
        })
        .catch((err) => {
          $el.submitLoading = false;
        });
    }
  });
};
export default submit;
