<template>
	<!-- 新增奖项 -->
	<div class="addAwards">
		<!-- <el-button type="primary" class="mb-10" icon="el-icon-plus" size="medium" @click="dialogVisible = true">新增奖项</el-button> -->
        <el-form :model="form" label-width="90px">
            <el-form-item label="奖项名称：">
                <el-input v-model="form.AwardsName" class="w-200" placeholder="请输入奖项名称" maxlength=30></el-input>
            </el-form-item>
            <el-form-item label="奖品数量：">
                <el-input v-model="form.AwardsNum" class="w-200" placeholder="请输入奖品数量"></el-input>
            </el-form-item>
            <el-form-item label="奖品内容：">
                <div class="card-box">
                    <el-card shadow="always" class="pos-r mb-10" v-for="(p,index) in PrizeContent" :key="index" v-show="p.OperateType!='del'">
                        <el-button type="danger" icon="el-icon-delete" class="delete-btn" circle size="mini" @click="deletePrizeContent(index)"></el-button>
                        <el-form-item label="奖品类型：" class="mb-10">
                            <el-radio-group v-model="p.GiftType" @change="radioChange(index)">
                                <el-radio label="3">实物礼品</el-radio>
                                <el-radio label="1">虚拟卡券</el-radio>
                                <el-radio label="2">现金红包</el-radio>
                                <el-radio label="4">积分</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="奖品名称：" v-if="p.GiftType==1||p.GiftType==3">
                            <el-input v-model="p.GiftVaue" style="width:200px" readonly placeholder="请选择奖品"></el-input>
                            <el-button type="primary" @click="selectPrize(p.GiftType,index)">选择</el-button>
                        </el-form-item>
                        <el-form-item label="积分数量：" v-if="p.GiftType==4">
                            <el-input-number v-model="p.GiftVaue" style="width:200px" 
                            placeholder="请输入积分数量" :precision="0"
                            :min="1" :max="999999" :controls="false"></el-input-number>
                        </el-form-item>
                        <el-form-item label="红包金额：" v-if="p.GiftType==2">
                            <el-input-number v-model="p.GiftVaue" style="width:200px" 
                            placeholder="请输入红包金额" :precision="2"
                            :min="0.3" :max="5000" :controls="false"></el-input-number>
                        </el-form-item>
                    </el-card>
                    <div class="text-r">
                        <el-button type="primary" class="mb-10" icon="el-icon-plus" size="mini" @click="addPrizeContent()">新增奖品</el-button>
                    </div>
                </div>
            </el-form-item>
            <!-- <el-form-item label="发放限制：">
                <el-select v-model="form.GiveOutLimit" placeholder="请选择" style="width:200px;">
                    <el-option :label="g.Text" :value="g.Value" v-for="g in GiveOutLimitList" :key="g.Value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发放模式：">
                <el-select v-model="form.GiveOutModel" placeholder="请选择" style="width:200px;">
                    <el-option :label="m.Text" :value="m.Value" v-for="m in GiveOutModelList" :key="m.Value"></el-option>
                </el-select>
            </el-form-item> -->
			<el-row v-show="actType==10">
				<el-col :span="12">
					<el-form-item label="发放限制：">
						<el-select v-model="form.GiveOutLimit" placeholder="请选择" style="width:200px;">
							<el-option :label="g.Text" :value="g.Value" v-for="g in GiveOutLimitList" :key="g.Value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="发放模式：" v-show="showTime">
						<el-select v-model="form.GiveOutModel" placeholder="请选择" style="width:200px;">
							<el-option :label="m.Text" :value="m.Value" v-for="m in GiveOutModelList" :key="m.Value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row v-show="form.GiveOutLimit==1&&actType==10">
				<el-col :span="12">
					<el-form-item label="活动名称：">
						<el-select v-model="form.RelatedActivity" multiple placeholder="请选择" style="width:200px;">
							<el-option :label="g.ActivityName" :value="g.ActivityId" v-for="g in RelatedActivityList" :key="g.ActivityId"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
            <el-form-item label="审核限制：">
                <el-switch 
                v-model="form.GiveOutType" 
                active-value="1"
                inactive-value="0"
                active-text="开"
                inactive-text="关">
                </el-switch>
            </el-form-item>
            <el-form-item label="通知预警：">
                <el-input v-model="form.WarningNum" class="w-200" placeholder="请输入预警数量"></el-input>
            </el-form-item>
            <el-form-item label="备注：">
                <div><textarea id="remarks" class="tinymce-textarea"></textarea></div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer text-r">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="addPrizeRules()" :disabled="btnDisabled">确 定</el-button>
        </div>
        <!-- 礼品列表 -->
        <el-dialog
        width="900px"
        title="奖品列表"
        :visible.sync="prizeDialog"
        append-to-body 
        :close-on-click-modal="false">
            <gift-list :GiftType="GiftType" @prizeAdd="prizeAdd"></gift-list>
        </el-dialog>
	</div>
</template>

<script>
import ut from "@/assets/js/utils.js";
import apiHelper from "@/assets/js/apiHelper.js";
import GiftList from "./GiftList.vue";
import tinymce from 'tinymce'
import 'tinymce/themes/silver/theme'
import 'tinymce/skins/ui/oxide/skin.css'
import '@/assets/js/libs/zh_CN'
import 'tinymce/plugins/textcolor'
import 'tinymce/plugins/advlist'
import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/paste'
import 'tinymce/plugins/code'
import 'tinymce/plugins/image'
export default {
	name: "addAwards",
	components:{
		GiftList
	},
	props: ["actType"],
	data() {
		return {
            url: this.sup8._appConf.apiUrl.alioss,
            dialogVisible:false,
            prizeDialog:false,
			form: {
                guid:"",
				AwardsName: '',
                AwardsNum: "",
                GiveOutType:"1",
                WarningNum:"",
                OperateType:"",
                AwardsRemark:"",
                GiveOutLimit:"",//发放限制
				GiveOutModel:"",//发放模式
				RelatedActivity:[]//活动名称
			},
			PrizeContent:[
				{
                    GiftId:"",
                    AwardId:"",
					GiftType:"3",
					GiftTypeId:"",
					GiftVaue:"",
					OperateType:"add"
				}
            ],
            guid:"",
            GiftType:"3",
            index:-1,//编辑奖品的序号
            prizeIndex:-1,//编辑奖项序号
            btnDisabled:true,
            IntegralQuantity: "",
            RedPacketQuantity: [],
            PhysicalGift:[],//实物奖品剩余集合
            VirtualCard:[],//虚拟卡券集合
            AwardOptions:[], //奖项列表
            GiveOutLimitList:[],//发放限制
            GiveOutModelList:[],//发放模式
            RelatedActivityList:[],//发放模式
			showTime:false,//发放时间限制
            wxInfo:{},
            vFlag:-1 //奖项校验标记
            
		};
	},
	watch: {
        form:{
			deep: true,
            handler: function (){
                this.verification();
            }
        },
        PrizeContent:{
			deep: true,
            handler: function (n){
				console.log(n);
				this.showTime = false;
				n.forEach(v=>{
					if(v.GiftType == 2){
						this.showTime = true;
					}
				});
				if(!this.showTime){
					// this.form.GiveOutModel = "";
					this.$set(this.form, 'GiveOutModel', "");
				}
                this.verification();
            }
        },
        "form.WarningNum":function(n){
            if(!/^(0|[1-9][0-9]*)$/.test(n)){
                this.form.WarningNum = "";
            }
            if(n<0){
                this.form.WarningNum = "";
            }
            if(Number(this.form.WarningNum) > Number(this.form.AwardsNum)){
                this.form.WarningNum = this.form.AwardsNum;
            }
        },
        "form.AwardsNum":function(n){
            if(!/^(0|[1-9][0-9]*)$/.test(n)){
                this.form.AwardsNum = "";
            }
            if(n<0){
                this.form.AwardsNum = "";
            }
            if(n.length>10){
                this.form.AwardsNum = n.substring(0,10);
            }
            if(this.form.WarningNum > this.form.AwardsNum){
                this.form.WarningNum = "";
            }
        }
    },
	created () {
        this.getGiftQuantity();
        
		if(this.actType == 10){
			this.getGiveOutLimitList();
			this.getGiveOutModelList();
			this.getRelatedActivityList();
		}else{
			this.GiveOutLimitList=[];//发放限制
            this.GiveOutModelList=[];//发放模式
            this.RelatedActivityList=[];//发放模式
		}
	},
	mounted () {
        
    },
	methods: {
        editPrize(AwardOptions,index,row){
            console.log(AwardOptions);
            this.prizeIndex = index;
            this.AwardOptions = _.cloneDeep(AwardOptions);
            this.getWxConfig();
            // tinymce.get("remarks").destroy();
            if(index !=-1){
                this.form = _.cloneDeep(row);
                this.PrizeContent = row.PrizeContent;
                this.creatEditor(this.form.AwardsRemark);
            }else{
                this.form = {
                    guid:"",
                    AwardsName: '',
                    AwardsNum: "",
                    GiveOutType:"1",
                    WarningNum:"",
                    OperateType:"",
                    AwardsRemark:""
                };
                this.PrizeContent = [
                    {
                        GiftId:"",
                        AwardId:"",
                        GiftType:"3",
                        GiftTypeId:"",
                        GiftVaue:"",
                        OperateType:"add"
                    }
                ];
                this.form.guid = ut.newGuid();
                this.creatEditor("");
            }
        },
        // 获取用户配置的微信公众号信息
        getWxConfig(){
            let activityInfo = ut.ssg('activityInfo');
            if(ut.ssg('OfficialAccount')){
                this.wxInfo = ut.ssg('OfficialAccount');
            }else{
                this.wxInfo = activityInfo.OfficialAccount;
            }
        },
        // 选择奖品，打开奖品列表
        selectPrize(type,index){
            this.GiftType = type;
            this.index = index;
            this.prizeDialog = true;
        },
        // 返回的奖品赋值
        prizeAdd(v){
            this.PrizeContent[this.index].GiftVaue = v.GiftName;
            this.PrizeContent[this.index].GiftTypeId = v.GiftId;
            this.prizeDialog = false;
        },
		addPrizeContent(){
			this.PrizeContent.push({
                GiftId:"",
                AwardId:this.guid,
                GiftType:"3",
                GiftTypeId:"",
                GiftVaue:"",
                OperateType:"add"
            });
		},
		deletePrizeContent(index){
			this.PrizeContent.splice(index,1);
        },
        addPrizeRules(){
            this.awardVerification();
            //1红包金额填写不对，2公众号未填，3红包余额不足,4积分不足,5实物礼品数量不足,6虚拟奖品数量不足,7公众号未充值
            if(this.vFlag==1){
                this.$message.error('红包金额最小0.3元，最大5000元');
                return;
            }else if(this.vFlag==2){
                this.$message.error('公众号没有设置，请先设置公众号');
                return;
            }else if(this.vFlag==3){
                this.$message.error('红包余额不足');
                return;
            }else if(this.vFlag==4){
                this.$message.error('积分不足');
                return;
            }else if(this.vFlag==5){
                this.$message.error('实物礼品数量不足');
                return;
            }else if(this.vFlag==6){
                this.$message.error('虚拟奖品数量不足');
                return;
            }else if(this.vFlag==7){
                this.$message.error('请确认公众号已充值');
                return;
            }
            let obj = {};
            let ContainsPrize = [];
            this.PrizeContent.forEach(v => {
                if(v.GiftType==4){
                    ContainsPrize.push(v.GiftVaue+"积分");
                }else if(v.GiftType==2){
                    ContainsPrize.push(v.GiftVaue+"元红包");
                }else{
                    ContainsPrize.push(v.GiftVaue);
                }
                // ContainsPrize.push(v.GiftVaue);
            });
            // console.log(tinyMCE.activeEditor.getContent());
            obj.AwardsId = this.prizeIndex==-1?this.form.guid:this.form.AwardsId;
            obj.AwardsName = this.form.AwardsName;
            obj.AwardsNum = this.form.AwardsNum;
            obj.PrizeContent = this.PrizeContent;
            obj.AwardsType = 2;
            obj.GiveOutType = this.form.GiveOutType;
            obj.WarningNum = this.form.WarningNum;
            obj.AwardsRemark = encodeURIComponent(tinyMCE.activeEditor.getContent());
            // obj.AwardsRemark = this.form.AwardsRemark;
            obj.GiveOutLimit = this.form.GiveOutLimit;
            obj.GiveOutModel = this.form.GiveOutModel;
            obj.RelatedActivity = this.form.RelatedActivity;
            obj.ContainsPrize = ContainsPrize.join();
            obj.OperateType = this.prizeIndex==-1?"add":"edit";
            if(this.prizeIndex==-1){
                this.$emit("addPrizeData",obj);
            }else{
                this.$emit("editPrizeData",obj);
            }
        },
        cancel(){
            this.$emit("hideAddRuleDialog");
        },
        radioChange(index){
            this.PrizeContent[index].GiftVaue = "";
            this.PrizeContent[index].GiftTypeId = "";
            if(this.PrizeContent[index].GiftType==2){
                this.PrizeContent[index].GiftTypeId = this.wxInfo.GiftId;
            }
        },
        // 子规则数据验证
        verification (){
            let operateTypeArr = [];
            let withoutArr = [];
            if(this.form.AwardsName=='' || this.form.AwardsNum=='' || this.PrizeContent.length==0){
                this.btnDisabled = true;
                return;
			}
			if(this.actType==10){
				if(!this.form.GiveOutLimit){
					this.btnDisabled = true;
					return;
				}
				if(this.form.GiveOutLimit=='1'&&this.form.RelatedActivity.length==0){
					this.btnDisabled = true;
					return;
				}
			}

            for(let a=0;a<this.PrizeContent.length;a++){
                if(this.PrizeContent[a].GiftVaue == ""){
                    this.btnDisabled = true;
                    return;
                }
            }
            this.btnDisabled = false;
        },
        // 奖项校验
        awardVerification(){
            let flag = -1;//1红包金额填写不对，2公众号未填，3红包余额不足,4积分不足,5实物礼品数量不足,6虚拟奖品数量不足
            let wx = true;
            let integral = 0;//积分总数
            let money = 0;//红包金额总数
            let entity = [];//实物礼品总数集合
            let invented = [];//虚拟奖品额总数集合
            // 检验微信公众号是否填写
            if(ut.parseUrl().option==1){
                if(!ut.ssg('OfficialAccount')){
                    wx = false;
                }
            }
            
            // 检验当前红包金额和积分的正确性
            for(let i=0;i<this.PrizeContent.length;i++){
                if(this.PrizeContent[i].GiftType==2){
                    if(this.PrizeContent[i].GiftVaue>5000 || this.PrizeContent[i].GiftVaue<0.3){
                        flag = 1;
                        break;
                    }else{
                        money = money + Number(this.PrizeContent[i].GiftVaue) * Number(this.form.AwardsNum);
                    }
                }
                if(this.PrizeContent[i].GiftType==4){
                    integral = integral + Number(this.PrizeContent[i].GiftVaue) * Number(this.form.AwardsNum);
                }
                if(this.PrizeContent[i].GiftType==3){
                    let sf = false;//奖品重复标志
                    for(let a=0;a < entity.length; a++){
                        if(entity[a].id == this.PrizeContent[i].GiftTypeId){
                            entity[a].num += Number(this.form.AwardsNum);
                            sf = false;
                            break;
                        }else{
                            sf = true;
                        }
                    }
                    if(sf || entity.length==0){
                        entity.push({id:this.PrizeContent[i].GiftTypeId,name:this.PrizeContent[i].GiftVaue,num:Number(this.form.AwardsNum)});
                    }
                }
                if(this.PrizeContent[i].GiftType==1){
                    let cf = false;//奖品重复标志
                    for(let a=0;a < invented.length; a++){
                        if(invented[a].id == this.PrizeContent[i].GiftTypeId){
                            invented[a].num += Number(this.form.AwardsNum);
                            cf = false;
                            break;
                        }else{
                            cf = true;
                        }
                    }
                    if(cf || invented.length==0){
                        invented.push({id:this.PrizeContent[i].GiftTypeId,name:this.PrizeContent[i].GiftVaue,num:Number(this.form.AwardsNum)});
                    }
                }
            }
            // 检验已存在的奖品数量 prizeIndex
            this.AwardOptions.forEach((v,index) => {
                console.log(index,this.prizeIndex);
                // 编辑的时候排除当前编辑项
                if(index!=this.prizeIndex){
                    v.PrizeContent.forEach(n => {
                        // debugger
                        switch (n.GiftType) {
                            case "1":
                                //虚拟卡券
                                let cf = false;//奖品重复标志
                                for(let a=0;a < invented.length; a++){
                                    if(invented[a].id == n.GiftTypeId){
                                        invented[a].num += Number(v.AwardsNum);
                                        cf = false;
                                        break;
                                    }else{
                                        cf = true;
                                    }
                                }
                                if(cf || invented.length==0){
                                    invented.push({id:n.GiftTypeId,name:n.GiftVaue,num:Number(v.AwardsNum)});
                                }
                                break;
                            case "2":
                                //现金红包
                                money = money + Number(n.GiftVaue) * v.AwardsNum;
                                break;
                            case "3":
                                //实物礼品
                                let sf = false;//奖品重复标志
                                for(let a=0;a < entity.length; a++){
                                    if(entity[a].id == n.GiftTypeId){
                                        entity[a].num += Number(v.AwardsNum);
                                        sf = false;
                                        break;
                                    }else{
                                        sf = true;
                                    }
                                }
                                if(sf || entity.length==0){
                                    entity.push({id:n.GiftTypeId,name:n.GiftVaue,num:Number(v.AwardsNum)});
                                }
                                break;
                            case "4":
                                //积分
                                integral = integral + Number(n.GiftVaue) * v.AwardsNum;
                                break;
                        
                            default:
                                break;
                        }
                    });
                }
            });
            // money = money * this.form.AwardsNum;
            // integral = integral * this.form.AwardsNum;
            //提示用户填写微信公众号
            if(!wx && money>0){
                flag = 2;
            }
            // 余额校验
            // debugger
            let RedPacketNum = 0;
            if(money>0){
                if(this.wxInfo.GiftId===""){
                    flag = 7;
                }else{
                    this.RedPacketQuantity.forEach(v => {
                        if(v.GiftId == this.wxInfo.GiftId){
                            RedPacketNum = v.GiftCount;
                        }
                    });
                    if(Number(RedPacketNum)<money && money>0){
                        flag = 3;
                    }
                }
            }
            // 积分校验
            if(Number(this.IntegralQuantity)<integral && integral>0){
                flag = 4;
            }
            //实物礼品数量校验
            for(let b=0;b<entity.length;b++){
                this.PhysicalGift.forEach(v => {
                    if(entity[b].id == v.GiftId && entity[b].num>v.GiftCount){
                        flag = 5;
                    }
                });
            }
            //虚拟卡券数量校验
            for(let c=0;c<invented.length;c++){
                this.VirtualCard.forEach(v => {
                    if(invented[c].id == v.GiftId && invented[c].num>v.GiftCount){
                        flag = 6;
                    }
                });
            }
            // return flag;
            this.vFlag = flag;
        },
        //获取红包和积分剩余数量
        getGiftQuantity(){
            let that = this;
            let eno = that.sup8.urlparams.eid;
            apiHelper.getGiftQuantity(eno, function(res) {
                if (res.flag) {
                    that.IntegralQuantity = res.data.IntegralQuantity;
                    that.RedPacketQuantity = res.data.RedPacket;
                    that.PhysicalGift = res.data.PhysicalGift;
                    that.VirtualCard = res.data.VirtualCard;
                }
            });
        },
        creatEditor (value="") {
            let that = this;
            console.log(value);
            
            this.$nextTick(() => {
                tinymce.remove(`#remarks`);
                const setting =
                    {
                        selector: '#remarks',
                        language: 'zh_CN',
                        init_instance_callback: editor => {
                            // console.log(value)
                            editor.setContent(decodeURIComponent(value));
                            // if (value=="") {
                            //     editor.setContent(decodeURIComponent(value));
                            // }    `
                            // editor.on('Change', (e) => {
                            //     console.log("备注："+editor.getContent());
                            //     this.form.AwardsRemark = encodeURIComponent(editor.getContent());
                            // })
                        },
                        images_upload_handler: (blobInfo, success, failure) =>{
                            var formData;
                            formData = new FormData();
                            formData.append('file', blobInfo.blob(), blobInfo.filename());
                            $.ajax({
                                url:this.url,
                                dataType:'json',
                                type:'POST',
                                async: false,
                                data: formData,
                                processData : false, // 使数据不做处理
                                contentType : false, // 不要设置Content-Type请求头
                                success: function(data){
                                    success(data.data.url);
                                },
                                error:function(response){
                                    failure(response);
                                }
                            });
                        },
                        browser_spellcheck: false, // 拼写检查
                        branding: false, // 去水印
                        // elementpath: false,  //禁用编辑器底部的状态栏
                        statusbar: false, // 隐藏编辑器底部的状态栏
                        paste_data_images: true, // 允许粘贴图像
                        menubar: false, // 隐藏最上方menu
                        image_advtab: true,
                        image_title: false, // 是否开启图片标题设置的选择，这里设置否
                        automatic_uploads: true,
                        plugins: 'advlist table lists paste code image',
                        toolbar: `code fontselect fontsizeselect forecolor backcolor 
                        bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | 
                        quicklink h2 h3 blockquote table numlist bullist image`,
                    }
                tinymce.init(setting)
            })
        },
        // 获取发放限制
        getGiveOutLimitList(){
            // 目标人群  typeid: 0086aafd572247c3a1889f6bb238bd14
            // 发放模式  typeid: f05ea5880d0511eab09d000c290950c7
            // 发放限制  typeid: 86c4213f0d0711eab09d000c290950c7
            apiHelper.getDicList("86c4213f0d0711eab09d000c290950c7","0", (res) =>{
                if (res.flag) {
                    this.GiveOutLimitList = res.data;
                }else{
                    this.GiveOutLimitList = [];
                }
            });
        },
        // 获取发放模式
        getGiveOutModelList(){
            // 目标人群  typeid: 0086aafd572247c3a1889f6bb238bd14
            // 发放模式  typeid: f05ea5880d0511eab09d000c290950c7
            // 发放限制  typeid: 86c4213f0d0711eab09d000c290950c7
            apiHelper.getDicList("f05ea5880d0511eab09d000c290950c7","0", (res) =>{
                if (res.flag) {
                    this.GiveOutModelList = res.data;
                }else{
                    this.GiveOutModelList = [];
                }
            });
        },
        // 获取奖项关联活动列表接口
        getRelatedActivityList(){
            apiHelper.getRelatedActivityList(this.sup8.urlparams.eid,this.sup8.urlparams.activityid, (res) =>{
                if (res.flag) {
                    this.RelatedActivityList = res.data;
                }else{
                    this.RelatedActivityList = [];
                }
            });
        },
	}
};

</script>
<style>
.text-r{text-align: right;}
.pos-r{position: relative;}
.dis-ib{display: inline-block;}
.mb-10{margin-bottom: 10px;}
.mb-20{margin-bottom: 20px;}
.w-200{width: 200px;}
.card-box{
	border: 1px solid #DCDFE6;
	padding: 20px;
	border-radius: 4px;
}
.delete-btn{
	position: absolute;
	top:10px;
	right: 10px;
	z-index: 10000;
}
.tox-tinymce-aux{
   z-index: 100000!important; 
}
</style>