<template>
  <div id="decMoudleWrap" class="dec-layout-wrap">
    <!-- 顶部操作按钮-->
    <div class="dec-layout-top">
      <a-button @click="reBack" class="reBack" type="link"
        >返回列表主页</a-button
      >
      <a-button type="primary" @click="toSee">预览</a-button>
      <a-button type="primary" @click="save">保存</a-button>
      <a-button @click="reBack">返回</a-button>
      <span class="create">
        <svg
          style="
            width: 1em;
            height: 1em;
            vertical-align: middle;
            fill: currentColor;
            overflow: hidden;
          "
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="8517"
        >
          <path
            d="M857.403 147.819H841.04V228.3h16.364a31.925 31.925 0 0 1 31.925 31.924V424.41c0 17.17-17.17 20.925-31.925 20.925h-442.92a49.63 49.63 0 0 0-49.63 49.094V700.73h-20.389a53.655 53.655 0 0 0-57.142 52.314v217.033a55.8 55.8 0 0 0 57.142 53.655H469.48a55.8 55.8 0 0 0 57.679-53.655V752.775a55.264 55.264 0 0 0-57.411-53.654h-20.12V552.643a26.827 26.827 0 0 1 26.827-26.827h383.631a122.601 122.601 0 0 0 76.19-24.413 96.042 96.042 0 0 0 36.753-76.994V260.494a112.943 112.943 0 0 0-113.48-112.407h-1.878zM822.796 298.857V71.629A70.02 70.02 0 0 0 754.654 0H120.188a70.288 70.288 0 0 0-69.215 71.629v227.228a70.288 70.288 0 0 0 69.215 71.36h634.198a70.02 70.02 0 0 0 68.678-71.36z"
            p-id="8518"
          ></path>
        </svg>
      </span>
    </div>
    <!-- 左侧功能选择导航-160px -->
    <div class="dec-layout-left" v-if="isInited">
      <div v-for="list in iconMap" :key="list.tag">
        <template v-if="iconArr[list.tag]">
          <div class="d-tag">{{ list.name }}</div>
          <draggable
            v-model="iconArr[list.tag]"
            filter=".forbid"
            animation="100"
            :group="{ name: 'itxst', pull: 'clone', put: false }"
            :sort="false"
            :clone="changeIconId"
            :move="tabMove"
            @unchoose="finishDrag"
          >
            <transition-group>
              <div
                v-for="item in iconArr[list.tag]"
                :key="item.type"
                class="d-tab"
              >
                <div class="d-img" :class="item.type"></div>
                <div class="d-name">{{ item.name }}</div>
              </div>
            </transition-group>
          </draggable>
        </template>
      </div>
    </div>
    <!-- 中间手机展示-手机内容层35 7-320 20  420 = 800px-->
    <div class="dec-layout-content" v-if="isInited">
      <div class="dec-layout-phone">
        <div class="d-top"></div>
        <div class="d-content">
          <div id="phonePageCoverId">
            <div class="dec-bottom" :style="{ ...globalStyle }"></div>
            <div
              @click="focusAction()"
              class="decCompsWrap"
              :class="{ focus: shopBase.id === focusCom.id }"
            >
              <shop-base :tab="shopBase" :title="pageSet.pageName"></shop-base>
            </div>
            <div class="dec-screen" :style="{ ...globalStyle2 }">
              <draggable
                v-model="tabs"
                :group="{ name: 'itxst', draggable: '.decCompsWrap' }"
                :disabled="sortDisabled"
                class="decDragGroupClass"
                :style="{ 'min-height': minScreenH }"
                filter=".autoLoadForbid"
                :move="tabMove"
                @update="updateTab"
              >
                <div
                  class="decCompsWrap"
                  v-for="(item, index) in tabs"
                  :key="item.id"
                  :id="item.type + item.id"
                  :class="{
                    focus: item.id === focusCom.id,
                    autoLoadForbid: autoLoadId == item.id,
                    isBackground: item.arg.isBackground,
                  }"
                  @click.stop="focusAction(item)"
                >
                  <show-tabel :tab="item" />
                  <ul class="dec-opt">
                    <li
                      class="del-wrap"
                      @click.stop="confirmDel(index, $event)"
                    >
                      <a-icon type="delete" />
                    </li>
                  </ul>
                </div>
              </draggable>
            </div>
          </div>
        </div>
        <div class="d-home"></div>
      </div>
    </div>
    <ul class="dec-layout-hovor">
      <li style="cursor: default" :class="{ focus: optMode == 'edit' }">...</li>
      <li @click.stop="optMode = 'name'" :class="{ focus: optMode == 'name' }">
        装修名称
      </li>
      <li @click.stop="optMode = 'page'" :class="{ focus: optMode == 'page' }">
        页面设置
      </li>
      <li
        v-if="!shopBase.hide"
        @click.stop="optMode = 'nav'"
        :class="{ focus: optMode == 'nav' }"
      >
        顶部导航
      </li>
      <li
        @click.stop="optMode = 'manage'"
        :class="{ focus: optMode == 'manage' }"
      >
        组件管理
      </li>
    </ul>
    <!-- 右侧页面编辑 -->
    <div class="dec-layout-right" v-if="optMode === 'name'">
      <div class="d-modify">
        <div class="d-title">组件管理</div>
        <div class="d-content">
          <div class="dec-flex-list middle">
            <span class="d-left">装修名称：</span>
            <div class="d-right">
              <a-input
                v-model="pageName"
                @change="nameChange"
                placeholder="请输入微页面名称标示"
              />
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="dec-layout-right" v-else-if="optMode === 'manage'">
      <manage :tab="focusItem" :refresh="focusRefresh" @opt="optTab"></manage>
    </div>
    <div class="dec-layout-right" v-else>
      <set :comId="focusCom.id" :tab="focusItem" :checked="checkedFail"></set>
    </div>
    <div class="dec-loading" v-show="loading">
      <div class="ant-spin ant-spin-spinning">
        <span class="ant-spin-dot ant-spin-dot-spin">
          <i class="ant-spin-dot-item"></i>
          <i class="ant-spin-dot-item"></i>
          <i class="ant-spin-dot-item"></i>
          <i class="ant-spin-dot-item"></i>
        </span>
      </div>
    </div>
    <!-- 图片选框-choose -->
    <pic-win imgSize="750 * 374" :imgArg="'5'" ref="decImgMdRef"></pic-win>
    <linkBox ref="decLinkBoxRef" />
    <!-- 预览窗口 -->
    <template v-if="preView">
      <a-modal
        class="dec-layout-view"
        :mask="false"
        @cancel="closeView"
        title="预览"
        v-model="preView"
        :width="420"
        :footer="false"
      >
        <iframe
          style="border: 1px solid #afabab"
          id="preViewIframe"
          width="377"
          :src="viewDomain"
        ></iframe>
      </a-modal>
    </template>
    <!-- 删除框  title="删除确认"-->
    <del-modal ref="decDelModalRef" />
  </div>
</template>
<script>
import Vue from "vue";
import html2canvas from "html2canvas";
import draggable from "vuedraggable";
import manage from "./manage";
import set from "./set.vue";
import showTabel from "./table";
import shopBase from "./lib/shopBase";
import picWin from "../modal/imgModal.vue";
import linkBox from "../modal/linkBox.js";
import { decState } from "./config.js";
import delModal from "../modal/delModal.vue";
const $isEmptyObj = function (val) {
  if (typeof val === "object") {
    const str = JSON.stringify(val);
    return str === "{}" || str === "[]" ? true : false;
  }
  return !val;
};
// 配置的入口：1.props-config传过来;2.组件自带一个config
export default {
  name: "shopDecorater",
  components: {
    manage,
    picWin,
    linkBox,
    draggable,
    showTabel,
    shopBase,
    set,
    delModal,
  },
  props: {
    option: {
      type: Object,
      default() {
        return {
          tempId: "",
          jsonTemp: "",
          setId: "",
        };
      },
    },
    config: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    globalStyle() {
      if (!this.shopBase.mode) {
        return {
          backgroundColor: this.pageSet.bgColor,
        };
      } else {
        let params = {};
        if (this.pageSet.bgColor) {
          params.backgroundColor = this.pageSet.bgColor;
        }
        if (this.pageSet.bgImg) {
          const bgImgW = this.pageSet.bgImgW || 100;
          params.backgroundImage = `url('${this.pageSet.bgImg}')`;
          params.backgroundRepeat = this.pageSet.repeat
            ? "repeat"
            : "no-repeat";
          params.backgroundSize = `${bgImgW}% auto`;
          params.backgroundPosition = "center top";
        }
        return params;
      }
    },
    globalStyle2() {
      if (!this.shopBase.mode) {
        let params = {};
        if (this.pageSet.bgColor) {
          params.backgroundColor = this.pageSet.bgColor;
        }
        if (this.pageSet.bgImg) {
          const bgImgW = this.pageSet.bgImgW || 100;
          params.backgroundImage = `url('${this.pageSet.bgImg}')`;
          params.backgroundRepeat = this.pageSet.repeat
            ? "repeat"
            : "no-repeat";
          params.backgroundSize = `${bgImgW}% auto`;
          params.backgroundPosition = "center top";
        }
        return params;
      } else {
        return {};
      }
    },
  },
  data() {
    return {
      setId: "",
      isInited: false,
      loading: true, // 加载标示
      sortDisabled: false, // 不允许在操作的时候拖动页面
      checkedFail: false, // 校验不通过标示
      iconMap: [
        { name: "基础组件", tag: "base" },
        { name: "营销组件", tag: "market" },
      ],
      iconArr: [], // 右侧图标列表
      setting: {}, // 配置数据容器
      decAxios: {},
      tabs: [], // 左侧组件参数数组
      shopBase: {},
      pageSet: {},
      pageName: "",
      minScreenH: "500px",
      preFocusItem: null,
      focusCom: {}, // 选中的组件信息
      focusItem: null, // 选中的组件数据
      focusRefresh: false,
      optMode: "", // 操作模式：管理组件，页面设置，导航设置
      preView: false, // 小程序预览页面
      hander: null,
      autoLoadId: "",
      viewDomain: window.location.origin + "/app/index.html",
    };
  },
  provide() {
    const global = this.initConfig();
    const that = this;
    return {
      decAxios: global.decAxios,
      decImgDomain: global.decImgDomain,
      $isEmptyObj: $isEmptyObj,
      judgeAutoLoad(id, val) {
        if (that.getAutoLoadTab(id)) {
          that.autoLoadId = val ? id : "";
          if (val) {
            const h = that.$createElement;
            that.$info({
              title: "自动加载组件提示",
              content: h("div", {}, [
                h("p", "可自动加载的组件处于组件的末尾，"),
                h("p", "其他的组件都不可移动到组件末尾。"),
              ]),
              onOk() {},
            });
          }
          return true;
        } else {
          return false;
        }
      },
    };
  },
  created() {
    if (!$isEmptyObj(this.setting)) {
      this.isInited = false;
      const { tempId, jsonTemp, setId } = this.option;
      this.setId = setId;
      this.initData(setId, tempId, jsonTemp);
    } else {
      this.isInited = true;
    }
  },
  mounted() {
    Vue.prototype.$decImgMdRef = this.$refs.decImgMdRef;
    Vue.prototype.$decLinkBoxRef = this.$refs.decLinkBoxRef;
    Vue.prototype.$decDelModalRef = this.$refs.decDelModalRef;
  },
  beforeDestroy() {
    // 销毁设置的全局变量
    Vue.prototype.$decImgMdRef = {};
    Vue.prototype.$decLinkBoxRef = {};
    Vue.prototype.$decDelModalRef = {};
    window.removeEventListener("message", this.hander);
    this.hander = null;
  },
  watch: {
    optMode(val, val2) {
      if (val != val2 && val != "edit") {
        this.updateMode(val);
      }
      this.preView = false;
    },
  },
  methods: {
    initConfig() {
      const configObj = $isEmptyObj(this.config) ? {} : this.config;
      this.decAxios = configObj.decAxios;
      const customState = configObj.decState;
      this.pageSet = { ...decState.pageSet };
      this.shopBase = Object.assign({}, decState.shopBase, {
        hide: customState.shopBase == "hide",
      });
      // 左侧图标集合
      if (!$isEmptyObj(decState)) {
        const allKeys = Object.keys(decState);
        //传入的配置keys
        let needkeys = [],
          isArray = false;
        if (Array.isArray(customState)) {
          isArray = true;
          needkeys = customState;
        } else if (typeof customState == "object") {
          needkeys = Object.keys(customState);
        }
        //获取非pageSet，shopBase配置对象,需要的key集合
        const arr = needkeys.filter((key) => {
          if (!["pageSet", "shopBase"].includes(key)) {
            return allKeys.includes(key);
          }
          return false;
        });
        //组装左侧功能集合
        let iconObj = {};
        arr.forEach((key) => {
          const tag = decState[key].icon.tag;
          if (!iconObj[tag]) iconObj[tag] = [];
          iconObj[tag].push(decState[key].icon);
        });
        this.iconArr = iconObj;
        //组件配置对象集合
        if (isArray) {
          this.setting = decState;
        } else {
          //合并配置到setting
          arr.forEach((key) => {
            if (customState[key]) {
              this.setting[key] = (function (toVal, fromVal) {
                let toArg = toVal.arg || {},
                  toShow = toArg.show || {};
                let fromArg = fromVal.arg || {},
                  fromShow = fromArg.show || {};
                //先合并数据
                let show = Object.assign({}, toShow, fromShow);
                let arg = { ...toArg, ...fromArg };
                if (arg) {
                  delete arg.show;
                  arg._hide = arg._hide || [];
                  arg._hide.forEach((key) => {
                    if (typeof arg[key] == "boolean") arg[key] = false;
                    else if (typeof arg[key] == "string") arg[key] = "";
                    else if (typeof arg[key] == "object") arg[key] = {};
                  });
                }
                if (show && JSON.stringify(show) != "{}") {
                  show._hide = show._hide || [];
                  show._hide.forEach((key) => {
                    if (typeof show[key] == "boolean") show[key] = false;
                    else if (typeof show[key] == "string") show[key] = "";
                    else if (typeof show[key] == "object") show[key] = {};
                  });
                  arg.show = show;
                }
                const haha = Object.assign({}, toVal, fromVal, { arg });
                return Object.assign({}, toVal, fromVal, { arg });
              })(decState[key], customState[key]);
            } else {
              let toArg = decState[key].arg || {},
                toShow = toArg.show || {};
              if (toShow && JSON.stringify(toShow) != "{}") {
                toShow = { ...toShow, _hide: [] };
                const arg = { ...toArg, show: toShow, _hide: [] };
                this.setting[key] = Object.assign({}, decState[key], { arg });
              } else {
                const arg = { ...decState[key].arg, _hide: [] };
                this.setting[key] = Object.assign({}, decState[key], { arg });
              }
            }
          });
        }
      } else {
        this.$message.error("缺失配置文件，请联系管理人员");
        return {};
      }
      // 设置接口配置为全局变量
      const global = {
        decAxios: this.decAxios,
        decImgDomain: this.decAxios.decImgDomain,
      };
      return global;
    },
    initData(setId, tempId, jsonTemp) {
      this.loading = true;
      let promiseArr = [];
      if (setId) {
        promiseArr.push(this.decAxios.getInfo({ id: setId }));
      } else if (tempId) {
        promiseArr.push(this.decAxios.getTemp({ id: tempId }));
      } else if (jsonTemp) {
        const p = new Promise(function (resolve) {
          resolve({ code: 200, result: { pageLayout: jsonTemp } });
        });
        promiseArr.push(p);
      } else {
        const p = new Promise(function (resolve) {
          resolve({ code: "" });
        });
        promiseArr.push(p);
      }
      const that = this;
      Promise.all(promiseArr).then((ress) => {
        const res = ress[0];
        that.loading = false;
        that.isInited = true;
        if (res.code == "200") {
          try {
            let result = unescape(res.result.pageLayout),
              templateJson = JSON.parse(result),
              tabs = [],
              hasPageSet = false;
            templateJson.forEach((tab) => {
              if (tab.type == "pageSet") {
                hasPageSet = true;
                that.pageSet = Object.assign({}, that.pageSet, tab);
              } else if (tab.type == "shopBase") {
                if (hasPageSet) {
                  that.shopBase = Object.assign({}, that.shopBase, tab);
                } else {
                  that.pageSet = Object.assign({}, that.pageSet, tab, {
                    type: "pageSet",
                  });
                }
              } else if (!$isEmptyObj(tab)) {
                tab.refresh = false;
                tab.inited = false;
                if (tab.arg.show || tab.arg.goodShow) {
                  tab.arg.show = tab.arg.show || tab.arg.goodShow || {};
                  delete tab.arg.goodShow;
                }
                const arg = JSON.parse(
                  JSON.stringify(that.setting[tab.type].arg)
                );
                if (arg._hide && arg._hide.length > 0) {
                  arg._hide.forEach((key) => {
                    if (typeof tab.arg[key] == "boolean") tab.arg[key] = false;
                    else if (typeof tab.arg[key] == "string") tab.arg[key] = "";
                    else if (typeof tab.arg[key] == "object") tab.arg[key] = {};
                  });
                  delete tab.arg._hide;
                }
                if (arg.show) {
                  if (arg.show._hide && arg.show._hide.length > 0) {
                    arg.show._hide.forEach((key) => {
                      if (typeof tab.arg.show[key] == "boolean")
                        tab.arg.show[key] = false;
                      else if (typeof tab.arg.show[key] == "string")
                        tab.arg.show[key] = "";
                      else if (typeof tab.arg.show[key] == "object")
                        tab.arg.show[key] = {};
                    });
                  }
                  delete tab.arg.show._hide;
                  tab.arg.show = Object.assign({}, arg.show, tab.arg.show);
                }
                tab.arg = Object.assign({}, arg, tab.arg);
                tabs.push(tab);
              }
            });
            that.pageName =
              res.result.pageName || that.pageSet.pageName || "未命名";
            that.tabs = tabs;
            that.optMode = "page";
            //获取当前自动加载组件
            const lastTab = tabs[tabs.length - 1] || {};
            that.autoLoadId =
              lastTab.arg && lastTab.arg.autoLoad == "Y" ? lastTab.id : "";
          } catch (err) {
            that.pageName = "未命名";
            that.tabs = [];
            that.optMode = "page";
          }
        } else {
          that.pageName = "未命名";
          that.tabs = [];
          that.optMode = "page";
          that.autoLoadId = "";
        }
      });
    },
    updateMode(val) {
      let item, com;
      if (val == "name") {
        com = item = { id: "name", type: "name", name: "name" };
      } else if (val == "page") {
        com = item = this.pageSet;
      } else if (val == "nav") {
        com = item = this.shopBase;
      } else if (val == "manage") {
        com = {
          id: "1",
          type: "manage",
          name: "组件管理",
        };
        item = this.tabs.map((item) => {
          const { id, type, name } = item;
          return { id, type, name };
        });
      }
      const { id, type, name } = com;
      this.focusCom = { id, type, name };
      this.focusItem = item;
    },
    updateTab() {
      if (this.optMode == "manage") {
        this.focusRefresh = !this.focusRefresh;
        this.updateMode("manage");
      }
    },
    optTab(obj) {
      const { flag, i } = obj;
      if (flag == "del") {
        const id = this.tabs[i].id;
        if (this.focusItem.id === id) {
          this.tabs.splice(i, 1);
          const len = this.tabs.length;
          const focus = i - 1 || 0;
          this.focusAction(len ? this.tabs[focus] : "");
        } else {
          this.tabs.splice(i, 1);
        }
      } else if (flag == "up") {
        const current = this.tabs[i];
        const up = this.tabs[i - 1];
        this.tabs[i - 1] = current;
        this.tabs[i] = up;
        this.updateTab();
      } else if (flag == "down") {
        const current = this.tabs[i];
        const down = this.tabs[i + 1];
        this.tabs[i + 1] = current;
        this.tabs[i] = down;
        this.updateTab();
      }
    },
    tabMove(e) {
      const i = (e.relatedContext || {}).index || 0;
      const len = this.tabs.length;
      if (i + 1 == len) {
        const id = (this.tabs[len - 1] || {}).id || "none";
        if (id != this.autoLoadId) {
          return true;
        } else {
          return false;
        }
      }
      return true;
    },
    //预览微页面
    toSee() {
      let target = JSON.stringify([this.pageSet, this.shopBase, ...this.tabs]);
      this.preView = true;
      const that = this;
      if (!this.hander) {
        this.hander = function (res) {
          if (res.data.type == "onLoad") {
            const iframe =
              document.getElementById("preViewIframe").contentWindow;
            iframe.postMessage(
              { type: "onLoad", res: target },
              that.viewDomain
            );
          } else if (res.data.type) {
            const resType = (res.data.type || "").split("@")[0];
            const iframe =
              document.getElementById("preViewIframe").contentWindow;
            that.decAxios[resType](res.data.params).then((res2) => {
              iframe.postMessage(
                { type: res.data.type, res: res2 },
                that.viewDomain
              );
            });
          }
        };
        window.addEventListener("message", this.hander);
      }
    },
    closeView() {
      this.preView = false;
      window.removeEventListener("message", this.hander);
      this.hander = null;
    },
    //拖拽前设置好tabs的项数据-深拷贝数据模型
    changeIconId(e) {
      const id = new Date().getTime();
      let tab = {
        id: id,
        refresh: true, // 手动刷新标示
        inited: false, // 数据获取成功标示
        arg: JSON.parse(JSON.stringify(this.setting[e.type].arg)),
      };
      this.preFocusItem = Object.assign({}, e, tab);
      return this.preFocusItem;
    },
    //拖拽成功后设置全局变量
    finishDrag(e) {
      if (e.to.className === "decDragGroupClass") {
        this.focusAction(this.preFocusItem);
      }
    },
    //选择要编辑的组件
    focusAction(item) {
      if (!item) {
        this.optMode = !this.shopBase.hide ? "nav" : this.optMode;
        return;
      }
      this.optMode = "edit";
      const { id, type, name } = item;
      this.focusCom = { id, type, name };
      this.focusItem = item;
      this.preView = false;
    },
    //保存数据-校验
    save() {
      if (this.tabs.length === 0) {
        this.$message.error("微页面内容不可为空，请添加组件");
      } else {
        this.loading = true;
        let checkedResult = [];
        for (var i = 0; i < this.tabs.length; i++) {
          let target = this.tabs[i],
            arg = target.arg;
          const validFn = this.setting[target.type].valid;
          if (typeof validFn == "function") {
            const result = validFn(arg);
            if (result && typeof result == "object" && !result.result) {
              checkedResult.push({ index: i, ...result }); //校验结果处理
              break;
            }
          }
        }
        // 到不符合规则的高度
        if (!$isEmptyObj(checkedResult) && checkedResult.length > 0) {
          this.loading = false;
          this.checkedFail = true;
          const targetIndex = checkedResult[0].index;
          this.focusAction(this.tabs[targetIndex]);
          let domTarget = document.querySelector(
            "#" + this.tabs[targetIndex].type + this.tabs[targetIndex].id
          );
          let ScrollTop = domTarget && domTarget.offsetTop;
          ScrollTop &&
            window.scroll({ top: ScrollTop + 105, behavior: "smooth" });
          this.$message.error(checkedResult[0].message);
        } else {
          // 处理事情:图片的截取需要缓一段时间
          if (this.$parent.option == "table") {
            this.saveData();
          } else {
            this.$confirm({
              title: "封面提示",
              content: this.setId
                ? "是否更新微页面封面？"
                : "是否要创建微页面封面？",
              okText: this.setId ? "更新" : "创建",
              cancelText: this.setId ? "不更新" : "不创建",
              onOk: () => {
                this.clip();
              },
              onCancel: () => {
                this.saveData();
              },
            });
          }
        }
      }
    },
    //返回功能
    reBack() {
      this.$emit("promise", { success: false });
    },
    //截取图片
    clip() {
      const that = this;
      let domTarget = document.querySelector("#phonePageCoverId");
      let H = domTarget && domTarget.offsetHeight;

      function successCallback(imgurl) {
        that.saveData(imgurl);
      }
      function failCallback(mes) {
        mes && that.$message.error(mes);
      }
      html2canvas(domTarget, { useCORS: true, height: H > 563 ? 563 : H }).then(
        function (canvas) {
          var dataURL = canvas.toDataURL("image/png"); //base64
          const blobDate = dataURLtoBlob(dataURL);
          let fileInfo = {
            fileTyle: "png",
            fileName: "cover.png",
            biz: "pageCoverImage",
            file: blobDate,
          };
          that.decAxios
            .uploadSource(fileInfo, successCallback, failCallback, false)
            .then((res) => {
              if (res.code === 200) {
                !res.message && successCallback(res.url);
              } else {
                failCallback(res.message);
              }
            });
        }
      );

      function dataURLtoBlob(dataurl) {
        var arr = dataurl.split(",");
        var mime = arr[0].match(/:(.*?);/)[1];
        var bstr = atob(arr[1]);
        var n = bstr.length;
        var u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      }

      function dataURLtoFile(dataurl, filename) {
        var arr = dataurl.split(","),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, { type: mime });
      }
    },
    //检验通过-数据保存:数据丑化
    saveData(imgUrl) {
      const tabs = this.tabs.map((item) => {
        const { id, name, type } = item;
        let arg = { ...item.arg },
          show = arg.show ? { ...arg.show } : null;
        if (arg && arg._hide) delete arg._hide;
        if (show && show._hide) {
          delete show._hide;
          arg.show = show;
        }
        return { id, name, type, arg };
      });
      let target = escape(
        JSON.stringify([this.pageSet, this.shopBase, ...tabs])
      );
      const { pageName, pageDesc, bgColor } = this.pageSet;
      let pageName1 =
        this.pageName && this.pageName != "未命名" ? this.pageName : "";
      let params = {
        pageName: pageName1 || pageName,
        pageDesc,
        bgColor,
        pageLayout: target,
      };
      if (this.setId) {
        params.id = this.setId;
        imgUrl && (params.pageCover = imgUrl);
      }
      if (this.option.shopId) params.shopId = this.option.shopId;
      this.decAxios
        .saveInfo(params)
        .then((res) => {
          this.loading = false;
          if (res.code == "200") {
            this.loading = false;
            this.$message.success("保存成功");
            // 清理数据
            this.tabs = [];
            this.minScreenH = "500px";
            this.$emit("promise", { success: true });
          } else {
            this.$message.error("保存失败");
          }
        })
        .catch((err) => {});
    },
    confirmDel(i, e) {
      this.$refs.decDelModalRef.show(e, "del-wrap");
      const that = this;
      this.$refs.decDelModalRef.$once("promise", (res) => {
        if (res.success) that.optTab({ flag: "del", i });
      });
    },
    nameChange() {
      const str = this.pageName;
      if (str.length > 14) {
        this.pageName = str.substring(0, 14);
      }
    },
    //获取最后一个组件是否是自动加载组件
    getAutoLoadTab(id) {
      const len = this.tabs.length || 1;
      const lastCom = this.tabs[len - 1] || {};
      if (lastCom.id == id) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
