package com.cweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
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.AESEncodeUtil;
import com.hai.common.security.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.*;
import com.hai.enum_type.DiscountUseScope;
import com.hai.enum_type.OrderChildGoodsTypeEnum;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/4/4 15:41
 */
@Controller
@RequestMapping(value = "/userDiscount")
@Api(value = "用户优惠券接口")
public class HighUserDiscountController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighDiscountService discountService;

    @Resource
    private HighDiscountAgentRelService discountAgentRelService;

    @Resource
    private HighDiscountUserRelService highDiscountUserRelService;

    @Resource
    private HighDiscountCouponRelService highDiscountCouponRelService;

    @Resource
    private HighOpenApiService highOpenApiService;

    @RequestMapping(value="/receiveDiscount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户领取优惠券码【领取优惠码值】")
    public ResponseData receiveDiscount(@RequestBody String reqBody, HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            Long codeId = jsonObject.getLong("codeId");
            if (codeId == null) {
                log.error("HighDiscountController -> receiveDiscount() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 领取
            highDiscountUserRelService.receiveDiscount(userInfoModel.getHighUser().getId(), codeId);
            return ResponseMsgUtil.success("领取成功");

        } 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("HighDiscountController -> receiveDiscount() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/receive",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "用户领取优惠券【领取优惠】")
    public ResponseData receive(@RequestBody String reqBody, HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            JSONObject jsonObject = JSONObject.parseObject(reqBody);
            String discountAgentCode = jsonObject.getString("code");
            if (StringUtils.isBlank(discountAgentCode)) {
                log.error("HighDiscountController -> receiveDiscount() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 解密
            String discountAgentId = AESEncodeUtil.aesDecrypt(URLDecoder.decode(discountAgentCode, "UTF-8"));

            HighDiscountAgentRel discountAgentRel = discountAgentRelService.getRelById(Long.parseLong(discountAgentId));
            if (discountAgentRel == null) {
                log.error("HighDiscountController -> receiveDiscount() error!", "参数错误");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知优惠券");
            }
            // 查询优惠券信息
            HighDiscount discount = discountService.getDiscountById(discountAgentRel.getDiscountId());
            if (discount == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的优惠券");
            }
            if (!discount.getStatus().equals(2)) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "无法领取，优惠券活动已过期");
            }

            // 领取
            highDiscountUserRelService.receive(userInfoModel.getHighUser().getId(), discountAgentRel.getId());
            return ResponseMsgUtil.success("领取成功");

        } 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("HighDiscountController -> receiveDiscount() error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }


    @RequestMapping(value="/getUserDiscountList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户的优惠券列表")
    public ResponseData getUserDiscountList(@RequestParam(name = "status", required = false) Integer status,
                                            @RequestParam(name = "useScope", required = false) Integer useScope,
                                            @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                            @RequestParam(name = "pageSize", required = true) Integer pageSize,
                                            HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String,Object> map = new HashMap<>();
            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("useScope", useScope);
            map.put("status", status);

            PageHelper.startPage(pageNum,pageSize);
            return ResponseMsgUtil.success(new PageInfo<>(highDiscountUserRelService.getDiscountList(map)));

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

    @RequestMapping(value="/getDiscountByUserDiscountId",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据用户和优惠券关系id 查询优惠券详情")
    public ResponseData getDiscountByUserDiscountId(@RequestParam(name = "userDiscountId", required = true) Long userDiscountId) {
        try {

            return ResponseMsgUtil.success(highDiscountUserRelService.getRelById(userDiscountId));

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


    @RequestMapping(value="/getUserNormalDiscountList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据卡券,查询【可以使用】优惠券列表")
    public ResponseData getDiscountListByCoupon(@RequestParam(name = "couponId", required = true) Long couponId,HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            Map<String,Object> map = new HashMap<>();
            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("status", 1);

            List<HighDiscountUserRel> list = new ArrayList<>();
            // 查询用户的优惠券
            List<HighDiscountUserRel> userRels = highDiscountUserRelService.getDiscountList(map);
            if (userRels.size() > 0) {
                // 查询当前卡券有哪些优惠券
                List<HighDiscountCouponRel> discountCouponRelList = highDiscountCouponRelService.getRelByCoupon(couponId);
                if (discountCouponRelList.size() > 0) {
                    for (HighDiscountCouponRel highDiscountCouponRel : discountCouponRelList) {
                        List<HighDiscountUserRel> collect = userRels.stream().filter(o -> o.getDiscountId().equals(highDiscountCouponRel.getDiscountId())).collect(Collectors.toList());
                        if (collect != null && collect.size() > 0) {
                            for (HighDiscountUserRel discountUser : collect) {
                                list.add(discountUser);
                            }
                        }
                    }
                }
            }
            list.sort(Comparator.comparing(o -> o.getUseEndTime()));
            return ResponseMsgUtil.success(list);

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

    @RequestMapping(value = "/getUserExclusiveDiscount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户专属优惠券")
    public ResponseData getUserExclusiveDiscount(@RequestParam(name = "useScope", required = false) Integer usingAttribution,
                                            @RequestParam(name = "year", required = false) String year,
                                            HttpServletRequest request) {
        try {

            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();


            Map<String,Object> map = new HashMap<>();
            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("useScope", usingAttribution);
            map.put("status" , 1);
            if (year != null) {
                map.put("createTimeS", year + "-01-01 00:00:00");
                map.put("createTimeE", year + "-12-31 23:59:59");
            }

            return ResponseMsgUtil.success(highOpenApiService.getUserCouponsList(map));

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


    @RequestMapping(value="/canUseDiscount",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "商品可以使用的优惠券")
    public ResponseData canUseDiscount(@RequestBody JSONObject body) {
        try {
            // 用户
            HighUserModel userInfoModel = userCenter.getSessionModel(HighUserModel.class);
            if (userInfoModel == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMPETENCE_INSUFFICIENT, "");
            }
            if (body == null
                    || body.getInteger("goodsType") == null
                    || body.getLong("goodsId") == null
                    || body.getBigDecimal("goodsPrice") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            // 商品类型
            OrderChildGoodsTypeEnum goodsType = OrderChildGoodsTypeEnum.getDataByType(body.getInteger("goodsType"));
            if (goodsType == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的商品类型");
            }

            Map<String,Object> map = new HashMap<>();
            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("status", 1);
            // 查询用户的优惠券
            List<HighDiscountUserRel> userDiscountList = highDiscountUserRelService.getDiscountList(map);

            List<HighDiscountUserRel> list = new ArrayList<>();

            if (userDiscountList.size() > 0) {

                if (goodsType.getType().equals(OrderChildGoodsTypeEnum.type1.getType())) {
                    // 查询当前卡券有哪些优惠券
                    List<HighDiscountCouponRel> discountCouponRelList = highDiscountCouponRelService.getRelByCoupon(body.getLong("goodsId"));
                    if (discountCouponRelList.size() > 0) {
                        for (HighDiscountCouponRel highDiscountCouponRel : discountCouponRelList) {
                            List<HighDiscountUserRel> collect = userDiscountList.stream().filter(o -> o.getDiscountId().equals(highDiscountCouponRel.getDiscountId())).collect(Collectors.toList());
                            if (collect != null && collect.size() > 0) {
                                for (HighDiscountUserRel discountUser : collect) {
                                    list.add(discountUser);
                                }
                            }
                        }
                    }
                }

                if (goodsType.getType().equals(OrderChildGoodsTypeEnum.type3.getType())) {
                    // 过滤出加油服务的加油券
                    List<HighDiscountUserRel> collect = userDiscountList.stream().filter(o -> o.getHighDiscount().getUseScope().equals(DiscountUseScope.type7.getType())).collect(Collectors.toList());
                    for (HighDiscountUserRel userDiscount : collect) {
                        // 满减
                        if (userDiscount.getHighDiscount().getDiscountType().equals(1)) {
                            if (body.getBigDecimal("goodsPrice").compareTo(userDiscount.getHighDiscount().getDiscountCondition()) >= 0) {
                                list.add(userDiscount);
                            }
                        }

                        if (userDiscount.getHighDiscount().getDiscountType().equals(2)
                                || userDiscount.getHighDiscount().getDiscountType().equals(3)) {
                            list.add(userDiscount);
                        }

                    }
                }
                list.sort(Comparator.comparing(o -> o.getUseEndTime()));
            }
            return ResponseMsgUtil.success(list);

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

}
