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.SessionObject;
import com.hai.common.security.UserCenter;
import com.hai.common.utils.ResponseMsgUtil;
import com.hai.entity.HighDiscount;
import com.hai.entity.HighDiscountAgentCode;
import com.hai.entity.HighDiscountCouponRel;
import com.hai.entity.HighDiscountUserRel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.service.HighDiscountAgentCodeService;
import com.hai.service.HighDiscountCouponRelService;
import com.hai.service.HighDiscountUserRelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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 HighDiscountUserRelService highDiscountUserRelService;

    @Resource
    private HighDiscountCouponRelService highDiscountCouponRelService;

    @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="/getUserDiscountList",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户的优惠券列表")
    public ResponseData getUserDiscountList(@RequestParam(name = "status", required = false) Integer status,
                                            @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("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) {
                            list.add(collect.get(0));
                        }
                    }
                }
            }
            return ResponseMsgUtil.success(list);

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