package com.iamberry.wechat.service.integral;

import com.github.pagehelper.PageHelper;
import com.iamberry.wechat.core.entity.coupon.CouponItem;
import com.iamberry.wechat.core.entity.coupon.CouponType;
import com.iamberry.wechat.core.entity.integral.*;
import com.iamberry.wechat.core.entity.member.Member;
import com.iamberry.wechat.core.entity.page.PageRequest;
import com.iamberry.wechat.core.entity.page.PagedResult;
import com.iamberry.wechat.face.coupon.CouponItemService;
import com.iamberry.wechat.face.coupon.CouponTypeService;
import com.iamberry.wechat.face.integral.IntegralItemService;
import com.iamberry.wechat.face.integral.IntegralOrderService;
import com.iamberry.wechat.face.integral.IntegralProductConvertService;
import com.iamberry.wechat.face.integral.IntegralProductService;
import com.iamberry.wechat.face.member.MemberService;
import com.iamberry.wechat.service.mapper.*;
import com.iamberry.wechat.tools.OrderNOUtil;
import com.iamberry.wechat.tools.StrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.PageUtil;

import java.util.*;

/**
 *  积分商城订单表接口
 * @author ys
 * @Date 2018-04-28
 */
@Service
public class IntegralOrderServiceImpl  implements IntegralOrderService {

    private Logger logger = LoggerFactory.getLogger(IntegralOrderServiceImpl.class);

    @Autowired
    private IntegralOrderMapper integralOrderMapper;
    @Autowired
    private IntegralOrderService integralOrderService;
    @Autowired
    private IntegralItemMapper integralItemMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private IntegralProductConvertMapper integralProductConvertMapper;
    @Autowired
    private IntegralProductMapper integralProductMapper;
    @Autowired
    private CouponTypeMapper couponTypeMapper;
    @Autowired
    private CouponItemMapper couponItemMapper;
    @Autowired
    private UseIntegralMapper useIntegralMapper;
    @Autowired
    private IntegralProductGradeMapper integralProductGradeMapper;

    /**
     * 添加订单
     * @param openId
     * @param integralCartList
     * @return
     */
    @Override
    @Transactional
    public synchronized Map<String, Object> addOrder(String openId, List<IntegralCart> integralCartList) {
        /**
         * 查询商品是否有库存
         * 查询用户积分是否大于商品积分
         * 拼接订单值
         * 添加订单
         * 优惠券直接用朵粉币兑换成功直接生成优惠券
         * 减去用户朵粉币，生成积分使用记录
         * 减去商品库存
         */
        Integer flag = 0;
        Map<String,Object> map = new HashMap<>();
        Member member = memberMapper.getMemberByUserOpenId(openId);

        /*获取用户当前等级*/
        Integer rankRuleId = memberService.getUserGrad(member.getUserId());

         /*创建订单*/
        IntegralOrder IntegralOrder = new IntegralOrder();
         IntegralOrder.setIntegralOrderOpenId(member.getUserOpenid());
        IntegralOrder.setIntegralOrderId(OrderNOUtil.createOrderCode(member.getUserId()));
        IntegralOrder.setIntegralOrderUserRemark("");       //用户备注

        /*订单项*/
        List<IntegralItem> integralItemList = new ArrayList<>();

        Integer dfbiTotal = 0,monTotal = 0;
        Integer isPay = 0;  //是否需要支付
        for (int i = 0; i < integralCartList.size(); i++) {
            IntegralCart integralCart = integralCartList.get(i);

            IntegralItem integralItem = new IntegralItem();

            IntegralProduct integralProduct = integralProductMapper.getIntegralProductById(integralCart.getProductId());
            if(integralProduct == null ){
                throw new RuntimeException("商品不存在，请重新添加");
            }

            boolean isRank = false;
            IntegralProductGrade integralProductGrade = new IntegralProductGrade();
            integralProductGrade.setIntegralProductId(integralProduct.getIntegralProductId());
            List<IntegralProductGrade> integralProductGradeList = integralProductGradeMapper.getIntegralProductGradeList(integralProductGrade);
            if(integralProductGradeList != null && integralProductGradeList.size() >0){
                for (IntegralProductGrade ipg:integralProductGradeList) {
                    if(rankRuleId == ipg.getRankId()){
                        isRank = true;
                    }
                }
            }else{
                isRank = true;
            }
            if(!isRank){
                throw new RuntimeException("对不起你的等级无法购买"+integralProduct.getIntegralProductName());
            }

            //商品总数量 - 商品已兑换数量
            if(integralProduct.getIntegralProductNum() == null || integralProduct.getIntegralProductRemainingNum() == null){
                throw new RuntimeException("数量不足");
            }
            if(integralProduct.getIntegralProductNum() - integralProduct.getIntegralProductRemainingNum() < 0){
                throw new RuntimeException(integralProduct.getIntegralProductName() + "商品已售空");
            }

            /*获取商品兑换信息*/
            IntegralProductConvert ipc = integralProductConvertMapper.getIntegralProductConvertByProductId(integralProduct.getIntegralProductId());
            if(ipc == null ){
                throw new RuntimeException("该商品不能兑换");
            }
            if(ipc.getConvertIsPay() == 1){     //需要支付, //1:需要支付 2:不需要支付
                /*此处写支付*/
                Integer monTol = ipc.getConvertPrice() * integralCart.getNum();
                integralItem.setIntegralItemTotal(monTol);
                monTotal += monTol;
                isPay = 1;
                throw new RuntimeException("暂不支持支付");
            }

            /*朵粉币*/
            Integer dfbiTol = ipc.getConvertDfbi() * integralCart.getNum();
            integralItem.setIntegralItemDfbi(dfbiTol);
            dfbiTotal += dfbiTol;

            if(ipc.getConvertIsMailing() == 1){ //需要邮寄，需要判断邮寄地址信息
                throw new RuntimeException("邮寄地址为空");
            }

            integralItem.setIntegralProductId(integralCart.getProductId());
            integralItem.setIntegralItemNum(integralCart.getNum());
            integralItem.setIntegralItemProductPic(integralProduct.getIntegralProductImg());    //介绍图
            integralItem.setIntegralItemDfbi(dfbiTotal);    //朵粉币
            integralItem.setIntegralItemTotal(monTotal);    //小计
            integralItem.setIntegralItemProductType(integralProduct.getIntegralProductType());
            integralItem.setIntegralItemCouponId(ipc.getCouponId());    //优惠券类型
            integralItem.setIntegralItemProductDfbi(ipc.getConvertDfbi());
            integralItem.setIntegralItemProductPrice(ipc.getConvertPrice());
            integralItem.setIntegralItemProductName(integralProduct.getIntegralProductName());
            integralItemList.add(integralItem);

            /*减去商品库存*/
            IntegralProduct ip = new IntegralProduct();
            ip.setIntegralProductId(integralProduct.getIntegralProductId());
            ip.setIntegralProductRemainingNum(integralProduct.getIntegralProductRemainingNum()+integralCart.getNum());
            try{
                flag =  integralProductMapper.update(ip);
            }catch (Exception e){
                throw new RuntimeException("商品减去库存失败");
            }
            if(flag < 1){
                throw new RuntimeException("商品减去库存失败");
            }
        }

        if(member.getUserSurplusIntegral() < dfbiTotal){     //剩余积分-朵粉币   <  所需朵粉币数量
            throw new RuntimeException("朵粉币数量不够");
        }

        if(isPay == 1){
            IntegralOrder.setIntegralOrderYetAmount(monTotal);  //订单付款金额 实付
            IntegralOrder.setIntegralOrderAmount(monTotal);     //订单金额
            IntegralOrder.setIntegralOrderStatus(1);        //需要支付，状态为未兑换
        }else{
            IntegralOrder.setIntegralOrderYetAmount(0);  //订单付款金额 实付
            IntegralOrder.setIntegralOrderAmount(0);     //订单金额
            IntegralOrder.setIntegralOrderStatus(2);     //直接用朵粉币兑换，状态直接为已兑换
        }
        IntegralOrder.setIntegralOrderDfbi(dfbiTotal);

        /*判断是否用积分兑换，支付为0，直接操作*/
        if(isPay != 1 || monTotal == 0){
            for (IntegralItem ii: integralItemList) {
                if(ii.getIntegralItemProductType() == 1){        //积分商品类型 1:商城内优惠券 2:其他
                    Integer couponTypeId = ii.getIntegralItemCouponId();
                    CouponType couponType = couponTypeMapper.getCouponTypeById(couponTypeId);
                    CouponItem couponItem = new CouponItem();
                    String uuidStr = StrUtils.getUUID();
                    couponItem.setCouponItemId(uuidStr);
                    ii.setIntegralItemCouponItemId(uuidStr);
                    couponItem.setCouponId(couponTypeId);

                    Calendar calendar = Calendar.getInstance();
                     calendar.add(Calendar.DATE,couponType.getCouponGetDays());  //领取后有效天数

                    couponItem.setCouponUseEndDate(calendar.getTime());
                    couponItem.setCouponReceiveDate(new Date());
                    couponItem.setCouponItemUseropenid(member.getUserOpenid());
                    couponItem.setCouponUseStatus(1);
                    couponItem.setCouponIsDonation(2);
                    couponItem.setCouponItemRemark("朵粉币兑换");
                    flag = couponItemMapper.insertCouponItem(couponItem);
                    if(flag < 1){
                        throw new RuntimeException("添加优惠券失败");
                    }
                    CouponType ct = new CouponType();
                    ct.setCouponId(couponType.getCouponId());
                    ct.setCouponUsedNum(couponType.getCouponUsedNum()+1);       ////已经领取券数量
                    ct.setCouponRemainingNum(couponType.getCouponRemainingNum()-1); ////剩余券数
                    flag = couponTypeMapper.updateCouponTypeById(ct);
                    if(flag < 1){
                        throw new RuntimeException("修改优惠券失败");
                    }
                }
                ii.setIntegralItemOrderId(IntegralOrder.getIntegralOrderId());
            }
        }

        flag = integralOrderMapper.save(IntegralOrder);    //添加订单
        if(flag < 1){
            throw new RuntimeException("添加订单失败");
        }

        for (IntegralItem ii: integralItemList) {
            ii.setIntegralItemOrderId(IntegralOrder.getIntegralOrderId());
        }

        flag = integralItemMapper.saveList(integralItemList);
        if(flag < 1){
            throw new RuntimeException("添加订单项失败");
        }

        //变动前可用积分总额
        Integer integralBeforeNumber = member.getUserSurplusIntegral();
        //变动后可用积分总额
        Integer integralEndNumber=member.getUserSurplusIntegral()-dfbiTotal;

        Member mem = new Member();
        mem.setUserId(member.getUserId());
        mem.setUserSurplusIntegral(member.getUserSurplusIntegral()-dfbiTotal);  //剩余积分		朵粉币
        mem.setUserUseIntegral(member.getUserUseIntegral()+dfbiTotal);    //已用积分
        flag = memberMapper.updateMemberByUserId(mem);
        if(flag < 1){
            throw new RuntimeException("修改用户朵粉币失败");
        }

        UseIntegral useIntegral = new UseIntegral();
        useIntegral.setUserOpenId(member.getUserOpenid());
        useIntegral.setIntegralType(2);
        useIntegral.setConfigId(17);
        useIntegral.setIntegralNumber(dfbiTotal);
        useIntegral.setIntegralBeforeNumber(integralBeforeNumber);
        useIntegral.setIntegralEndNumber(integralEndNumber);
        useIntegral.setIntegralRemarks("兑换积分商品，兑换订单号为："+IntegralOrder.getIntegralOrderId());
        flag = useIntegralMapper.addUseIntegral(useIntegral);
        if(flag < 1){
            throw new RuntimeException("添加积分使用记录");
        }
        return map;
    }

    /**
     * 获取集合
     * @param  integralOrder
     * @return List
     */
    @Override
    public List<IntegralOrder> getIntegralOrderListAndItem(IntegralOrder  integralOrder){
        List<IntegralOrder> integralOrderList = integralOrderMapper.getIntegralOrderList(integralOrder);
        for (IntegralOrder io:integralOrderList) {
            IntegralItem integralItem = new IntegralItem();
            integralItem.setIntegralItemOrderId(io.getIntegralOrderId());
            List<IntegralItem> integralItemList = integralItemMapper.getIntegralItemList(integralItem);
            io.setIntegralItemList(integralItemList);
        }
        return  integralOrderList;
    }

    /**
     * 获取集合
     * @param  integralOrder
     * @return List
     */
    @Override
    public List<IntegralOrder> getIntegralOrderList(IntegralOrder  integralOrder){
        return  integralOrderMapper.getIntegralOrderList(integralOrder);
    }

    @Override
    public PagedResult<IntegralOrder> listIntegralProductPage(PageRequest<IntegralOrder> pageRequest) {
        PageHelper.startPage(pageRequest.getPageNO(), pageRequest.getPageSize(), pageRequest.isPageTotal());
        List<IntegralOrder> detedctList = integralOrderService.getIntegralOrderListAndItem(pageRequest.getData());
        return PageUtil.getPage(detedctList);
    }

    /**
     * 查询单条数据
     * @param  id
     * @return  integralOrder
     */
    @Override
    public  IntegralOrder  getIntegralOrderById(String  id){
        return  integralOrderMapper.getIntegralOrderById(id);
    }
    /**
     * 增加数据
     * @param  integralOrder
     * @return Integer
     */
    @Override
    public  Integer  save(IntegralOrder  integralOrder){
        return  integralOrderMapper.save(integralOrder);
    }
    /**
     * 修改数据
     * @param  integralOrder
     * @return Integer
     */
    @Override
    public  Integer  update(IntegralOrder integralOrder){
        return  integralOrderMapper.update(integralOrder);
    }
    /**
     * 删除数据
     * @param  id
     * @return Integer
     */
    @Override
    public  Integer  delete(String  id){
        return  integralOrderMapper.delete(id);
    }
}