package org.jeecg.api.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.api.bean.PageBean;
import org.jeecg.api.service.AppletOrderService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.commonAddOrder.entity.CommonAddOrder;
import org.jeecg.modules.commonAddOrder.service.ICommonAddOrderService;
import org.jeecg.modules.commonAddress.entity.CommonAddress;
import org.jeecg.modules.commonAddress.service.ICommonAddressService;
import org.jeecg.modules.commonConfig.entity.CommonConfig;
import org.jeecg.modules.commonMoneyLog.entity.CommonMoneyLog;
import org.jeecg.modules.commonMoneyLog.service.ICommonMoneyLogService;
import org.jeecg.modules.commonOrder.entity.CommonOrder;
import org.jeecg.modules.commonOrder.service.ICommonOrderService;
import org.jeecg.modules.commonShop.entity.CommonShop;
import org.jeecg.modules.commonShop.service.ICommonShopService;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.pay.MpWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class AppletOrderServiceImpl implements AppletOrderService {

    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    @Resource
    private ICommonOrderService commonOrderService;
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;
    @Resource
    private ICommonMoneyLogService commonMoneyLogService;
    @Resource
    private ICommonAddressService commonAddressService;
    @Resource
    private ICommonShopService commonShopService;
    @Resource
    private ICommonAddOrderService iCommonAddOrderService;

    //获取订单信息列表带分页
    @Override
    public Result<?> getOrderPageBean(String token, Integer state, PageBean pageBean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        Page<CommonOrder> page = new Page<CommonOrder>(pageBean.getPageNo(), pageBean.getPageSize());
        Page<CommonOrder> page1 = commonOrderService.lambdaQuery()
                .eq(CommonOrder::getUserId, hanHaiMember.getId())
                .orderByDesc(CommonOrder::getCreateTime)
                .page(page);
        if(state != null){
           page1 = commonOrderService.lambdaQuery()
                    .eq(CommonOrder::getUserId, hanHaiMember.getId())
                    .eq(CommonOrder::getStatus, state)
                    .orderByDesc(CommonOrder::getCreateTime)
                    .page(page);
        }
        //循环得到订单信息
        List<CommonOrder> records = page1.getRecords();
        for (CommonOrder commonOrder : records) {
            commonOrder.setChildren(commonOrderService.lambdaQuery().eq(CommonOrder::getPid, commonOrder.getId()).list());
        }






        return Result.OK("订单信息查询成功",page1);
    }

    //根据订单标识查询订单信息
    @Override
    public Result<?> getOrderInfo(String token,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        CommonOrder commonOrder = commonOrderService.lambdaQuery()
                .eq(CommonOrder::getUserId, hanHaiMember.getId())
                .eq(CommonOrder::getId, orderId)
                .one();
        commonOrder.setChildren(commonOrderService.lambdaQuery().eq(CommonOrder::getPid, commonOrder.getId()).list());
        return Result.OK("订单信息查询成功",commonOrder);
    }

    //再次支付
    @Override
    public Result<?> payOrder(String token,Integer type,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        if (type==0){
            CommonOrder commonOrder = commonOrderService.getById(orderId);
            if (commonOrder.getStatus().equals("0")){
                if (hanHaiMember.getMoney().compareTo(commonOrder.getPrice())==-1){
                    return Result.error("余额不足");
                }
            }
            if (commonOrder.getStatus().equals("0")){
                commonOrder.setStatus("1");
                commonOrderService.updateById(commonOrder);
                HanHaiMember hanHaiMember1 = hanHaiMemberService.getById(hanHaiMember.getId());
                hanHaiMember1.setMoney(hanHaiMember1.getMoney().subtract(commonOrder.getPrice()));
                hanHaiMemberService.updateById(hanHaiMember1);
                CommonMoneyLog commonMoneyLog = new CommonMoneyLog();
                commonMoneyLog.setCreateTime(new Date());
                commonMoneyLog.setTitle("支付订单");
                commonMoneyLog.setMoney(commonOrder.getPrice());
                commonMoneyLog.setUserId(hanHaiMember.getId());
                commonMoneyLog.setOldMoney(hanHaiMember1.getMoney());
                commonMoneyLog.setType(1);
                commonMoneyLog.setState(0);
                commonMoneyLogService.save(commonMoneyLog);
                return Result.OK("支付成功");

            }
        }else {
            CommonOrder commonOrder = commonOrderService.getById(orderId);
            if (commonOrder.getStatus().equals("0")){
                BigDecimal payPrice = commonOrder.getPrice();

                //吊起微信支付
                String s = payPrice.multiply(new BigDecimal(100)).toString();
                int i1 = Double.valueOf(s).intValue();
                Object appOrder = mpWxPayService.createOrder(
                        "购买"+commonOrder.getTitle(),
                        "127.0.0.1",
                        commonOrder.getId(),
                        i1,
                        commonOrder.getId(),
                        hanHaiMember.getAppletOpenid(),
                        commonOrder.toString());

                return Result.OK("支付成功",appOrder);
            }
        }
        return  Result.error("订单已支付");
    }

    //确认订单送达
    @Override
    public Result<?> confirmOrder(String token,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        CommonOrder commonOrder = commonOrderService.getById(orderId);
        if (commonOrder.getStatus().equals("2")){
            commonOrder.setStatus("3");
            commonOrderService.updateById(commonOrder);
            return Result.OK("确认成功");
        }
        return Result.error("订单状态错误");
    }


    //取消订单
    @Override
    public Result<?> cancelOrder(String token,String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        CommonOrder commonOrder = commonOrderService.getById(orderId);
        if (commonOrder.getStatus().equals("0")){
            commonOrder.setStatus("4");
            commonOrderService.updateById(commonOrder);
            HanHaiMember hanHaiMember1 = hanHaiMemberService.getById(hanHaiMember.getId());
            hanHaiMember1.setMoney(hanHaiMember1.getMoney().add(commonOrder.getPrice()));
            hanHaiMemberService.updateById(hanHaiMember1);
        }
        return Result.OK("取消成功");
    }



    //商城-支付回调
    @Override
    public Result<?> payNotify(String requestBody){
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        String outTradeNo = notify.getOutTradeNo();
        log.info("支付回调订单号码："+outTradeNo);
        //查询订单信息
        CommonOrder commonOrder = commonOrderService.getById(outTradeNo);
        //如果该订单为未支付，修改订单状态
        if (commonOrder.getStatus().equals("0")){
            commonOrder.setTitle("微信支付订单");
            commonOrder.setStatus("1");
            commonOrderService.updateById(commonOrder);
            //查询用户信息
            HanHaiMember member = hanHaiMemberService.getById(commonOrder.getUserId());

            CommonMoneyLog commonMoneyLog = new CommonMoneyLog();
            commonMoneyLog.setCreateTime(new Date());
            commonMoneyLog.setTitle("微信支付订单");
            commonMoneyLog.setMoney(commonOrder.getPrice());
            commonMoneyLog.setUserId(commonOrder.getUserId());
            commonMoneyLog.setOldMoney(member.getMoney());
            commonMoneyLog.setType(1);
            commonMoneyLog.setState(1);
            commonMoneyLogService.save(commonMoneyLog);

            //订单直推佣金
            BigDecimal oneMoney = commonOrder.getOneMoney();
            //订单间推佣金
            BigDecimal twoMoney = commonOrder.getTwoMoney();
            log.info("订单直推佣金："+oneMoney);
            log.info("订单间推佣金："+twoMoney);
            //返佣
            HanHaiMember hanHaiMember1 = hanHaiMemberService.getById(commonOrder.getUserId());
            log.info("下单用户："+hanHaiMember1.getNickName()+"电话号码："+hanHaiMember1.getPhone());
            log.info("订单号：" + commonOrder.getId());
            //上级标识
            String oneId = hanHaiMember1.getShareId();
            log.info("上级标识："+oneId);
            //如果上级标识不为空
            if(StringUtils.isNotBlank(oneId)){
                HanHaiMember hanHaiMember2 = hanHaiMemberService.getById(oneId);

                if(hanHaiMember2 !=null) {
                    //上级返佣
                    hanHaiMember2.setMoney(hanHaiMember2.getMoney().add(oneMoney));
                    hanHaiMemberService.updateById(hanHaiMember2);
                    //添加佣金记录
                    CommonMoneyLog moneyLog1 = new CommonMoneyLog();
                    moneyLog1.setId(UUID.randomUUID().toString().replace("-", "")+"1");
                    moneyLog1.setCreateTime(new Date());
                    moneyLog1.setTitle("微信支付直推佣金");
                    moneyLog1.setMoney(oneMoney);
                    moneyLog1.setUserId(hanHaiMember2.getId());
                    moneyLog1.setOldMoney(hanHaiMember2.getMoney());
                    moneyLog1.setType(0);
                    moneyLog1.setState(1);
                    commonMoneyLogService.save(moneyLog1);

                }

            }
            //上上级标识
            String twoId = hanHaiMember1.getVid();
            log.info("上上级标识："+twoId);
            if(StringUtils.isNotBlank(twoId)){
                HanHaiMember hanHaiMember3 = hanHaiMemberService.getById(twoId);
                if(hanHaiMember3 !=null) {
                    //上级返佣
                    hanHaiMember3.setMoney(hanHaiMember3.getMoney().add(twoMoney));
                    hanHaiMemberService.updateById(hanHaiMember3);
                    //添加佣金记录
                    CommonMoneyLog moneyLog2 = new CommonMoneyLog();
                    moneyLog2.setId(UUID.randomUUID().toString().replace("-", "")+"2");
                    moneyLog2.setCreateTime(new Date());
                    moneyLog2.setTitle("微信支付间推佣金");
                    moneyLog2.setMoney(twoMoney);
                    moneyLog2.setUserId(hanHaiMember3.getId());
                    moneyLog2.setOldMoney(hanHaiMember3.getMoney());
                    moneyLog2.setType(0);
                    moneyLog2.setState(1);
                    commonMoneyLogService.save(moneyLog2);
                }

            }








        }
        return null;
    }




    //商城-加入购物车之后一次下多个订单
    //商城-立即购买多少商品
    @Transactional
    @Synchronized
    @Override
    public Result<?> createSumOrder(String token,String list,String addressId,Integer payType,String orderAddId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        //orderId 不为  空
        if(StringUtils.isNotBlank(orderAddId)){
            CommonAddOrder commonAddOrder = iCommonAddOrderService.getById(orderAddId);
            //修改订单状态
            commonAddOrder.setIsPay("Y");
            iCommonAddOrderService.updateById(commonAddOrder);
        }









        //用户地址不能为空
        if(StringUtils.isBlank(addressId)){
            return Result.error("请选择收货地址");
        }
        //查询地址是否存在
        CommonAddress commonAddress = commonAddressService.getById(addressId);
        if (commonAddress==null){
            return Result.error("地址不存在");
        }
        //把list转为对象 list = [{"shopId":"1","num":1},{"shopId":"2","num":2}]
        List<CommonOrder> list1 = JSON.parseArray(list, CommonOrder.class);
        //创建订单标识
        String orderId = IdWorker.getIdStr();
        if(null!=list1 && list1.size()>0){
            //订单总额
            BigDecimal totalPrice = new BigDecimal(0);
            //总直推金额
            BigDecimal totalOneMoney = new BigDecimal(0);
            //总二级代理金额
            BigDecimal totalTwoMoney = new BigDecimal(0);
            //订单商品数量
            Integer totalNum = 0;

            //创建订单详情
            for (CommonOrder sku : list1) {
                //查询商品信息
                CommonShop commonShop = commonShopService.getById(sku.getShopId());
                //商品不能为空
                if (commonShop==null){
                    return Result.error("商品不存在");
                }
                //创建订单
                BigDecimal price = commonShop.getPrice().multiply(new BigDecimal(sku.getNum()));

                //创建直推佣金
                BigDecimal oneMoney = commonShop.getOneMoney().multiply(new BigDecimal(sku.getNum()));

                BigDecimal twoMoney = commonShop.getTwoMoney().multiply(new BigDecimal(sku.getNum()));





                sku.setPid(orderId);

                sku.setHasChild("0");
                sku.setShopId(commonShop.getId());
                sku.setTitle(commonShop.getName());
                sku.setImage(commonShop.getImage());
                sku.setPrice(price);
                sku.setNum(sku.getNum());
                sku.setMaterial(commonShop.getMaterial());
                sku.setCreateTime(new Date());
                sku.setPrice(price);
                sku.setOneMoney(oneMoney);
                sku.setTwoMoney(twoMoney);

                sku.setImage(commonShop.getImage());
                sku.setCreateTime(new Date());

                commonOrderService.save(sku);

                //计算总价格
                totalPrice = totalPrice.add(price);

                totalNum = totalNum + sku.getNum();

                totalOneMoney = totalOneMoney.add(oneMoney);

                totalTwoMoney = totalTwoMoney.add(twoMoney);

            }


            //创建主订单
            CommonOrder cityOrder = new CommonOrder();
            cityOrder.setId(orderId);
            cityOrder.setUserId(hanHaiMember.getId());
            cityOrder.setShopId(null);
            cityOrder.setNum(totalNum);
            cityOrder.setAddress(commonAddress.getAddress());
            cityOrder.setName(commonAddress.getName());
            cityOrder.setPhone(commonAddress.getPhone());
            cityOrder.setAddressDetail(commonAddress.getAddressDetails());
//            cityOrder.seta(addressId);
            cityOrder.setName(commonAddress.getName());
            cityOrder.setTitle("组合订单");
            cityOrder.setPrice(totalPrice);
            cityOrder.setOneMoney(totalOneMoney);
            cityOrder.setTwoMoney(totalTwoMoney);
            cityOrder.setPid("0");
            cityOrder.setHasChild("1");

//            cityOrder.setShopState(2);

            cityOrder.setImage(null);
            cityOrder.setStatus("0");
            cityOrder.setCreateTime(new Date());

            commonOrderService.save(cityOrder);


            if (payType==0){
                cityOrder.setTitle("余额支付订单");
                cityOrder.setStatus("1");
                commonOrderService.updateById(cityOrder);
                HanHaiMember member = hanHaiMemberService.getById(hanHaiMember.getId());
                member.setMoney(member.getMoney().subtract(cityOrder.getPrice()));

                hanHaiMemberService.updateById(member);
                CommonMoneyLog commonMoneyLog = new CommonMoneyLog();
                commonMoneyLog.setCreateTime(new Date());
                commonMoneyLog.setTitle("余额支付订单");
                commonMoneyLog.setMoney(cityOrder.getPrice());
                commonMoneyLog.setUserId(hanHaiMember.getId());
                commonMoneyLog.setOldMoney(member.getMoney());
                commonMoneyLog.setType(1);
                commonMoneyLog.setState(1);
                commonMoneyLogService.save(commonMoneyLog);


                //订单直推佣金
                BigDecimal oneMoney = cityOrder.getOneMoney();
                //订单间推佣金
                BigDecimal twoMoney = cityOrder.getTwoMoney();
                log.info("订单直推佣金："+oneMoney);
                log.info("订单间推佣金："+twoMoney);
                //返佣
                HanHaiMember hanHaiMember1 = hanHaiMemberService.getById(cityOrder.getUserId());
                log.info("下单用户："+hanHaiMember1.getNickName()+"电话号码："+hanHaiMember1.getPhone());
                log.info("订单号：" + cityOrder.getId());
                //上级标识
                String oneId = hanHaiMember1.getShareId();
                log.info("上级标识："+oneId);
                //如果上级标识不为空
                if(StringUtils.isNotBlank(oneId)){
                    HanHaiMember hanHaiMember2 = hanHaiMemberService.getById(oneId);

                    if(hanHaiMember2 !=null) {
                        //上级返佣
                        hanHaiMember2.setMoney(hanHaiMember2.getMoney().add(oneMoney));
                        hanHaiMemberService.updateById(hanHaiMember2);
                        //添加佣金记录
                        CommonMoneyLog moneyLog1 = new CommonMoneyLog();
                        moneyLog1.setId(UUID.randomUUID().toString().replace("-", "")+"1");
                        moneyLog1.setCreateTime(new Date());
                        moneyLog1.setTitle("余额支付直推佣金");
                        moneyLog1.setMoney(oneMoney);
                        moneyLog1.setUserId(hanHaiMember2.getId());
                        moneyLog1.setOldMoney(hanHaiMember2.getMoney());
                        moneyLog1.setType(0);
                        moneyLog1.setState(1);
                        commonMoneyLogService.save(moneyLog1);

                    }

                }
                //上上级标识
                String twoId = hanHaiMember1.getVid();
                log.info("上上级标识："+twoId);
                if(StringUtils.isNotBlank(twoId)){
                    HanHaiMember hanHaiMember3 = hanHaiMemberService.getById(twoId);
                    if(hanHaiMember3 !=null) {
                        //上级返佣
                        hanHaiMember3.setMoney(hanHaiMember3.getMoney().add(twoMoney));
                        hanHaiMemberService.updateById(hanHaiMember3);
                        //添加佣金记录
                        CommonMoneyLog moneyLog2 = new CommonMoneyLog();
                        moneyLog2.setId(UUID.randomUUID().toString().replace("-", "")+"2");
                        moneyLog2.setCreateTime(new Date());
                        moneyLog2.setTitle("余额支付间推佣金");
                        moneyLog2.setMoney(twoMoney);
                        moneyLog2.setUserId(hanHaiMember3.getId());
                        moneyLog2.setOldMoney(hanHaiMember3.getMoney());
                        moneyLog2.setType(0);
                        moneyLog2.setState(1);
                        commonMoneyLogService.save(moneyLog2);
                    }

                }
                return Result.OK("余额支付成功");

            }else{
                //吊起微信支付
                String s = totalPrice.multiply(new BigDecimal(100)).toString();
                int i1 = Double.valueOf(1).intValue();
                Object appOrder = mpWxPayService.createOrder(
                        "购买"+ "组合订单" ,
                        "127.0.0.1",
                        orderId,
                        i1,
                        orderId,
                        hanHaiMember.getAppletOpenid(),
                        cityOrder.toString());

                return Result.OK("支付成功",appOrder);
            }





        }
        return null;
    }

}
