<template>
  <div class="add_template">
    <!-- 提示用语 -->
    <!-- <div class="add-template__confirm" v-if="returnConfirm">
      <div class="template-confirm__center">
        <div class="confirm-left">
          <i class="iconfont icongantanhao-xianxingyuankuang"></i>
          <p>您还未保存，返回后信息不会保存。</p>
        </div>
        <div class="confirm-btn" @click="gogo">继续返回</div>
      </div>
      <i class="iconfont iconjiufuqianbaoicon08" @click="backCancel"></i>
    </div>-->
    <!-- end -->
    <div class="add_template__center">
      <div
        class="col_left"
        :class="{ col_left_full: !isShowBar }"
        @click="onCancelSelected"
      >
        <header class="header">
          <button class="header-btn_back" @click="back">
            <i class="iconfont iconZUO1 header-btn_back-icon"></i>
            <span class="header-btn_back-text">返回</span>
          </button>
          <name-editor
            class="header-title"
            :operation="!ShowPastData"
            v-model="templateName"
            ref="editor"
          >
            <!-- 新增三个按钮 -->
            <div class="header-btnbox" v-if="!ShowPastData">
              <div class="header-btnbox__btn" @click="UpperChain">
                <span> <i class="iconfont iconshanglian"></i> </span>上链
              </div>
              <div class="header-btnbox__btn" @click="SelectTemplate">
                <span> <i class="iconfont iconxuanzemoban"></i> </span>选择模板
              </div>
              <div
                class="header-btnbox__btn"
                @click="uploadBanner"
                v-if="existingEvidenceList.length < 1"
              >
                <span> <i class="iconfont iconshenglvehao1"></i> </span
                >上传banner图
              </div>
            </div>
          </name-editor>
          <!-- 增量数据列表 -->
          <ul class="existing-evidence" v-if="existingEvidenceList">
            <li
              :class="{ 'existing-evidence__list': item.id === checkId }"
              v-for="(item, index) in existingEvidenceList"
              :key="index"
              @click="DataHandover(item, index)"
            >
              {{ item.name }}
              <i
                class="iconfont iconwsmp-bianji"
                v-show="item.status === 0"
              ></i>
            </li>
          </ul>
        </header>
        <read-only :displayData="displayData"></read-only>
        <main class="main_container" v-if="!ShowPastData">
          <add-level1-button
            v-if="rootUnitList.length === 0"
            @click="showAddRootDialog"
            title="点击添加"
            class="main-btn_add_l1_center"
          />
          <div class="main-template_wrapper">
            <div>
              <root-unit
                v-for="item in rootUnitList"
                :unit="item"
                @del="deleteItem"
                @addNextlevel="showAddChildDialog"
                @modifyTitle="modifyTitleShow"
                :selectedItem="selectedEditItem"
                @selected="handleSelectedProperty"
                @modifyForms="modifyFormsShow = true"
                :key="item.id"
              />
            </div>
            <div class="mask"></div>
            <footer class="main-footer" v-if="rootUnitList.length !== 0">
              <add-level1-button @click="showAddRootDialog" />
            </footer>

            <div class="main-top-btn-zone">
              <div
                @click="save(saveState)"
                class="richTextShow_btn"
                :class="{ 'richTextShow_btn--focus': personalTemplateId !== 0 }"
              >
                <i class="iconfont iconbaocun-"></i>
                保存存证
              </div>
              <div
                class="richTextShow_btn"
                @click="SaveTemplate(TemplateType)"
                :class="{
                  'richTextShow_btn--focus':
                    $route.query.systemTemplateId ||
                    $route.query.personalTemplate,
                }"
              >
                <i class="iconfont iconbaocun-"></i>
                保存模板
              </div>
            </div>
          </div>
        </main>
      </div>
      <!-- 右侧 -->
      <div class="col_right" v-if="!ShowPastData">
        <set-bar
          v-show="isShowBar"
          class="col_right-bar"
          @add-child="showAddChildDialog"
          :selectTarget="selectedEditItem"
          @select-type="changeType"
          @delete="deleteItem"
        ></set-bar>
        <div
          class="col_right-switch"
          ref="col_right_switch"
          @click="isShowBar = !isShowBar"
        >
          <i
            class="iconfont iconxiangxia col_right-switch-icon"
            :class="{ 'js-col_right-switch-icon_left': !isShowBar }"
          ></i>
        </div>
      </div>
    </div>
    <!-- 添加一级标题弹窗 -->
    <add-root-dialog
      v-if="isShowAddRootDialog"
      @close="isShowAddRootDialog = false"
      @confirm="addRootUnit"
    ></add-root-dialog>
    <!-- 子级标题添加弹窗 -->
    <add-child-dialog
      v-if="isShowAddChildDialog"
      @close="isShowAddChildDialog = false"
      @confirm="confirmAddChild"
    ></add-child-dialog>
    <!-- 选择模板弹窗 -->
    <common-dialog
      v-if="SelectTemplateShow"
      @closePopup="SelectTemplateShow = false"
      showMask
      class="template-popup__style"
    >
      <template-popup @Determine="Determine"></template-popup>
    </common-dialog>
    <!-- 上链弹窗 -->
    <div class="chain-dialog" v-show="isShowToChainDialog">
      <div class="chain-mask" @click="isShowToChainDialog = false"></div>
      <div class="chain-content">
        <i
          class="iconfont iconjiufuqianbaoicon08"
          @click="isShowToChainDialog = false"
        ></i>
        <img src="../../assets/images/category/chain_notice.png" />
        <div class="part-bottom">
          <h3>上链提示</h3>
          <p class="line-one">
            信息上链后，即将展示在区块链上以作永恒记录，如有虚假，
          </p>
          <p class="line-two">登记⽅需⾃愿承担由此产⽣的⼀切后果。</p>
          <div class="chain-btn" @click="uploadConfirm">确定上链</div>
        </div>
      </div>
    </div>
    <!-- banner部分 -->
    <common-dialog
      v-if="isShowBanner"
      @closePopup="isShowBanner = false"
      showMask
      class="style-ShowReduction"
    >
      <banner
        :TemplateId="personalTemplateId"
        :incrementId="incrementId"
        @closeBanner="closeBanner"
      />
    </common-dialog>
    <!-- 修改标题 -->
    <common-dialog
      v-if="isModifyTitleShow"
      @closePopup="isModifyTitleShow = false"
      showMask
    >
      <modify-title
        :selectedEditItem="selectedEditItem"
        @close="isModifyTitleShow = false"
      ></modify-title>
    </common-dialog>
    <!-- 改变形式 -->
    <common-dialog
      v-if="modifyFormsShow"
      @closePopup="modifyFormsShow = false"
      showMask
    >
      <modify-presentation
        :selectedEditItem="selectedEditItem"
        @select-type="changeType"
        @cancel="modifyFormsShow = false"
      ></modify-presentation>
    </common-dialog>
    <uncertified
      v-if="showUncertified"
      @confirm="showUncertified = false"
      @cancel="UncertifiedConfirm"
    ></uncertified>
    <common-dialog
      v-if="ClassificationPopups"
      @closePopup="ClassificationPopups = false"
      showMask
    >
      <choose-classification
        @successCallback="successCallback"
        @close="ClassificationPopups = false"
      />
    </common-dialog>
    <!-- 引导页 -->
    <!-- <common-dialog close class="dg-guide" v-if="showGuide">
      <guide @close="showGuide=false" :stepIndex="stepIndex"></guide>
    </common-dialog>-->
  </div>
</template>
<script lang="ts">
import { Component, Vue, Watch } from "vue-property-decorator";
import { formatTemplateApi2Local, formatApiJson } from "@/plugins/Template";
import { PropertyType } from "@/plugins/types";
import { Property, Unit,ResUploadFiles } from "@/plugins/types2";
import { GO_URLS } from "@/config/URLS";
import { ImageInfo, ImageItem } from "@/utils/app/AddProductTypes";
import CommonDialog from "@/components/CommonDialog.vue";
import NameEditor from "@/components/NameEditor.vue";
import ReadOnly from "@/views/template/readOnly.vue"; // 回显
import AddLevel1Button from "@/components/editTemplate/AddLevel1Button.vue";
import SetBar from "@/components/editTemplate/SetBar.vue";
import RootUnit from "@/components/editTemplate/RootUnit.vue";
import ModifyPresentation from "@/components/editTemplate/ModifyPresentation.vue"; //修改表现形式
import banner from "@/components/editTemplate/banner.vue";
import TemplatePopup from "@/views/template/TemplatePopup.vue";
import AddChildDialog from "@/components/editTemplate/AddChildDialog.vue"; //添加下一级
import AddRootDialog from "@/components/editTemplate/AddRootDialog.vue";
import ModifyTitle from "@/components/editTemplate/ModifyTitle.vue"; //修改标题
// 未认证提示组件
import Uncertified from "@/components/Uncertified.vue";
import ChooseClassification from "@/components/editTemplate/ChooseClassification.vue";
// import guide from "@/views/template/AddTemplate/guide.vue";
@Component({
  components: {
    NameEditor,
    CommonDialog,
    ReadOnly,
    AddLevel1Button,
    RootUnit,
    SetBar,
    ModifyPresentation,
    banner,
    TemplatePopup,
    AddChildDialog,
    AddRootDialog,
    ModifyTitle,
    Uncertified,
    ChooseClassification,
    // guide
  },
})
export default class editTemplate extends Vue {
  public isShowAddChildDialog: boolean = false; // 子级添加弹窗
  public selectedEditItem: Unit | Property | null = null; // 选中编辑的项
  public isShowBar: boolean = false; // 展开右栏
  public isShowBanner = false; //banner图组件显示or隐藏
  public SelectTemplateShow: Boolean = false; // 选择模板显示or隐藏
  public personalTemplateId: number = 0; //个人存证id
  public saveState: Number = 0; // 保存存证需要的状态
  public ShowPastData: Boolean = false; // 显示过往数据
  public isShowToChainDialog: Boolean = false; //控制上链弹窗显示or隐藏
  public rootUnitList: Unit[] = []; // 一级单元
  public templateName: string = ""; // 模板名称
  public isInActive: boolean = false; //防抖
  public localData: string = ""; //本地化note数据
  public isModifyTitleShow: Boolean = false; //修改标题
  public modifyFormsShow: Boolean = false; // 改变表现形式
  public existingEvidenceList: any = []; //增量数据列表
  public checkId: number = -1;
  public incrementId: number = 0;
  public isShowAddRootDialog: boolean = false;
  public displayData: any = [];
  public TemplateType: number = 0;
  public showUncertified: Boolean = false;
  public ClassificationPopups: boolean = false;
  public MemoryCardType: String = ""; //存证类型
  // 系统模板>建立个人模板or建立存证
  // 个人模板>建立存证or更新模板
  // 建立存证>保存存证or保存模板
  @Watch("templateName")
  public onChange(newVal: number, oldVal: number) {
    if (
      this.existingEvidenceList[0] &&
      this.checkId !== this.existingEvidenceList[0].id
    )
      return false;
    if (this.existingEvidenceList.length > 0 && !this.ShowPastData)
      this.existingEvidenceList[0].name = newVal;
  }
  public created() {
    // 取值
    const query = this.$route.query;
    if (query.personalTemplate) {
      this.gettemplate(query.personalTemplate);
      this.TemplateType = 1;
    } else if (query.systemTemplateId) {
      // 模板进入
      this.gettemplate(query.systemTemplateId);
    } else if (query.personalTemplateId && !query.childId) {
      // 个人存证进入
      this.personalTemplateId = Number(query.personalTemplateId);
      this.checkId = Number(query.personalTemplateId);
      this.information(3);
      this.saveState = 1;
      // 父存证>进入页面>获取数据>根据参数决定是否调用增量列表接口
    } else if (
      query.personalTemplateId &&
      query.childId &&
      query.personalTemplateName
    ) {
      this.personalTemplateId = Number(query.personalTemplateId);
      this.checkId = Number(query.childId);
      this.incrementId = Number(query.childId);
      this.saveState = 2;
      this.information(1);
    }
  }
  // 更新个人模板
  public async SaveTemplate(key: number) {
    switch (key) {
      case 0:
        // 创建个人模板
        this.CreateTemplate();
        break;
      case 1:
        // 更新个人模板
        this.updateCustomize();
        break;
      default:
        break;
    }
  }
  public async successCallback(val: number) {
    var newrout = formatApiJson(this.rootUnitList);
    for (let index = 0; index < newrout.length; index++) {
      const element = newrout[index];
      if (element.label === "ext") {
        newrout.splice(index, 1);
      }
    }
    const res = await this.$ajax({
      type: "post",
      url: GO_URLS.customize,
      params: {
        folder_id: val,
        name: this.templateName,
        info: this.templateName,
        detail: JSON.stringify(newrout),
      },
    });
    if (res) {
      this.$message({
        message: "创建成功",
        type: "success",
      });
      this.$router.push({
        path: "/categoryManage",
        query: { type: "MyTemplate" },
      });
    }
  }
  // 创建个人模板
  public async CreateTemplate() {
    this.ClassificationPopups = true;
  }
  // 更新个人模板
  public async updateCustomize() {
    await this.fileHandler();

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

        this.displayData = res.data.detail;
      } else if (state === 3) {
        this.localData = res.data.note;
        // 存证进入，可能有增量，可能无增量
        if (
          res.data.status === 2 ||
          res.data.status === 4 ||
          res.data.status === 5 ||
          res.data.status === 6
        ) {
          this.displayData = res.data.detail;
          this.ShowPastData = true;
          if (res.data.increment_num > 0) {
            this.expandTheList(res.data.hash);
          }
        } else {
          if (res.data.detail !== "") {
            this.rootUnitList = formatTemplateApi2Local(
              JSON.parse(res.data.detail)
            );
          } else {
            this.rootUnitList = [];
          }
        }
      }
    }
  }
  // 获取增量的数据
  public async getincrement(id: number) {
    const res = await this.$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
      ) {
        this.ShowPastData = true;
        this.templateName = res.data.name;
        this.displayData = res.data.detail;
      } else {
        this.ShowPastData = false;
        this.templateName = res.data.name;
        this.localData = res.data.note;
        if (res.data.detail !== "") {
          this.rootUnitList = formatTemplateApi2Local(
            JSON.parse(res.data.detail)
          );
        } else {
          this.rootUnitList = [];
        }
      }
    }
  }
  // 关闭banner图设置窗口
  public closeBanner(val: string) {
    this.isShowBanner = false;
    if (val) {
      if (this.localData !== "") {
        var newBanner = JSON.parse(this.localData);
        newBanner.banners = JSON.parse(val);
        this.localData = JSON.stringify(newBanner);
      }
    }
  }
  // 设置banner图
  public uploadBanner() {
    this.isShowBanner = true;
  }
  // 获取模板
  public async gettemplate(id: any) {
    const res = await this.$ajax({
      type: "get",
      url: GO_URLS.getSystemTemplate,
      params: {
        id: id,
      },
    });
    if (res) {
      // 获取模板数据
      this.templateName = res.data.name;
      this.MemoryCardType = res.data.name;
      if (res.data.detail)
        this.rootUnitList = formatTemplateApi2Local(
          JSON.parse(res.data.detail)
        );
    }
  }
  // 保存存证
  public save(key: number) {
    switch (key) {
      case 0:
        this.addTemplate();
        break;
      case 1:
        this.updateTemplate();
        break;
      case 2:
        this.updateIncremental();
        break;
      default:
        break;
    }
  }
  // 更新增量存证
  public async updateIncremental() {
    await this.fileHandler();
    var newDetail = new Array();
    newDetail = formatApiJson(this.rootUnitList);
    // 更新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 = this.templateName;
          } else if (
            element2.label === "存证类型" &&
            this.MemoryCardType !== ""
          ) {
            element2.data.value = this.MemoryCardType;
          }
        }
        if (index === 0) {
          newDetail.push(newDetail.shift());
        }
      }
    }
    if (JSON.parse(this.localData).stepName !== this.templateName) {
      var newdata = JSON.parse(this.localData);
      newdata.stepName = this.templateName;
      this.localData = JSON.stringify(newdata);
    }
    const res = await this.$ajax({
      type: "put",
      url: GO_URLS.incrementId + `/` + this.incrementId,
      params: {
        detail: JSON.stringify(newDetail),
        id: this.incrementId,
        name: this.templateName,
        note: this.localData,
      },
    });
    if (res) {
      this.$message({
        message: "编辑成功",
        type: "success",
      });
      this.$router.push("/categoryManage");
    }
  }
  // 更新普通存证
  public async updateTemplate() {
    await this.fileHandler();
    var newDetail = new Array();
    newDetail = formatApiJson(this.rootUnitList);

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

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

    const res = await this.$ajax({
      type: "put",
      url: GO_URLS.update,
      params: {
        id: Number(this.$route.query.personalTemplateId),
        name: this.templateName,
        detail: JSON.stringify(newDetail),
        note: this.localData,
      },
    });
    if (res) {
      this.$message({
        message: "编辑成功",
        type: "success",
      });
      this.$router.push("/categoryManage");
    }
  }
  // 模板>新存证
  public async addTemplate() {
    await this.fileHandler();
    let newext = {
      label: "ext",
      key: "",
      type: 3,
      data: [
        {
          data: {
            type: "text",
            format: "string",
            value: this.templateName,
          },
          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: this.MemoryCardType,
          },
          type: 0,
          key: "存证类型",
          label: "存证类型",
        },
      ],
    };
    var newDetail = new Array();
    newDetail = formatApiJson(this.rootUnitList);

    newDetail.push(newext);

    const res = await this.$ajax({
      type: "post",
      url: GO_URLS.add,
      params: {
        name: this.templateName,
        detail: JSON.stringify(newDetail),
        note: JSON.stringify({
          version: 1,
          userName: this.$store.state.userInfos.user || "",
          userIcon: this.$store.state.userInfos.icon || "",
          evidenceName: this.templateName,
          stepName: "",
          banners: [],
        }),
      },
    });
    if (res) {
      this.$message({
        message: "创建成功",
        type: "success",
      });
      this.$router.push("/categoryManage");
    }
  }
  // 展示修改标题弹窗
  public modifyTitleShow() {
    this.isModifyTitleShow = true;
  }
  // 新增增量数据列表的请求
  async expandTheList(hash: string) {
    const res = await this.$ajax({
      type: "post",
      url: GO_URLS.incrementList,
      params: {
        base_hash: hash,
        page: 1,
        page_size: 10,
      },
    });
    if (res) {
      // 第二步
      var firstData = {
        name: this.templateName,
        id: this.personalTemplateId,
        hash: hash,
      };
      res.data.results.push(firstData);
      this.existingEvidenceList = res.data.results;
      for (let index = 0; index < this.existingEvidenceList.length; index++) {
        const element = this.existingEvidenceList[index];
        if (this.checkId === element.id) {
          this.templateName = element.name;
        }
      }
    }
  }
  // 切换数据显示
  public DataHandover(item: any, index: number) {
    if (item.status === 1) return false;
    if (this.checkId === item.id) return false;
    this.checkId = item.id;
    // this.templateName = item.name;
    if (this.existingEvidenceList.length - index > 1) {
      // 切换至增量数据
      let child: any = this.$refs["editor"];
      child.startEdit();
      this.displayData = [];
      this.incrementId = item.id;
      this.personalTemplateId = 0;
      this.getincrement(item.id);
      this.saveState = 2;
    } else {
      // 切换至第一条数据
      this.personalTemplateId = item.id;
      this.incrementId = 0;
      this.ShowPastData = true;
      this.saveState = 1;
      this.information(2);
    }
  }
  // 切换模板
  public async Determine(val: number) {
    this.SelectTemplateShow = false;
    const data = await this.$ajax({
      type: "get",
      params: {
        id: val,
      },
      url: GO_URLS.getSystemTemplate,
    });
    if (data && data.data.detail) {
      this.MemoryCardType = data.data.name;
      if (this.rootUnitList.length === 1) {
        this.rootUnitList.push(
          ...formatTemplateApi2Local(JSON.parse(data.data.detail))
        );
      } else {
        for (let index = 0; index < this.rootUnitList.length; index++) {
          const element = this.rootUnitList[index];
          if (element.title === "ext") {
            var newroot = this.rootUnitList.splice(index, 1);
            this.rootUnitList = [];
            this.rootUnitList.push(
              ...formatTemplateApi2Local(JSON.parse(data.data.detail))
            );
            this.rootUnitList.push(newroot[0]);
          }
        }
      }
    }
  }
  // 选择模板
  public SelectTemplate() {
    this.SelectTemplateShow = true;
  }
  // 上链请求
  async uploadConfirm() {
    this.incrementId === 0
      ? this.witnessTheChain()
      : this.incrementWitnessTheChain();
  }
  async incrementWitnessTheChain() {
    if (this.isInActive) return;
    this.isInActive = true;
    const res = await this.$ajax({
      type: "post",
      url: GO_URLS.sendBlockIncrementChain,
      params: { id: this.incrementId },
    });
    if (res) {
      this.$message({
        type: "success",
        message: "上链信息提交成功!",
      });
      this.isShowToChainDialog = false;
      this.$router.push("/categoryManage");
    }
    this.isInActive = false;
  }
  // 存证上链
  async witnessTheChain() {
    if (this.isInActive) return;
    this.isInActive = true;
    const res = await this.$ajax({
      type: "post",
      url: GO_URLS.sendBlockChian,
      params: { id: this.personalTemplateId },
    });
    if (res) {
      // this.getList();
      this.$message({
        type: "success",
        message: "上链信息提交成功!",
      });
      this.isShowToChainDialog = false;
      this.$router.push("/categoryManage");
    }
    this.isInActive = false;
  }
  // 上链
  async UpperChain() {
    const res = await this.$ajax({
      type: "get",
      url:
        GO_URLS.user +
        `/` +
        JSON.parse(String(sessionStorage.getItem("user"))).id,
    });
    if (res) {
      if (res.data.auth_suc === 1) {
        this.isShowToChainDialog = true;
      } else {
        this.showUncertified = true;
      }
    }
  }
  // 跳转个人中心
  UncertifiedConfirm() {
    this.$router.push("/userCenter");
  }

  // 返回确认框
  public back() {
    this.$router.go(-1);
  }
  // 打开一级标题添加
  public showAddRootDialog() {
    this.isShowAddRootDialog = true;
  }
  // 选中效果去除
  public handleSelectedProperty(item: Unit | Property) {
    this.selectedEditItem = item;
  }
  // 右侧变更触发
  public changeType(val: PropertyType) {
    (this.selectedEditItem as Property).type = val;
    (this.selectedEditItem as Property).value = "";
  }

  /**
   * 点击添加下一级
   */
  public showAddChildDialog() {
    this.isShowAddChildDialog = true;
  }
  // 删除子级
  public deleteItem() {
    const target = this.selectedEditItem;
    if (target) {
      let list = target.parent ? target.parent.children : this.rootUnitList;
      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);
          Vue.set(
            target.parent.parent.children,
            justIdx,
            new Property(target.parent.title, "", target.parent.parent)
          );
        }
      }
    }
  }

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

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

  // 一级标题成功之后的回调
  public addRootUnit(title: string) {
    this.rootUnitList.push(new Unit(title));
  }
  // 点击空白部分触发
  public onCancelSelected() {
    // 清空选中数据
    this.selectedEditItem = null;
  }

  /**
   * 获取需要上传的文件数组和对应的对应的本地图片对象数组
   */
  private 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,
    };
  }
  // 图片上传请求
  private async imageUpload(formData: object) {
    const res = await this.$ajax({
      type: "post",
      url: GO_URLS.upload + `?file_type=png`,
      params: formData,
    });
    if (res) {
      return (res as ResUploadFiles).data;
    }
  }
  /**
   *上传文件
   */

  private async submitFiles(files: File[]) {
    var res = [];
    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 this.imageUpload(formData));
    }
    if (res.length === files.length) {
      return res;
    }
  }
  public async fileHandler() {
    const { files, fileInfos } = this.getFiles(this.rootUnitList);
    if (files.length > 0) {
      const fileItems = await this.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 scoped lang='less'>
.style-ShowReduction {
  .dialog_content {
    background: none;
    max-height: none;
  }
}
.dg-guide {
  /deep/.dialog_content {
    width: 100%;
    height: 100%;
    box-shadow: none;
    background: none;
    position: relative;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    transform: none;
    max-height: none;
  }
}
.existing-evidence {
  overflow: hidden;
  margin: 0;
  margin-bottom: 18px;
  padding: 0;
  .existing-evidence__list {
    color: white;
    background: #3f79fe;
    border: 1px solid #3f79fe;
  }
  li {
    list-style: none;
    font-size: 14px;
    cursor: pointer;
    font-weight: 400;
    float: left;
    color: #353535;
    padding: 0 16px;
    border: 1px solid #e3e7ed;
    border-radius: 5px;
    margin-right: 10px;
    line-height: 34px;
    i {
      color: white;
    }
  }
}
.menu {
  z-index: 100;
  position: absolute;
  top: 60px;
  right: -32px;
  margin: 0;
  padding: 0;
  width: 107px;
  list-style: none;
  background: #fff;
  text-align: center;
  border: 1px solid #e7e7e7;
  border-radius: 2px;
}
.menu-item__one {
  &::after {
    content: "";
    display: block;
    position: absolute;
    width: 10px;
    height: 10px;
    border-top: 1px solid #e7e7e7;
    border-left: 1px solid #e7e7e7;
    background: white;
    top: -6px;
    left: 32px;
    transform: rotate(45deg);
  }
  &:hover {
    background: rgba(242, 244, 246, 1);
    &::after {
      background: rgba(242, 244, 246, 1);
    }
  }
}
.menu-item {
  line-height: 43px;
  color: #797d84;
  font-size: 14px;
  cursor: pointer;
}
.chain-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}
.chain-mask {
  width: 100%;
  height: 100%;
  background-color: black;
  opacity: 0.2;
}
.chain-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  height: 550px;
  background-color: white;
  .iconjiufuqianbaoicon08 {
    position: absolute;
    top: -30px;
    font-size: 28px;
    cursor: pointer;
    right: -30px;
    color: rgba(0, 0, 0, 0.4);
  }
}
.chain-content .part-bottom {
  padding-top: 30px;
  text-align: center;
}
.chain-content .part-bottom h3 {
  font-size: 20px;
  color: #353535;
  margin-bottom: 15px;
}
.chain-content .part-bottom p {
  font-size: 16px;
  color: #989fa5;
  // margin-bottom: 36px;
}
.chain-content .part-bottom .line-two {
  margin-bottom: 36px;
}
.chain-content .part-bottom .chain-btn {
  font-size: 14px;
  color: white;
  background-color: #3f79fe;
  border-radius: 4px;
  width: 120px;
  height: 40px;
  line-height: 40px;

  cursor: pointer;
  display: inline-block;
}
.add_template {
  display: flex;
  height: 100%;
  min-height: 0;
  overflow: auto;
  background: white;
  flex-direction: column; // 设置方向
  /*隐藏滚动条，当IE下溢出，仍然可以滚动*/
  -ms-overflow-style: none;
  /*火狐下隐藏滚动条*/
  overflow: -moz-scrollbars-none;
  &::-webkit-scrollbar {
    display: none;
  }
  .add-template__confirm {
    width: 100%;
    height: 40px;
    max-height: 40px;
    flex: 1;
    background: rgba(250, 118, 67, 0.1);
    position: relative;
    text-align: center;
    .iconjiufuqianbaoicon08 {
      position: absolute;
      right: 30px;
      top: 50%;
      font-size: 20px;
      transform: translateY(-50%);
      cursor: pointer;
      color: #fa7640;
    }
    .template-confirm__center {
      width: 387px;
      display: inline-block;
      line-height: 40px;
      font-size: 16px;
      font-family: PingFangSC;
      font-weight: 400;
      overflow: hidden;
      color: rgba(252, 118, 67, 1);
      .confirm-left {
        float: left;
        line-height: 40px;
        p {
          display: inline-block;
          margin: 0;
          padding: 0;
          font-size: 16px;
          vertical-align: top;
        }
        i {
          vertical-align: top;
          font-size: 20px;
          margin-right: 6px;
        }
      }
      .confirm-btn {
        float: right;
        width: 100px;
        height: 30px;
        margin-top: 5px;
        cursor: pointer;
        line-height: 30px;
        text-align: center;
        background: rgba(250, 118, 64, 1);
        border-radius: 4px;
        font-size: 14px;
        font-family: PingFangSC;
        font-weight: 400;
        color: rgba(255, 255, 255, 1);
      }
    }
  }
  .add_template__center {
    display: flex;
    flex: 1;
    flex-direction: row;
  }
}
.col_left {
  width: calc(100% - 254px);
  overflow-y: scroll; /* 超出横向滚动 ui未给出 */
  scrollbar-color: transparent transparent;
}
.col_left_full {
  width: 100%;
}
.col_left::-webkit-scrollbar {
  /*滚动条整体样式*/
  display: none;
  /*高宽分别对应横竖滚动条的尺寸*/
  // height: 1px;
}
.col_left::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  display: none;
}
.col_right {
  position: fixed;
  right: 0;
  height: calc(100% - 50px);
}
.col_right--hidden {
  display: none;
}
.col_right-bar {
  width: 258px;
  background: #fafafd;
}

.col_right-switch {
  position: absolute;
  top: 50%;
  margin-top: -35px;
  left: -17px;
  width: 17px;
  height: 69px;
  line-height: 69px;
  background: #8ca5ff;
  border-radius: 7px 0 0 7px;
  cursor: pointer;
}

.col_right-switch-icon {
  display: inline-block;
  font-size: 12px; /* 估10px */
  transform: scale(0.833) rotate(90deg);
  color: #fff;
}

.js-col_right-switch-icon_left {
  transform: scale(0.833) rotate(-90deg);
}

.header {
  padding-left: 53px;
  line-height: 80px;
}
.header-btnbox {
  // overflow: hidden;
  font-weight: 400;
  position: relative;
  font-size: 12px;
  line-height: 84px;
  padding-left: 30px;
  float: right;
  .header-btnbox__btn {
    &:first-child {
      padding-right: 18px;
    }
    &:nth-child(2) {
      padding-right: 18px;
    }
    color: #797d84;
    cursor: pointer;
    span {
      width: 26px;
      height: 26px;
      display: inline-block;
      border-radius: 50%;
      text-align: center;
      line-height: 26px;
      margin-right: 4px;
      background: #dadada;
      i {
        font-size: 12px;
        color: white;
      }
    }
    float: left;
  }
}
.header-btn_back {
  vertical-align: middle;
  width: 110px;
  height: 40px;
  background: transparent;
  border: 1px solid #e8e8e8;
  border-radius: 22px;
  outline: none;
  cursor: pointer;
}

.header-btn_back-icon {
  font-size: 16px; /* 有空白 */
  color: #8e8e8e;
  vertical-align: middle;
}

.header-btn_back-text {
  vertical-align: middle;
  margin-left: 5px;
  font-size: 14px;
}

.header-title {
  margin-left: 31px;
}
.header-select {
  float: right;
  margin-right: 50px;
}

.main_container {
  flex: 1;
  position: relative;
}

.main-btn_add_l1_center {
  display: block;
  width: 138px;
  margin: 284px auto 0;
}
// 隐藏添加一级标题按钮
.add-level1-button--hidden {
  display: none;
}
.main_upload {
  margin-left: 45px;
}
// 富文本存在的情况下隐藏图片上传
.main_upload--hidden {
  display: none;
}
// 富文本编辑器
.richText {
  // margin-left: 45px;
  margin-top: 38px;
}
.main-template_wrapper {
  padding-left: 45px; /* 63 - 18 */
}

.main-footer {
  height: 49px;
  bottom: 49px;
  width: 40px;
  position: fixed;
}
.main-top-btn-zone {
  position: fixed;
  top: 0;
  right: 338px;
  z-index: 1;
  overflow: hidden;
}
// 富文本编辑器保存按钮
.richTextShow_btn {
  width: 96px;
  height: 30px;
  z-index: 99;
  float: left;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  color: #757575;
  margin-right: 10px;
  font-family: PingFangSC;
  text-align: center;
  font-weight: 400;
  line-height: 30px;
  margin-top: 10px;

  i {
    font-size: 14px;
  }
}
.richTextShow_btn--focus {
  background: #5779f4;
  color: white;
}
.btn-box {
  height: 50px;
  .main-top-btn_save {
    float: right;
    height: 50px;
    line-height: 50px;
    cursor: pointer;
    text-align: center;
    color: #757575;
    font-size: 14px;
    font-family: PingFangSC-Regular;
    font-weight: 400;
    i {
      font-size: 14px;
    }
  }
  .main-top-btn_save--one {
    width: 96px;
    height: 30px;
    background: rgba(87, 121, 244, 1);
    border-radius: 4px;
    line-height: 30px;
    text-align: center;
    color: white;
    margin-top: 10px;
  }
  .main-top-btn_save--two {
    width: 144px;
  }
  .main-top-btn_save--three {
    width: 120px;
  }
}
.btn-box--hidden {
  display: none;
}
.mask {
  height: 145px;
}
.template-popup__style {
  /deep/.dialog_content {
    background: none;
    max-height: none;
  }
}
</style>
