<template>
  <div class="env-design">
    <el-container
      v-loading="loading"
      :element-loading-text="loadingText"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(170,170,170,0.8)"
    >
      <!-- 头部 -->
      <el-header class="part-header" style="height:7vh">
        <span class="title">溯源模板编辑</span>
        <el-button
          v-if="sup8.urlparams.option==sup8._def.optionType.addPortal||sup8.urlparams.option==sup8._def.optionType.modifyPortal"
          class="btn-goback"
          icon="el-icon-back"
          @click="goBack"
        >返回模板列表</el-button>
        <!-- <el-button class="btn-save" type="primary"  icon="el-icon-check" @click="online">上线</el-button> -->
        <el-button
          class="btn-save"
          type="primary"
          @click="onClickSave()"
          icon="el-icon-message"
          :disabled="saveDisabled"
        >保存</el-button>
        <el-button class="btn-save" type icon="el-icon-close" @click="goBack()">取消</el-button>
      </el-header>
      <!-- 页面列表 -->
      <el-header>
        <el-tabs v-model="selectedPageId">
          <el-tab-pane
            :label="page.name"
            :name="page.id"
            v-for="page in cfg.pages"
            :key="page.id"
            @click="selectedPage=page"
          ></el-tab-pane>
        </el-tabs>
      </el-header>

      <el-container style="height:90vh">
        <!-- 中 -->
        <el-aside class="part part-center">
          <div id="part_phone" class="mobiReviewBackground">
            <div v-if="selectedPage&&selectedPage.components" class="part_phone_screen">
              <div
                v-for="(comp,index) in selectedPage.components"
                :key="comp.id"
                class="comp"
                :class="{active:comp.id===selectedComp.id}"
                :data-comp-name="comp.componentViewName"
                draggable="true"
                keep-alive
              >
                <el-row class="design-tool-bar">
                  <el-button-group>
                    <el-button
                      type="success"
                      size="small"
                      icon="el-icon-edit"
                      circle
                      @click="onClickSetting(comp,index)"
                    ></el-button>
                  </el-button-group>
                </el-row>
                <component
                  :key="comp.id"
                  :is="comp.componentViewName+comp.baseCompId"
                  :comp="comp"
                  @ChangeSelectComp="ChangeSelectComp"
                  :cfg="cfg"
                  :selectedPage="selectedPage"
                  @changeData="changeData"
                  keep-alive
                ></component>
              </div>
            </div>
          </div>
        </el-aside>

        <!-- 右 beg-->
        <el-main class="part part-right">
          <el-tabs v-model="partRightActiveTab">
            <el-tab-pane label="创建溯源" name="tab_activity">
              <component
                :is="'CreatPublic'"
                v-if="partRightActiveTab=='tab_activity'"
                keep-alive
                :activityType="2"
              ></component>
            </el-tab-pane>

            <el-tab-pane label="模板装修" name="tab_prop">
              <component
                v-if="selectedComp"
                :is="selectedComp.componentPropViewName?selectedComp.componentPropViewName+selectedComp.baseCompId:'PartPropsSetting'"
                @PropsChange="PropsChange"
                :key="selectedComp?selectedComp.id:'0000'"
                keep-alive
                :comp="selectedComp"
                :cfg="cfg"
                :selectedPage="selectedPage"
              ></component>
            </el-tab-pane>
          </el-tabs>
        </el-main>
        <!-- 右 end-->
      </el-container>

      <!-- <el-footer class='part-footer'>Footer</el-footer> -->
    </el-container>
    <!-- <component :is="'CompQr'" :qrConfig="qrConfig"></component>-->
    <!-- <component
      :is="'CompSaveDialog'"
      :cfg="cfg"
      :saveDialogVisible="saveDialogVisible"
      @changeData="changeData"
    ></component>-->

    <!-- 活动上线 -->
    <el-dialog
      title="活动上线"
      :visible.sync="activeLineDialog"
      width="50%"
      :close-on-click-modal="false"
      top="20px"
    >
      <active-line ref="onLine" @hideActiveLineDialog="hideActiveLineDialog"></active-line>
    </el-dialog>
  </div>
</template>

<script>
import Vue from "vue";
// import $ from "jquery";
import ElementUI from "element-ui";
import "mint-ui/lib/style.css";
import "element-ui/lib/theme-chalk/index.css";
import "./assets/mobiModule.min.css";
import _apiHelper from "./assets/js/apiHelper.js";
import { setInterval, setTimeout } from "timers";
import eventBus from "./assets/js/eventBus.js";
import ActiveLine from "./components/container/ActiveLine";

Vue.use(ElementUI);
export default {
  name: "designEnv_antiFake",
  data: function() {
    return {
      qrConfig: {
        previewUrl: "x",
        dialogVisible: false
      },

      loading: false, // 是否显示加载效果
      loadingText: "加载中...",
      cfg: {}, // 全套配置
      selectedComp: undefined,
      selectedPageId: "",
      selectedPage: {
        name: ""
      },
      saveDialogVisible: false, // 是否显示保存配置的弹框
      partRightActiveTab: "tab_activity", // 右侧tab
      tabDisabled: false,
      updateType: [],
      activeLineDialog: false,
      activityid: "",
      saveDisabled: false
    };
  },
  components: {
    ActiveLine
  },
  methods: {
    hideActiveLineDialog() {
      this.activeLineDialog = false;
    },
    online() {
      this.$confirm("当前编辑是否已保存", "提示", {
        confirmButtonText: "已保存继续",
        cancelButtonText: "继续编辑",
        type: "warning"
      })
        .then(() => {
          this.activeLineDialog = true;
          this.$nextTick(() => {
            this.$refs.onLine.getMarketingActivityInfo(
              this.sup8.urlparams.eid,
              this.sup8.urlparams.activityid
            );
          });
        })
        .catch(() => {});
    },
    onClickSetting(comp) {
      this.selectedComp = comp;
      if (!this.tabDisabled) {
        this.partRightActiveTab = "tab_prop";
      }
      this.$forceUpdate();
    },

    ChangeSelectComp(comp) {
      this.selectedComp = comp;
    },
    PropsChange(newPropsVal) {
      console.log("App.vue:methods:PropsChange:newPropsVal", newPropsVal);
      this.$set(this.selectedComp, newPropsVal);
      this.$forceUpdate();
    },

    onClickPreview() {
      this.qrConfig.previewUrl = window.location.host + "?id=" + this.cfg.id;
      this.qrConfig.dialogVisible = true;
    },
    onClickSave() {
      let that = this;
      let BasicActivityInfo = that.sup8.$utils.ssg("BasicActivityInfo");
      if (
        !BasicActivityInfo.ActivityName ||
        !BasicActivityInfo.ActivityNo ||
        !BasicActivityInfo.ObjectValue[0]
      ) {
        that.$message.warning("基础信息不完善，请完善信息");
        return;
      }
      // 整理模板数据
      let copyData = _.cloneDeep(this.cfg);
      copyData.state = !!copyData.state ? "Y" : "N"; //是否启用
      copyData.isOpen = !!copyData.isOpen ? "Y" : "N"; //是否公开
      copyData.updateId = that.sup8.urlparams.uid;
      copyData.createId = that.sup8.urlparams.uid;
      copyData.enterpriseId = that.sup8.urlparams.eid;
      copyData.title = that.sup8.$utils.ssg("BasicActivityInfo").ActivityName; //模板名称
      // copyData.type = 2;//模板类型，2营销模板
      // copyData.entryType = 0;//入口设备，不限
      // copyData.needSubscibe = 0;//是否需要关注公众号
      let templateinfo = encodeURI(
        JSON.stringify(this.convertCompPropsToList(_.cloneDeep(copyData)))
      );
      // return
      // 整理活动数据
      let activityinfo = {};
      activityinfo = {
        BasicActivityInfo: {},
        UserId: that.sup8.urlparams.userid,
        UserName: that.sup8.urlparams.username,
        OperUserId: that.sup8.urlparams.userid,
        OperUserName: that.sup8.urlparams.username,
        EnterpriseNo: that.sup8.urlparams.eid
      };
      activityinfo.BasicActivityInfo = that.sup8.$utils.ssg(
        "BasicActivityInfo"
      );
      this.saveDisabled = true;
      if (that.sup8.urlparams.option == 1) {
        _apiHelper.addActivity(
          JSON.stringify(activityinfo),
          templateinfo,
          1,
          function(res) {
            that.saveDisabled = false;
            if (res.flag) {
              that.$message.success("保存成功");
              let templatetype = that.sup8.urlparams.templatetype;
              let userid = that.sup8.urlparams.userid;
              let username = that.sup8.urlparams.username;
              let eid = that.sup8.urlparams.eid;
              setTimeout(function() {
                // 如果是新增配置，再完成保存后要进入 修改模式
                let newUrl = `${window.location.origin}/design_source/?id=${res.data.TemplateId}&templatetype=${templatetype}&userid=${userid}&username=${username}&eid=${eid}&option=2&activityid=${res.data.ActivityId}`;
                window.location.href = newUrl;
                // window.history.back();
              }, 800);
            } else {
              that.$message.error("保存失败");
            }
          }
        );
      }
      if (that.sup8.urlparams.option == 2) {
        _apiHelper.editActivity(
          JSON.stringify(activityinfo),
          templateinfo,
          2,
          function(res) {
            that.saveDisabled = false;
            if (res.flag) {
			  that.$message.success("保存成功");
			  setTimeout(function() {
				window.location.reload();
			  }, 1000);
            } else {
              that.$message.error("保存失败");
            }
          }
        );
      }
    },
    // 修改当前vue中的数据
    changeData: function(opt) {
      //debugger
      this._data = _.assign(this._data, opt);
      this.$forceUpdate();
    },

    registerComp: function(cb_success) {
      var that = this;
      var reqParam = {
        appkey: sessionStorage.appkey,
        accesstoken: sessionStorage.accesstoken,
        level: that.sup8.role.permissionLevel
      };

      _apiHelper.getBaseComponentList(
        undefined,
        that.sup8.role.permissionLevel,
        function(res) {
          if (res.flag && res.data) {
            that.sup8._baseComponentList = res.data;
            that.$parent.registComponent(res.data, true);
            cb_success && cb_success();
          }
        },
        function(res) {
          console.log("error", res);
        }
      );
    },

    load: function() {
      var that = this;
      that.loading = true;
      that.loadingText = "加载中，请稍候...";
      _apiHelper.getConfig(
        that.sup8.urlparams.id,
        undefined,
        that.sup8.urlparams.pageid ? that.sup8.urlparams.pageid : "",
        function(response) {
          that.loading = false;
          var data = response.data;
          if (!data || !data.length <= 0) {
            return;
          }
          that.cfg = data;
          that.cfg.state = that.cfg.state === "Y";
          that.cfg.isOpen = that.cfg.isOpen === "Y";

          if (that.sup8.urlparams.option === "1") {
            that.cfg.title = "";
            that.cfg.description = "";
          }

          // 转换属性形式
          _.forEach(that.cfg.pages, function(page, i) {
            _.forEach(page.components, function(com, k) {
              com.props = that.convertCompProps(com.props);
            });
          });
        },
        function(response) {
          //   console.log(response);
          that.loading = false;
        }
      );
    },
    // 设置组件属性值
    setCompProps: function(compProps) {
      this.selectedComp = compProps;
    },
    goBack() {
      let config = this.sup8.$utils.ssg("appConfig");
      if (!!config) {
        window.location.href =
          config.dash + "/MarketingActivityManage/WisdomTraceability/Index";
      } else {
        history.go(-1);
      }
    }
  },
  watch: {
    partRightActiveTab: function(n) {
      switch (n) {
        case "tab_participateRules":
          this.updateType.push(1);
          break;
        case "tab_awards":
          this.updateType.push(2);
          break;
        case "tab_winningRules":
          this.updateType.push(3);
          break;

        default:
          break;
      }
    },
    cfg: function(n, o) {
      //   console.log("watch:cfg", n, o);
      if (n.pages == null) {
        return;
      }
      var homePage = _.find(n.pages, {
        isHome: true
      });
      if (homePage) {
        this.selectedPage = homePage;
      } else {
        this.selectedPage = n.pages[0];
      }

      this.selectedComp = this.selectedPage.components[0];
      this.selectedPageId = this.selectedPage.id;
    },
    selectedComp: function(n, o) {},
    selectedPageId: function(n, o) {
      if (!this.cfg.pages) {
        return;
      }
      this.cfg.pages.forEach(element => {
        var isCurrent = element.id === n;
        element.isSelected = isCurrent;
      });

      var p = _.find(this.cfg.pages, {
        id: n
      });

      if (!p) return;
      //p.isSelected=true
      this.selectedPage = p;

      if (
        this.selectedPage.components &&
        this.selectedPage.components.length > 0
      ) {
        this.selectedComp = this.selectedPage.components[0];
      }

      this.$forceUpdate();
    },
    selectedPage: function(n, o) {
      //debugger
      //   console.log("DesignEnv::watch:selectedPage", n);
      if (
        !this.selectedPage.components ||
        this.selectedPage.components.length <= 0
      ) {
        this.selectedComp = undefined;
        return;
      }

      // 排序
      this.selectedPage.components = _.sortBy(
        this.selectedPage.components,
        "sort"
      );

      this.selectedComp = this.selectedPage.components[0];
    }
  },

  beforeCreate() {
    let that = this;
    //初始化、整理各种参数
    that.sup8.env = that.sup8._def.env.design;
    // 注册必须的页面组件
    let compPath = that.sup8._appConf.systemComponentsPath;
    _.forEach(that.sup8._appConf.design_antiFake.components, function(ch, i) {
      let compViewPath = compPath + ch + ".vue";
      let compViewName = ch;

      if (!!ch.path) {
        compViewPath = ch.path;
        compViewName = ch.componentViewName;
      }
      console.log("compViewName---:" + compViewName);
      Vue.component(compViewName, () => import(compViewPath + ""));
    });
    sessionStorage.removeItem("BasicActivityInfo");
  },
  created() {
    let that = this;
    document.title = "超级8|防伪编辑";
    this.registerComp(that.load);
  },
  mounted() {
    eventBus.subscribe("updatetab", data => {
      this.updateType.push(data);
    });
  }
};
</script>

<style>
@import "./assets/css/index.css";
</style>


<style>
.btn-goback {
  float: unset;
  background-color: #f7f7f7;
  padding: 3px 5px;
  font-size: 12px;
  border-radius: 0;
}

.btn-goback:hover {
  background-color: white;
}
/* input[type="number"]{
  padding-right: 0px;
} */
.el-input-number .el-input__inner {
  text-align: left;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>



