package org.jeecg.modules.apiService.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
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.apiBean.PageBean;
import org.jeecg.modules.apiService.OrderService;
import org.jeecg.modules.apiUtils.CommonUtils;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.pay.MpWxPayService;
import org.jeecg.modules.teambuyBalanceLog.entity.TeambuyBalanceLog;
import org.jeecg.modules.teambuyBalanceLog.service.ITeambuyBalanceLogService;
import org.jeecg.modules.teambuyCoupon.entity.TeambuyCoupon;
import org.jeecg.modules.teambuyCouponUser.entity.TeambuyCouponUser;
import org.jeecg.modules.teambuyCouponUser.service.ITeambuyCouponUserService;
import org.jeecg.modules.teambuyGoods.entity.TeambuyGoods;
import org.jeecg.modules.teambuyGoods.service.ITeambuyGoodsService;
import org.jeecg.modules.teambuyLevel.entity.TeambuyLevel;
import org.jeecg.modules.teambuyLevel.service.ITeambuyLevelService;
import org.jeecg.modules.teambuyOrderGoods.entity.TeambuyOrderGoods;
import org.jeecg.modules.teambuyOrderGoods.service.ITeambuyOrderGoodsService;
import org.jeecg.modules.teambuyOrderLeader.entity.TeambuyOrderLeader;
import org.jeecg.modules.teambuyOrderLeader.service.ITeambuyOrderLeaderService;
import org.jeecg.modules.teambuyOrderMember.entity.TeambuyOrderMember;
import org.jeecg.modules.teambuyOrderMember.service.ITeambuyOrderMemberService;
import org.jeecg.modules.teambuyTeamLeader.entity.TeambuyTeamLeader;
import org.jeecg.modules.teambuyTeamLeader.service.ITeambuyTeamLeaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    /******************************************************************************************************************/
    //支付回调地址
    @Value("${wx.miniapp.payNotifyUrl}")
    private String payNotifyUrl;
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //用户信息
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    //佣金等级
    @Resource
    private ITeambuyLevelService teambuyLevelService;
    //团长信息
    @Resource
    private ITeambuyTeamLeaderService teambuyTeamLeaderService;
    //团餐订单信息
    @Resource
    private ITeambuyOrderLeaderService teambuyOrderLeaderService;
    //团员订单信息
    @Resource
    private ITeambuyOrderMemberService teambuyOrderMemberService;
    //团员订单商品信息
    @Resource
    private ITeambuyOrderGoodsService teambuyOrderGoodsService;
    //商品信息信息
    @Resource
    private ITeambuyGoodsService teambuyGoodsService;
    //商品信息信息
    @Resource
    private ITeambuyCouponUserService teambuyCouponUserService;
    //收支信息
    @Resource
    private ITeambuyBalanceLogService teambuyBalanceLogService;
    /******************************************************************************************************************/
    //查看团餐订单列表
    @Override
    public Result<?> queryLeaderOrderList(String token, TeambuyOrderLeader teambuyOrderLeader, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

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

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

            //组装查询条件
            if(StringUtils.isNotBlank(teambuyOrderLeader.getId())){
                //订单编号
                query.eq(TeambuyOrderLeader::getId, teambuyOrderLeader.getId());
            }
            if(StringUtils.isNotBlank(teambuyOrderLeader.getStatus())){
                //订单状态
                query.eq(TeambuyOrderLeader::getStatus, teambuyOrderLeader.getStatus());
            }
            //团餐订单所属
            TeambuyTeamLeader leader = teambuyTeamLeaderService
                    .lambdaQuery()
                    .eq(TeambuyTeamLeader::getUserId, hanHaiMember.getId())
                    .one();
            //团长id
            query.eq(TeambuyOrderLeader::getUserId, leader.getId());
            //按照创建时间降序排列
            query.orderByDesc(TeambuyOrderLeader::getCreateTime);

            //获取团餐内团员订单信息
            pageList = query.page(page);
//            if(null == pageList){
//                return Result.OK("团餐订单列表为空", pageList);
//            }
//            for (TeambuyOrderLeader record : pageList.getRecords()) {
//                List<TeambuyOrderMember> orderMemberList = getOrderMemberList(record.getId());
//                record.setOrderMemberList(orderMemberList);
//            }

            return Result.OK("订单列表", pageList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("订单列表查询失败");
        }
    }
    //查看团餐订单列表
    @Override
    public Result<?> queryLeaderOrderListById(String token, String teambuyOrderId, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";

        try{
            TeambuyOrderLeader order = teambuyOrderLeaderService.getById(teambuyOrderId);
            List<TeambuyOrderMember> orderMemberList = getOrderMemberList(order.getId());
            order.setOrderMemberList(orderMemberList);
            order.setTotal(orderMemberList.size());

            return Result.OK("订单列表", order);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("订单列表查询失败");
        }
    }
    //查询团餐订单内的团员订单列表
    public List<TeambuyOrderMember> getOrderMemberList(String orderLeaderId){
        try{
            //查询团员订单列表
            List<TeambuyOrderMember> orderList = teambuyOrderMemberService
                    .lambdaQuery()
                    .eq(TeambuyOrderMember::getOrderLeaderId, orderLeaderId)
                    .eq(TeambuyOrderMember::getIsDel, "0")
                    .list();

            //查询团员订单商品信息列表列表
            for (TeambuyOrderMember teambuyOrderMember : orderList) {
                List<TeambuyOrderGoods> goodsList = teambuyOrderGoodsService
                        .lambdaQuery()
                        .eq(TeambuyOrderGoods::getOrderId, teambuyOrderMember.getId())
                        .list();
                //商品详情
                for (TeambuyOrderGoods teambuyOrderGoods : goodsList) {
                    TeambuyGoods goods = teambuyGoodsService.getById(teambuyOrderGoods.getGoodsId());
                    teambuyOrderGoods.setGoods(goods);
                }
                teambuyOrderMember.setGoodsList(goodsList);
            }

            //查询订单所属用户信息
            for (TeambuyOrderMember teambuyOrderMember : orderList) {
                HanHaiMember hanHaiMember = hanHaiMemberService.getById(teambuyOrderMember.getUserId());
                teambuyOrderMember.setHanHaiMember(hanHaiMember);
            }

            //返回订单列表
            return orderList;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    //查看团员订单列表
    @Override
    public Result<?> queryMemberOrderList(String token, TeambuyOrderMember teambuyOrderMember, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";
        //分页信息
        Page<TeambuyOrderMember> page = null;
        //查询信息
        LambdaQueryChainWrapper<TeambuyOrderMember> query = null;
        //返回信息
        Page<TeambuyOrderMember> pageList = null;

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

            //组装查询条件
            if(StringUtils.isNotBlank(teambuyOrderMember.getTitle())){
                //订单名称
                query.like(TeambuyOrderMember::getTitle, teambuyOrderMember.getTitle());
            }
            if(StringUtils.isNotBlank(teambuyOrderMember.getId())){
                //订单编号
                query.eq(TeambuyOrderMember::getId, teambuyOrderMember.getId());
            }
            if(StringUtils.isNotBlank(teambuyOrderMember.getStatus())){
                //订单状态
                query.eq(TeambuyOrderMember::getStatus, teambuyOrderMember.getStatus());
            }
            //未删除订单
            query.eq(TeambuyOrderMember::getIsDel, "0");
            //团员订单所属
            query.eq(TeambuyOrderMember::getUserId, hanHaiMember.getId());
            //按照创建时间降序排列
            query.orderByDesc(TeambuyOrderMember::getCreateTime);

            //获取团员订单信息列表
            pageList = query.page(page);

            //查询团员订单商品信息列表列表
            for (TeambuyOrderMember record : pageList.getRecords()) {
                //订单所属团长信息
                TeambuyOrderLeader orderLeader = teambuyOrderLeaderService.getById(record.getOrderLeaderId());
                TeambuyTeamLeader leader = teambuyTeamLeaderService.getById(orderLeader.getUserId());
                record.setTeamLeader(leader);

                //订单商品列表
                List<TeambuyOrderGoods> goodsList = teambuyOrderGoodsService
                        .lambdaQuery()
                        .eq(TeambuyOrderGoods::getOrderId, record.getId())
                        .list();
                //商品详情
                for (TeambuyOrderGoods teambuyOrderGoods : goodsList) {
                    TeambuyGoods goods = teambuyGoodsService.getById(teambuyOrderGoods.getGoodsId());
                    teambuyOrderGoods.setGoods(goods);
                }
                record.setGoodsList(goodsList);
            }

            //查询订单所属用户信息
            for (TeambuyOrderMember record : pageList.getRecords()) {
                HanHaiMember member = hanHaiMemberService.getById(record.getUserId());
                record.setHanHaiMember(member);
            }

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

    //团长通知全体团员取餐
    @Override
    public Result<?> informOrderAll(String token, String leaderOrderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";

        try{
            //查询团长信息
            TeambuyTeamLeader leader = teambuyTeamLeaderService
                    .lambdaQuery()
                    .eq(TeambuyTeamLeader::getUserId, hanHaiMember.getId())
                    .one();
            //判断该团餐订单是否为团长所有
            TeambuyOrderLeader orderLeader = teambuyOrderLeaderService
                    .lambdaQuery()
                    .eq(TeambuyOrderLeader::getId, leaderOrderId)
                    .eq(TeambuyOrderLeader::getUserId, leader.getId())
                    .one();
            if(null == orderLeader){
                return Result.error("该订单不属于该团长，请核对订单编号："+leaderOrderId);
            }
            //将团餐订单下的团员订单状态改为待取餐
            boolean result = teambuyOrderMemberService
                    .lambdaUpdate()
                    .eq(TeambuyOrderMember::getOrderLeaderId, leaderOrderId)
                    .set(TeambuyOrderMember::getStatus, "3")
                    .update();


            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.error("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //团长完成全体取餐
    @Override
    public Result<?> finishOrderAll(String token, String leaderOrderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";

        try{
            //查询团长信息
            TeambuyTeamLeader leader = teambuyTeamLeaderService
                    .lambdaQuery()
                    .eq(TeambuyTeamLeader::getUserId, hanHaiMember.getId())
                    .one();
            //判断该团餐订单是否为团长所有
            TeambuyOrderLeader orderLeader = teambuyOrderLeaderService
                    .lambdaQuery()
                    .eq(TeambuyOrderLeader::getId, leaderOrderId)
                    .eq(TeambuyOrderLeader::getUserId, leader.getId())
                    .one();
            if(null == orderLeader){
                return Result.error("该订单不属于该团长，请核对订单编号："+leaderOrderId);
            }
            //将团餐订单下的团员订单状态改为待取餐
            boolean result = teambuyOrderMemberService
                    .lambdaUpdate()
                    .eq(TeambuyOrderMember::getOrderLeaderId, leaderOrderId)
                    .set(TeambuyOrderMember::getStatus, "4")
                    .update();

            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.error("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //团长通知全体团员取餐
    @Override
    public Result<?> informOrderOne(String token, String memberOrderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";

        try{
            //将团餐订单下的团员订单状态改为待取餐
            boolean result = teambuyOrderMemberService
                    .lambdaUpdate()
                    .eq(TeambuyOrderMember::getId, memberOrderId)
                    .set(TeambuyOrderMember::getStatus, "3")
                    .update();


            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.error("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //团长完成单体体取餐
    @Override
    public Result<?> finishOrderOne(String token, String memberOrderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";

        try{
            //将团餐订单下的团员订单状态改为待取餐
            boolean result = teambuyOrderMemberService
                    .lambdaUpdate()
                    .eq(TeambuyOrderMember::getId, memberOrderId)
                    .set(TeambuyOrderMember::getStatus, "4")
                    .update();

            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.error("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //修改团长订单
    @Override
    public Result<?> updateLeaderOrderById(String token, TeambuyOrderLeader teambuyOrderLeader) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1898983659468853250");
        //返回信息
        String massege = "";

        try{
            //执行新增操作(不传id进行新增，传了id则进行修改)
            teambuyOrderLeader.setUserId(hanHaiMember.getId());
            boolean result = teambuyOrderLeaderService.saveOrUpdate(teambuyOrderLeader);

            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.OK("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //修改团员订单
    @Override
    public Result<?> updateMemberOrderById(String token, TeambuyOrderMember teambuyOrderMember) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1898983659468853250");
        //返回信息
        String massege = "";

        try{
            //执行新增操作(不传id进行新增，传了id则进行修改)
            teambuyOrderMember.setUserId(hanHaiMember.getId());
            boolean result = teambuyOrderMemberService.saveOrUpdate(teambuyOrderMember);

            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.OK("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //团员完成取餐
    @Override
    public Result<?> finishMemberOrderById(String token, String memberOrderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1898983659468853250");
        //返回信息
        String massege = "";

        try{
            //查看团员订单
            TeambuyOrderMember teambuyOrderMember = teambuyOrderMemberService
                    .lambdaQuery()
                    .eq(TeambuyOrderMember::getId, memberOrderId)
                    .eq(TeambuyOrderMember::getUserId, hanHaiMember.getId())
                    .one();
            if(null == teambuyOrderMember){
                return Result.error("该用户没有该订单，请检查订单编号："+memberOrderId);
            }
            //执行修改操作
            teambuyOrderMember.setStatus("4");
            boolean result = teambuyOrderMemberService.updateById(teambuyOrderMember);

            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.error("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

//    //创建订单
//    @Override
//    public Result<?> createOrder(String token, TeambuyOrderMember teambuyOrderMember, String payType) {
//        //权限验证
//        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
//
//        try{
//            //订单信息
//            String payNo = IdWorker.getIdStr();//生成订单号
//            teambuyOrderMember.setId(payNo);
//            teambuyOrderMember.setUserId(hanHaiMember.getId());
//
//            //订单信息编辑
//            teambuyOrderMember.setTitle("的订单");//订单名称
//            teambuyOrderMember.setUserId(hanHaiMember.getId());//订单拥有者
//            teambuyOrderMember.setOrderLeaderId("");//团餐订单编号
//
//            //查询团长信息
//
//
//            //创建团员订单
//            teambuyOrderMemberService.save(teambuyOrderMember);
//
//            //订单支付
//            switch (payType){
//                //微信支付
//                case "0":
//                    //吊起微信支付
//                    BigDecimal price = teambuyOrderMember.getPricePay();//价格
//                    String productName = teambuyOrderMember.getTitle();//服务名称
//
//                    String s = price.multiply(new BigDecimal(100)).toString();
//                    int i1 = Double.valueOf(s).intValue();
//                    Object appOrder = mpWxPayService.createOrder(
//                            "购买"+ productName ,
//                            "127.0.0.1",
//                            teambuyOrderMember.getId(),
//                            i1,
//                            teambuyOrderMember.getId(),
//                            hanHaiMember.getAppletOpenid(),
//                            teambuyOrderMember.toString());
//                    return Result.OK("支付成功",appOrder);
//
//                //余额支付
//                case "1":
//                    //用户余额
//                    BigDecimal balance = hanHaiMember.getBalance();
//                    //订单实付金额
//                    BigDecimal amount = teambuyOrderMember.getPricePay();
//
//                    if(balance.compareTo(amount) == 1 ){
//                        //等同于a>b
//                        balance = balance.subtract(amount);
//                    }else {
//                        return Result.error("余额不足");
//                    }
//                    //修改用户余额
//                    hanHaiMember.setBalance(balance);
//                    hanHaiMemberService.updateById(hanHaiMember);
//
//                    //修改订单信息
//                    teambuyOrderMember.setStatus("1");//订单状态
//                    teambuyOrderMember.setPayTime(CommonUtils.getCurrentTime());//订单支付时间
//                    teambuyOrderMemberService.updateById(teambuyOrderMember);
//                    return Result.OK("支付成功");
//
//            }
//            return Result.error("支付失败");
//        }catch (Exception e){
//            e.printStackTrace();
//            return Result.error("支付失败");
//        }
//
//    }

    //创建订单
    @Override
    public Result<?> createOrder2(String token, TeambuyOrderMember teambuyOrderMember, String leaderId, String goodss, String userCouponId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");

        try{
            if(StringUtils.isNotEmpty(userCouponId)){
                //查看优惠券是否存在
                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);
                }

                //使用优惠券
                teambuyOrderMember.setUserCouponId(coupon.getId());
                teambuyOrderMember.setPricePreferential(coupon.getDiscount());

            }

            //订单信息
            String payNo = IdWorker.getIdStr();//生成订单号
            teambuyOrderMember.setId(payNo);
            teambuyOrderMember.setUserId(hanHaiMember.getId());

            //订单信息编辑
            teambuyOrderMember.setTitle("团员订单"+CommonUtils.getCurrentTimeFormat());//订单名称
            teambuyOrderMember.setUserId(hanHaiMember.getId());//订单拥有者
            teambuyOrderMember.setOrderLeaderId("");//团餐订单编号

            //查询团长信息
            TeambuyTeamLeader teamLeader = teambuyTeamLeaderService.getById(leaderId);
            if(null == teamLeader){
                return Result.error("团长不存在，请查看团长id是否正确" + leaderId);
            }

            //查询团长正在团餐的订单，如果没有则创建团餐订单
            TeambuyOrderLeader orderLeader = teambuyOrderLeaderService
                    .lambdaQuery()
                    .eq(TeambuyOrderLeader::getUserId, leaderId)
                    .eq(TeambuyOrderLeader::getStatus, 0)
                    .one();
            if(null == orderLeader){
                //团长信息
                HanHaiMember leader = hanHaiMemberService.getById(teamLeader.getUserId());
                //团长佣金
                TeambuyLevel level = teambuyLevelService.getById(leader.getLeaderLevelId());

                TeambuyOrderLeader orderLeader1 = new TeambuyOrderLeader();
                orderLeader1.setTitle("团长订单"+CommonUtils.getCurrentTimeFormat());
                orderLeader1.setUserId(teamLeader.getId());
                orderLeader1.setCommission(level.getAmount());
                teambuyOrderLeaderService.save(orderLeader1);

                //延迟2s
                //Thread.sleep(2000);

                TeambuyOrderLeader orderLeader2 = teambuyOrderLeaderService
                        .lambdaQuery()
                        .eq(TeambuyOrderLeader::getUserId, leaderId)
                        .eq(TeambuyOrderLeader::getStatus, 0)
                        .one();
                teambuyOrderMember.setOrderLeaderId(orderLeader2.getId());
            }else {
                teambuyOrderMember.setOrderLeaderId(orderLeader.getId());
            }

            //创建团员订单
            teambuyOrderMemberService.save(teambuyOrderMember);

            //创建团员餐品信息
            List<TeambuyOrderGoods> list = new ArrayList<>();
            String[] goods = goodss.split(";");
            for (int i = 0; i < goods.length; i++) {
                String[] param = goods[i].split(",");
                TeambuyOrderGoods goods1 = new TeambuyOrderGoods();
                goods1.setOrderId(teambuyOrderMember.getId());//团员订单id
                goods1.setGoodsId(param[0]);//商品id
                goods1.setNum(Integer.valueOf(param[1]));//商品数量
                goods1.setPrice(new BigDecimal(param[2]));//商品总价格
                //goods1.setPrice(BigDecimal.valueOf(10));//商品总价格
                list.add(goods1);
            }
            teambuyOrderGoodsService.saveBatch(list);

            //订单支付
            switch (teambuyOrderMember.getPayType()){
                //微信支付
                case "0":
                    //吊起微信支付
                    BigDecimal price = teambuyOrderMember.getPricePay();//价格
                    String productName = teambuyOrderMember.getTitle();//服务名称

                    String s = price.multiply(new BigDecimal(100)).toString();
                    int i1 = Double.valueOf(s).intValue();
                    Object appOrder = mpWxPayService.createOrder(
                            "购买"+ productName ,
                            "127.0.0.1",
                            teambuyOrderMember.getId(),
                            i1,
                            teambuyOrderMember.getId(),
                            hanHaiMember.getAppletOpenid(),
                            teambuyOrderMember.toString(),
                            payNotifyUrl);
                    return Result.OK("支付成功",appOrder);

                //余额支付
                case "1":
                    //用户余额
                    BigDecimal balance = hanHaiMember.getBalance();
                    //订单实付金额
                    BigDecimal amount = teambuyOrderMember.getPricePay();

                    if(balance.compareTo(amount) == 1 ){
                        //等同于a>b
                        balance = balance.subtract(amount);
                    }else {
                        return Result.error("余额不足");
                    }
                    //修改用户余额
                    hanHaiMember.setBalance(balance);
                    hanHaiMemberService.updateById(hanHaiMember);

                    //修改优惠券状态为已使用
                    if(null != teambuyOrderMember.getUserCouponId()){
                        TeambuyCouponUser coupon = teambuyCouponUserService.getById(teambuyOrderMember.getUserCouponId());
                        coupon.setStatus("1");
                        teambuyCouponUserService.updateById(coupon);
                    }

                    //修改订单信息
                    teambuyOrderMember.setStatus("1");//订单状态
                    teambuyOrderMember.setPayTime(CommonUtils.getCurrentTime());//订单支付时间
                    teambuyOrderMemberService.updateById(teambuyOrderMember);

                    //添加消费日志
                    TeambuyBalanceLog balanceLog = new TeambuyBalanceLog();
                    balanceLog.setAmount(teambuyOrderMember.getPricePay());//实付金额
                    balanceLog.setCashType("1");//支出
                    balanceLog.setRecordType("0");//日常消费
                    balanceLog.setUserId(teambuyOrderMember.getUserId());
                    balanceLog.setTitle("日常消费");
                    teambuyBalanceLogService.save(balanceLog);

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


            }
            return Result.error("支付失败");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("支付失败");
        }

    }

    //取消团员订单
    @Override
    public Result<?> deleteMemberOrderById(String token, String memberOrderId) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //HanHaiMember hanHaiMember = hanHaiMemberService.getById("1919589727643111426");
        //返回信息
        String massege = "";

        try{
            //查询订单是否存在
            TeambuyOrderMember teambuyOrderMember = teambuyOrderMemberService
                    .lambdaQuery()
                    .eq(TeambuyOrderMember::getId, memberOrderId)
                    .eq(TeambuyOrderMember::getUserId, hanHaiMember.getId())
                    .one();
            if(null == teambuyOrderMember){
                return Result.error("该用户没有该订单，请检查订单编号："+memberOrderId);
            }

            //执行取消操作
            teambuyOrderMember.setIsDel("1");
            boolean result = teambuyOrderMemberService.updateById(teambuyOrderMember);

//            //删除订单菜品关联信息
//            List<TeambuyOrderGoods> goodsList = teambuyOrderGoodsService
//                    .lambdaQuery()
//                    .eq(Te)

            //删除团员订单信息

            //删除团长订单关联信息

            //判断是否新增成功
            if(result){
                return Result.OK("操作成功");
            }else {
                return Result.error("操作失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    //支付订单
    @Override
    public Result<?> payOrder(String token, String orderId, String payType) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            //订单信息
            TeambuyOrderMember teambuyOrderMember = teambuyOrderMemberService.getById(orderId);
            teambuyOrderMember.setPayType(payType);

            //订单支付
            switch (payType){
                //微信支付
                case "0":
                    //吊起微信支付
                    BigDecimal price = teambuyOrderMember.getPricePay();//价格
                    String productName = teambuyOrderMember.getTitle();//服务名称

                    String s = price.multiply(new BigDecimal(100)).toString();
                    int i1 = Double.valueOf(s).intValue();
                    Object appOrder = mpWxPayService.createOrder(
                            "购买"+ productName ,
                            "127.0.0.1",
                            teambuyOrderMember.getId(),
                            i1,
                            teambuyOrderMember.getId(),
                            hanHaiMember.getAppletOpenid(),
                            teambuyOrderMember.toString(),
                            payNotifyUrl);
                    return Result.OK("支付成功",appOrder);

                //余额支付
                case "1":
                    //用户余额
                    BigDecimal balance = hanHaiMember.getBalance();
                    //订单实付金额
                    BigDecimal amount = teambuyOrderMember.getPricePay();

                    if(balance.compareTo(amount) == 1 ){
                        //等同于a>b
                        balance = balance.subtract(amount);
                    }else {
                        return Result.error("余额不足，支付失败");
                    }
                    //修改用户余额
                    hanHaiMember.setBalance(balance);
                    hanHaiMemberService.updateById(hanHaiMember);

                    //修改订单信息
                    teambuyOrderMember.setStatus("1");//订单状态
                    teambuyOrderMember.setPayTime(CommonUtils.getCurrentTime());//订单支付时间
                    teambuyOrderMemberService.updateById(teambuyOrderMember);

                    //添加消费日志
                    TeambuyBalanceLog balanceLog = new TeambuyBalanceLog();
                    balanceLog.setAmount(teambuyOrderMember.getPricePay());//实付金额
                    balanceLog.setCashType("1");//支出
                    balanceLog.setRecordType("0");//日常消费
                    balanceLog.setUserId(teambuyOrderMember.getUserId());
                    balanceLog.setTitle("日常消费");
                    teambuyBalanceLogService.save(balanceLog);

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

            }

            return Result.error("支付失败");

        }catch (Exception e){
            e.printStackTrace();
            return Result.error("支付失败");
        }
    }

    //订单支付回调
    public Result<?> payOrderNotify(String requestBody){
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        String outTradeNo = notify.getOutTradeNo();
        log.info("支付回调订单号码："+outTradeNo);

        try{
            //查询订单信息
            TeambuyOrderMember teambuyOrderMember = teambuyOrderMemberService.getById(outTradeNo);
            //如果订单存在则修改订单状态
            if (null != teambuyOrderMember){
                if("0".equals(teambuyOrderMember.getStatus())){
                    teambuyOrderMember.setStatus("1");//订单状态
                    teambuyOrderMember.setPayTime(CommonUtils.getCurrentTime());//订单支付时间
                    teambuyOrderMemberService.updateById(teambuyOrderMember);

                    //修改优惠券状态为已使用
                    if(null != teambuyOrderMember.getUserCouponId()){
                        TeambuyCouponUser coupon = teambuyCouponUserService.getById(teambuyOrderMember.getUserCouponId());
                        coupon.setStatus("1");
                        teambuyCouponUserService.updateById(coupon);
                    }

                    //添加消费日志
                    TeambuyBalanceLog balanceLog = new TeambuyBalanceLog();
                    balanceLog.setAmount(teambuyOrderMember.getPricePay());//实付金额
                    balanceLog.setCashType("1");//支出
                    balanceLog.setRecordType("0");//日常消费
                    balanceLog.setUserId(teambuyOrderMember.getUserId());
                    balanceLog.setTitle("日常消费");
                    teambuyBalanceLogService.save(balanceLog);
                }
            }

        }catch (Exception e){
            log.info("支付回调失败，订单号码："+outTradeNo);
            e.printStackTrace();
        }
        return null;
    }
}
