//#import DateUtil.js
//#import $owl_mall_u:services/modelService.jsx
//#import $owl_lottery_activity:services/modelService.jsx
//#import $owl_lottery_activity_item:services/modelService.jsx
//#import $owl_lottery_hit_record:services/modelService.jsx
//#import $owl_lottery_qualification_amount:services/modelService.jsx
//#import $owl_mall_big_member_integrallog:services/modelService.jsx
//#import $wsBigMemberInterface:services/TotappsCRMService.jsx
//#import $wsBigMemberInterface:services/BigMemberEnumUtil.jsx
//#import $wsBigMemberInterface:services/BigMemberUtil.jsx
//#import $commonService:services/FreeGetCardUtil.jsx
//#import $commonService:services/CommonUtil.jsx
//#import $owlService:services/common/CommonUtil.jsx

var LotteryUtil = (function () {
    var f = {
        doAward: function (lotteryActivityId, userId) {
            var lockId = "LockDoAward_" + lotteryActivityId;
            owl_lottery_activityService.lock(lockId);
            try {
                var jUser = owl_mall_uService.get(userId);
                var jLotteryActivity = owl_lottery_activityService.get(lotteryActivityId);
                if (!f.isMatchLotteryRule(jLotteryActivity, jUser)) {
                    return {code: "301", msg: jLotteryActivity.show_msg_2 || "无抽奖资格"};
                }

                var total = jLotteryActivity.amount;
                var items = f.getItems(jLotteryActivity.id);

                var availableItems = [];
                for (var i = 0; i < items.length; i++) {
                    var jItem = items[i];

                    //只取有库存的奖项来参与中奖
                    $.log("LotteryUtil.jsx...doAward...lotteryActivityId=" + lotteryActivityId + "...jItem.id=" + jItem.id + "...jItem.amount=" + jItem.amount + "...jItem.unit_amount=" + jItem.unit_amount + "...jItem.rate=" + jItem.rate);
                    if (Number(jItem.amount) < Number(jItem.unit_amount)) {
                        //将总参与人数减掉没有奖品的中奖区间
                        total = total - Number(jItem.rate);
                        continue;
                    }

                    availableItems.push(jItem);
                }

                $.log("LotteryUtil.jsx...doAward...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...total=" + total);
                var jItem = f.doRandomAward(availableItems, total);
                if (jItem) {
                    if (Number(jItem.amount) >= Number(jItem.unit_amount)) {
                        var jHitRecord = {};
                        jHitRecord.lottery_activity_id = jLotteryActivity.id;
                        jHitRecord.lottery_activity_name = jLotteryActivity.name;
                        jHitRecord.create_time = new Date().getTime();
                        jHitRecord.user_id = userId;
                        jHitRecord.user_mobile = jUser.mobile || "";
                        jHitRecord.is_win = "n";
                        jHitRecord.is_true = "y";
                        jHitRecord.is_accept = "n";
                        jHitRecord.item_id = jItem.id;
                        jHitRecord.item_name = jItem.name;
                        jHitRecord.item_type = jItem.type;
                        owl_lottery_hit_recordService.add(jHitRecord);

                        //扣减抽奖资格次数
                        f.reduceHitAmount(jLotteryActivity, jUser, jHitRecord);

                        //扣减奖品库存
                        jItem = owl_lottery_activity_itemService.get(jItem.id);
                        jItem.amount = Number(jItem.amount) - 1;
                        owl_lottery_activity_itemService.update(jItem);

                        if (jItem.type != "none") {
                            //jHitRecord之前先设置is_win=n，因为前面的代码暂时需要用到抽奖记录，如果是中奖了，这里要设置is_win=y
                            jHitRecord = owl_lottery_hit_recordService.get(jHitRecord.id);
                            jHitRecord.is_win = "y";
                            owl_lottery_hit_recordService.update(jHitRecord);

                            //根据不同的奖品类型发放奖品
                            f.doGiveAward(jLotteryActivity, jItem, jUser, jHitRecord);

                            return {code: "0", msg: jItem.show_msg || jLotteryActivity.show_msg_0 || "恭喜，中奖了！", data: jHitRecord};
                        }
                    }
                }

                return {code: "1", msg: jLotteryActivity.show_msg_1 || "未中奖"};
            } finally {
                owl_lottery_activityService.unlock(lockId);
            }
        },
        isMatchLotteryRule: function (jLotteryActivity, jUser) {
            var userId = jUser.id;
            var lotteryActivityId = jLotteryActivity.id;
            var type = jLotteryActivity.type;
            $.log("LotteryUtil.jsx...isMatchLotteryRule...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...type=" + type);
            if (type == "byDay") {
                //每天可抽奖
                var jQualification = owl_lottery_qualification_amountService.get("owl_lottery_qualification_amount_" + lotteryActivityId + "_" + userId);
                var default_amount = 0;//默认已抽奖次数
                var amount = 0;//剩余可用数量
                if (jQualification) {
                    amount = jQualification.amount || 0;
                    var last_used_time = jQualification.last_used_time;
                    if (last_used_time) {
                        var curTime = new Date().getTime();
                        var curDate = DateUtil.getShortDate(curTime);
                        var lastDate = DateUtil.getShortDate(new Date(last_used_time).getTime());//默认抽奖资格计算日期
                        if (curDate == lastDate) {
                            default_amount = Number(jQualification.default_amount || 0);
                        }
                    }
                }

                var defaultLotteryAmount = f.getDefaultQualificationAmount(jLotteryActivity, jUser, Number(jLotteryActivity.lottery_amount || 0));//默认可抽奖次数
                var canUseAmount = defaultLotteryAmount - default_amount + amount;
                $.log("LotteryUtil.jsx...isMatchLotteryRule...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...111...defaultLotteryAmount=" + defaultLotteryAmount + "...default_amount=" + default_amount + "...amount=" + amount + "...canUseAmount=" + canUseAmount);
                if (canUseAmount > 0) {
                    return true;
                }
                return false;
            } else if (type == "dyna") {
                //动态抽奖资格
                var jQualification = owl_lottery_qualification_amountService.get("owl_lottery_qualification_amount_" + lotteryActivityId + "_" + userId);
                var default_amount = 0;//默认已抽奖次数
                var amount = 0;//剩余可用数量
                if (jQualification) {
                    default_amount = Number(jQualification.default_amount || 0);
                    amount = Number(jQualification.amount || 0);
                }

                var defaultLotteryAmount = f.getDefaultQualificationAmount(jLotteryActivity, jUser, 0);//默认可抽奖次数
                var canUseAmount = defaultLotteryAmount - default_amount + amount;
                $.log("LotteryUtil.jsx...isMatchLotteryRule...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...222...defaultLotteryAmount=" + defaultLotteryAmount + "...default_amount=" + default_amount + "...amount=" + amount + "...canUseAmount=" + canUseAmount);
                if (canUseAmount > 0) {
                    return true;
                }

                return false;
            } else if (type == "point") {
                //积分抽奖
                var jArgs = TotappsCRMService.getArgs();
                var branchcode = "124";
                var memberId = null;
                var bigMemberInfo = jUser.bigMemberInfo;
                if (bigMemberInfo && bigMemberInfo.memberid) {
                    memberId = bigMemberInfo.memberid;
                }
                if (!memberId) {
                    var memberInfo = BigMemberUtil.getMemberInfoByUser(jArgs, jUser, branchcode, true);
                    memberId = memberInfo.memberid;
                }
                if (!memberId) {
                    return false;
                }
                var totalLessPoint = BigMemberUtil.getMemberPoint(jArgs, branchcode, memberId);
                $.log("LotteryUtil.jsx...isMatchLotteryRule...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...333...totalLessPoint=" + totalLessPoint);
                if (totalLessPoint >= Number(jLotteryActivity.lottery_point)) {
                    return true;
                }
                return false;
            }
            return false;
        },
        /**
         * 扣减抽奖资格
         */
        reduceHitAmount: function (jLotteryActivity, jUser, jHitRecord) {
            var userId = jUser.id;
            var lotteryActivityId = jLotteryActivity.id;
            var type = jLotteryActivity.type;
            $.log("LotteryUtil.jsx...reduceHitAmount...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...type=" + type);
            if (type == "byDay") {
                //每天可抽奖
                var jQualification = owl_lottery_qualification_amountService.get("owl_lottery_qualification_amount_" + lotteryActivityId + "_" + userId);
                var default_amount = 0;//默认已抽奖次数
                var lastDate = "";
                var curTime = new Date().getTime();
                var curDate = DateUtil.getShortDate(curTime);
                if (jQualification) {
                    default_amount = jQualification.default_amount;
                    var last_used_time = jQualification.last_used_time;
                    if (last_used_time) {
                        lastDate = DateUtil.getShortDate(new Date(last_used_time).getTime());//默认抽奖资格计算日期
                    }

                    if (curDate == lastDate) {
                        jQualification.default_amount = Number(default_amount) + 1;
                    } else {
                        jQualification.default_amount = 1;
                    }
                    jQualification.last_used_time = new Date().getTime();
                    owl_lottery_qualification_amountService.update(jQualification);

                    $.log("LotteryUtil.jsx...reduceHitAmount...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...update...default_amount=" + jQualification.default_amount);
                } else {
                    jQualification = {};
                    jQualification.lottery_activity_id = lotteryActivityId;
                    jQualification.user_id = userId;
                    jQualification.amount = 0;
                    jQualification.default_amount = 1;
                    jQualification.last_used_time = new Date().getTime();
                    owl_lottery_qualification_amountService.add(jQualification);

                    $.log("LotteryUtil.jsx...reduceHitAmount...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...add...default_amount=" + jQualification.default_amount);
                }
            } else if (type == "dyna") {
                //动态抽奖资格
                var jQualification = owl_lottery_qualification_amountService.get("owl_lottery_qualification_amount_" + lotteryActivityId + "_" + userId);
                var default_amount = 0;//默认已抽奖次数
                var amount = 0;//剩余可用数量
                var defaultLotteryAmount = f.getDefaultQualificationAmount(jLotteryActivity, jUser, 0);//默认可抽奖次数
                if (jQualification) {
                    default_amount = Number(jQualification.default_amount || 0);
                    amount = Number(jQualification.amount || 0);

                    if (default_amount < defaultLotteryAmount) {
                        jQualification.default_amount = default_amount + 1;
                    } else {
                        jQualification.amount = amount - 1;
                    }
                    jQualification.last_used_time = new Date().getTime();
                    owl_lottery_qualification_amountService.update(jQualification);
                    $.log("LotteryUtil.jsx...reduceHitAmount...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...update...amount=" + jQualification.amount + "...default_amount=" + jQualification.default_amount);
                } else {
                    jQualification = {};
                    jQualification.lottery_activity_id = lotteryActivityId;
                    jQualification.user_id = userId;
                    jQualification.default_amount = 1;
                    jQualification.amount = 0;
                    jQualification.last_used_time = new Date().getTime();
                    owl_lottery_qualification_amountService.add(jQualification);
                    $.log("LotteryUtil.jsx...reduceHitAmount...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...add...amount=" + jQualification.amount + "...default_amount=" + jQualification.default_amount);
                }
            } else if (type == "point") {
                //积分抽奖
                if (!jLotteryActivity.lottery_point) {
                    return;
                }
                var jArgs = TotappsCRMService.getArgs();
                var branchcode = "124";
                var memberId = null;
                var bigMemberInfo = jUser.bigMemberInfo;
                if (bigMemberInfo && bigMemberInfo.memberid) {
                    memberId = bigMemberInfo.memberid;
                }
                if (!memberId) {
                    var memberInfo = BigMemberUtil.getMemberInfoByUser(jArgs, jUser, branchcode, true);
                    memberId = memberInfo.memberid;
                }
                if (!memberId) {
                    return;
                }
                var totalLessPoint = BigMemberUtil.getMemberPoint(jArgs, branchcode, memberId);
                $.log("LotteryUtil.jsx...reduceHitAmount...lotteryActivityId=" + lotteryActivityId + "...userId=" + userId + "...totalLessPoint=" + totalLessPoint + "...lottery_point=" + jLotteryActivity.lottery_point);
                f.reduceUserPoint(jArgs, totalLessPoint, jLotteryActivity.lottery_point, branchcode, userId, memberId, jHitRecord.id);
            }
        },
        /**
         * 根据会员所属分类获取默认可抽奖资格次数
         */
        getDefaultQualificationAmount: function (jLotteryActivity, jUser, defaultValue) {
            var defaultAmountList = jLotteryActivity.default_amount;

            $.log("LotteryUtil.jsx...getDefaultQualificationAmount...lotteryActivityId=" + jLotteryActivity.id + "...defaultValue=" + defaultValue + "...jLotteryActivity=" + JSON.stringify(jLotteryActivity));

            var user_catIds = CommonUtilEx.getUserCatIds(jUser.id);
            var maxDefaultAmount = defaultValue;
            if (defaultAmountList) {
                defaultAmountList.forEach(function (jRecord) {
                    var user_cat_id = jRecord.user_cat_id;
                    var amount = jRecord.amount;
                    if (user_cat_id && amount) {
                        //所有会员都属于普通会员
                        if (user_cat_id == "owl_mall_u_category__c_101_o" || CommonUtil.isExist(user_catIds, user_cat_id)) {
                            if (maxDefaultAmount < Number(amount)) {
                                maxDefaultAmount = Number(amount);
                            }
                        }
                    }
                });
            }
            return maxDefaultAmount;
        },
        getLastHitRecord: function (lotteryActivityId, userId) {
            var searchArgs = {};
            searchArgs.lottery_activity_id = lotteryActivityId;
            searchArgs.user_id = userId;
            var searchResult = owl_lottery_hit_recordService.search(null, searchArgs, null, 0, 1, [{"owl_createTime": {order: "desc"}}]);

            if (searchResult.state === 'ok') {
                var list = searchResult.list;
                if (list && list.length > 0) {
                    return list[0];
                }
            }
            return null;
        },
        getItems: function (lotteryActivityId) {
            var searchArgs = {};
            searchArgs.lottery_activity_id = lotteryActivityId;
            var searchResult = owl_lottery_activity_itemService.search(null, searchArgs, null, 0, 200, [{"owl_createTime": {order: "desc"}}]);

            if (searchResult.state === 'ok') {
                return searchResult.list;
            }
            return [];
        },
        /**
         * 根据奖品类型发奖
         */
        doGiveAward: function (jLotteryActivity, jItem, jUser, jHitRecord) {
            var lotteryActivityId = jLotteryActivity.id;
            var userId = jUser.id;
            var type = jItem.type;
            if (type == "ticket") {
                //送券奖
                if (!jItem.ticket_type_id || !jItem.unit_amount) {
                    return;
                }
                var freeRes = FreeGetCardUtil.doGiveCard(userId, jItem.ticket_type_id, Number(jItem.unit_amount), "", "", "", "", "", "lottery", null);
                $.log("LotteryUtil.jsx...doGiveAward...freeRes=" + JSON.stringify(freeRes));
            } else if (type == "point") {
                //送积分奖
                if (!jItem.unit_amount) {
                    return;
                }
                var jArgs = TotappsCRMService.getArgs();
                var branchcode = "124";
                var memberId = null;
                var bigMemberInfo = jUser.bigMemberInfo;
                if (bigMemberInfo && bigMemberInfo.memberid) {
                    memberId = bigMemberInfo.memberid;
                }
                if (!memberId) {
                    var memberInfo = BigMemberUtil.getMemberInfoByUser(jArgs, jUser, branchcode, true);
                    memberId = memberInfo.memberid;
                }
                if (!memberId) {
                    return;
                }
                var totalLessPoint = BigMemberUtil.getMemberPoint(jArgs, branchcode, memberId);
                f.givePoint(jArgs, totalLessPoint, jItem.unit_amount, branchcode, userId, memberId, jHitRecord.id);
            } else if (type == "lottery") {
                //抽奖机会
                if (!jItem.unit_amount) {
                    return;
                }
                var jQualification = owl_lottery_qualification_amountService.get("owl_lottery_qualification_amount_" + lotteryActivityId + "_" + userId);
                if (!jQualification) {
                    jQualification = {};
                    jQualification.lottery_activity_id = lotteryActivityId;
                    jQualification.user_id = userId;
                    jQualification.amount = Number(jItem.unit_amount);
                    jQualification.default_amount = 0;
                    owl_lottery_qualification_amountService.add(jQualification);
                } else {
                    jQualification.amount = Number(jQualification.amount || 0) + Number(jItem.unit_amount);
                    owl_lottery_qualification_amountService.update(jQualification);
                }
            } else if (type == "other") {
                //其他奖品

            } else if (type == "usergroup") {
                //会员组特权
                if (!jItem.user_cat_id) {
                    return;
                }
                var jUserCategory = owl_mall_u_categoryService.get(jItem.user_cat_id);
                if (!jUserCategory) {
                    return;
                }

                var user_catIds = CommonUtilEx.getUserCatIds(jUser.id);
                if (CommonUtil.isExist(user_catIds, jItem.user_cat_id)) {
                    //已经是属于该会员组了，就不继续了
                    return;
                }

                jUser = owl_mall_uService.get(jUser.id);
                var user_categories = jUser.user_categories;
                if (!user_categories) {
                    user_categories = [];
                    jUser.user_categories = user_categories;
                }

                var jCategory = {
                    "id": jUserCategory.id,
                    "name": jUserCategory.name,
                    "createTime": new Date().getTime()
                };
                if (jItem.user_cat_begin_time) {
                    jCategory.beginTime = new Date(jItem.user_cat_begin_time).getTime();
                }
                if (jItem.user_cat_end_time) {
                    jCategory.endTime = new Date(jItem.user_cat_end_time).getTime();
                }
                user_categories.push(jCategory);
                owl_mall_uService.update(jUser);
            }
        },
        doRandomAward: function (items, rangeNum) {
            try {
                if (items.length > 0) {
                    var randomNum = f.getRandomInt(1, rangeNum);//产生中奖随机数

                    var hitPercents = [];//中奖机率，排列与上面对应
                    var i = 0;
                    for (var k = 0; k < items.length; k++) {
                        var jItem = items[k];
                        hitPercents[i] = jItem.rate;
                        //以下算出每个中奖级别的中奖范围
                        var beginNum = 0;
                        var endNum = 0;
                        for (var j = 0; j < i; j++) {
                            beginNum += hitPercents[j];//此值是这个的简化：rangeNum * hitPercents[j] / rangeNum;
                        }
                        endNum = beginNum + hitPercents[i];

                        if (randomNum > beginNum && randomNum <= endNum) {
                            return jItem;
                        }
                        i++;
                    }
                }
            } catch (e) {
                //出异常默认不中奖
            }
            return null;
        },
        getRandomInt: function (min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值，含最小值
        },
        reduceUserPoint: function (jArgs, totalLessPoint, amount, branchcode, userId, memberId, order_id) {
            var curTime = new Date().getTime();
            var billdate = DateUtil.getStringDate(curTime, "yyyyMMddHHmmss");
            var posno = BigMemberEnumUtil.POS_NO;//终端编码，例如收银机编号，无法提供时约定固定值
            var billno = "";//交易小票号，无法提供时约定固定值
            var logId = owl_mall_big_member_integrallogService.getId({});

            amount = Number(0 - Number(amount)).toFixed(2);

            var tranReason = BigMemberEnumUtil.lotteryReduce;
            var merchantId = "0";
            var shopName = "江豚网";

            var data = {
                type: tranReason.big,
                billdate: billdate,
                point: amount,
                cno: logId,
                saleid: logId,
                posno: posno,
                billno: billno,
                actcode: "",
                othernotype: "5",
                otherno: memberId
            };

            var postData = TotappsCRMService.getPostData(jArgs, branchcode);
            postData.data = data;

            var result = TotappsCRMService.updatePoint(jArgs, postData);
            var jResult = JSON.parse(result);

            var ret = {};
            if (Number(jResult.rescode) != 0) {
                ret.state = "err";
                ret.msg = "积分扣减失败，失败原因：" + jResult.restext;
                return ret;
            }


            //增加交易明细记录....begin
            var transactionLog = {};
            transactionLog.id = logId;
            transactionLog.merchantId = merchantId;
            transactionLog.branchcode = branchcode;
            transactionLog.shopName = shopName;
            transactionLog.memberId = memberId;
            transactionLog.userId = userId;
            transactionLog.beforeAmount = Number(totalLessPoint).toFixed(2);
            transactionLog.amount = amount;
            transactionLog.afterAmount = Number((Number(transactionLog.beforeAmount) + Number(amount))).toFixed(2);
            transactionLog.reason = tranReason.name;
            transactionLog.orderId = order_id;
            transactionLog.type = "reduce";
            transactionLog.source_id = tranReason.ws;
            transactionLog.source_name = tranReason.name;
            transactionLog.createTime = new Date().getTime();
            owl_mall_big_member_integrallogService.add(transactionLog);

            ret.state = "ok";
            ret.msg = "扣减积分成功";
            return ret;
        },
        givePoint: function (jArgs, totalLessPoint, amount, branchcode, userId, memberId, order_id) {
            var curTime = new Date().getTime();
            var billdate = DateUtil.getStringDate(curTime, "yyyyMMddHHmmss");
            var posno = BigMemberEnumUtil.POS_NO;//终端编码，例如收银机编号，无法提供时约定固定值
            var billno = "";//交易小票号，无法提供时约定固定值
            var logId = owl_mall_big_member_integrallogService.getId({});

            amount = Number(amount).toFixed(2);

            var tranReason = BigMemberEnumUtil.lotteryGive;
            var merchantId = "0";
            var shopName = "江豚网";

            var data = {
                type: tranReason.big,
                billdate: billdate,
                point: amount,
                cno: logId,
                saleid: logId,
                posno: posno,
                billno: billno,
                actcode: "",
                othernotype: "5",
                otherno: memberId
            };

            var postData = TotappsCRMService.getPostData(jArgs, branchcode);
            postData.data = data;

            var result = TotappsCRMService.updatePoint(jArgs, postData);
            var jResult = JSON.parse(result);

            var ret = {};
            if (Number(jResult.rescode) != 0) {
                ret.state = "err";
                ret.msg = "发放积分失败，失败原因：" + jResult.restext;
                return ret;
            }


            //增加交易明细记录....begin
            var transactionLog = {};
            transactionLog.id = logId;
            transactionLog.merchantId = merchantId;
            transactionLog.branchcode = branchcode;
            transactionLog.shopName = shopName;
            transactionLog.memberId = memberId;
            transactionLog.userId = userId;
            transactionLog.beforeAmount = Number(totalLessPoint).toFixed(2);
            transactionLog.amount = amount;
            transactionLog.afterAmount = Number((Number(transactionLog.beforeAmount) + Number(amount))).toFixed(2);
            transactionLog.reason = tranReason.name;
            transactionLog.orderId = order_id;
            transactionLog.type = "recharge";
            transactionLog.source_id = tranReason.ws;
            transactionLog.source_name = tranReason.name;
            transactionLog.createTime = new Date().getTime();
            owl_mall_big_member_integrallogService.add(transactionLog);

            ret.state = "ok";
            ret.msg = "发放积分成功";
            return ret;
        }
    };
    return f;

})();