<script setup>
import { ref,reactive,onUnmounted} from "vue";
import {ElMessageBox,ElMessage} from 'element-plus'
import {DArrowRight,DArrowLeft,Search} from '@element-plus/icons-vue'
import _ from 'lodash'

import { dataBaseInterface,departInterence } from "@/api/api.js";
import * as priceApi from "@/api/modules/priceDriven.js";
import {editorHook} from "./hooks/editor";

const {ischange,froalaConfig,insertHtml} = editorHook()

const isSlideLeft=ref(false)
const activeTab=ref([0])
const select_variety=ref("")
const varietyList=ref([]) //品种列表
const form=reactive({
  formData:{
    status: "", //品种状态
    keyVariable: "",
    driverType: 1,
    driverCont: "",
    lastUpdateTime: "",
    content: "",
    allowSendTemplateMsg: true, //允许模板消息
    allowSendgroupMsg: true, //允许推送客群消息
    pricedrivenId: "", //驱动报告id
    lastUpdateAdminId: "",
    lastUpdateAdminName: "",
    publishState: '',//更新状态
  }
})
const key_word=ref("") //图表搜索
const chartArr=ref([])
let timer=null

// 每十秒自动保存
const autoSave=()=>{
  if (form.formData.pricedrivenId && ischange.value) {
    updateApiHandle('autosave')
    ischange.value = false;
  }
}
/* 获取品种 */
const getClassify=()=>{
  //接口更换
  departInterence.getTagTree({
    IncludeDisableTag:1
  }).then((res)=>{
    if(res.Ret !== 200) return;
    const result = res.Data||[];
    varietyList.value = 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;
    })
    init();
  })
}

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

      resetData(res.Data);
    });
}

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

const init=()=>{
  select_variety.value = varietyList.value[0].Items[0].PermissionId;
  form.formData.status = varietyList.value[0].Items[0].PriceDrivenState;
  getReportDetail();
}

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

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

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

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

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

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

/* 更新品种 */
const updateVariety=()=>{
  const {
    keyVariable,
    driverCont,
    content,
    allowSendgroupMsg,
  } = form.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 ElMessage.warning(
      `${
        !keyVariable
          ? "请输入关键变量"
          : !driverCont
          ? "请输入核心驱动"
          : "请输入核心内容"
      }`
    );

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

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

/* 更新接口 */
const updateApiHandle=(savetype="",isPushMsg=false)=>{
  const {
    keyVariable,
    driverType,
    driverCont,
    content,
    lastUpdateAdminId,
    lastUpdateAdminName,
  } = form.formData;
  priceApi
    .saveReport({
      VarietyTagId: select_variety.value,
      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' &&  ElMessage.success("发布成功");
      resetData(res.Data);

      isPushMsg && pushGroupHandle();
      
    });
}

/* 推送模板消息 */
const pushTemplateMsgHandle=()=>{
  priceApi.pushTemplateMessage({
    PriceDrivenId: form.formData.pricedrivenId,
  }).then(res => {
    if(res.Ret !== 200) return
    ElMessage.success('已推送')
    form.formData.allowSendTemplateMsg = 1; 
  })
}

onUnmounted(()=>{
  if (timer) clearInterval(timer);
})

getClassify();
getreportList();
timer = setInterval(() => {
  autoSave();
}, 6000);

</script>

<template>
  <div class="pricedriven-container">
    <!-- 展开 -->
    <span
      class="slide-icon slide-right"
      @click="isSlideLeft = !isSlideLeft"
      v-show="isSlideLeft"
    >
      <el-icon><DArrowRight /></el-icon>
    </span>
    <div class="left-wrapper wrapper" v-show="!isSlideLeft">
      
      <!-- 收起 -->
      <span class="slide-icon slide-left" @click="isSlideLeft = !isSlideLeft">
        <el-icon><DArrowLeft /></el-icon>
      </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>上次发布时间：{{ form.formData.lastUpdateTime }}</span>
        <div class="right-actions">
          <el-button
            type="primary"
            :disabled="!!form.formData.allowSendTemplateMsg || !form.formData.publishState"
            @click="pushTemplateMsgHandle"
            >{{
              form.formData.allowSendTemplateMsg ? "已推送模板消息" : "推送模板消息"
            }}</el-button
          >
          <el-button
            type="primary"
            :disabled="!!form.formData.allowSendgroupMsg || !form.formData.publishState"
            @click="pushGroupHandle"
            >{{
              form.formData.allowSendgroupMsg ? "已推送客群消息" : "推送客群消息"
            }}</el-button
          >
          <el-button
            type="primary"
            :disabled="!form.formData.status"
            @click="updateVariety"
            >更新</el-button
          >
          <el-button
            type="danger"
            v-if="form.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="form.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="form.formData"
              >
                <el-form-item label="关键变量">
                  <el-input
                    v-model="form.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="form.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="form.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="default"
                :prefix-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>

<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>
