package com.cweb.controller.discount;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.SessionObject;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.model.SecUserSessionObject;
import com.hfkj.model.UserSessionObject;
import com.hfkj.model.discount.DiscountGoodsModel;
import com.hfkj.service.CommonService;
import com.hfkj.service.SecDictionaryService;
import com.hfkj.service.discount.CouponDiscountPackageService;
import com.hfkj.service.discount.CouponDiscountService;
import com.hfkj.service.discount.CouponDiscountUserRelService;
import com.hfkj.service.goods.impl.GoodsMsgServiceImpl;
import com.hfkj.service.goods.impl.GoodsSpecsServiceImpl;
import com.hfkj.sysenum.UserLoginPlatform;
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.BeanUtils;
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.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value="/discount")
@Api(value="优惠券")
public class DiscountController {

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

    @Resource
    private UserCenter userCenter;

    @Resource
    private CouponDiscountUserRelService discountUserRelService;
    @Resource
    private CouponDiscountService couponDiscountService;
    @Resource
    private CouponDiscountPackageService couponDiscountPackageService;

    @Resource
    private SecDictionaryService dictionaryService;

    @RequestMapping(value = "/getListUserDiscount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取用户优惠券列表")
    public ResponseData getListUserDiscount(@RequestParam(value = "status", required = true) Integer status) {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userSession.getUser().getId());
            map.put("status", status);

            return ResponseMsgUtil.success(discountUserRelService.getList(map));

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

    @RequestMapping(value = "/getGoodsDiscount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取商品可用优惠券")
    public ResponseData getGoodsDiscount(@RequestParam(value = "specsIds", required = true) String specsIds,
                                         @RequestParam(value = "platformCode" , required = false) String platformCode
    ) {
        try {

            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);

            Map<String, Object> map = new HashMap<>();

            map.put("userId", userSession.getUser().getId());
            if (platformCode == null) {
                map.put("platformCode", UserLoginPlatform.WXAPPLETS.getCode());
            } else {
                map.put("platformCode", platformCode);
            }

            map.put("status", 1);

            List<CouponDiscountUserRel> list = discountUserRelService.getList(map);

            List<CouponDiscountUserRel> listDiscount = list.stream().filter(distinctByKey(CouponDiscountUserRel::getDiscountId)).collect(Collectors.toList());

            List<CouponDiscountUserRel> listFind = new ArrayList<>();

            listDiscount.forEach(d -> {
                Map<String, Object> mapSpecs = new HashMap<>();
                mapSpecs.put("discountId", d.getDiscountId());
                mapSpecs.put("specsIds", specsIds);
                // 查询规格可用优惠券
                List<CouponDiscountGoodsRel> couponDiscountGoodsRel = couponDiscountService.getListGoodsRel(mapSpecs);
                List<Long> specsIdList = new ArrayList<>();
                List<Long> specsIdListS = new ArrayList<>();

                couponDiscountGoodsRel.forEach(dg -> {
                    specsIdList.add(dg.getSpecsId());
                });

                String[] s = specsIds.split(",");

                for(String ss : s) {
                    specsIdListS.add(Long.parseLong(ss));
                }
                Collections.sort(specsIdList);
                Collections.sort(specsIdListS);
                if (specsIdList.toString().equals(specsIdListS.toString())) {
                    listFind.add(d);
                }
            });


            List<CouponDiscountUserRel> filteredList = list.stream()
                    .filter(obj -> listFind.stream()
                            .map(CouponDiscountUserRel::getDiscountId)
                            .collect(Collectors.toList())
                            .contains(obj.getDiscountId()))
                    .collect(Collectors.toList());


            return ResponseMsgUtil.success(filteredList);

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

    @RequestMapping(value = "/giveDiscountPackage", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "赠送券包")
    public ResponseData giveDiscountPackage(@RequestBody JSONObject body) {
        try {

            if ( body == null
                    || body.getInteger("discountPackageId") == null
                    || body.getString("phone") == null
            ) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }

            couponDiscountPackageService.giveDiscountPackage(body.getInteger("discountPackageId") , body.getString("phone"));

            return ResponseMsgUtil.success("成功！");

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

    private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Set<Object> seen = ConcurrentHashMap.newKeySet();
        return t -> seen.add(keyExtractor.apply(t));
    }

    @RequestMapping(value = "/userDiscount", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "用户送券")
    public ResponseData userDiscount(@RequestParam(value = "code", required = true) String code) {
        try {
            // 用户session
            UserSessionObject userSession = userCenter.getSessionModel(UserSessionObject.class);
            List<SecDictionary> dictionary = dictionaryService.getDictionaryByOl(code);

            if (!dictionary.isEmpty()) {
                for (SecDictionary secDictionary : dictionary) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("userId", userSession.getUser().getId());
                    map.put("status", 1);
                    map.put("discountId", secDictionary.getCodeValue());

                    List<CouponDiscountUserRel> list = discountUserRelService.getList(map);
                    if (list.isEmpty()) {
                        couponDiscountPackageService.giveDiscountPackage(Integer.valueOf(secDictionary.getCodeName()), userSession.getUser().getPhone());
                    }

                }
            }

            return ResponseMsgUtil.success("送券成功");

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


}
