package com.cweb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.CoordCommonUtil;
import com.hai.common.utils.PageUtil;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.*;
import com.hai.enum_type.ActivityInfoStatus;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *
 * @author hurui
 */
@Controller
@RequestMapping(value = "/activity")
@Api(value = "活动业务接口")
public class HighActivityController {

    private static Logger log = LoggerFactory.getLogger(HighActivityController.class);

    @Resource
    private UserCenter userCenter;

    @Resource
    private HighActivityInfoService highActivityInfoService;

    @Resource
    private HighActivityAwardService highActivityAwardService;

    @Resource
    private HighActivityAwardUserService highActivityAwardUserService;

    @Resource
    private HighActivityPrizeService highActivityPrizeService;

    @Resource
    private HighActivityUserLotteryNumService highActivityUserLotteryNumService;

    @RequestMapping(value="/userLottery",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户抽奖业务")
        public ResponseData userLottery(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            if (body == null || body.getLong("activityId") == null) {
                log.error("HighActivityController --> lottery() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 活动信息
            HighActivityInfo activityInfo = highActivityInfoService.getDetailById(body.getLong("activityId"));
            if (activityInfo == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到数据");
            }
            if (!activityInfo.getStatus().equals(ActivityInfoStatus.status2.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "活动已结束");
            }
            Date currentDate = new Date();
            if (currentDate.getTime() < activityInfo.getStartTime().getTime()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "活动还未开始");
            }
            if (currentDate.getTime() > activityInfo.getEndTime().getTime()) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "活动已结束");
            }
            // 校验用户是否有抽奖次数
            if (highActivityUserLotteryNumService.getLotteryNum(body.getLong("activityId"), userInfoModel.getHighUser().getId()) <= 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "抽奖次数已经用完了");
            }

            return ResponseMsgUtil.success(highActivityUserLotteryNumService.userLottery(body.getLong("activityId"),userInfoModel.getHighUser().getId()));

        } catch (DeadlockLoserDataAccessException deadlockLoserDataAccessException) {
            log.error("HighActivityController -> userLottery() error!", "服务器繁忙");
            return ResponseMsgUtil.builderResponse(ErrorCode.SERVER_BUSY_ERROR.getCode(),ErrorCode.SERVER_BUSY_ERROR.getMsg(),null);

        } catch (Exception e) {
            log.error("HighActivityController -> userLottery() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getUserLotteryNum",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户抽奖次数")
    public ResponseData getUserLotteryNum(@RequestParam(name = "activityId", required = true) Long activityId,
                                      HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            return ResponseMsgUtil.success(highActivityUserLotteryNumService.getLotteryNum(activityId,userInfoModel.getHighUser().getId()));
        } catch (Exception e) {
            log.error("HighActivityController -> getLotteryNum() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getActivityByCoupon",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据卡券查询活动信息")
    public ResponseData getActivityByCoupon(@RequestParam(name = "couponId", required = true) Long couponId) {
        try {
            // 查询活动
            Map<String, Object> activity = highActivityInfoService.getNewActivityByCouponId(couponId);
            if (activity != null) {
                Map<String,Object> map = new HashMap<>();
                map.put("activityInfo", activity);

                // 奖励
                JSONArray awardList = JSONArray.parseArray(JSONArray.toJSONString(highActivityAwardService.getListByActivityId(MapUtils.getLong(activity, "id"))));
                for (Object awardObject : awardList) {
                    JSONObject award = (JSONObject) awardObject;
                    // 查询奖品
                    String prizeStr = "";
                    List<HighActivityPrize> list = highActivityPrizeService.getListByAwardId(award.getLong("id"));
                    for (HighActivityPrize prize : list) {
                        if (StringUtils.isBlank(prizeStr)) {
                            prizeStr = prize.getPrizeName() +"("+ prize.getPrizeNum() +"张)";
                        } else {
                            prizeStr += "、"+prize.getPrizeName() +"("+ prize.getPrizeNum() +"张)";
                        }
                    }
                    award.put("prizeStr", prizeStr);
                }
                map.put("activityAward", awardList);
                return ResponseMsgUtil.success(map);
            }
            return ResponseMsgUtil.success(null);

        } catch (Exception e) {
            log.error("HighActivityController -> getActivityByCoupon() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getDetail",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询活动详情")
    public ResponseData getDetail(@RequestParam(name = "activityId", required = true) Long activityId) {
        try {
            // 查询活动
            HighActivityInfo detail = highActivityInfoService.getDetailById(activityId);
            if (detail != null) {
                Map<String,Object> map = new HashMap<>();
                map.put("activityInfo", detail);
                // 奖励
                JSONArray awardList = JSONArray.parseArray(JSONArray.toJSONString(highActivityAwardService.getListByActivityId(activityId)));
                for (Object awardObject : awardList) {
                    JSONObject award = (JSONObject) awardObject;
                    // 查询奖品
                    String prizeStr = "";
                    List<HighActivityPrize> list = highActivityPrizeService.getListByAwardId(award.getLong("id"));
                    for (HighActivityPrize prize : list) {
                        if (StringUtils.isBlank(prizeStr)) {
                            prizeStr = prize.getPrizeName() +"("+ prize.getPrizeNum() +"张)";
                        } else {
                            prizeStr += "、"+prize.getPrizeName() +"("+ prize.getPrizeNum() +"张)";
                        }
                    }
                    award.put("prizeStr", prizeStr);
                }
                map.put("activityAward", awardList);
                return ResponseMsgUtil.success(map);
            }
            return ResponseMsgUtil.success(null);
        } catch (Exception e) {
            log.error("HighActivityController -> getDetail() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/getWinLotteryList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询中奖记录")
    public ResponseData getWinLotteryList(@RequestParam(name = "activityId", required = true) Long activityId) {
        try {

            return ResponseMsgUtil.success(highActivityAwardUserService.getWinLotteryList(activityId));

        } catch (Exception e) {
            log.error("HighActivityController -> getWinLotteryList() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


}
