<template>
  <el-form ref="form" :model="form" label-width="100px" :rules="rules" v-loading="loading" element-loading-text="拼命加载中" >
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">计划内容设置</h3>
      <el-form-item label="计划名称" prop="ecmPlanName" class="width50">
        <dm-input class="w400" :maxlength="9" v-model="form.ecmPlanName" :disabled="detailFlag"></dm-input>
      </el-form-item>
      <el-form-item label="时效" class="width50">
        <el-radio v-model="form.effectType" :label="0">实时</el-radio>
        <el-radio class="mr10" v-model="form.effectType" :label="1">每天</el-radio>
        <el-select style="width:262px;" v-model="form.effectTime"  v-if="form.effectType" :disabled="detailFlag" placeholder="请选择时间">
          <el-option v-for="(v,i) in dayOptions" :key="i" :label="v.label" :value="v.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="触发行为" class="width50" v-if="!form.effectType">
        <el-select class="w400" v-model="form.effectAction" :disabled="detailFlag" placeholder="选择发送状态">
          <el-option v-for="(v,i) in effectActionOptions" :key="i" :label="v.label" :value="v.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="常用场景" class="width50" v-if="form.effectType">
        <div class="fz12 gray">选填，勾选后生效</div>
        <div class="pb10">
          <el-radio v-model="radio" class="w150" label="brithday_day">会员生日前 </el-radio>
          <el-input-number controls-position="right" :min="0" style="width:244px;" :disabled="radio !== 'brithday_day'" v-model="form.brithday_day"></el-input-number> 天
        </div>
        <div class="pb10">
          <el-radio v-model="radio" class="w150" label="attention_day">关注时长超过 </el-radio>
          <el-input-number controls-position="right" :min="0" :max="100000" style="width:244px;" :disabled="radio !== 'attention_day'" v-model="form.attention_day"></el-input-number> 天
        </div>
        <div class="pb10">
          <el-radio v-model="radio" class="w150" label="lastCost_day">最近消费间隔 </el-radio>
          <el-input-number controls-position="right" :min="0" style="width:244px;" :disabled="radio !== 'lastCost_day'" v-model="form.lastCost_day"></el-input-number> 天
        </div>
      </el-form-item>
      <el-form-item label="营销场景">
        <span v-if="editFlag">{{form.sceneSettingName}}</span>
        <el-select  v-else class="w400"  v-model="form.sceneSettingId" placeholder="选择营销场景">
          <el-option v-for="item in sceneSettingIdOptions" :key="item.sceneSettingId" :label="item.sceneName" :value="item.sceneSettingId"></el-option>
        </el-select>
      </el-form-item>
     </section>
     <section class="dm-form__wrap">
      <h3 class="dm-title__label">适用人群</h3>
        <div class="mb20">
            <vue-gic-people :projectName="projectName" :useId="useId" :hasSearchData="hasSearchData" :sceneValue="sceneValue" ref="peopleFilter" @findFilter="findFilter" @getBackData="getBackData"  @editHide= "editHide" @editShow="editShow" @hideBtn="hideBtn"/>
            <div class="gic-people--button" v-show="toggleTag">
              <el-button size="small" type="primary" @click="getData">确 定</el-button>
              <el-button size="small" @click="cancelFilter">取 消</el-button>
            </div>
            <!-- <div v-else>
              <el-button @click="saveTempData">保存</el-button>
            </div> -->
        </div>
    </section>
    <section class="dm-form__wrap">
      <h3 class="dm-title__label">营销方式</h3>
      <div class="pb20 pt10">
        <el-radio-group v-model="form.marketingType">
          <el-radio label="message">短信营销</el-radio>
          <el-radio label="card">卡券营销</el-radio>
          <el-radio label="teletext">图文营销</el-radio>
          <el-radio label="text">文本营销</el-radio>
          <el-radio label="image">图片营销</el-radio>
          <el-radio v-if="enterpriseEdition" label="teltask">话务营销</el-radio>
        </el-radio-group>
      </div>
      <div v-if="form.marketingType === 'teltask'" class="border-radius2" style="padding:15px;">
        <el-form-item label="话务任务标题" class="pb10 pt5">
          <dm-input class="w400" v-model="form.title" placeholder="限制20个字符" :maxlength="20"></dm-input>
        </el-form-item>
        <el-form-item label="话务任务内容" class="pb10">
          <dm-input class="w400" :rows="4"  type="textarea" v-model="form.describe" placeholder="限制200个字符" :maxlength="200"></dm-input>
        </el-form-item>
        <el-form-item  label="任务逾期判定">
          <el-input-number controls-position="right" class="w400" v-model="form.lateDays"></el-input-number> 天之后
        </el-form-item>
      </div>
      <!-- 短信 cardId -->
      <div v-if="form.marketingType === 'message'" class="border-radius2" style="padding:15px;">
        <sms-temp :activeId.sync="form.cardId" pbSize="pb15"></sms-temp>
      </div>
      <!-- 图文 cardId  mediaId  imageTextId -->
      <div v-if="form.marketingType === 'teletext'"  class="border-radius2" style="padding:15px;">
        <dm-img-text @get-data="getImgTextData" pbSize="pb15" :activeId.sync="form.mediaId" :radioShow="true" :auto="false" ></dm-img-text>
      </div>
      <!-- 图片 cardId  mediaId -->
      <dm-img-box v-if="form.marketingType === 'image'" @get-data="getImgData" :mediaId.sync="form.mediaId"></dm-img-box>
       <!-- 卡券 cardId -->
      <div v-if="form.marketingType === 'card'" class="border-radius2" style="padding:15px;">
        <cardTemp pbSize="pb15" :activeId.sync="form.cardId" cardIdName="wechatCardId"></cardTemp>
      </div>
      <!-- 文本 textContent -->
      <div v-show="form.marketingType === 'text'">
          <wxText :msgText="form.textContent" @listenWxText="getWxText"></wxText>
      </div>

    </section>
    <div class="btn-wrap_fixed" :class="{'on':asideShow}">
      <el-button type="primary" @click="submit('form')" v-if="!detailFlag">保 存</el-button>
      <el-button  @click="$router.go(-1)">返 回</el-button>
    </div>
  </el-form>
</template>

<script>
import {getEcmInfo,saveEcmInfo} from '@/service/api/ecmApi.js';
import {sceneSettingList} from '@/service/api/commonApi.js';
import smsTemp from '@/components/libs/smsTemp';
import dmImgText from '@/components/libs/imgTextTemp'
import dmImgBox from '@/components/libs/imgTemp/index-box.vue'
import cardTemp from '@/components/libs/cardTemp'
import config from '@/config'
import wxText from '@/components/wxText/wxText'
import {checkMessageSendCount} from '@/service/api/messageApi.js';
export default {
  data () {
    return {
      loading:false,
      effectActionOptions:[{value:'subscribe',label:'关注触发'},{value:'authentication',label:'认证触发'}],
      dayOptions:[
        {value:0,label:'0:00'},
        {value:1,label:'1:00'},
        {value:2,label:'2:00'},
        {value:3,label:'3:00'},
        {value:4,label:'4:00'},
        {value:5,label:'5:00'},
        {value:6,label:'6:00'},
        {value:7,label:'7:00'},
        {value:8,label:'8:00'},
        {value:9,label:'9:00'},
        {value:10,label:'10:00'},
        {value:11,label:'11:00'},
        {value:12,label:'12:00'},
        {value:13,label:'13:00'},
        {value:14,label:'14:00'},
        {value:15,label:'15:00'},
        {value:16,label:'16:00'},
        {value:17,label:'17:00'},
        {value:18,label:'18:00'},
        {value:19,label:'19:00'},
        {value:20,label:'20:00'},
        {value:21,label:'21:00'},
        {value:22,label:'22:00'},
        {value:23,label:'23:00'},
        ],
      sceneSettingIdOptions:[],
      form:{
        ecmPlanName:'',
        effectType:0,
        effectTime:0,
        effectAction:'subscribe',
        sceneSettingId:'',
        sceneSettingName:'',
        marketingType:'message',
        cardId:'',
        mediaId:'',
        imageTextId:'',
        textContent:'',
        title:'',
        describe:'',
        lateDays:'',
        brithday_day:'',
        attention_day:'',
        lastCost_day:'',
        memberSearchDTO:''
      },
      radio:'',
      rules:{
        ecmPlanName:{type:'string', required: true, message: '计划名称不能为空', trigger: 'blur' },
      },
      editFlag:this.$route.meta.type === 'edit',
      detailFlag:this.$route.meta.type === 'detail',
      content: '',
      customToolbar: [['link']],
      // 人群筛选器可传参数
      projectName: '', // 当前项目名
      sceneValue: 'member', // 场景值
      useId: '', // 模板id
      hasSearchData: '' , // 当前页回显的数据(接口返回)
      toggleTag: false, // 控制按钮显示的参数,仅供参考,可自行修改
      getSaveData:'',
      saveTag:false,

      enterpriseEdition:true,
      enabledMessageState:true,
    }
  },
  components:{
    smsTemp,
    dmImgText,
    dmImgBox,
    cardTemp,
    wxText
  },
  computed: {
    asideShow() {
      return this.$store.state.marketing.asideShow
    }
  },
  created(){
    this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'智能营销',path:'/ecm'},{name:'智能营销管理',path:''}]);
    if (this.editFlag || this.detailFlag) {
      this.getEcmInfo();
    } else {
      this.sceneSettingList();
    }
  },
  methods: {
    // 微信文本
    getWxText(data){
      this.form.textContent = data.textarea;
      this.form.imageMediaId = data.imageMediaId;
    },
    getData() {
      this.$refs.peopleFilter.confirmSet()
    },
    // 子组件触发父组件事件,返回过滤条件数据
    findFilter(value){
      console.log(value)
      this.form.memberSearchDTO = value;
    },
    // 取消
    cancelFilter(){
      this.$refs.peopleFilter.cancelSet()
    },
    // 获取需要回显的数据, 供保存时候使用
    getBackData(val) {
      console.log(val)
      this.getSaveData = val;
    },
    // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
    editShow() {
      var that = this
      console.log('editShow')
      that.toggleTag = true
      that.saveTag = false
    },
    // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
    editHide() {
      var that = this
      console.log('editHide')
      that.toggleTag = false
      that.saveTag = true
    },
    // 隐藏保存按钮和确认按钮  (子组件会调用)
    hideBtn() {
      var that = this
      that.toggleTag = false;
      that.saveTag = false
    },
    //获取图文id
    getImgTextData(val) {
       console.log(val)
      this.form.mediaId = val.imageTextWechatId;
      this.form.imageTextId = val.imageTextId;
    },
    //获取图片id
    getImgData(val) {
      console.log(val)
      this.form.mediaId = val;
    },
    async sceneSettingList() {
        let res = await sceneSettingList();
        this.sceneSettingIdOptions = res.result;
    },
    async getEcmInfo() {
      this.loading = true;
      let res = await getEcmInfo({ecmPlanId:this.$route.params.id});
      this.loading = false;
      const result = res.result.ecmDTO;
      const commonScene = res.result.commonScene;

      this.enterpriseEdition = !!res.result.enterpriseEdition
      this.enabledMessageState = !!res.result.enterpriseEdition

      if(result) {
        this.form.ecmPlanId = result.ecmPlanId || '';
        this.form.ecmPlanName = result.ecmPlanName;
        this.form.effectType = result.effectType;
        this.form.effectTime = result.effectTime;
        this.form.effectAction = result.effectAction;
        this.form.marketingType = result.marketingType;
        this.form.sceneSettingId = result.sceneSettingId;
        this.form.sceneSettingName = result.sceneSettingName;
        this.form.memberSearchDTO = result.filterJson;
        if (res.result.searchId) {
          this.useId = res.result.searchId
          this.hasSearchData = result.filterJson;
        }
        if ( this.form.marketingType === 'card' || this.form.marketingType === 'message') {
          this.form.cardId = result.cardId || '';
        }
        if (this.form.marketingType==="teletext") {
          this.form.mediaId = result.mediaId || '';
          this.form.imageTextId = result.imageTextId || '';
        }
        if (this.form.marketingType==="image") {
          this.form.mediaId = result.mediaId || '';
        }
        if (this.form.marketingType=="text") {
          this.form.textContent = result.textContent || '';
        }
        if(this.form.marketingType==="teltask") {
          this.form.title = result.title;        // 话务任务标题
          this.form.describe = result.describe;    // 话务任务描述
          this.form.lateDays = result.lateDays;    // 任务逾期判定天数
        }
        if (this.form.effectType === 1) {
          this.form.brithday_day = commonScene.brithday_day;
          this.form.attention_day = commonScene.attention_day;
          this.form.lastCost_day = commonScene.lastCost_day;

          if (this.form.brithday_day) {
            this.radio = 'brithday_day'
          } else if (this.form.attention_day) {
            this.radio = 'attention_day'
          } else if (this.form.lastCost_day) {
            this.radio = 'lastCost_day'
          }
        }
      }
    },
    //提交表单验证人数  只有人员筛选需要
    async checkMessageSendCount() {
      if (this.form.effectType) {
        const params = {
          memberSearchDTO:this.form.memberSearchDTO,
          marketingType:this.form.marketingType === 'message'?0:1
        }
        const res = await checkMessageSendCount(params);
        if (res.errorCode === 0) {
          let msg = `合计发送${res.result}人，是否发送?`
          if (this.form.marketingType === 'message') {
            msg = `合计发送${res.result}人，短信按67字/条分割成多条并按条计费，请注意控制短信文本长度，是否发送?`
          }
          this.$confirm(msg,'提示', {
            confirmButtonText: '确定',
            cancelBUttonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveEcmInfo();
          }).catch(() => {
              this.$tips({type: 'info',message: '已取消发送'});
          });
        }
      } else {
        this.saveEcmInfo();
      }
    },
    //提交保存
    submit (formName) {
      if (this.toggleTag && !this.getSaveData ) {
        this.$tips({type:'warning',message:'人群筛选未保存条件'})
        return;
      }
      if (this.form.marketingType === 'message') {
        if (!this.enabledMessageState) {
          this.$tips({type:"warning",message:"'您的通讯费已欠费，请及时于计费中心充值，并联系我司客服恢复功能使用，谢谢。"})
          return;
        }
      }
      if ((this.form.marketingType === 'card' ||  this.form.marketingType === 'message') && !this.form.cardId ) {
        console.log(this.form.marketingType === 'card')

        this.$tips({type:"warning",message:"请勾选卡券营销选项"})
        return;
      }
      if ((this.form.marketingType==="teletext" || this.form.marketingType==="image") && !this.form.mediaId ) {
        this.$tips({type:"warning",message:"请勾选图文营销或图片营销选项"})
        return;
      }

      if ((this.form.marketingType==="teletext") && !this.form.imageTextId ) {
        this.$tips({type:"warning",message:"请勾选图文营销选项"})
        return;
      }

      if ((this.form.marketingType=="text") && !this.form.textContent ) {
        this.$tips({type:"warning",message:"请勾选本文营销选项"})
        return;
      }

      if ((this.form.marketingType=="teltask") && (!this.form.title || !this.form.describe || !this.form.lateDays) ) {
        this.$tips({type:"warning",message:"话务未填写完整"})
        return;
      }

      // if (!this.form.memberSearchDTO) {
      //   this.$tips({type:'warning',message:'会员筛选不能为空'});
      //   return;
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.checkMessageSendCount();
        } else {
          this.$tips({type:'warning',message:'表单填写不完整'});
          return false;
        }
      });
    },
    saveEcmInfo() {
      this.loading = true;
      let params = {
        ecmPlanId:this.form.ecmPlanId || '',
        ecmPlanName:this.form.ecmPlanName,  //	是	int	计划名称不能为空,且最多9个汉字
        effectType:	this.form.effectType,//是	int	时效: 实时: 0; 每天: 1
        effectTime:this.form.effectTime,	//否	int	effectType = 1每天时必填, 时效为时间为0-23
        effectAction:this.form.effectAction, //	否	string	effectType = 0实时时必填, 关注触发: ‘subscribe’; 认证触发: ‘authentication’
        marketingType:this.form.marketingType,	//是	String	营销方式: 卡券营销: ‘card’; 短信营销 : ‘message’; 图文营销: ‘teletext’; 文本营销: ‘text’; 话务: ‘teltask’; 微信图片: ‘image’
        cardId:(this.form.marketingType === 'card' || this.form.marketingType === 'message')?this.form.cardId:'',
        mediaId:(this.form.marketingType==="teletext" || this.form.marketingType==="image")?this.form.mediaId:'',
        imageTextId:this.form.marketingType==="teletext"?this.form.imageTextId:'',
        textContent:this.form.marketingType=="text"? this.form.textContent.replace(/<p>/g,'').replace(/<\/p>/g,'').replace(/<br\/>/g,''):'',
        memberSearchDTO:this.form.memberSearchDTO,
        searchJson:this.getSaveData
      }
      if (this.form.effectType) {
        params[this.radio] = this.form[this.radio] || 0;
      }

      if (!this.$route.params.id) {
          params.sceneSettingId = this.form.sceneSettingId;//	否	String	营销场景
      }

      if (this.form.marketingType==="teltask") {
        params.telTaskInfo = JSON.stringify({
          title:this.form.title,
          describe:this.form.describe,
          lateDays:this.form.lateDays
        });
      }
      saveEcmInfo(params).then(res => {
        this.loading = false;
        if (res.errorCode === 0) {
          if (this.editFlag) {
            this.$confirm('操作成功, 是否返回列表?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.$router.go(-1);
            }).catch(err => { this.getEcmInfo(); });
          } else {
            this.$router.go(-1);
          }
        } else {
          this.$tips({type:'error',message:res.message || '操作失败'});
        }
      }).catch(err => {
        this.loading = false;
      })
    },
  }
}
</script>
