<template>
  <el-form :model="info" ref="info" :rules="rules" label-width="80px"  v-loading="loading">
    <div class="dm-form__wrap">
      <h3 class="dm-title__label">基础设置</h3>
      <el-form-item label="活动名称" prop="putOnName">
        <dm-input class="w250" v-model="info.putOnName" :maxlength="9" :disabled="infoFlag"></dm-input>
      </el-form-item>
      <el-form-item label="投放卡券">
        <el-input class="w250" v-model="info.cardName" disabled></el-input>
      </el-form-item>
      <el-form-item label="发送时间">
        <el-select class="w250" v-model="info.putOnType" :disabled="infoFlag">
          <el-option v-for="(v,i) in putOnTypeOptions" :key="i" :value="v.value" :label="v.label"></el-option>
        </el-select>
        <el-date-picker :disabled="infoFlag" class="w250"  v-if="info.putOnType" v-model="info.putOnTime" type="datetime" placeholder="选择日期时间" align="right" :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
      <el-form-item label="营销场景">
        <span>{{info.sceneSettingName || '--'}}</span>
      </el-form-item>
    </div>
    <div class="dm-form__wrap">
      <h3 class="dm-title__label">会员设置</h3>
      <div class="pb20">
        <span class="dm-input_label pr10">选择会员</span>
        <el-radio :disabled="infoFlag" v-model="info.memberType" :label="0">会员筛选</el-radio>
        <el-radio :disabled="infoFlag" v-model="info.memberType" :label="1">指定会员</el-radio>
      </div>
      <div v-show="!info.memberType">
        <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>
      <vue-gic-confirm-people v-show="info.memberType" idType="memberId"  @get-data="getConfirmData" :list="memberList"></vue-gic-confirm-people>
    </div>
    <div class="btn-wrap_fixed" :class="{'on':asideShow}">
      <el-button v-if="!infoFlag" type="primary" @click="submit('info')">提 交</el-button>
      <el-button @click="$router.go(-1)">返回</el-button>
    </div>
  </el-form>
</template>
<script>
import { checkPutonMemberIds, saveUpdatePutonCard, getCardPutonDetail } from '@/service/api/cardApi.js'
import { sceneSettingList } from '@/service/api/wechatApi.js'
import { formateDateTimeByType } from '@/utils/index.js'
export default {
    name: 'card-group',
    data () {
      return {
        loading:false,
        putOnTypeOptions:[{value:0,label:'立即发送'},{value:1,label:'选择时间发送'}],
        pickerOptions: {
          disabledDate(val) {
            return Date.now() >= (val.getTime() + 24*60*60*1000)
          }
        },
        // 人群筛选器可传参数
        projectName: '', // 当前项目名
        sceneValue: 'member', // 场景值
        useId: '', // 模板id
        hasSearchData: '' , // 当前页回显的数据(接口返回)
        toggleTag: false, // 控制按钮显示的参数,仅供参考,可自行修改
        getSaveData:'',
        saveTag:false,
        info:{
          memberType:0,
          sceneSettingId:'',
          putOnTime:'',
          putOnType:0,
          memberSearchDTO:'',
          openIds:'',
          putOnName:'',
          sceneSettingName:'',
          cardId:this.$route.params.id,
          cardName:this.$route.params.name,
        },
        rules:{
          putOnName:{required:true,message:'活动名称不能为空',trigger:'blur'}
        },
        memberList:[],
        editFlag:this.$route.meta.type === 'edit',
        infoFlag:this.$route.meta.type === 'info',
      }
    },
    computed: {
      asideShow() {
        return this.$store.state.marketing.asideShow
      }
    },
    created() {
      console.log(this.$route.meta.type)
      if (this.editFlag || this.infoFlag) {
        this.getCardPutonDetail();
      }
      this.$store.commit('mutations_breadcrumb',[{name:'营销管理',path:''},{name:'卡券营销',path:'/card'},{name:'卡券库',path:'/card/list'},{name:'卡券群发',path:''}])
    },
    methods:{
      getData() {
        this.$refs.peopleFilter.confirmSet()
      },
      // 子组件触发父组件事件,返回过滤条件数据
      findFilter(value){
        this.info.memberSearchDTO = value
      },
      // 取消
      cancelFilter(){
        this.$refs.peopleFilter.cancelSet()
      },
      // 获取需要回显的数据, 供保存时候使用
      getBackData(val) {
        console.log(val)
        this.getSaveData = val;
      },
      // 显示编辑,保存按钮隐藏,确认按钮显示 (子组件会调用)
      editShow() {
        this.toggleTag = true
        this.saveTag = false
      },
      // 显示保存按钮,隐藏确认按钮显示  (子组件会调用)
      editHide() {
        this.toggleTag = false
        this.saveTag = true
      },
      // 隐藏保存按钮和确认按钮  (子组件会调用)
      hideBtn() {
        this.toggleTag = false;
        this.saveTag = false
      },
      //获取指定会员
      getConfirmData(val) {
        this.info.openIds = val;
      },
      submit(formName) {

        if (!this.info.memberType && this.toggleTag && !this.getSaveData ) {
          this.$tips({type:'warning',message:'人群筛选未保存条件'})
          return;
        }
        // if (this.info.memberType) {
        //   if (!this.info.openIds) {
        //     this.$tips({type:'warning',message:'指定会员不能为空'});
        //     return;
        //   }
        // }

         this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm('是否群发卡券?', '提示', {
              confirmButtonText: '确定',
              cancelBUttonText: '取消',
              type: 'warning'
            }).then(() => {
              this.sendCard();
            }).catch(() => {
              this.$tips({type: 'info',message: '已取消提交'})
            });
          } else {
              this.$tips({type: 'warning',message: '表单未填写完整'})
            return false
          }
        });
      },
      async sendCard() {
        let params = {
          memberSearchDTO:this.info.memberSearchDTO,
          memberType:this.info.memberType,
          memberIds:this.info.openIds,
          cardId:this.info.cardId,
        }
        let res = await checkPutonMemberIds(params);
        if (res.errorCode === 0) {
            var sumPerson = res.result.totalSendCount;
            var reducePerson = res.result.repeatMemberIds.length;

            // if(sumPerson-reducePerson>1000){
            //   this.$tips({type:'warning',message:'投放人数不能大于1000'});
            //   return ;
            // }
            this.$confirm(`合计发送${sumPerson}人，存在已投放过该卡券的会员${reducePerson}人，是否剔除这些会员并发送？`, '提示', {
              confirmButtonText: '确定',
              cancelBUttonText: '取消',
              type: 'warning'
            }).then(() => {
              this.saveUpdatePutonCard()
            }).catch(() => {
              this.$tips({type: 'info',message: '已取消提交'})
            });
        } else {
          this.$tips({type:'error',message:'操作失败'})
        }
        console.log(res)
      },

      async saveUpdatePutonCard() {
         let params = {
          putOnName:this.info.putOnName, // 1.活动名称
          cardId:this.info.cardId, // 2.投放卡券,卡券主键ID
          sceneSettingId:this.info.sceneSettingId, // 3.营销场景
          memberType:this.info.memberType, // 4.选择会员类型: 会员筛选: 0; 指定会员: 1
          memberSearchDTO:this.info.memberSearchDTO, // JSON.Stringify 人群筛选器
          putOnType:this.info.putOnType, // 发送时间, 0:立即发送; 1:定时发送(定时必须选择时间)
          searchJson:this.getSaveData
        }
        if (this.info.memberType) {
          params.memberIds = this.info.openIds; // 指定会员:memberType = 1, 多个会员memberId用逗号拼接
        }
        if (this.info.putOnType) {
          params.putOnTime = formateDateTimeByType(this.info.putOnTime,'yyyy-MM-dd-HH-mm-ss');
        }
        if (this.$route.meta.type === 'edit') {
          params.coupCardPutOnId =  this.$route.params.id;// 投放主键ID, 新建不传; 修改传
        }
        saveUpdatePutonCard(params).then(res => {
          if (res.errorCode === 0) {
            if (this.editFlag) {
              this.$confirm('卡券投放成功, 是否返回列表?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$router.go(-1);
              }).catch(err => {
                this.getCardPutonDetail();
              });
            } else {
              this.$router.go(-1);
            }
          } else {
            this.$tips({type:'error',message:'操作失败'});
          }
        }).catch(err => {
          this.$tips({type:'error',message:'操作失败'});
        })
      },
      getCardPutonDetail(){
        getCardPutonDetail({putonId:this.$route.params.id}).then(res => {
          if (res.errorCode === 0) {
           let info = res.result.puton;
            this.info.putOnName = info.putOnName;
            this.info.putOnType = info.putOnType;
            this.info.memberType = info.memberType;
            this.info.sceneSettingId = info.sceneSettingId;
            this.info.sceneSettingName = info.sceneSettingName;
            this.info.memberSearchDTO = info.searchParams;
            this.info.cardId = info.cardId;
            this.info.putOnTime = info.putOnTime;
            this.info.cardName = res.result.card.cardName;
            if (res.result.searchId) {
              this.useId = res.result.searchId
              this.hasSearchData = info.searchParams;
            }
            if (this.info.memberType) {
              this.memberList = res.result.memberList;
            }
          }
        })
      }
    },
}
</script>
