<template>
  <EditTool
    class="h-full"
    v-model:title="templateName"
    :showAddRootDialog="showAddRootDialog"
    :changeUnit="(indexOfList, value) => changeUnit(indexOfList, value)"
    :rootUnitList="rootUnitList"
    :delete-item="deleteItem"
    :showAddChildDialog="showAddChildDialog"
    :route="route"
    :modifyTitleShow="modifyTitleShow"
    :selectedEditItem="selectedEditItem"
    :setSelectedItem="
      (v) => {
        selectedEditItem = v;
        selectEditItemId = v.id;
      }
    "
    :handleSelectedProperty="handleSelectedProperty"
    :showModifyForms="() => (modifyFormsShow = true)"
    :switchPosition="switchPosition"
    @select-type="changeType"
    @uploadBanner="uploadBanner"
  ></EditTool>
  <!-- 添加一级标题弹窗 -->
  <add-root-dialog
    :visible="isShowAddRootDialog"
    @close="isShowAddRootDialog = false"
    @confirm="addRootUnit"
  ></add-root-dialog>
  <!-- 子级标题添加弹窗 -->
  <add-child-dialog
    :visible="isShowAddChildDialog"
    @close="isShowAddChildDialog = false"
    @confirm="confirmAddChild"
  ></add-child-dialog>
  <SelectTemplateDialog
    v-model:visible="SelectTemplateShow"
    :determine="determine"
  ></SelectTemplateDialog>
  <!-- 上链弹窗 -->
  <OnChainNotifyDialog
    v-if="isShowToChainDialog"
    @closePopup="isShowToChainDialog = false"
    :uploadConfirm="uploadConfirm"
  ></OnChainNotifyDialog>
  <!-- banner部分 -->
  <common-dialog
    :visible="isShowBanner"
    @closePopup="isShowBanner = false"
    type="element"
    :elementDialogProps="{
      title: '上传手机banner图',
    }"
    elementDialogSize="big"
    :noPadding="true"
    :btnConfig="{
      type: 'withBorder',
      btns,
      btnFunctions: [
        {
          name: '取消',
          click: async () => dialogConfirm($refs.bannerRef, 'imgCancel'),
        },
        {
          name: '确定',
          click: async () => dialogConfirm($refs.bannerRef, 'imgConfirm'),
        },
      ],
    }"
    showMask
  >
    <banner
      v-if="isShowBanner"
      ref="bannerRef"
      :TemplateId="personalTemplateId"
      :incrementId="incrementId"
      @closeBanner="closeBanner"
    />
  </common-dialog>
  <!-- 修改标题 -->
  <common-dialog
    :visible="isModifyTitleShow"
    @closePopup="isModifyTitleShow = false"
    showMask
    type="element"
    :elementDialogProps="{
      title: '修改标题名',
    }"
    :btnConfig="{
      type: 'noBorder',
      btns: btns,
      btnFunctions: [
        {
          name: '取消',
          async click() {
            return true;
          },
        },
        {
          name: '确定',
          click: () => dialogConfirm($refs.modifyTitle, 'changeEdit'),
        },
      ],
    }"
  >
    <modify-title
      ref="modifyTitle"
      v-if="isModifyTitleShow"
      :selectedEditItem="selectedEditItem"
      :setSelectedEditItem="
        (v: any) => {
          selectedEditItem = v;
        }
      "
      @close="isModifyTitleShow = false"
    ></modify-title>
  </common-dialog>
  <!-- 改变形式 -->
  <common-dialog
    :visible="modifyFormsShow"
    @closePopup="modifyFormsShow = false"
    type="element"
    :elementDialogProps="{
      title: '设置表现形式',
    }"
    elementDialogSize="medium"
    :noPadding="true"
    :btnConfig="{
      type: 'noBorder',
      btns,
      btnFunctions: [
        {
          name: '取消',
          async click() {
            return true;
          },
        },
        {
          name: '确定',
          click: () => dialogConfirm($refs.modifyPresentation, 'selectType'),
        },
      ],
    }"
    showMask
  >
    <modify-presentation
      v-if="modifyFormsShow"
      ref="modifyPresentation"
      :selectedEditItem="selectedEditItem"
      @select-type="changeType"
      @cancel="modifyFormsShow = false"
    ></modify-presentation>
  </common-dialog>
  <uncertified
    :visible="showUncertified"
    @close="showUncertified = false"
    @confirm="UncertifiedConfirm"
    @cancel="showUncertified = false"
    :navigate="navigate"
  ></uncertified>
  <common-dialog
    type="element"
    :visible="ClassificationPopups"
    @closePopup="ClassificationPopups = false"
    :elementDialogProps="{
      title: '请选择模板分类',
    }"
    :btnConfig="{
      type: 'noBorder',
      btns,
      btnFunctions: [
        {
          name: '取消',
          async click() {
            return true;
          },
        },
        {
          name: '确定',
          click: () => dialogConfirm($refs.chooseClassification, 'checkForm'),
        },
      ],
    }"
    showMask
  >
    <choose-classification
      v-if="ClassificationPopups"
      ref="chooseClassification"
      @successCallback="successCallback"
      @close="ClassificationPopups = false"
    />
  </common-dialog>
</template>
<script lang="ts" setup>
/* eslint-disable */
import { formatTemplateApi2Local, formatApiJson } from "./Template";
import { PropertyType } from "../newEditTemplate/types";
import { Property, Unit, ResUploadFiles } from "../newEditTemplate/types2";
import { debounce, GO_URLS, syCommonDialog as CommonDialog } from "cqk-sy-ui";
import { ImageInfo, ImageItem } from "../newEditTemplate/AddProductTypes";
import ModifyPresentation from "../newEditTemplate/ModifyPresentation.vue"; //修改表现形式
import banner from "../newEditTemplate/banner.vue";
import AddChildDialog from "../newEditTemplate/AddChildDialog.vue"; //添加下一级
import AddRootDialog from "../newEditTemplate/AddRootDialog.vue";
import ModifyTitle from "../newEditTemplate/ModifyTitle.vue"; //修改标题
import Uncertified from "./Uncertified.vue";
import ChooseClassification from "../newEditTemplate/ChooseClassification.vue";
import { ref, provide, computed, watch, onBeforeMount } from "vue";
import { $ajax } from "@/service";
import { ElMessage } from "element-plus";
import OnChainNotifyDialog from "../newEditTemplate/onChainNotifyDialog.vue";

import EditTool from "./components/EditTool/index.vue";
import SelectTemplateDialog from "./SelectTemplateDialog/index.vue";
import { findSelectTarget } from "../newEditTemplate/ModifySelectTarget";
import { btns } from "@/config/btns";

const props = defineProps<{
  navigate: any;
  route: any;
  go: any;
  showTip: any;
  detail: string;
  name: string;
  note: string;
  id: string;
  increasementProof: boolean;
  baseProofHash?: string;
  baseProofName?: string;
}>();

const isShowAddChildDialog = ref(false); // 子级添加弹窗
const selectedEditItem = ref(null as Unit | Property | null | undefined); // 选中编辑的项
const selectEditItemId = ref("");
const isShowBanner = ref(false); //banner图组件显示or隐藏
const SelectTemplateShow = ref(false); // 选择模板显示or隐藏
const personalTemplateId = ref(""); //个人存证id
const ShowPastData = ref(false); // 显示过往数据
const isShowToChainDialog = ref(false); //控制上链弹窗显示or隐藏
const rootUnitList = ref([] as Unit[]); // 一级单元
const templateName = ref(""); // 模板名称
const isInActive = ref(false); //防抖
const localData = ref(""); //本地化note数据
const isModifyTitleShow = ref(false); //修改标题
const modifyFormsShow = ref(false); // 改变表现形式
const existingEvidenceList = ref([] as any[]); //增量数据列表
const checkId = ref("");
const incrementId = ref("");
const isShowAddRootDialog = ref(false);
const displayData = ref([] as any[]);
const TemplateType = ref(0);
const showUncertified = ref(false);
const ClassificationPopups = ref(false);
const MemoryCardType = ref(""); //存证类型
const personalTemplate = ref(0); // 个人模版的 id

const focusedTarget = computed(() => {
  return findSelectTarget(rootUnitList.value, selectEditItemId.value).item;
});

provide("editRootState", {
  selectEditItemId,
  rootUnitList,
  setRootUnitList: (list: Unit[]) => {
    rootUnitList.value = list;
  },
  focusedTarget,
});

let unitListChangeCount = 0;
let nameChangeCount = 0;

provide("showTip", props.showTip);

const emit = defineEmits(["change"]);

const unitListCountPlus = debounce(
  () => {
    unitListChangeCount++;
    console.log(unitListChangeCount, "unitListChangeCount");
    if (unitListChangeCount >= 2) {
      emit("change");
    }
  },
  500,
  true
);

watch(
  rootUnitList,
  (nv, ov) => {
    unitListCountPlus();
  },
  {
    deep: true,
  }
);

watch(templateName, (newVal, oldVal) => {
  nameChangeCount++;
  console.log(newVal, oldVal, nameChangeCount);
  if (nameChangeCount >= 2) {
    emit("change");
  }
  if (
    existingEvidenceList.value[0] &&
    checkId.value !== existingEvidenceList.value[0].id
  )
    return false;
  if (existingEvidenceList.value.length > 0 && !ShowPastData.value)
    existingEvidenceList.value[0].name = newVal;
});

onBeforeMount(() => {
  if (props.detail !== "") {
    const list = JSON.parse(props.detail!);
    rootUnitList.value = formatTemplateApi2Local(
      list.filter((i: any) => {
        return JSON.stringify(i) !== JSON.stringify({});
      })
    );
  }
  templateName.value = props.name || "";
  localData.value = props.note || JSON.stringify({});
  if (props.increasementProof) {
    incrementId.value = props.id!;
  } else {
    personalTemplateId.value = props.id!;
  }
});

function switchPosition(id1: string, id2: string) {
  const id1Index = rootUnitList.value.findIndex((i) => i.id === id1);
  const id2Index = rootUnitList.value.findIndex((i) => i.id === id2);

  const list = [...rootUnitList.value];
  const temp = list[id1Index];
  list[id1Index] = list[id2Index];
  list[id2Index] = temp;
  rootUnitList.value = list;
}

async function dialogConfirm(
  component: any,
  methodName: string | number,
  params: any = undefined
) {
  console.log(component, "show component");
  return component[methodName](params);
}

function changeUnit(
  indexOfList: number,
  value: {
    id: string;
    title: string;
    children: (
      | any
      | {
          id: string;
          label: string;
          key: string;
          type: PropertyType;
          options: string[];
          value: string | string[];
          parent: any;
          data?: { value: string; format: string; type: string } | undefined;
        }
    )[];
    parent: any | null;
    type: PropertyType;
    addInputChildren: (label: string) => void;
    changeChild2Unit: (child: Property) => Unit;
  }
) {
  rootUnitList.value.splice(indexOfList, 1, value);
}

async function successCallback(val: number) {
  var newrout = formatApiJson(rootUnitList.value);
  for (let index = 0; index < newrout.length; index++) {
    const element = newrout[index];
    if (element.label === "ext") {
      newrout.splice(index, 1);
    }
  }
  const res = await $ajax({
    type: "post",
    url: GO_URLS.customize,
    params: {
      folder_id: val,
      name: templateName.value,
      info: templateName.value,
      detail: JSON.stringify(newrout),
    },
  });
  if (res) {
    ElMessage({
      message: "保存成功",
      type: "success",
    });
    ClassificationPopups.value = false;
    TemplateType.value = 1;
    personalTemplate.value = res.data.id;
  }
}

// 创建个人模板
async function CreateTemplate() {
  ClassificationPopups.value = true;
}

// 更新个人模板
async function updateCustomize() {
  await fileHandler();
  const res = await $ajax({
    type: "put",
    url: GO_URLS.updateCustomize,
    params: {
      id: Number(props.route.query.id),
      name: templateName.value,
      detail: JSON.stringify(formatApiJson(rootUnitList.value)),
    },
  });
  if (res) {
    ElMessage({
      message: "更新成功",
      type: "success",
    });
    props.go(-1);
  }
}
// 获取基础信息
async function information(state: number) {
  const res = await $ajax({
    type: "get",
    params: {
      id: personalTemplateId.value,
    },
    url: GO_URLS.proof,
  });
  if (res) {
    // 第一步
    templateName.value = res.data.name;
    if (state === 1 || state === 0) {
      // 增量存证进入，先获取所有的增量存证列表，再获取当前增量存证数据
      await expandTheList(res.data.hash);
      getincrement(checkId.value);
    } else if (state === 2) {
      // 切换至原始存证的数据

      displayData.value = res.data.detail;
    } else if (state === 3) {
      localData.value = res.data.note;
      // 存证进入，可能有增量，可能无增量
      if (
        res.data.status === 2 ||
        res.data.status === 4 ||
        res.data.status === 5 ||
        res.data.status === 6
      ) {
        displayData.value = res.data.detail;
        ShowPastData.value = true;
        if (res.data.increment_num > 0) {
          expandTheList(res.data.hash);
        }
      } else {
        if (res.data.detail !== "") {
          rootUnitList.value = formatTemplateApi2Local(
            JSON.parse(res.data.detail)
          );
        } else {
          rootUnitList.value = [];
        }
      }
    }
  }
}
// 获取增量的数据
async function getincrement(id: string) {
  const res = await $ajax({
    type: "get",
    url: GO_URLS.incrementId + `/` + id,
  });
  if (res) {
    // 第三步
    if (
      res.data.status === 2 ||
      res.data.status === 4 ||
      res.data.status === 5 ||
      res.data.status === 6
    ) {
      ShowPastData.value = true;
      templateName.value = res.data.name;
      displayData.value = res.data.detail;
    } else {
      ShowPastData.value = false;
      templateName.value = res.data.name;
      localData.value = res.data.note;
      if (res.data.detail !== "") {
        rootUnitList.value = formatTemplateApi2Local(
          JSON.parse(res.data.detail)
        );
      } else {
        rootUnitList.value = [];
      }
    }
  }
}
// 关闭banner图设置窗口
function closeBanner(val: string) {
  isShowBanner.value = false;
  if (val) {
    if (localData.value !== "") {
      var newBanner = JSON.parse(localData.value);
      newBanner.banners = JSON.parse(val);
      localData.value = JSON.stringify(newBanner);
    }
  }
}
// 设置banner图
function uploadBanner() {
  isShowBanner.value = true;
}

// 获取模板
async function gettemplate(id: any) {
  const res = await $ajax({
    type: "get",
    url: GO_URLS.getSystemTemplate,
    params: {
      id: id,
    },
  });
  if (res) {
    // 获取模板数据
    templateName.value = res.data.name;
    MemoryCardType.value = res.data.name;
    if (res.data.detail)
      rootUnitList.value = formatTemplateApi2Local(JSON.parse(res.data.detail));
  }
}
// 保存存证
function save(key: number) {
  switch (key) {
    case 0:
      addTemplate();
      break;
    case 1:
      updateTemplate();
      break;
    case 2:
      updateIncremental();
      break;
    default:
      break;
  }
}

defineExpose({
  CreateTemplate,
  updateCustomize,
  updateIncremental,
  updateTemplate,
  UpperChain,
  addTemplate,
  SelectTemplate,
});

// 更新增量存证
async function updateIncremental(id?: string | undefined) {
  await fileHandler();
  var newDetail = [] as any;
  newDetail = formatApiJson(rootUnitList.value);
  // 更新ext数据
  for (let index = 0; index < newDetail.length; index++) {
    const element = newDetail[index];
    if (element.label === "ext") {
      for (let index2 = 0; index2 < element.data.length; index2++) {
        const element2 = element.data[index2];
        if (element2.label === "存证名称") {
          element2.data.value = templateName.value;
        } else if (
          element2.label === "存证类型" &&
          MemoryCardType.value !== ""
        ) {
          element2.data.value = MemoryCardType.value;
        }
      }
      if (index === 0) {
        newDetail.push(newDetail.shift());
      }
    }
  }
  if (JSON.parse(localData.value).stepName !== templateName.value) {
    var newdata = JSON.parse(localData.value);
    newdata.stepName = templateName.value;
    localData.value = JSON.stringify(newdata);
  }
  const res = await $ajax({
    type: "put",
    url: GO_URLS.incrementId + `/` + id || incrementId.value,
    params: {
      detail: JSON.stringify(newDetail),
      id: id || incrementId.value,
      name: templateName.value,
      note: localData.value,
    },
  });
  return res;
}
// 更新普通存证
async function updateTemplate(id?: undefined) {
  await fileHandler();
  var newDetail = [] as any;
  newDetail = formatApiJson(rootUnitList.value);
  // return;
  // 更新ext数据
  for (let index = 0; index < newDetail.length; index++) {
    const element = newDetail[index];

    if (element.label === "ext") {
      for (let index2 = 0; index2 < element.data.length; index2++) {
        const element2 = element.data[index2];
        if (element2.label === "存证名称") {
          element2.data.value = templateName.value;
        } else if (
          element2.label === "存证类型" &&
          MemoryCardType.value !== ""
        ) {
          element2.data.value = MemoryCardType.value;
        }
      }
      if (index === 0) {
        newDetail.push(newDetail.shift());
      }
    }
  }

  if (JSON.parse(localData.value).evidenceName !== templateName.value) {
    var newdata = JSON.parse(localData.value);
    newdata.evidenceName = templateName.value;
    localData.value = JSON.stringify(newdata);
  }

  const res = await $ajax({
    type: "put",
    url: GO_URLS.update,
    params: {
      id: id || props.route.query.personalTemplateId,
      name: templateName.value,
      detail: JSON.stringify(newDetail),
      note: localData.value,
    },
  });
  return res;
}
// 模板>新存证
async function addTemplate() {
  await fileHandler();
  let newext = {
    label: "ext",
    key: "",
    type: 3,
    data: [
      {
        data: {
          type: "text",
          format: "string",
          value: templateName.value,
        },
        type: 0,
        key: "存证名称",
        label: "存证名称",
      },
      {
        data: {
          type: "text",
          format: "hash",
          value: "null",
        },
        type: 0,
        key: "basehash",
        label: "basehash",
      },
      {
        data: {
          type: "text",
          format: "hash",
          value: "null",
        },
        type: 0,
        key: "prehash",
        label: "prehash",
      },
      {
        data: {
          type: "text",
          format: "string",
          value: MemoryCardType.value,
        },
        type: 0,
        key: "存证类型",
        label: "存证类型",
      },
    ],
  };
  var newDetail = [] as any;
  newDetail = formatApiJson(rootUnitList.value);

  newDetail.push(newext);

  const res = await $ajax({
    type: "post",
    url: GO_URLS.add,
    params: {
      name: templateName.value,
      detail: JSON.stringify(newDetail),
      note: JSON.stringify({
        version: 1,
        evidenceName: templateName.value,
        stepName: "",
        banners: [],
      }),
    },
  });
  if (res) {
    ElMessage({
      message: "创建成功",
      type: "success",
    });
    props.navigate("/tracingManagement");
  }
}
// 展示修改标题弹窗
function modifyTitleShow() {
  isModifyTitleShow.value = true;
}
// 新增增量数据列表的请求
async function expandTheList(hash: string) {
  const res = await $ajax({
    type: "post",
    url: GO_URLS.incrementList,
    params: {
      base_hash: hash,
      page: 1,
      page_size: 10,
    },
  });
  if (res) {
    // 第二步
    var firstData = {
      name: templateName.value,
      id: personalTemplateId.value,
      hash: hash,
    };
    res.data.results.push(firstData);
    existingEvidenceList.value = res.data.results;
    for (let index = 0; index < existingEvidenceList.value.length; index++) {
      const element = existingEvidenceList.value[index];
      if (checkId.value === element.id) {
        templateName.value = element.name;
      }
    }
  }
}

// 切换模板
async function determine(val: number) {
  SelectTemplateShow.value = false;
  const data = await $ajax({
    type: "get",
    params: {
      id: val,
    },
    url: GO_URLS.getSystemTemplate,
  });
  if (data && data.data.detail) {
    MemoryCardType.value = data.data.name;
    if (rootUnitList.value.length === 1) {
      rootUnitList.value.push(
        ...formatTemplateApi2Local(JSON.parse(data.data.detail))
      );
    } else {
      for (let index = 0; index < rootUnitList.value.length; index++) {
        const element = rootUnitList.value[index];
        if (element.title === "ext") {
          var newroot = rootUnitList.value.splice(index, 1);
          rootUnitList.value = [];
          rootUnitList.value.push(
            ...formatTemplateApi2Local(JSON.parse(data.data.detail))
          );
          rootUnitList.value.push(newroot[0]);
        }
      }
    }
  }
}
// 选择模板
function SelectTemplate() {
  SelectTemplateShow.value = true;
}
// 上链请求
async function uploadConfirm() {
  incrementId.value === "" ? witnessTheChain() : incrementWitnessTheChain();
}
async function incrementWitnessTheChain() {
  if (isInActive.value) return;
  isInActive.value = true;
  const res = await $ajax({
    type: "post",
    url: GO_URLS.sendBlockIncrementChain,
    params: { id: incrementId.value },
  });
  if (res) {
    ElMessage({
      type: "success",
      message: "上链信息提交成功!",
    });
    isShowToChainDialog.value = false;
    props.navigate("/tracingManagement");
  }
  isInActive.value = false;
}
// 存证上链
async function witnessTheChain() {
  if (isInActive.value) return;
  isInActive.value = true;
  const res = await $ajax({
    type: "post",
    url: GO_URLS.sendBlockChian,
    params: { id: personalTemplateId.value },
  });
  if (res) {
    ElMessage({
      type: "success",
      message: "上链信息提交成功!",
    });
    isShowToChainDialog.value = false;
    props.navigate("/tracingManagement");
  }
  isInActive.value = false;
}

// 上链
async function UpperChain() {
  const res = await $ajax({
    type: "get",
    url:
      GO_URLS.user +
      `/` +
      JSON.parse(String(sessionStorage.getItem("user"))).id,
  });
  if (res) {
    if (res.data.auth_suc === 1) {
      isShowToChainDialog.value = true;
    } else {
      showUncertified.value = true;
    }
  }
}
// 跳转个人中心
function UncertifiedConfirm() {
  props.navigate("/userCenter");
}

// 打开一级标题添加
function showAddRootDialog() {
  isShowAddRootDialog.value = true;
}
// 选中效果去除
function handleSelectedProperty(item: Unit | Property | undefined) {
  selectedEditItem.value = item;
  selectEditItemId.value = item?.id || "";
}
// 右侧变更触发
function changeType(val: PropertyType) {
  (selectedEditItem.value as Property).type = val;
  (selectedEditItem.value as Property).value = "";
}

/**
 * 点击添加下一级
 */
function showAddChildDialog(data?: any) {
  isShowAddChildDialog.value = true;
}
// 删除子级
function deleteItem(
  data?:
    | {
        id: string;
        title: string;
        children: (
          | any
          | {
              id: string;
              label: string;
              key: string;
              type: PropertyType;
              options: string[];
              value: string | string[];
              parent: any;
              data?:
                | { value: string; format: string; type: string }
                | undefined;
            }
        )[];
        parent: any | null;
        type: PropertyType;
        addInputChildren: (label: string) => void;
        changeChild2Unit: (child: Property) => Unit;
      }
    | {
        id: string;
        label: string;
        key: string;
        type: PropertyType;
        options: string[];
        value: string | string[];
        parent: {
          id: string;
          title: string;
          children: (any | any)[];
          parent: any | null;
          type: PropertyType;
          addInputChildren: (label: string) => void;
          changeChild2Unit: (child: Property) => Unit;
        };
        data?: { value: string; format: string; type: string } | undefined;
      }
    | null
    | undefined
) {
  const target = data || selectedEditItem.value;
  if (target) {
    let list = target.parent ? target.parent.children : rootUnitList.value;
    const index = list.indexOf(target);
    if (index > -1) {
      list.splice(index, 1);
    }
    //删除干净之后
    if (list.length == 0) {
      if (target && target.parent && target.parent.parent) {
        let justIdx = target.parent.parent.children.indexOf(target.parent);
        const p = new Property(target.parent.title, "", target.parent.parent);
        target.parent.parent.children[justIdx] = p;
        selectedEditItem.value = {
          ...target,
        };
      }
    }
  }
}

// 子级添加回调
function confirmAddChild(name: string[]) {
  const target = selectedEditItem.value;
  if (target) {
    const newTarget =
      target instanceof Property
        ? target.parent.changeChild2Unit(target)
        : target;

    name.forEach((item) => {
      (newTarget as any).addInputChildren(item);
    });
  }
}

// 一级标题成功之后的回调
function addRootUnit(title: string, unitType: number) {
  const u = new Unit(title, {}, undefined, unitType);
  rootUnitList.value.push(u);
}

// 点击空白部分触发
function onCancelSelected() {
  // 清空选中数据
  selectedEditItem.value = null;
}
/**
 * 获取需要上传的文件数组和对应的对应的本地图片对象数组
 */
function getFiles(apiUnits: any[]) {
  let files: File[] = [];
  let fileInfos: ImageInfo[] = [];
  apiUnits.forEach((l1) => {
    l1.children.forEach((l2: any) => {
      if (l2.type === PropertyType.Image) {
        let dd = Array.from(l2.value);
        if (dd) {
          (dd as ImageItem[]).forEach((img) => {
            if (img.file) {
              files.push(img.file);
            }
          });
          fileInfos.push(l2);
        }
      }
    });
  });
  return {
    files,
    fileInfos,
  };
}
// 图片上传请求
async function imageUpload(formData: object) {
  const res = await $ajax({
    type: "post",
    url: GO_URLS.upload + `?file_type=png`,
    params: formData,
  });
  if (res) {
    return (res as unknown as ResUploadFiles).data;
  }
}
/**
 *上传文件
 */

async function submitFiles(files: File[]) {
  var res = [] as any[];
  for (let index = 0; index < files.length; index++) {
    const formData = new FormData();
    const element = files[index];
    formData.append("file_data", element, new Date() + ".png");
    res.push(await imageUpload(formData));
  }
  if (res.length === files.length) {
    return res;
  }
}
async function fileHandler() {
  const { files, fileInfos } = getFiles(rootUnitList.value);
  if (files.length > 0) {
    const fileItems = await submitFiles(files);
    // files是未上传的图片数组
    if (fileItems) {
      //fileInfos是已有的
      fileInfos.forEach((imageInfo: any) => {
        //去除以前的空白元素
        for (let i = imageInfo.value.length; i > -1; i--) {
          if (
            !imageInfo.value[i] ||
            (!imageInfo.value[i].dataUrl && !imageInfo.value[i].url)
          ) {
            imageInfo.value.splice(i, 1);
          }
        }
        //
        for (let i = 0; i < imageInfo.value.length; i++) {
          let img = imageInfo.value[i];
          // img已经存在,不能用这个赋值.
          if (!img.url) {
            let fileItems_fmt = fileItems[0] as any;
            img.url = fileItems_fmt.url;
            img.hash = fileItems_fmt.hash;
            fileItems.splice(0, 1);
          }
        }
      });
    }
  }
}
</script>

<style lang="scss">
* {
  box-sizing: content-box;
}
</style>
