package org.jeecg.modules.apiService.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.apiBean.PageBean;
import org.jeecg.modules.apiService.CouponService;
import org.jeecg.modules.apiUtils.CommonUtils;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.teambuyCoupon.entity.TeambuyCoupon;
import org.jeecg.modules.teambuyCoupon.service.ITeambuyCouponService;
import org.jeecg.modules.teambuyCouponUser.entity.TeambuyCouponUser;
import org.jeecg.modules.teambuyCouponUser.service.ITeambuyCouponUserService;
import org.springframework.stereotype.Service;

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

@Service
public class CouponServiceImpl implements CouponService {
    /******************************************************************************************************************/
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //用户信息
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    //优惠券信息
    @Resource
    private ITeambuyCouponService teambuyCouponService;
    //用户优惠券信息
    @Resource
    private ITeambuyCouponUserService teambuyCouponUserService;
    /******************************************************************************************************************/
    //查看优惠券列表
    @Override
    public Result<?> queryCouponList(String token, TeambuyCouponUser teambuyCouponUser, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

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

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

            //组装查询条件
            if(StringUtils.isNotBlank(teambuyCouponUser.getId())){
                //优惠券编号
                query.eq(TeambuyCouponUser::getId, teambuyCouponUser.getId());
            }
            if(StringUtils.isNotBlank(teambuyCouponUser.getStatus())){
                if("2".equals(teambuyCouponUser.getStatus())){
                    query.lt(TeambuyCouponUser::getValidDate, CommonUtils.getCurrentTime());//已失效
                }else {
                    //优惠券状态
                    query.eq(TeambuyCouponUser::getStatus, teambuyCouponUser.getStatus());
                    if("0".equals(teambuyCouponUser.getStatus())){
                        query.gt(TeambuyCouponUser::getValidDate, CommonUtils.getCurrentTime());//未失效
                    }
                }
            }
            //优惠券所属
            query.eq(TeambuyCouponUser::getUserId, hanHaiMember.getId());
            //按照创建时间降序排列
            query.orderByDesc(TeambuyCouponUser::getCreateTime);

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

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

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

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

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

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

            //剔除已领取的优惠券信息
            //查询已领取的优惠券信息
            List<String> ids = new ArrayList<>();
            for (TeambuyCoupon coupon : pageList) {
                for (TeambuyCouponUser teambuyCouponUser : couponUserList) {
                    String couponId = teambuyCouponUser.getCouponId();
                    if(coupon.getId().equals(couponId)){
                        ids.add(couponId);
                        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{
            //查看优惠券是否存在
            TeambuyCoupon coupon = teambuyCouponService.getById(couponId);
            if(null == coupon){
                return Result.error("优惠券不存在，请检查优惠券id："+couponId);
            }

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

            //添加用户优惠券信息
            TeambuyCouponUser couponUser = new TeambuyCouponUser();
            couponUser.setUserId(hanHaiMember.getId());
            couponUser.setCouponId(coupon.getId());
            couponUser.setDiscount(coupon.getAmount());
            couponUser.setStatus("0");
            couponUser.setValidDate(coupon.getValidDate());
            boolean result = teambuyCouponUserService.save(couponUser);

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

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

    //使用优惠券
    @Override
    public Result<?> useCoupon(String token, String userCouponId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            //查看优惠券是否存在
            TeambuyCouponUser coupon = teambuyCouponUserService
                    .lambdaQuery()
                    .eq(TeambuyCouponUser::getId, userCouponId)
                    .eq(TeambuyCouponUser::getUserId, hanHaiMember.getId())
                    .eq(TeambuyCouponUser::getStatus, "0")//状态为未使用
                    .gt(TeambuyCouponUser::getValidDate, CommonUtils.getCurrentTime())//状态为未失效
                    .one();
            if(null == coupon){
                return Result.error("优惠券不存在或已使用、已失效，请检查优惠券id："+userCouponId);
            }

            //使用优惠券
            coupon.setStatus("1");
            boolean result = teambuyCouponUserService.updateById(coupon);

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

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

}
