package com.cweb.controller;

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.BsCompany;
import com.hai.entity.HighCoupon;
import com.hai.entity.HighUserCoupon;
import com.hai.entity.SecRegion;
import com.hai.model.HighUserCouponModel;
import com.hai.model.HighUserModel;
import com.hai.model.ResponseData;
import com.hai.model.UserInfoModel;
import com.hai.service.*;
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.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Auther: 胡锐
 * @Description:
 * @Date: 2021/3/11 22:16
 */
@Controller
@RequestMapping(value = "/coupon")
@Api(value = "卡卷接口")
public class HighCouponController {

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

    @Autowired
    private UserCenter userCenter;

    @Resource
    private HighCouponService highCouponService;

    @Resource
    private BsCompanyService bsCompanyService;

    @Resource
    private HighCouponCodeService highCouponCodeService;

    @Resource
    private HighUserCouponService highUserCouponService;

    @Resource
    private HighMerchantStoreService highMerchantStoreService;

    @Resource
    private CommonService commonService;

    @RequestMapping(value = "/getCouponList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "卡卷列表")
    public ResponseData getCouponList(@RequestParam(name = "regionId", required = true) String regionId,
                                      @RequestParam(name = "merchantId", required = false) Long merchantId,
                                      @RequestParam(name = "couponName", required = false) String couponName,
                                      @RequestParam(name = "couponType", required = false) Integer couponType,
                                      @RequestParam(name = "displayArea", required = false) Integer displayArea,
                                      @RequestParam(name = "brandId", required = false) Integer brandId,
                                      @RequestParam(name = "goodsTypeId", required = false) Integer goodsTypeId,
                                      @RequestParam(name = "pageNum", required = true) Integer pageNum,
                                      @RequestParam(name = "pageSize", required = true) Integer pageSize) {
        try {

            SecRegion region = commonService.getParentByRegion(Long.parseLong(regionId));
            if (region != null) {
                BsCompany bsCompany = bsCompanyService.selectCompanyByRegion(region.getRegionId().toString());
                if (bsCompany != null) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("companyId", bsCompany.getId());
                    map.put("merchantId", merchantId);
                    map.put("couponName", couponName);
                    map.put("couponType", couponType);
                    map.put("brandId", brandId);
                    map.put("goodsTypeId", goodsTypeId);
                    map.put("displayArea", displayArea);
                    map.put("notCouponSource", 2);
                    map.put("status", 2);
                    PageHelper.startPage(pageNum, pageSize);
                    return ResponseMsgUtil.success(new PageInfo<>(highCouponService.getCouponList(map)));
                }
            }
            return ResponseMsgUtil.success(new PageInfo<>());

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

    @RequestMapping(value = "/getCouponById", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "卡卷信息")
    public ResponseData getCouponById(@RequestParam(name = "userId", required = false) Long userId,
                                      @RequestParam(name = "couponId", required = true) Long couponId) {
        try {

            HighCoupon coupon = highCouponService.getCouponById(couponId);
            if (coupon != null & userId != null) {
                coupon.setNumberUpperLimitStatus(highCouponService.userBuyLimitNumber(userId, coupon.getId()));
            }
            return ResponseMsgUtil.success(coupon);

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

    @RequestMapping(value = "/getUserCouponList", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户卡卷列表")
    public ResponseData getUserCouponList(@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<>(highUserCouponService.getUserCouponList(map)));

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

    @RequestMapping(value = "/getUserCouponDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户卡卷详细")
    public ResponseData getUserCouponDetail(@RequestParam(name = "userCouponId", required = true) Long userCouponId,
                                            HttpServletRequest request) {
        try {

            HighUserCoupon coupon = highUserCouponService.getDetailById(userCouponId);
            if (coupon == null) {
                log.error("HighCouponController --> getUserCouponDetail() error!", "未找到卡券");
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到卡券");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("highUserCoupon", coupon);
            map.put("couponInfo", highCouponService.getCouponById(coupon.getCouponId()));
            map.put("couponCodeInfo", highCouponCodeService.getCouponCodeById(coupon.getCouponCodeId()));

            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/getUserNewCouponDetail", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户最新的卡卷详细")
    public ResponseData getUserNewCouponDetail(@RequestParam(name = "couponId", required = true) Long couponId,
                                            HttpServletRequest request) {
        try {
            // 用户
            SessionObject sessionObject = userCenter.getSessionObject(request);
            HighUserModel userInfoModel = (HighUserModel) sessionObject.getObject();

            // 查询最新一张可用的卡券
            HighUserCoupon newCoupon = highUserCouponService.getUserNewCoupon(userInfoModel.getHighUser().getId(), couponId);

            if (newCoupon != null) {
                Map<String, Object> map = new HashMap<>();
                map.put("highUserCoupon", newCoupon);
                map.put("couponInfo", highCouponService.getCouponById(newCoupon.getCouponId()));
                map.put("couponCodeInfo", highCouponCodeService.getCouponCodeById(newCoupon.getCouponCodeId()));
                return ResponseMsgUtil.success(map);
            }
            return ResponseMsgUtil.success(null);

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

    @RequestMapping(value = "/againReceiveCoupon", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "卡卷过期，再次领取")
    public ResponseData againReceiveCoupon(@RequestParam(name = "couponId", required = true) Long couponId,
                                           HttpServletRequest request) {
        try {

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

            // 重新领取
            HighUserCoupon userCoupon = highUserCouponService.againReceiveCoupon(userInfoModel.getHighUser().getId(), couponId);

            Map<String, Object> map = new HashMap<>();
            map.put("highUserCoupon", userCoupon);
            map.put("couponInfo", highCouponService.getCouponById(userCoupon.getCouponId()));
            map.put("couponCodeInfo", highCouponCodeService.getCouponCodeById(userCoupon.getCouponCodeId()));
            return ResponseMsgUtil.success(map);

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

    @RequestMapping(value = "/getCouponListByStoreId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "根据门店ID查询用户卡卷列表")
    public ResponseData getCouponListByStoreId(
            @RequestParam(name = "storeId", required = false) Long storeId,
            @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("merchantId", highMerchantStoreService.getMerchantStoreById(storeId).getMerchantId());
            map.put("userId", userInfoModel.getHighUser().getId());
            map.put("status", 1);
            PageHelper.startPage(pageNum, pageSize);

            return ResponseMsgUtil.success(new PageInfo<>(highUserCouponService.getUserCouponList(map)));

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

}
