<template>
  <section class="dm-marketing">
    <!-- 操作区 -->
    <div class="dm-marketing__opt--wrap" v-if="list.length === 0">
      <span class="dm-marketing__opt--label">添加内容</span>
      <i class="el-icon-plus dm-marketing__opt--icon" @click="optTopShow = !optTopShow"></i>
      <transition name="fade">
        <opt @addItem="addItem" :options="showOptionList" v-if="optTopShow"></opt>
      </transition>
    </div>
    <!-- item组件区 -->
    <div class="dm-marketing__content--wrap" v-if="list.length">
      <span class="dm-marketing__content--label">回复内容</span>
      <div class="dm-marketing__content">
        <!-- 组件 区域 -->
        <div class="dm-marketing__content__item" v-for="(v, i) in list" :key="i">
          <i class="dm-marketing__content--index">{{ i + 1 }}</i>
          <component :is="v.comName" :item="v.item" :isSupportVar="isSupportVar"></component>
          <template v-if="!readOnly">
            <i class="el-icon-edit dm-marketing__opt--icon" v-if="showEdit(v) && (v.comName === 'item-teltask' || v.comName === 'item-text' || v.comName === 'item-wxa' || v.comName === 'item-integral' || v.comName === 'item-qywx' || v.comName === 'item-qfxx')" @click="editItem(v)"></i>
            <i v-else-if="v.comName == 'item-qywx' || v.comName == 'item-qfxx'" class="el-icon-view dm-marketing__opt--icon" @click="editItem(v, true)"></i>
            <dm-delete :tips="showDeleteTooltip ? '是否确定删除该营销事件？删除后，该计划营销分析数据可能会不准确。' : '是否删除？'" @confirm="delItem(v)">
              <i class="el-icon-delete dm-marketing__opt--icon"></i>
            </dm-delete>
          </template>
          <i v-else-if="v.comName == 'item-qywx' || v.comName == 'item-qfxx'" class="el-icon-view dm-marketing__opt--icon" @click="editItem(v)"></i>
        </div>
      </div>
    </div>
    <div v-if="!readOnly" class="dm-marketing__opt--wrap" @mouseleave="optShow = false">
      <i class="el-icon-plus dm-marketing__opt--icon--bottom" v-if="list.length && list.length < maxEventCount" @mouseover="optShow = true"></i>
      <transition name="fade">
        <opt @addItem="addItem" :options="showOptionList" v-if="list.length && list.length < maxEventCount && optShow" style="margin:0px 0 0 15px;position:relative;top:10px;"></opt>
      </transition>
    </div>
    <!-- 弹窗组件 -->
    <component :is="dialogCom" @sendItem="saveToList" :showOutCouponIcon="showOutCouponIcon" :item="currentItem" :show.sync="dialogShow" :isSupportVar="isSupportVar" :cardLimitType="cardLimitType" :integralMultiple="integralMultiple" :singleFlag="singleFlag" :read-only="readOnly || showView"></component>
  </section>
</template>

<script>
import { getMarketingEvent, getMarketingTypeDetails, saveUpdateMarketingType, deleteMarketingType } from './assets/api.js';
// 删除组件
import dmDelete from './components/dm-delete.vue';
// 操作组件
import opt from './components/opt.vue';
// 页面item组件
import itemTeletext from './components/item-teletext.vue';
import itemWxa from './components/item-wxa.vue';
import itemCard from './components/item-card.vue';
import itemText from './components/item-text.vue';
import itemImage from './components/item-image.vue';
import itemMessage from './components/item-Message.vue';
import itemTeltask from './components/item-teltask.vue';
import itemIntegral from './components/item-integral.vue';
import itemGrade from './components/item-grade';
import itemQywx from './components/item-qywx';
import itemQfxx from './components/item-qfxx';
//弹窗组件
import libTeletext from './components/lib-teletext.vue';
import libMessage from './components/lib-Message.vue';
import libCard from './components/lib-card.vue';
import libText from './components/lib-text.vue';
import libWxa from './components/lib-wxa.vue';
import libImage from './components/lib-image.vue';
import libTeltask from './components/lib-teltask.vue';
import libIntegral from './components/lib-integral.vue';
import libGrade from './components/lib-grade';
import libQywx from './components/lib-qywx';
import libQfxx from './components/lib-qfxx';

// 全部的操作项
// eslint-disable-next-line
let allOptions = [{ name: '企微任务', value: 'qywx', key: 10, img: require('./assets/img/qywx.svg'), hoverImg: require('./assets/img/qywx-1.svg'), show: true }, { name: '群发消息', value: 'qfxx', key: 11, img: require('./assets/img/qfxx.svg'), hoverImg: require('./assets/img/qfxx-1.svg'), disabledImg: require('./assets/img/qfxx-2.svg'), show: false, disabled: false }, { name: '图文', value: 'teletext', key: 1, img: require('./assets/img/teletext.svg'), hoverImg: require('./assets/img/teletext-1.svg'), show: true }, { name: '文本', value: 'text', key: 2, img: require('./assets/img/text.svg'), hoverImg: require('./assets/img/text-1.svg'), show: true }, { name: '小程序', value: 'wxa', key: 3, img: require('./assets/img/wxa.svg'), hoverImg: require('./assets/img/wxa-1.svg'), show: true }, { name: '图片', value: 'image', key: 4, img: require('./assets/img/image.svg'), hoverImg: require('./assets/img/image-1.svg'), show: true }, { name: '卡券', value: 'card', key: 5, img: require('./assets/img/card.svg'), hoverImg: require('./assets/img/card-1.svg'), show: true }, { name: '短信', value: 'message', key: 6, img: require('./assets/img/message.svg'), hoverImg: require('./assets/img/message-1.svg'), show: true }, { name: '话务', value: 'teltask', key: 7, img: require('./assets/img/teltask.svg'), hoverImg: require('./assets/img/teltask-1.svg'), show: true }, { name: '积分', value: 'integral', key: 8, img: require('./assets/img/integral.svg'), hoverImg: require('./assets/img/integral-1.svg'), show: true },{ name: '会员卡升级', value: 'grade', key: 9, img: require('./assets/img/grade.svg'), hoverImg: require('./assets/img/grade-1.svg'), disabledImg: require('./assets/img/grade-2.svg'), show: false, disabled: false }];
export default {
  name: 'vue-gic-marketing-event',
  components: {
    opt: opt,
    'dm-delete': dmDelete,

    'item-teletext': itemTeletext,
    'item-wxa': itemWxa,
    'item-card': itemCard,
    'item-text': itemText,
    'item-image': itemImage,
    'item-message': itemMessage,
    'item-teltask': itemTeltask,
    'item-integral': itemIntegral,

    'lib-teletext': libTeletext,
    'lib-message': libMessage,
    'lib-card': libCard,
    'lib-text': libText,
    'lib-wxa': libWxa,
    'lib-image': libImage,
    'lib-teltask': libTeltask,
    'lib-integral': libIntegral,
    'item-grade': itemGrade,
    'lib-grade': libGrade,
    'item-qywx': itemQywx,
    'lib-qywx': libQywx,
    'lib-qfxx': libQfxx,
    'item-qfxx': itemQfxx
  },
  props: {
    //  页面编码——- 1001-智能引擎; 1002-微信营销; 1003-被关注回复; 1004-关键字回复
    code: {
      type: String,
      default: '1001'
    },
    ecmPlanId: {
      type: String,
      default: ''
    },
    // 是否能发短信的flag
    enabledMessageState: {
      type: Number,
      default: 1
    },
    isSupportVar: {
      type: Boolean,
      default: false
    },
    cardLimitType: {
      type: Number,
      default: 1
    },
    integralMultiple: {
      // 积分 是否需要倍数（场景：消费触发）
      type: Boolean,
      default: false
    },
    singleFlag: {
      // 图文 实时发送这个参数为true，过滤图文仅要单图文
      type: Boolean,
      default: false
    },
    readOnly: {
      // 只读
      type: Boolean,
      default: false
    },
    // 是否展示外部券标识，仅用于卡券选择器中控制外部券标识展示 true：展示 false不展示
    showOutCouponIcon: {
      type: Boolean,
      default: false
    },
    useStored: {
      type: Boolean
    },
    useQywx: {
      type: Boolean,
      default: true
    },
    useQfxx: Boolean,
    showDeleteTooltip: Boolean
  },
  data() {
    return {
      showView: false,
      list: [],
      dialogShow: false,
      dialogCom: '',
      options: [],
      maxEventCount: 0, //item最大数
      currentItem: {},
      optShow: false,
      optTopShow: true
    };
  },
  created() {
    this.allOptions = [...allOptions];
    // if (this.useStored) {
    //   this.allOptions.push({ name: '会员卡升级', value: 'grade', key: 9, img: require('./assets/img/grade.svg') }); //eslint-disable-line
    // }
    this.init();
  },
  computed: {
    showOptionList() {
      if (this.useStored) {
        this.options.forEach(item => {
          if (item.value == 'grade') {
            item.show = true;
          }
        });
      } else {
        this.options.forEach(item => {
          if (item.value == 'grade') {
            item.show = false;
          }
        });
      }
      if (this.useQywx) {
        this.options.forEach(item => {
          if (item.value == 'qywx') {
            item.show = true;
          }
        });
      } else {
        this.options.forEach(item => {
          if (item.value == 'qywx') {
            item.show = false;
          }
        });
      }
      if (this.useQfxx) {
        this.options.forEach(item => {
          if (item.value == 'qfxx') {
            item.show = true;
          }
        });
      } else {
        this.options.forEach(item => {
          if (item.value == 'qfxx') {
            item.show = false;
          }
        });
      }
      return this.options.filter(item => item.show == true);
    }
  },
  watch: {
    // useStored: {
    //   handler() {
    //     console.log('useStored');
    //     if (this.useStored) {
    //       // this.options = [ ...this.options, { name: '会员卡升级', value: 'grade', key: 9, img: require('./assets/img/grade.svg'), disabled: false }]; //eslint-disable-line
    //       this.options.forEach(item => {
    //         if (item.value == 'grade') {
    //           item.show = false;
    //         }
    //       });
    //     } else {
    //       // this.options = this.options.filter(item => item.value !== 'grade');
    //       this.options.forEach(item => {
    //         if (item.value == 'grade') {
    //           item.show = true;
    //         }
    //       });
    //     }
    //   }
    // },
    // useQywx: {
    //   handler() {
    //     console.log('qywx');
    //     if (this.useQywx) {
    //       this.options.forEach(item => {
    //         if (item.value == 'qywx') {
    //           item.show = false;
    //         }
    //       });
    //     } else {
    //       this.options.forEach(item => {
    //         if (item.value == 'qywx') {
    //           item.show = true;
    //         }
    //       });
    //     }
    //   },
    // },
    list() {
      if (this.list.some(item => item.comName === 'item-grade')) {
        this.options.forEach(item => {
          if (item.value == 'grade') {
            item.disabled = true;
          }
        });
      } else {
        this.options.forEach(item => {
          if (item.value == 'grade') {
            item.disabled = false;
          }
        });
      }
      if (this.list.some(item => item.comName === 'item-qfxx')) {
        this.options.forEach(item => {
          if (item.value == 'qfxx') {
            item.disabled = true;
          }
        });
      } else {
        this.options.forEach(item => {
          if (item.value == 'qfxx') {
            item.disabled = false;
          }
        });
      }
      this.hasDeleted = this.list.some(el => el.item.status == 0);
      this.hasMaterialDeleted = this.list
        .filter(el => el.marketingType == 'qfxx')
        .some(el => {
          let item = JSON.parse(el.qfxx.chatContent);
          return item.statusFlag == 0;
        });
    }
  },
  methods: {
    /*------------------逻辑方法--------------*/
    // 初始化获取配置项
    init() {
      getMarketingEvent({ pageCode: this.code }).then(res => {
        console.log(res);
        if (res.errorCode === 0) {
          this.maxEventCount = Number(res.result.maxEventCount || 0);
          let list = res.result.list || [];
          let optionNameList = list.map(v => v.eventName);
          this.allOptions.map(v => {
            if (optionNameList.indexOf(v.name) >= 0) {
              this.options.push(v);
            }
          });
          this.getMarketingList();
        } else {
          this.$message({ type: 'warning', message: '组件初始化失败' });
        }
        console.log(res);
      });
    },
    // 初始化获取列表
    getMarketingList() {
      // console.log(this.ecmPlanId);
      getMarketingTypeDetails({ ecmPlanId: this.ecmPlanId }).then(res => {
        if (res.errorCode === 0) {
          this.list = [];
          let result = res.result.typeRelationList || [];
          let brandInfo = res.result.enterprise || {};
          // 八种类型 处理
          result.map(v => {
            switch (v.marketingType) {
              case 'teletext': // 1 图文
                this.list.push({ name: '图文', comName: 'item-teletext', item: { ...v.imageText, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId, status: v.status } });
                break;
              case 'text': // 2 文本
                this.list.push({ name: '文本', comName: 'item-text', item: { ...v.text, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                break;
              case 'wxa': // 3 小程序
                this.list.push({ name: '小程序', comName: 'item-wxa', item: { ...v.wxa, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId, brandLogo: brandInfo.qcloudImageUrl, brandName: brandInfo.brandName, status: v.status } });
                break;
              case 'card': // 5 卡券
                this.list.push({ name: '卡券', comName: 'item-card', item: { ...v.card, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId, brandLogo: brandInfo.qcloudImageUrl } });
                break;
              case 'image': // 4 图片
                this.list.push({ name: '图片', comName: 'item-image', item: { ...v.image, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId, status: v.status } });
                break;
              case 'message': // 6 短信
                const sms = v.sms || {};
                this.list.push({ name: '短信', comName: 'item-message', item: { title: v.title, ...sms, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId, status: v.status } });
                break;
              case 'teltask': // 7 话务
                this.list.push({ name: '话务', comName: 'item-teltask', item: { ...v.teltask, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                break;
              case 'integral': // 8 积分
                this.list.push({ name: '积分', comName: 'item-integral', item: { multipleNum: v.multipleNum, integralType: v.integralType, integralCount: v.integralCount, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                // this.list.push({ comName: 'item-teltask', item: { ...v.teltask, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                break;
              case 'grade': // 9 会员卡升级
                this.list.push({ name: '会员卡升级', comName: 'item-grade', item: { title: v.title, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                break;
              case 'qywx': // 10 企微任务
                this.list.push({ name: '企微任务', comName: 'item-qywx', item: { title: v.title, qywx: v.qywx, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                break;
              case 'qfxx': // 11 群发消息
                this.list.push({ name: '群发消息', comName: 'item-qfxx', item: { title: v.title, qfxx: v.qfxx, ecmMarketingTypeRelationId: v.ecmMarketingTypeRelationId, relationId: v.relationId, ecmPlanId: v.ecmPlanId } });
                break;
            }
          });
          this.hasReturnCard();
        }
      });
    },
    // 保存操作
    saveToList(val) {
      // 这里得提示一下短信是否欠费
      if (val.comName === 'message' && !this.enabledMessageState) {
        this.$message({ type: 'warning', message: "'您的通讯费已欠费，请及时于计费中心充值，并联系我司客服恢复功能使用，谢谢。" });
      }
      let params = {
        ecmPlanId: this.ecmPlanId, //从prop中取
        marketingType: val.comName
      };
      // 营销事件类型主键id, 新增不传, 修改必传
      if (val.ecmMarketingTypeRelationId) {
        params.ecmMarketingTypeRelationId = val.ecmMarketingTypeRelationId;
      }
      // 八种传值  1.话务
      if (val.comName === 'teltask') {
        params.title = val.title;
        params.teltask = {
          // ecm话务对象
          title: val.title,
          content: val.content,
          lateDays: val.lateDays
        };
      }
      // 2.文本
      if (val.comName === 'text') {
        params.title = val.content;
        // 如果有链接，需要判断链接类型
        params.text = {
          content: val.content,
          jumpUrlInfo: val.jumpUrlInfo && JSON.stringify(val.jumpUrlInfo),
          urlType: val.urlType
        };
      }
      // 3.小程序
      if (val.comName === 'wxa') {
        params.title = val.title;
        params.wxa = {
          title: val.title,
          mediaId: val.mediaId,
          pagePath: val.pagePath
        };
      }
      //4.图文
      if (val.comName === 'teletext') {
        params.title = val.title;
        params.relationId = val.imageTextWechatId;
      }

      //5.图片
      if (val.comName === 'image') {
        params.title = val.title;
        params.relationId = val.imageMediaId;
      }

      //6.卡券
      if (val.comName === 'card') {
        params.title = val.cardName;
        params.relationId = val.coupCardId;
      }

      //7.短信
      if (val.comName === 'message') {
        params.title = val.title;
        params.relationId = val.gicSmsTemplateId;
      }

      //8.积分
      if (val.comName === 'integral') {
        params.integralType = val.integralType;
        if (params.integralType === 1) {
          params.integralCount = val.integralCount;
        }
        if (params.integralType === 2) {
          params.multipleNum = val.multipleNum;
          params.title = `${val.multipleNum}倍积分`;
        }
      }

      //9.会员卡升级
      if (val.comName === 'grade') {
        params.title = val.title;
        params.relationId = val.relationId;
      }
      if (val.comName === 'qywx' || val.comName === 'qfxx') {
        delete val.comName;
        delete val.ecmMarketingTypeRelationId;
        params = { ...params, ...val };
      }
      // 接口请求 保存
      saveUpdateMarketingType({ marketingType: JSON.stringify(params) })
        .then(res => {
          this.getMarketingList();
        })
        .catch(err => {
          this.$message({ message: err.data.message, type: 'error' });
        });
    },
    // 新增前置 不能超过营销事件限制数量
    addItem(v) {
      if (this.isOverMaxCount()) {
        this.$message({ type: 'warning', message: `最多只能添加${this.maxEventCount}个营销事件` });
        return;
      }
      // if (v.value === 'grade' && this.list.some(item => item.comName === 'item-grade')) {
      //   this.$message({ type: 'warning', message: `已添加会员卡升级营销事件` });
      //   return;
      // }
      // 判断是否欠费
      if (v.value === 'message' && this.checkAccountState()) return;
      this.dialogCom = 'lib-' + v.value;
      // 新增的时候设置为空对象
      this.currentItem = {};
      this.dialogShow = true;
    },
    // 删除操作
    delItem(item) {
      console.log(item);
      deleteMarketingType({ ecmMarketingTypeRelationId: item.item.ecmMarketingTypeRelationId, ecmPlanId: this.ecmPlanId })
        .then(res => {
          if (res.errorCode === 0) {
            this.getMarketingList();
          } else {
            this.$message({ message: res.message, type: 'error' });
          }
        })
        .catch(err => {
          this.$message({ message: err.data.message, type: 'error' });
        });
    },
    // 编辑前置
    editItem(obj, showView) {
      this.currentItem = obj.item;
      this.dialogCom = 'lib-' + obj.comName.slice(5);
      this.$nextTick(_ => {
        this.dialogShow = true;
      });
      this.showView = !!showView;
    },

    /*------------------辅助方法--------------*/
    // 账户状态判断
    checkAccountState() {
      // whiteStatus:1白名单账户
      if (localStorage.getItem('whiteStatus') != 1 && localStorage.getItem('accountStatus') == 2) {
        this.$alert(
          `<div>
        <i class="el-icon-warning warning-color fz30 vertical-middle mr20"></i>
        <p class="inline-block vertical-middle w300">当前账户已欠费，无法正常使用短信服务。为了保障您的权益，请及时充值。</p>
        </div>`,
          '提示',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '前往充值中心',
            customClass: 'message-box--btn-center'
          }
        ).then(res => {
          if (res === 'confirm') {
            this.$router.push('/recharge/do');
          }
        });
        return true;
      }
    },
    //  判断是否大于最大数量
    isOverMaxCount() {
      return this.list.length >= this.maxEventCount;
    },
    //判断营销列表里是否有短信 提供给父级使用
    hasMessageInList() {
      return this.list.some(v => v.comName === 'item-message' && v.item.type === 1);
    },
    //判断营销列表里是否包含积分--订单倍数 提供给父级使用
    hasIntegralMultiple() {
      return this.list.some(v => v.comName === 'item-integral' && v.item.integralType === 2);
    },
    //判断营销列表里是否有卡券 提供给父级使用
    hasReturnCard() {
      let item = {};
      try {
        this.list.forEach(v => {
          if (v.comName === 'item-card') {
            item = v;
            throw new Error();
          }
        });
      } catch (e) {
        console.log(e);
      }
      this.$emit('has-card', item);
    },
    showEdit(item) {
      return this.options.some(i => {
        return 'item-' + i.value == item.comName;
      });
    }
  }
};
</script>
<style lang="scss">
@import url('./assets/style/index.css');

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
  transform: translate(0);
}
.fade-enter, .fade-leave-to /* .fade-leave-active below version 2.1.8 */ {
  opacity: 0;
  display: none;
}
</style>
