<template>
  <div class="pricedriven-container">
    <!-- 展开 -->
    <span
      class="slide-icon slide-right"
      @click="isSlideLeft = !isSlideLeft"
      v-show="isSlideLeft"
    >
      <i class="el-icon-d-arrow-right"></i>
    </span>
    <div class="left-wrapper wrapper" v-show="!isSlideLeft">
      
      <!-- 收起 -->
      <span class="slide-icon slide-left" @click="isSlideLeft = !isSlideLeft">
        <i class="el-icon-d-arrow-left"></i>
      </span>

      <el-collapse v-model="activeTab" class="clasify-collapse">
        <el-collapse-item
          v-for="(item, index) in varietyList"
          :key="index"
          :title="item.ClassifyName"
          :name="index"
        >
          <div class="classify-cont">
            <span
              v-for="classify in item.Items"
              :key="classify.PermissionId"
              :class="[
                'classify-item',
                {
                  act: select_variety === classify.PermissionId,
                  disabled: !classify.PriceDrivenState,
                  'disabled-act':
                    select_variety === classify.PermissionId && !classify.PriceDrivenState,
                },
              ]"
              @click="selectClassifyHandle(classify)"
              >{{ classify.PermissionName }}</span
            >
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="right-wrapper wrapper">
      <div class="main-top">
        <span>上次发布时间：{{ formData.lastUpdateTime }}</span>
        <div class="right-actions">
          <el-button
            type="primary"
            :disabled="formData.allowSendTemplateMsg || !formData.publishState"
            @click="pushTemplateMsgHandle"
            >{{
              formData.allowSendTemplateMsg ? "已推送模板消息" : "推送模板消息"
            }}</el-button
          >
          <el-button
            type="primary"
            :disabled="formData.allowSendgroupMsg || !formData.publishState"
            @click="pushGroupHandle"
            >{{
              formData.allowSendgroupMsg ? "已推送客群消息" : "推送客群消息"
            }}</el-button
          >
          <el-button
            type="primary"
            :disabled="!formData.status"
            @click="updateVariety"
            >更新</el-button
          >
          <el-button
            type="danger"
            v-if="formData.status"
            @click="updateStatusHandle"
            >关闭</el-button
          >
          <el-button type="primary" v-else @click="updateStatusHandle"
            >开启</el-button
          >
        </div>
      </div>
      <h3>核心内容</h3>
      <div class="main-bottom">
        <div class="editor-cont">
          <froala
            id="froala-editor"
            ref="froalaEditor"
            :tag="'textarea'"
            :config="froalaConfig"
            v-model="formData.content"
          />
        </div>
        <div class="right-section">
          <el-tabs>
            <el-tab-pane label="基础信息">
              <el-form
                ref="diaForm"
                label-position="top"
                inline
                label-width="80px"
                :model="formData"
              >
                <el-form-item label="关键变量">
                  <el-input
                    v-model="formData.keyVariable"
                    type="textarea"
                    placeholder="请输入关键变量"
                    :autosize="{ minRows: 3, maxRows: 7 }"
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item label="核心驱动" class="form-flex">
                  <el-radio-group v-model="formData.driverType">
                    <el-radio :label="0">多</el-radio>
                    <el-radio :label="1">空</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="">
                  <el-input
                    v-model="formData.driverCont"
                    type="textarea"
                    placeholder="请输入核心驱动"
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="图表插入">
              <el-input
                placeholder="标题/子标题/作者"
                v-model="key_word"
                size="medium"
                prefix-icon="el-icon-search"
                @input="getreportList"
              />
              <div class="chart-img-wrapper">
                <div
                  v-for="(item, index) in chartArr"
                  :key="item.ChartInfoId"
                  :style="item.Disabled && 'cursor: not-allowed;'"
                  class="liststy"
                >
                  <p class="color_primary">{{ item.ChartName }}</p>
                  <img
                    :src="item.ChartImage"
                    :id="'listnode' + index"
                    @click="insertHtml(item)"
                  />
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { customInterence, dataBaseInterface,departInterence } from "@/api/api.js";
import * as priceApi from "@/api/modules/priceDriven.js";
import mixin from "./mixins/editor";

export default {
  data() {
    return {
      isSlideLeft: false,
      activeTab: [0],
      select_variety: "",
      varietyList: [], //品种列表
      formData: {
        status: "", //品种状态
        keyVariable: "",
        driverType: 1,
        driverCont: "",
        lastUpdateTime: "",
        content: "",
        allowSendTemplateMsg: true, //允许模板消息
        allowSendgroupMsg: true, //允许推送客群消息
        pricedrivenId: "", //驱动报告id
        lastUpdateAdminId: "",
        lastUpdateAdminName: "",
        publishState: '',//更新状态
      },
      key_word: "", //图表搜索
      chartArr: [],
    };
  },
  mixins: [mixin],
  methods: {
    	// 每十秒自动保存
		autoSave() {
			if (this.formData.pricedrivenId && this.ischange) {
        this.updateApiHandle('autosave')
				this.ischange = false;
			}
		},
    /* 获取品种 */
    getClassify() {
      /* priceApi.classifyList().then((res) => {
        if (res.Ret !== 200) return;

        this.varietyList = res.Data || [];
        this.init();
      }); */
      //接口更换
      departInterence.getTagTree({
        IncludeDisableTag:1
      }).then((res)=>{
        if(res.Ret !== 200) return;
        const result = res.Data||[];
        this.varietyList = result.map(item=>{
          let obj = {};
          obj.ClassifyName = item.classify_name;
          obj.Items = item.tags.map(_item=>{
            return {PermissionId:_item.tag_id,PermissionName:_item.tag_name,PriceDrivenState:_item.price_driven_state};
          })
          return obj;
        })
        this.init();
      })
    },

    /* 获取品种详情 */
    getReportDetail() {
      priceApi
        .reportDetail({
          VarietyTagId: this.select_variety,
        })
        .then((res) => {
          if (res.Ret !== 200) return;

          this.resetData(res.Data);
        });
    },

    /* 更新form内容 */
    resetData({
      MainVariable,
      CoreDrivenType,
      CoreDrivenContent,
      CoreContent,
      TemplateMsgState,
      ThsMsgState,
      ModifyTime,
      PriceDrivenId,
      LastUpdateAdminId,
      LastUpdateAdminName,
      PublishState
    }) {
      this.formData.keyVariable = MainVariable;
      this.formData.driverType = CoreDrivenType;
      this.formData.driverCont = CoreDrivenContent;
      this.formData.lastUpdateTime = ModifyTime;
      this.formData.content = CoreContent;
      this.formData.allowSendTemplateMsg = TemplateMsgState;
      this.formData.allowSendgroupMsg = ThsMsgState;
      this.formData.pricedrivenId = PriceDrivenId;
      this.formData.publishState = PublishState;
      this.formData.lastUpdateAdminId = LastUpdateAdminId;
      this.formData.lastUpdateAdminName = LastUpdateAdminName;
    },

    init() {
      this.select_variety = this.varietyList[0].Items[0].PermissionId;
      this.formData.status = this.varietyList[0].Items[0].PriceDrivenState;
      this.getReportDetail();
    },

    /* 获取商品图表 */
    getreportList() {
      dataBaseInterface
        .chartSearch({
          KeyWord: this.key_word || "",
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          this.chartArr = res.Data || [];
        });
    },

    /* 选择品种 */
    selectClassifyHandle({ PermissionId, PriceDrivenState }) {
      this.select_variety = PermissionId;
      this.formData.status = PriceDrivenState;
      this.getReportDetail();
    },

    /* 启用/关闭品种 */
    updateStatusHandle() {
      this.formData.status ? this.$confirm(
        "关闭后该品种不可更新，且小程序端不可见，确认关闭吗？",
        "关闭提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => { this.updateStatusApiHandle() })
        .catch(() => {})
      : this.updateStatusApiHandle()
    },

    /* 启用/关闭接口 */
    updateStatusApiHandle() {
      priceApi.updateState({
        VarietyTagId: this.select_variety,
        PriceDrivenState: this.formData.status ? 0 : 1
      }).then(res => {
        if(res.Ret !== 200) return

        this.formData.status = this.formData.status ? 0 : 1;

        let select_obj = this.varietyList.map(item => item.Items).flat(1).find(_ => _.PermissionId === this.select_variety)
        select_obj.PriceDrivenState = this.formData.status;
      })
    },

    /* 更新品种 */
    updateVariety() {
      const {
        keyVariable,
        driverCont,
        content,
        allowSendgroupMsg,
      } = this.formData;
      let cloneContent = _.cloneDeep(content);
      let ad_index = content.indexOf('<p data-f-id="pbf"');
      let filter_content =  ad_index  === -1 ? cloneContent : cloneContent.substring(0,ad_index);
      if (!keyVariable || !driverCont || !filter_content)
        return this.$message.warning(
          `${
            !keyVariable
              ? "请输入关键变量"
              : !driverCont
              ? "请输入核心驱动"
              : "请输入核心内容"
          }`
        );

      !allowSendgroupMsg
        ? this.$confirm("发布后,是否推送客户群?", "更新提示", {
            distinguishCancelAndClose: true,
            confirmButtonText: "推送",
            cancelButtonText: "不推送",
            type: "warning",
          })
            .then(() => {
              this.updateApiHandle('',true);
            })
            .catch(action => {
              action === 'cancel' ? this.updateApiHandle() : null
            })
        : this.updateApiHandle();
    },

    /* 推送客户群消息 */
    async pushGroupHandle() {
      const { Ret } = await priceApi.pushGroupMessage({
        PriceDrivenId: this.formData.pricedrivenId,
      });
      if(Ret !== 200) return
      this.$message.success('已推送客群')
      this.formData.allowSendgroupMsg = 1;
    },

    /* 更新接口 */
    updateApiHandle(savetype="",isPushMsg=false) {
      const {
        keyVariable,
        driverType,
        driverCont,
        content,
        lastUpdateAdminId,
        lastUpdateAdminName,
      } = this.formData;
      priceApi
        .saveReport({
          VarietyTagId: this.select_variety,
          MainVariable: keyVariable,
          CoreDrivenType: driverType,
          CoreDrivenContent: driverCont,
          CoreContent: content,
          LastUpdateAdminId: lastUpdateAdminId,
          LastUpdateAdminName: lastUpdateAdminName,
          AutoSave: savetype === 'autosave' ? 1 : 0
        })
        .then((res) => {
          if (res.Ret !== 200) return;
          savetype !== 'autosave' &&  this.$message.success("发布成功");
          this.resetData(res.Data);

          isPushMsg && this.pushGroupHandle();
          
        });
    },

    /* 推送模板消息 */
    pushTemplateMsgHandle() {
      priceApi.pushTemplateMessage({
        PriceDrivenId: this.formData.pricedrivenId,
      }).then(res => {
        if(res.Ret !== 200) return
        this.$message.success('已推送')
        this.formData.allowSendTemplateMsg = 1; 
      })
    }
  },
  mounted() {
    this.getClassify();
    this.getreportList();
    this.timer = setInterval(() => {
      this.autoSave();
    }, 6000);
  },

  destroyed() {
    if (this.timer) clearInterval(this.timer);
  }
};
</script>

<style scoped lang="scss">
* {
  box-sizing: border-box;
}
.pricedriven-container {
  display: flex;
  height: calc(100vh - 115px);
  .slide-icon {
    padding: 20px 0;
    /* display: block; */
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.3);
    border-radius: 5px;
    cursor: pointer;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    z-index: 99;
    &:hover {
      background-color: rgba(0, 0, 0, 0.05);
    }
    &.slide-left {
      right: 0;
    }
    &.slide-right {
      left: 0;
    }
  }
  .wrapper {
    padding: 20px 30px;
    background: #fff;
    border: 1px solid #ececec;
    border-radius: 4px;
    box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
    overflow-y: auto;
    &.left-wrapper {
      width: 280px;
      margin-right: 20px;
      position: relative;
      .classify-cont {
        display: flex;
        flex-wrap: wrap;
      }
      .classify-item {
        margin: 6px;
        color: #409eff;
        background: #ecf5ff;
        border: 1px solid #b3d8ff;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        &.disabled {
          background: #f0f2f5;
          border: 1px solid #dcdfe6;
          color: #666;
        }
        &.act {
          background: #409eff;
          color: #fff;
        }
        &.disabled-act {
          background: #666;
          color: #fff;
        }
      }
    }
    &.right-wrapper {
      flex: 1;
      .main-top {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .main-bottom {
        display: flex;
        margin-top: 10px;
        .editor-cont {
          min-width: 320px;
        }
      }
    }
  }
  .right-section {
    width: 40%;
    min-width: 350px;
    margin-left: 20px;
    border: 1px solid #409eff;
    border-radius: 10px;
    padding: 20px;

    .chart-img-wrapper {
      height: calc(100vh - 380px);
      overflow-x: hidden;
      overflow-y: auto;
      .liststy {
        width: 100%;
        margin: 20px 0;
        padding: 20px;
        box-sizing: border-box;
        border: 1px solid #eaeaea;
        border-radius: 10px;
        position: relative;
        overflow: hidden;
        > p {
          text-align: center;
          font-size: 16px;
          margin-bottom: 10px;
        }
        > img {
          width: 100%;
          height: auto;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.pricedriven-container {
  .clasify-collapse,
  .el-collapse-item__header,
  .el-collapse-item__wrap {
    border: none;
  }
  .el-collapse-item__arrow {
    margin-left: 8px;
    /* position: absolute;
    left: 60px; */
  }
  .el-collapse-item__header {
    height: 30px;
    line-height: 30px;
  }
  .el-form-item {
    width: 100%;
  }
  .form-flex {
    display: flex;
    margin-bottom: 0;
    .el-form-item__content {
      margin-left: 20px;
    }
  }
  .el-tabs__item {
    font-size: 16px;
    font-weight: 600;
  }
  .el-tabs__nav-wrap::after {
    background: transparent;
  }
  .fr-quick-insert {
    display: none;
  }
  .is-disabled {
    &.is-disabled {
      background: #666;
      border-color: #666;
    }
  }
}
</style>
