package com.kmall.api.api;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.kmall.api.annotation.LoginUser;
import com.kmall.api.entity.CouponVo;
import com.kmall.api.entity.UserCouponVo;
import com.kmall.api.entity.UserVo;
import com.kmall.api.entity.mk.MkStoreTicketDiscountVo;
import com.kmall.api.service.mk.ApiMkStoreTicketDiscountService;
import com.kmall.api.service.mk.ApiMkStoreTopicStatService;
import com.kmall.common.constant.Dict;
import com.kmall.common.utils.DateUtils;
import com.kmall.manager.entity.SysSmsLogEntity;
import com.kmall.manager.service.SysSmsLogService;
import com.kmall.api.service.ApiCouponService;
import com.kmall.api.service.ApiUserCouponService;
import com.kmall.api.service.ApiUserService;
import com.kmall.api.util.ApiBaseAction;
import com.kmall.common.utils.enums.CouponTypeEnum;
import com.qiniu.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * API优惠券管理
 *
 * @author Scott
 * @email
 * @date 2017-03-23 15:31
 */
@RestController
@RequestMapping("/api/coupon")
public class ApiCouponController extends ApiBaseAction {
    @Autowired
    private ApiUserService apiUserService;
    @Autowired
    private ApiCouponService apiCouponService;
    @Autowired
    private ApiUserCouponService apiUserCouponService;
    @Autowired
    private SysSmsLogService sysSmsLogService;
    @Autowired
    private ApiMkStoreTicketDiscountService apiMkStoreTicketDiscountService;

    /**
     * 是否有可以参加的活动
     *
     * @return
     */
   /* @GetMapping("enableActivity")
    public Object enableActivity() {
        Map resultObj = Maps.newHashMap();
        Map param = Maps.newHashMap();
        param.put("user_id", getUserId());
        // 需要点击领取的优惠券
        Integer[] send_types = new Integer[]{CouponTypeEnum.COUPONTYPE1.getIndex()};
        param.put("send_types", send_types);
        param.put("unObtain", true);// 未领取
        resultObj.put("takeCoupon", "");
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(param);
        if (null != couponVos && couponVos.size() > 0) {
            apiCouponService.takeCoupon(couponVos.get(0), getUserId(), "", 0L, 1);
            resultObj.put("takeCoupon", couponVos.get(0));
            return toResponsSuccess(resultObj);
        }
//        // 已经发放，但是没有提醒的
//        param = Maps.newHashMap();
//        send_types = new Integer[]{0, 2, 4, 5, 6};
//        param.put("user_id", loginUser.getId());
//        param.put("send_types", send_types);
//        param.put("show_state", 0); // 是否需要显示 0：未显示 1：已显示
//        param.put("unUsed", true);
//        param.put("enabled", true);
//        List<UserCouponVo> userCouponVos = apiUserCouponService.queryList(param);
//        if (null != userCouponVos && userCouponVos.size() > 0) {
//            UserCouponVo userCouponVo = userCouponVos.get(0);
//            userCouponVo.setShow_state(1);
//            apiUserCouponService.update(userCouponVo);
//            // 返回优惠券
//            CouponVo couponVo = apiCouponService.queryObject(userCouponVo.getCoupon_id());
//            resultObj.put("showCoupon", couponVo);
//            return toResponsSuccess(couponVo);
//        }
        // 无需领取的优惠券
//        param = Maps.newHashMap();
//        param.put("user_id", loginUser.getId());
//        send_types = new Integer[]{3, 7};
//        param.put("send_types", send_types);
//        param.put("filterCouponIds", couponIds);
//        CouponVo couponVo = apiCouponService.queryMaxUserEnableCoupon(param);
//        if (null != couponVo) {
//            resultObj.put("showCoupon", couponVo);
//            return toResponsSuccess(resultObj);
//        }
        return toResponsSuccess(resultObj);
    }*/

    /**
     * 获取优惠券列表
     */
    @GetMapping("list")
    public Object list(@LoginUser UserVo loginUser,Integer discStatus,String couponNumber) {

        Map param = Maps.newHashMap();
        param.put("userId", loginUser.getId());
        param.put("merchSn", getMerchSn());
        param.put("storeId", getStoreId());

        if(discStatus == 0){//未使用且已领取
            param.put("unUsed", true);
            param.put("enabled", true);
            param.put("isUsed", true);
        }
        if(discStatus == 1){//已使用且已领取
            param.put("isUsed", false);
        }
        if(discStatus == 2){//已过期
            param.put("enabled", false);
        }
        List<MkStoreTicketDiscountVo> couponVos = apiMkStoreTicketDiscountService.queryStoreDiscountByUserId(param);
        List<MkStoreTicketDiscountVo> discountVoList = new ArrayList<>();
        for (MkStoreTicketDiscountVo discountEntity : couponVos) {
            //已过期
            if(discStatus == 2) {
                discountEntity.setInValidTime(setInvalidTime(discountEntity));
                discountEntity.setInValidTime(setInvalidTime(discountEntity));
                discountEntity.setIsReceive(1);//优惠券是否可操作 1：不可操作 0：可操作
                discountVoList.add(discountEntity);
            }else{
                if(discStatus == 0) {
                    if (discountEntity.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_00.getItem())) {
                        if (!DateUtils.compareDate(discountEntity.getFixEndTime(), new Date())) {//有效
                            discountEntity.setIsReceive(0);//优惠券是否可操作 1：不可操作 0：可操作
                            discountEntity.setInValidTime(setInvalidTime(discountEntity));
                            discountVoList.add(discountEntity);
                        }
                    }
                    if (discountEntity.getEffectTimeType().equalsIgnoreCase(Dict.effectTimeType.item_01.getItem())) {
                        String postponeNum = com.kmall.common.utils.StringUtils.isNotEmpty(discountEntity.getPostponeNum()) ? discountEntity.getPostponeNum() : "0";
                        String validDayNum = com.kmall.common.utils.StringUtils.isNotEmpty(discountEntity.getValidDayNum()) ? discountEntity.getValidDayNum() : "0";
                        Integer day = Integer.parseInt(postponeNum) + Integer.parseInt(validDayNum);
                        Date endDate = DateUtils.addDay(discountEntity.getAddTime(), day);//失效时间，失效时间>当前时间
                        Date validTime = discountEntity.getValidTime();//生效时间，如生效时间>当前时间则优惠券才可用
                        if (!DateUtils.compareDate(endDate, new Date())) {//结束时间超过当前时间则过期
                            if(validTime.getTime() > new Date().getTime()){
                                discountEntity.setIsReceive(2);//优惠券是否可操作 1：不可操作 0：可操作 2:暂不可用
                                discountEntity.setInValidTime(DateUtils.format(validTime,DateUtils.DATE_TIME_PATTERN)+"生效");
                            }else{
                                discountEntity.setIsReceive(0);//优惠券是否可操作 1：不可操作 0：可操作
                                discountEntity.setInValidTime(setInvalidTime(discountEntity));
                            }
                            discountVoList.add(discountEntity);
                        }
                    }
                }else{
                    discountEntity.setIsReceive(3);
                    discountEntity.setInValidTime(setInvalidTime(discountEntity));
                    discountVoList = couponVos;
                }
            }
        }
        return toResponsSuccess(discountVoList);
    }

    /**
     * 兑换优惠券，暂时无用
     */
    @PostMapping("exchange")
    public Object exchange(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        String coupon_number = jsonParam.getString("coupon_number");
        if (StringUtils.isNullOrEmpty(coupon_number)) {
            return toResponsFail("当前优惠码无效");
        }
        //
        Map param = Maps.newHashMap();
        param.put("coupon_number", coupon_number);
        param.put("merchSn", getMerchSn());
        List<UserCouponVo> couponVos = apiUserCouponService.queryList(param);
        UserCouponVo userCouponVo = null;
        if (null == couponVos || couponVos.size() == 0) {
            return toResponsFail("当前优惠码无效");
        }
        userCouponVo = couponVos.get(0);
        if (null != userCouponVo.getUserId() && !userCouponVo.getUserId().equals(0L)) {
            return toResponsFail("当前优惠码已经兑换");
        }
//        CouponVo couponVo = apiCouponService.queryObject(userCouponVo.getCoupon_id());
//        if (null == couponVo || null == couponVo.getUse_end_date() || couponVo.getUse_end_date().before(new Date())) {
//            return toResponsFail("当前优惠码已经过期");
//        }
        userCouponVo.setUserId(loginUser.getId());
        userCouponVo.setAddTime(new Date());
        apiUserCouponService.update(userCouponVo);
        return toResponsSuccess(userCouponVo);
    }

    /**
     * 手机号绑定
     */
    @PostMapping("newuser")
    public Object newuser(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        //
        String phone = jsonParam.getString("phone");
        String smscode = jsonParam.getString("smscode");
        List<UserVo> userVoList = apiUserService.queryByMobile(phone);
        if(userVoList != null && userVoList.size() > 0){
            return toResponsFail("该手机号已绑定");
        }
        // 校验短信码
        SysSmsLogEntity smsLogVo = sysSmsLogService.querySmsCodeByUserId(loginUser.getId());
        if (null != smsLogVo) {
            if(!smsLogVo.getSmsCode().equals(smscode) || smsLogVo.getSendStatus() == 0){
                return toResponsFail("短信验证码错误");
            }
        }
        // 更新手机号码
        if (!StringUtils.isNullOrEmpty(phone)) {
            loginUser.setMobile(phone);
            apiUserService.update(loginUser);
        }
        /*// 判断是否是新用户
        if (!StringUtils.isNullOrEmpty(loginUser.getMobile())) {
            return toResponsFail("当前优惠券只能新用户领取");
        } else {
            loginUser.setMobile(phone);
            apiUserService.update(loginUser);
        }*/
        /*Boolean isCoupon = false;//false 不可以领优惠券
        Map queryMap = Maps.newHashMap();
        queryMap.put("store_id", getStoreId());
        List<CouponVo> list = apiCouponService.queryList(queryMap);
        if(null!= list && list.size()>0){
            CouponVo couponVo = list.get(0);
            if(couponVo.getIsAll().equalsIgnoreCase("1")){
                isCoupon = true;
            }
        }else{
            isCoupon = false;
        }
        if(isCoupon){
            // 是否领取过了
            Map params = Maps.newHashMap();
            params.put("user_id", loginUser.getId());
            params.put("store_id", getStoreId());
            params.put("send_type", 4);
            List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
            if (null != couponVos && couponVos.size() > 0) {
                return toResponsFail("已经领取过，不能重复领取");
            }
            // 领取
            Map couponParam = Maps.newHashMap();
            couponParam.put("send_type", CouponTypeEnum.COUPONTYPE4.getIndex());
            CouponVo newCouponConfig = apiCouponService.queryMaxUserEnableCoupon(couponParam);
            if (null != newCouponConfig) {
                UserCouponVo userCouponVo = apiCouponService.takeCoupon(newCouponConfig, loginUser.getId(), "", 0L, 1);
                return toResponsSuccess(userCouponVo);
            } else {
                return toResponsFail("领取失败");
            }
        }else{
            return toResponsSuccess(null);
        }*/
        return toResponsSuccess(null);
    }

    /**
     * 　校验是否领新用户注册取优惠券，暂时无用（没有注册用户优惠券）
     */
    /*@GetMapping("checkActivit")
    public Object checkActivit(@LoginUser UserVo loginUser) {
        // 是否领取过了
        Map params = Maps.newHashMap();
        params.put("user_id", loginUser.getId());
        params.put("send_type", 4);
        List<CouponVo> couponVos = apiCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return toResponsObject(2, "已经领取过，不能重复领取", couponVos);
        }

        return toResponsSuccess(couponVos);
    }*/

    /**
     * 转发，（领取红包，暂时无用）
     */
    /*@GetMapping("transActivit")
    public Object transActivit(@LoginUser UserVo loginUser, String sourceKey, Long referrer) {
        // 是否领取过了
        Map params = Maps.newHashMap();
        params.put("user_id", loginUser.getId());
        params.put("source_key", sourceKey);
        //查询已领取的转发优惠券
        List<UserCouponVo> couponVos = apiUserCouponService.queryUserCoupons(params);
        if (null != couponVos && couponVos.size() > 0) {
            return toResponsObject(2, "已经领取过", couponVos);
        }else{
            JSONObject jsonParam = getJsonRequest();
            apiUserCouponService.getUserCoupon(jsonParam, loginUser);
            //查询已领取的转发优惠券
            params = Maps.newHashMap();
            params.put("user_id", loginUser.getId());
            params.put("source_key", sourceKey);
            couponVos = apiUserCouponService.queryUserCoupons(params);
            return toResponsSuccess(couponVos);
        }
    }*/

    /**
     * 用户领取优惠券
     */
    @PostMapping("getUserCoupon")
    public Object getUserCoupon(@LoginUser UserVo loginUser) {
        JSONObject jsonParam = getJsonRequest();
        apiUserCouponService.getUserCoupon(jsonParam, loginUser);
        return toResponsSuccess(null);
    }
}
