package org.jeecg.modules.api.service.Impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.api.bean.PageBean;
import org.jeecg.modules.api.service.CouponService;
import org.jeecg.modules.api.utils.CommonUtils;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.pay.MpWxPayService;
import org.jeecg.modules.studytourCoupon.entity.StudytourCoupon;
import org.jeecg.modules.studytourCoupon.service.IStudytourCouponService;
import org.jeecg.modules.studytourCouponUser.entity.StudytourCouponUser;
import org.jeecg.modules.studytourCouponUser.service.IStudytourCouponUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CouponServiceImpl implements CouponService {

    /******************************************************************************************************************/
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //优惠券信息
    @Resource
    private IStudytourCouponService studytourCouponService;
    //用户持有优惠券
    @Resource
    private IStudytourCouponUserService studytourCouponUserService;
    /******************************************************************************************************************/


    //优惠券-优惠券列表
    @Override
    public Result<?> queryCouponList(String token, StudytourCouponUser studytourCouponUser, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        //返回信息
        String massege = "";
        //分页信息
        Page<StudytourCouponUser> page = null;
        //查询信息
        LambdaQueryChainWrapper<StudytourCouponUser> query = null;
        //返回信息
        Page<StudytourCouponUser> pageList = null;

        try{
            //分页
            page = new Page<StudytourCouponUser>(pageBean.getPageNo(), pageBean.getPageSize());
            query = studytourCouponUserService
                    .lambdaQuery();

            //组装查询条件
            //优惠券使用状态：0-未使用 1-已使用 2-已失效
            if(StringUtils.isNotEmpty(studytourCouponUser.getStatus())){
                if("2".equals(studytourCouponUser.getStatus())){
                    query.lt(StudytourCouponUser::getValidDate, CommonUtils.getCurrentTime());//已失效
                    query.notIn(StudytourCouponUser::getStatus, "1");
                }else {
                    query.eq(StudytourCouponUser::getStatus, studytourCouponUser.getStatus());
                    if("0".equals(studytourCouponUser.getStatus())){
                        query.gt(StudytourCouponUser::getValidDate, CommonUtils.getCurrentTime());//未失效
                    }
                }
            }

            //优惠券所属
            query.eq(StudytourCouponUser::getUserId, hanHaiMember.getId());
            //按照创建时间降序排列
            query.orderByDesc(StudytourCouponUser::getCreateTime);

            //获取优惠券信息
            pageList = query.page(page);

            return Result.OK("优惠券列表", pageList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("优惠券列表查询失败");
        }
    }

    //根据id查看优惠券详情
    @Override
    public Result<?> queryCouponById(String token, String usercouponId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            StudytourCouponUser couponUser = studytourCouponUserService
                    .lambdaQuery()
                    .eq(StudytourCouponUser::getUserId, hanHaiMember.getId())
                    .eq(StudytourCouponUser::getId, usercouponId)
                    .one();
            if(null == couponUser){
                return Result.error("优惠券不存在，请检查用户优惠券id：", usercouponId);
            }

            return Result.OK("优惠券详情", couponUser);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("优惠券详情获取失败");
        }
    }

    //查看可领取的优惠券
    @Override
    public Result<?> queryFetchCouponList(String token) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        //返回信息
        String massege = "";

        try{
            //获取可领取的优惠券
            List<StudytourCoupon> pageList = studytourCouponService
                    .lambdaQuery()
                    .eq(StudytourCoupon::getIsFetch, "1")
                    .gt(StudytourCoupon::getValidTime, CommonUtils.getCurrentTime())
                    .orderByDesc(StudytourCoupon::getCreateTime)
                    .list();

            //获取已领取的优惠券
            List<StudytourCouponUser> couponUserList = studytourCouponUserService
                    .lambdaQuery()
                    .eq(StudytourCouponUser::getUserId, hanHaiMember.getId())
                    .list();

            //剔除已领取的优惠券信息
            //查询已领取的优惠券信息
            List<String> ids = new ArrayList<>();
            for (StudytourCoupon vouchers : pageList) {
                for (StudytourCouponUser massageVouchersUser : couponUserList) {
                    String couponUserId = massageVouchersUser.getCouponId();
                    if(vouchers.getId().equals(couponUserId)){
                        ids.add(couponUserId);
                        break;
                    }
                }
            }
            //剔除优惠券信息
            for (int i = 0; i < pageList.size(); i++) {
                for (String id : ids) {
                    if(pageList.get(i).getId().equals(id)){
                        pageList.remove(i);
                    }
                }
            }

            return Result.OK("优惠券列表", pageList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("优惠券列表查询失败");
        }
    }

    //领取优惠券
    @Override
    public Result<?> fetchCoupon(String token, String couponId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            //查看优惠券是否存在
            StudytourCoupon coupon = studytourCouponService.getById(couponId);
            if(null == coupon){
                return Result.error("优惠券不存在，请检查优惠券id："+couponId);
            }

            //查看用户是否领取过优惠券
            StudytourCouponUser studytourCouponUser = studytourCouponUserService
                    .lambdaQuery()
                    .eq(StudytourCouponUser::getCouponId, couponId)
                    .eq(StudytourCouponUser::getUserId, hanHaiMember.getId())
                    .one();
            if(null != studytourCouponUser){
                return Result.error("已领取过优惠券，不可重复领取");
            }

            //添加用户优惠券信息
            StudytourCouponUser couponUser = new StudytourCouponUser();
            couponUser.setUserId(hanHaiMember.getId());
            couponUser.setCouponId(coupon.getId());
            couponUser.setDiscountAmount(coupon.getAmount());
            couponUser.setStatus("0");
            couponUser.setValidDate(coupon.getValidTime());
            boolean result = studytourCouponUserService.save(couponUser);

            if(result){
                return Result.error("优惠券领取成功");
            }else {
                return Result.error("优惠券领取失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("优惠券领取失败");
        }
    }
}
