package org.jeecg.modules.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
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.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.bean.OrderPageBean;
import org.jeecg.modules.bean.StatisBean;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.msgAddress.entity.MsgAddress;
import org.jeecg.modules.msgAddress.service.IMsgAddressService;
import org.jeecg.modules.msgBelece.entity.MsgBelece;
import org.jeecg.modules.msgBelece.service.IMsgBeleceService;
import org.jeecg.modules.msgCity.service.IMsgCityService;
import org.jeecg.modules.msgCollect.entity.MsgCollect;
import org.jeecg.modules.msgCollect.service.IMsgCollectService;
import org.jeecg.modules.msgConfig.entity.MsgConfig;
import org.jeecg.modules.msgConfig.service.IMsgConfigService;
import org.jeecg.modules.msgCoupon.entity.MsgCoupon;
import org.jeecg.modules.msgCoupon.service.IMsgCouponService;
import org.jeecg.modules.msgDate.entity.MsgDate;
import org.jeecg.modules.msgDate.service.IMsgDateService;
import org.jeecg.modules.msgDateConfig.entity.MsgDateConfig;
import org.jeecg.modules.msgDateConfig.service.IMsgDateConfigService;
import org.jeecg.modules.msgEvaluate.entity.MsgEvaluate;
import org.jeecg.modules.msgEvaluate.service.IMsgEvaluateService;
import org.jeecg.modules.msgOrder.entity.MsgOrder;
import org.jeecg.modules.msgOrder.service.IMsgOrderService;
import org.jeecg.modules.msgPackage.entity.MsgPackage;
import org.jeecg.modules.msgPackage.service.IMsgPackageService;
import org.jeecg.modules.msgShop.entity.MsgShop;
import org.jeecg.modules.msgShop.service.IMsgShopService;
import org.jeecg.modules.msgTechnician.entity.MsgTechnician;
import org.jeecg.modules.msgTechnician.service.IMsgTechnicianService;
import org.jeecg.modules.msgTer.entity.MsgTer;
import org.jeecg.modules.msgTer.service.IMsgTerService;
import org.jeecg.modules.msgTime.service.IMsgTimeService;
import org.jeecg.modules.msgWater.entity.MsgWater;
import org.jeecg.modules.msgWater.service.IMsgWaterService;
import org.jeecg.modules.pay.MpWxPayService;
import org.jeecg.modules.postBean.*;
import org.jeecg.modules.service.OrderCreateVipService;
import org.jeecg.modules.utils.Message;
import org.jeecg.modules.utils.SmsClient;
import org.jeecg.modules.utils.WeChatJSSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import static org.checkerframework.checker.units.qual.Prefix.one;

@Slf4j
@Service
public class OrderCreateVipServiceImpl implements OrderCreateVipService {
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //项目接口
    @Resource
    private IMsgShopService msgShopService;
    //技师接口
    @Resource
    private IMsgTechnicianService msgTechnicianService;
    //地址接口
    @Resource
    private IMsgAddressService msgAddressService;
    //优惠券接口
    @Resource
    private IMsgCouponService msgCouponService;
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;
    //订单接口
    @Resource
    private IMsgOrderService msgOrderService;
    //钱包接口
    @Resource
    private IMsgBeleceService msgBeleceService;
    //缓存记录
    @Resource
    private RedisUtil redisUtil;
    //用户接口
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    //排期接口
    @Resource
    private IMsgDateConfigService msgDateConfigService;
    //排期日期
    @Resource
    private IMsgDateService msgDateService;
    //排期时间
    @Resource
    private IMsgTimeService msgTimeService;
    //收藏接口
    @Resource
    private IMsgCollectService msgCollectService;
    //流水接口
    @Resource
    private IMsgWaterService msgWaterService;
    //套餐接口
    @Resource
    private IMsgPackageService msgPackageService;
    //评价接口
    @Resource
    private IMsgEvaluateService msgEvaluateService;
    //认证资料

    //配置管理
    @Resource
    private IMsgConfigService msgConfigService;


    @Resource
    private IMsgTerService msgTerService;
    //配置信息
    @Resource
    private IMsgConfigService configService;

    //用户下单流程接口

    //第一步：用户下单
    @Override
    public Result<?> createOrder(String token, OrderCreateBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        //项目标识不能为空
        if(bean.getProjectId() == null){
            return Result.error("项目标识不能为空");
        }
        //根据项目标识查询当前项目是否存在
        MsgShop msgShop = msgShopService.getById(bean.getProjectId());
        if( msgShop== null){
            return Result.error("当前项目不存在");
        }
        //项目金额
        BigDecimal price = msgShop.getPrice();
        //技师标识不能为空
        if(bean.getTechnicianId() == null){
            return Result.error("技师标识不能为空");
        }
        //根据技师标识查询当前技师是否存在
        MsgTechnician msgTechnician = msgTechnicianService.getById(bean.getTechnicianId());
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }

        MsgOrder order = new MsgOrder();
        order.setId("OD"+System.currentTimeMillis());
        order.setUserId(hanHaiMember.getId());
        order.setProjectId(bean.getProjectId());
        order.setTechnicianId(bean.getTechnicianId());
        order.setMoney(price);
        order.setState(0);//未支付
        order.setCreateTime(new Date());

        boolean save = msgOrderService.save(order);

        return Result.OK("订单创建成功",order);
    }


    //根据订单标识查询订单详情的方法
    @Override
    public Result<?> getOrderDetail(String token,String id){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        if(id == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.getById(id);
        if(msgOrder == null){
            return Result.error("订单不存在");
        }
        //根据订单中的项目标识查询项目
        MsgShop msgShop = msgShopService.getById(msgOrder.getProjectId());
        if(msgShop == null){
            return Result.error("当前项目不存在");
        }
        //根据订单中的技师标识查询
        MsgTechnician msgTechnician = msgTechnicianService.getById(msgOrder.getTechnicianId());
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("order",msgOrder);
        map.put("shop",msgShop);
        map.put("technician",msgTechnician);
        //根据订单中的优惠券标识获取优惠券信息
        MsgCoupon msgCoupon = msgCouponService.getById(msgOrder.getCouponId());
        map.put("coupon",msgCoupon);
        return Result.OK("订单详情",map);
    }



    //获取当前技师的排期
    @Override
    public Result<?> getVipTenOrderList(String token, String tenId,String name){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        if(tenId == null){
            return Result.error("技师标识不能为空");
        }
        if(msgTechnicianService.getById(tenId) == null){
            return Result.error("当前技师不存在");
        }
        //名称不能为空
        if(name == null){
            return Result.error("名称不能为空");
        }

        //传出数据
//        Map<Object, Object> map = new HashMap<>();
//        //查询排期日期
        MsgDate msgDate = msgDateService
                .lambdaQuery()
                .eq(MsgDate::getName, name)
                .one();

//
        //排期阶段
        List<MsgDateConfig> msgDateConfigList = msgDateConfigService
                .lambdaQuery()
                .eq(MsgDateConfig::getTenId,tenId)
                .eq(MsgDateConfig::getDateId,msgDate.getId())
                .list();
//
//        for (MsgDate msgDate : msgDateList){
//            for (MsgDateConfig msgDateConfig:msgDateConfigList) {
//                if(msgDate.getId().equals(msgDateConfig.getDateId())){
//                    List<MsgDateConfig> list = msgDateConfigService
//                            .lambdaQuery()
//                            .eq(MsgDateConfig::getTenId, tenId)
//                            .eq(MsgDateConfig::getDateId, msgDate.getId())
//                            .list();
//                    List<MsgDateConfig> newList = new ArrayList<>();
//                    for (MsgDateConfig msgDateConfig1: list) {
//                        MsgDateConfig msgDateConfig2 = new MsgDateConfig();
//                        msgDateConfig2.setTimeName(msgTimeService.getById(msgDateConfig1.getTimeId()).getName());
//                        msgDateConfig2.setIsDelete(msgDateConfig1.getIsDelete());
//                        newList.add(msgDateConfig2);
//                    }
//
//                    map.put(msgDate.getName(),newList);
//                }
//            }
//        }
        return Result.OK("查询成功",msgDateConfigList);
    }


    //第二步：用户支付
    @Override
    @Transactional
    @Synchronized
    public Result<?> payOrder(String token, OrderPayBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        if(bean.getOrderId() == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.getById(bean.getOrderId());
        if(msgOrder == null){
            return Result.error("订单不存在");
        }
        if(msgOrder.getState().equals("1")){
            return Result.error("订单已支付");
        }

        //根据订单查询项目是否存在
        MsgShop msgShop = msgShopService.getById(msgOrder.getProjectId());
        if(msgShop == null){
            return Result.error("当前项目不存在");
        }
        //根据订单查询技师是否存在
        MsgTechnician msgTechnician = msgTechnicianService.getById(msgOrder.getTechnicianId());
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        //获得订单金额
        BigDecimal money = msgOrder.getMoney();
        //地址标识不能为空
        if(bean.getAddressId() == null){
            return Result.error("地址标识不能为空");
        }
        //查询当前地址是否存在
        MsgAddress msgAddress = msgAddressService.getById(bean.getAddressId());
        if(msgAddress== null){
            return Result.error("当前地址不存在");
        }
        msgOrder.setAddressDetails(msgAddress.getAddressDetail());
        //预约服务时间不能为空 :这里的逻辑待定 - 需要跟前端讨论，目前就值存字符串时间
        if(bean.getServiceTime() == null){
            return Result.error("预约服务时间不能为空");
        }
        msgOrder.setServiceTime(bean.getServiceTime());
        //出行方式不能为空
        if(bean.getTravelType() == null){
            return Result.error("出行方式不能为空");
        }

        //服务时间不能为空
        if(bean.getServiceDate() == null){
            return Result.error("服务时间不能为空");
        }



        //出行1公里多少钱
        MsgConfig travel_money = configService.lambdaQuery()
                .eq(MsgConfig::getKeyValue, "travel_money")
                .one();
        //出行金额不能为空
        if(travel_money == null){
            return Result.error("出行金额不能为空");
        }
        BigDecimal tempConfig = new BigDecimal(travel_money.getContent());
        log.info(msgTechnician.getTitle()+"当前距离："+bean.getTravelDistance());
        if(bean.getTravelDistance() == null){
            return Result.error("距离不能为空");
        }
        BigDecimal temp = tempConfig.multiply(new BigDecimal(bean.getTravelDistance()));
        //两公里内免费
        if(bean.getTravelDistance() <=2){
            tempConfig.multiply(new BigDecimal(0));
        }
        msgOrder.setTemp(temp);//车费
        msgOrder.setServiceDate(bean.getServiceDate());


        //优惠券标识为空则不获取优惠券金额，优惠券金额不为空获取优惠券金额
        BigDecimal tempCoupon = new BigDecimal(0);
        if(bean.getCouponId() != null){
            //根据优惠券标识查询优惠券信息
            MsgCoupon msgCoupon = msgCouponService.getById(bean.getCouponId());
            if(msgCoupon == null){
                return Result.error("当前优惠券不存在");
            }
            //根据优惠券信息查询优惠券金额
            if(msgCoupon.getMoney() == null){
                return Result.error("当前优惠券金额不能为空");
            }
            //订单金额小于优惠券可使用金额
            if(msgCoupon.getUseMoney().compareTo(money) > 0){
                return Result.error("订单金额小于优惠券可使用金额");
            }
            tempCoupon = msgCoupon.getMoney();
        }
        //支付方式不能为空
        if(bean.getPayType() == null){
            return Result.error("支付方式不能为空");
        }

        //订单总金额
        money = money.add(temp).subtract(tempCoupon);

        //修改订单信息
        msgOrder.setMoney(money);
        msgOrder.setAddressId(bean.getAddressId());
        msgOrder.setCouponId(bean.getCouponId());
        msgOrder.setPayType(bean.getPayType());


        //项目图片
        msgOrder.setImage(msgShop.getImage());
        //项目名称
        msgOrder.setProjectName(msgShop.getTitle());
        //项目时长
        msgOrder.setUseTime(msgShop.getTimes());
        //技师名称
        msgOrder.setTerName(msgTechnician.getTitle());
        //项目地址
        msgOrder.setAddress(msgAddress.getAddress());
        //查询地址信息

        msgOrder.setName(msgAddress.getName());
        msgOrder.setPhone(msgAddress.getPhone());



        //订单备注
        msgOrder.setRemark(bean.getRemark());
        msgOrderService.updateById(msgOrder);


        if(bean.getPayType() == 0){
            String s = money.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createOrder(
                    "购买"+msgShop.getTitle()+ msgTechnician.getTitle() ,
                    "127.0.0.1",
                    msgOrder.getId(),
                    i1,
                    msgOrder.getId(),
                    hanHaiMember.getOfficialOpenid(),
                    msgOrder.toString());

            //返回支付结果
            return Result.OK("微信支付成功",appOrder);
        }else if(bean.getPayType() == 1){
           //根据用户标识查询当前钱包额度
            MsgBelece msgBelece = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
            if(msgBelece.getMoney().compareTo(money) == -1){
                return Result.error("余额不足");
            }
//            //拨打用户电话
//            this.online(msgOrder);





            msgBelece.setMoney(msgBelece.getMoney().subtract(money));
            msgBeleceService.updateById(msgBelece);

            //修改订单状态
            msgOrder.setState(1);
            msgOrder.setPayTime(new Date());
            msgOrderService.updateById(msgOrder);

//            //短信发送给技师
//            smsClient.sendSms(msgTechnician.getPhone(),"您有一笔订单需要处理，订单号："+msgOrder.getId());

            //增加流水
            MsgWater wallet = new MsgWater();
            wallet.setMoney(money);
            wallet.setTitle("余额支付订单");
            wallet.setType(2);
            wallet.setUserId(hanHaiMember.getId());
            wallet.setState(1);
            wallet.setCreateTime(new Date());
            msgWaterService.save(wallet);


            //根据订单中的优惠券标识修改优惠券使用情况
            if(bean.getCouponId() != null){
                MsgCoupon msgCoupon = msgCouponService.getById(bean.getCouponId());
                msgCoupon.setState(1);
                msgCoupon.setStateTime(new Date());
                msgCouponService.updateById(msgCoupon);
            }

            //发送提示
            this.sendSms(msgTechnician);

            return Result.OK("支付成功");
        }else{
//            //拨打用户电话
//            this.online(msgOrder);
//

            //修改订单状态
            msgOrder.setState(1);
            msgOrder.setPayTime(new Date());
            msgOrderService.updateById(msgOrder);

//            //短信发送给技师
//            smsClient.sendSms(msgTechnician.getPhone(),"您有一笔订单需要处理，订单号："+msgOrder.getId());

//            //增加流水
//            MsgWater wallet = new MsgWater();
//            wallet.setMoney(money);
//            wallet.setTitle("余额支付订单");
//            wallet.setType(2);
//            wallet.setUserId(hanHaiMember.getId());
//            wallet.setState(1);
//            wallet.setCreateTime(new Date());
//            msgWaterService.save(wallet);


//            //根据订单中的优惠券标识修改优惠券使用情况
//            if(bean.getCouponId() != null){
//                MsgCoupon msgCoupon = msgCouponService.getById(bean.getCouponId());
//                msgCoupon.setState(1);
//                msgCoupon.setStateTime(new Date());
//                msgCouponService.updateById(msgCoupon);
//            }

            //发送提示
            this.sendSms(msgTechnician);

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

    }



    //立即支付
    @Override
    @Transactional
    @Synchronized
    public Result<?> createWxPayOrder(String token, OrderPayBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(bean.getOrderId() == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.getById(bean.getOrderId());
        if(msgOrder == null){
            return Result.error("订单不存在");
        }
        if(msgOrder.getState().equals("1")){
            return Result.error("订单已支付");
        }


        //根据订单查询项目是否存在
        MsgShop msgShop = msgShopService.getById(msgOrder.getProjectId());
        if(msgShop == null){
            return Result.error("当前项目不存在");
        }
        //根据订单查询技师是否存在
        MsgTechnician msgTechnician = msgTechnicianService.getById(msgOrder.getTechnicianId());
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        BigDecimal money = msgOrder.getMoney();
        if(bean.getPayType() == 0){
            String s = money.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createOrder(
                    "购买"+msgShop.getTitle()+ msgTechnician.getTitle() ,
                    "127.0.0.1",
                    msgOrder.getId(),
                    i1,
                    msgOrder.getId(),
                    hanHaiMember.getOfficialOpenid(),
                    msgOrder.toString());

            //返回支付结果
            return Result.OK("微信支付成功",appOrder);
        }else if(bean.getPayType() == 1){
            //根据用户标识查询当前钱包额度
            MsgBelece msgBelece = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
            if(msgBelece.getMoney().compareTo(money) == -1){
                return Result.error("余额不足");
            }
            msgBelece.setMoney(msgBelece.getMoney().subtract(money));
            msgBeleceService.updateById(msgBelece);

            //修改订单状态
            msgOrder.setState(1);
            msgOrder.setPayTime(new Date());
            msgOrderService.updateById(msgOrder);




            //增加流水
            MsgWater wallet = new MsgWater();
            wallet.setMoney(money);
            wallet.setTitle("余额支付订单");
            wallet.setType(2);
            wallet.setUserId(hanHaiMember.getId());
            wallet.setState(1);
            wallet.setCreateTime(new Date());
            msgWaterService.save(wallet);


            //根据订单中的优惠券标识修改优惠券使用情况
            if(bean.getCouponId() != null){
                MsgCoupon msgCoupon = msgCouponService.getById(bean.getCouponId());
                msgCoupon.setState(1);
                msgCoupon.setStateTime(new Date());
                msgCouponService.updateById(msgCoupon);
            }


            //拨打电话
            this.online(msgOrder);


            //发送提示
            this.sendSms(msgTechnician);



            return Result.OK("支付成功");
        }
        return Result.error("支付失败");
    }



    //发送短信提现技师
    public void sendSms(MsgTechnician msgTechnician){
        //查询当前技师是否是测试技师
        if(msgTechnician.getIsTest() == 1){
            //查询配置管理里面的运营号
            MsgConfig msgConfig = msgConfigService.lambdaQuery().eq(MsgConfig::getKeyValue,"sms_phone").one();
            //发送短信给运营号
            SmsClient.sendMsg2(msgConfig.getContent(),msgTechnician.getTitle());
        }else{
            //根据技师中的用户标识查询用户信息
            HanHaiMember hanHaiMember = hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getId, msgTechnician.getUserId()).one();
            //发送短信给技师
            SmsClient.sendMsg2(hanHaiMember.getPhone(),msgTechnician.getTitle());
        }

    }



    //用户取消订单
    @Override
    public Result<?> cancelVipOrder(String token, String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(orderId == null){
            return Result.error("订单标识不能为空");
        }
        if(msgOrderService.lambdaQuery().eq(MsgOrder::getId,orderId).one() == null){
            return Result.error("当前订单不存在");
        }
        //修改订单状态
        msgOrderService.lambdaUpdate().eq(MsgOrder::getId,orderId).set(MsgOrder::getState,4).update();
        return Result.OK("订单取消成功");
    }


    //获取手机验证码 - 不需要token
    @Override
    public Result<?> getCode(String phone){
        if(phone == null){
            return Result.error("手机号不能为空");
        }
//        //根据电话号码查询该用户是否存在
//        HanHaiMember hanHaiMember = hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getPhone, phone).one();
//        if(hanHaiMember == null){
//            return Result.error("当前用户不存在");
//        }
//        //根据用户查询当前技师是否存在
//        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
//        if(msgTechnician == null){
//            return Result.error("当前技师不存在");
//        }
        //生成验证码随机数不重复
        String code = String.valueOf((int)((Math.random()*9+1)*1000));

        SmsClient.send(phone,code);

        //存入缓存15分钟
        redisUtil.set(phone,code,600);
        return Result.OK("验证码发送成功");
    }


    //技师登录
    @Override
    public Result<?> wxTechnicianLogin(String phone, String code) {
        Map loginMap = new HashMap<String, Object>();
        if(phone == null){
            return Result.error("手机号不能为空");
        }
        if(code == null){
            return Result.error("验证码不能为空");
        }
        //从缓存总得到code
        if(!code.equals(redisUtil.get(phone))){
            return Result.error("验证码错误");
        }
        //根据电话号码查询当前用户信息
        HanHaiMember member = hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getPhone, phone).one();
        if(member == null){
            return Result.error("当前用户不存在");
        }
        String token = JwtUtil.sign(member.getAccount(), member.getAccount());
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        // 设置超时时间
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 100);
        loginMap.put("token",token);
        loginMap.put("userInfo",member);
        loginMap.put("msgTen",msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId,member.getId()).one());
        loginMap.put("belece",msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, member.getId()).one());
        return Result.OK("登录成功",loginMap);
    }





    //技师根据标识查询自己的订单 - 技师端
    @Override
    public Result<?> getOrderList(String token, OrderPageBean pageBean) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //根据用户标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
        if (msgTechnician == null) {
            return Result.error("当前技师不存在");
        }
        //根据技师信息查询订单分页信息
        Page<MsgOrder> page = new Page<MsgOrder>(pageBean.getPageNo(), pageBean.getPageSize());
        IPage<MsgOrder> pageList = msgOrderService
                .lambdaQuery()
                .eq(MsgOrder::getTechnicianId, msgTechnician.getId())
                .eq(MsgOrder::getState,1)
                .isNotNull(MsgOrder::getAddressId)
                .orderByDesc(MsgOrder::getCreateTime)
                .page(page);
        return Result.OK(pageList);
    }

    //第三步：技师确认接单
    @Override
    public Result<?> confirmOrder(String token, String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //订单标识不能为空
        if(orderId == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.lambdaQuery().eq(MsgOrder::getId, orderId).one();
        //定单里面的技师标识跟当前登录的技师标识不一样
        //根据订单中的技师标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, msgOrder.getTechnicianId()).one();
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        if(!msgTechnician.getUserId().equals(hanHaiMember.getId())){
            return Result.error("当前技师不能接单");
        }
        if( msgOrder!= null){
            //订单状态不能为空
            if(msgOrder.getState() == null){
                return Result.error("订单状态不能为空");
            }
            //订单状态：1：待接单
            if(msgOrder.getState() == 1){
                msgOrder.setState(2); //确认接单
                msgOrder.setTenOk("Y");
                msgOrder.setTenState(1);
                msgOrder.setConfirmTime(new Date());
            }
            msgOrderService.updateById(msgOrder);
            return Result.OK("确认接单成功");
        }
        return null;
    }

    //第四步：技师出发
    @Override
    public Result<?> startOrder(String token, String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //订单标识不能为空
        if(orderId == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.lambdaQuery().eq(MsgOrder::getId, orderId).one();
        //根据订单中的技师标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, msgOrder.getTechnicianId()).one();
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        if(!msgTechnician.getUserId().equals(hanHaiMember.getId())){
            return Result.error("当前技师不能接单");
        }
        if( msgOrder!= null){
            //订单状态不能为空
            if(msgOrder.getState() == null){
                return Result.error("订单状态不能为空");
            }
            //订单状态：2：待到达
            if(msgOrder.getState()==2){
                msgOrder.setTenState(2);
                msgOrder.setArriveTime(new Date());
            }
            msgOrderService.updateById(msgOrder);
            return Result.OK("确认到达成功");
        }
        return null;


    }

    //第五步：技师到达
    @Override
    public Result<?> arriveOrder(String token, String orderId,String arrivalPicture){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //订单标识不能为空
        if(orderId == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.lambdaQuery().eq(MsgOrder::getId, orderId).one();
        //根据订单中的技师标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, msgOrder.getTechnicianId()).one();
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        if(!msgTechnician.getUserId().equals(hanHaiMember.getId())){
            return Result.error("当前技师不能接单");
        }
        if( msgOrder!= null){
            //订单状态不能为空
            if(msgOrder.getState() == null){
                return Result.error("订单状态不能为空");
            }
            //订单状态：2：待到达
            if(msgOrder.getState()==2){
                msgOrder.setTenState(3);
                msgOrder.setArrivalPicture(arrivalPicture);
                msgOrder.setArriveTime(new Date());
            }
            msgOrderService.updateById(msgOrder);
            return Result.OK("确认到达成功");
        }
        return null;
    }

    //第六步：技师开始服务
    @Override
    public Result<?> startService(String token, String orderId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //订单标识不能为空
        if(orderId == null){
            return Result.error("订单标识不能为空");
        }
        MsgOrder msgOrder = msgOrderService.lambdaQuery().eq(MsgOrder::getId, orderId).one();
        //根据订单中的技师标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, msgOrder.getTechnicianId()).one();
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        if(!msgTechnician.getUserId().equals(hanHaiMember.getId())){
            return Result.error("当前技师不能接单");
        }
        if( msgOrder!= null){
            //订单状态不能为空
            if(msgOrder.getState() == null){
                return Result.error("订单状态不能为空");
            }
            //订单状态
            if(msgOrder.getState()==2){
                msgOrder.setTenState(4);
                msgOrder.setStartServiceTime(new Date());
            }
            msgOrderService.updateById(msgOrder);
            return Result.OK("开始服务");
        }
        return null;
    }

    //第七步：技师结束服务
    @Override
    public Result<?> endService(String token, String orderId,String endPicture){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //订单标识不能为空
        if(orderId == null){
            return Result.error("订单标识不能为空");
        }



        MsgOrder msgOrder = msgOrderService.lambdaQuery().eq(MsgOrder::getId, orderId).one();
        //根据订单中的技师标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, msgOrder.getTechnicianId()).one();
        if(msgTechnician == null){
            return Result.error("当前技师不存在");
        }
        if(!msgTechnician.getUserId().equals(hanHaiMember.getId())){
            return Result.error("当前技师不能接单");
        }
        if( msgOrder!= null){
            //订单状态不能为空
            if(msgOrder.getState() == null){
                return Result.error("订单状态不能为空");
            }
            //订单状态
            if(msgOrder.getState()==2){
                msgOrder.setState(3);
                msgOrder.setTenState(5);
                msgOrder.setEndPicture(endPicture);
                msgOrder.setEndErviceTime(new Date());

                //进入分销代码
                this.getSetMoney(hanHaiMember,msgTechnician,msgOrder);

            }
//            msgOrderService.updateById(msgOrder);
            return Result.OK("结束服务");
        }
        return null;
    }


    //分销
    public void getSetMoney(HanHaiMember haiMember,MsgTechnician msgTechnician,MsgOrder order){
        //根据订单中的项目标识查询当前订单的项目
        MsgShop msgShop = msgShopService.lambdaQuery().eq(MsgShop::getId, order.getProjectId()).one();
        //获得技师所得
        BigDecimal tenMoney = msgShop.getTenMoney();
        //获得分销商所得
        BigDecimal shopMoney = msgShop.getShopMoney();
        //获得一级技师所得
        BigDecimal tenPrice = msgShop.getTenPrice();
        //获得二级推荐技师所得
        BigDecimal tenMinMoney = msgShop.getTenMinPrice();
        //获得打车费
        BigDecimal temp = order.getTemp();

        order.setTemp(temp);
        order.setTenMoney(tenMoney);
        order.setShopMoney(shopMoney);
        order.setTenPrice(tenPrice);
        order.setTenMinPrice(tenMinMoney);






        //给技师所得佣金  做事的技师
        log.info("做事的技师："+msgTechnician.getTitle()+"佣金为："+tenMoney);
        if(tenMoney != null && tenMoney.compareTo(BigDecimal.ZERO) > 0){
            MsgBelece one = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, msgTechnician.getUserId()).one();
            //增加余额
            one.setMoney(one.getMoney().add(tenMoney.add(temp)));
            msgBeleceService.updateById(one);

            //增加打车费流水
            MsgWater wallet1 = new MsgWater();
            wallet1.setMoney(temp);
            wallet1.setTitle(msgShop.getTitle()+"打车费");
            wallet1.setType(3);
            wallet1.setUserId(msgTechnician.getUserId());
            wallet1.setState(1);
            wallet1.setCreateTime(new Date());
            msgWaterService.save(wallet1);


            //增加流水
            MsgWater wallet = new MsgWater();
            wallet.setMoney(tenMoney);
            wallet.setTitle(msgShop.getTitle()+"服务佣金");
            wallet.setType(3);
            wallet.setUserId(msgTechnician.getUserId()); //给技师的
            wallet.setState(1);
            wallet.setCreateTime(new Date());
            wallet.setMoney(tenMoney);
            msgWaterService.save(wallet);
        }

        //给一级技师的推荐佣金
        if(haiMember != null){
            //根据当前用户的vid查询上级用户
            HanHaiMember pidMember =   hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getId, haiMember.getVid()).one();
            if(pidMember != null){
                //查询该用户关联的技师账号
                MsgTechnician msgTechnician1 = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, pidMember.getId()).one();
                if(msgTechnician1 != null){
                    //增加该技技师的余额
                    MsgBelece two = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, msgTechnician1.getUserId()).one();
                    if(tenPrice != null && tenPrice.compareTo(BigDecimal.ZERO) > 0){
                        //增加余额
                        two.setMoney(two.getMoney().add(tenPrice));
                        msgBeleceService.updateById(two);

                        //增加流水
                        MsgWater wallet = new MsgWater();
                        wallet.setMoney(tenPrice);
                        wallet.setTitle(msgShop.getTitle()+"直推佣金");
                        wallet.setType(3);
                        wallet.setUserId(msgTechnician1.getUserId());
                        wallet.setState(1);
                        wallet.setCreateTime(new Date());
                        msgWaterService.save(wallet);
                   }
                }


                //给该用户返点
                MsgBelece shop = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, pidMember.getId()).one();
                if(shopMoney != null && shopMoney.compareTo(BigDecimal.ZERO) > 0){
                    shop.setMoney(shop.getMoney().add(shopMoney));
                    msgBeleceService.updateById(shop);

                    MsgWater wallet = new MsgWater();
                    wallet.setMoney(shopMoney);
                    wallet.setTitle(msgShop.getTitle()+"推荐佣金");
                    wallet.setType(3);
                    wallet.setUserId(pidMember.getId());
                    wallet.setState(1);
                    wallet.setCreateTime(new Date());
                    msgWaterService.save(wallet);

                }





                //查询上上级用户
                if(pidMember.getVid() != null){
                    HanHaiMember pidMember1 =   hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getId, pidMember.getVid()).one();
                    if(pidMember1 != null){
                        //查询该用户关联的技师账号
                        MsgTechnician msgTechnician2 = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, pidMember1.getId()).one();
                        if(msgTechnician2 != null){
                            if(tenMinMoney != null && tenMinMoney.compareTo(BigDecimal.ZERO) > 0){
                                //增加余额
                                MsgBelece two = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, msgTechnician2.getUserId()).one();
                                two.setMoney(two.getMoney().add(tenMinMoney));
                                msgBeleceService.updateById(two);

                                //增加流水
                               MsgWater wallet = new MsgWater();
                               wallet.setMoney(tenMinMoney);
                               wallet.setTitle(msgShop.getTitle()+"间推佣金");
                               wallet.setType(3);
                               wallet.setUserId(msgTechnician2.getUserId());
                               wallet.setState(1);
                               wallet.setCreateTime(new Date());
                               msgWaterService.save(wallet);
                           }
                        }
                    }
                }




            }
        }



        msgOrderService.updateById(order);



    }






    //第八步：用户评价
    @Override
    public Result<?> evaluateOrder(String token, MsgEvaluate bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);

        //根据订单标识查询订单
        MsgOrder msgOrder = msgOrderService.lambdaQuery().eq(MsgOrder::getId, bean.getOrderId()).one();

        if(msgOrder == null){
            return Result.error("订单不存在");
        }

        //内容不能为空
        if(bean.getContent() == null){
            return Result.error("内容不能为空");
        }
        if(bean.getContent().length() > 200){
            return Result.error("内容不能超过200个字符");
        }
        if(bean.getLabelText() == null){
            return Result.error("标签不能为空");
        }
        if(bean.getLabelText().length() > 20){
            return Result.error("标签不能超过20个字符");
        }
        if(bean.getAttitudeNum() == null){
            return Result.error("态度评价不能为空");
        }
        if(bean.getResponseNum() == null){
            return Result.error("响应评价不能为空");
        }
        if(bean.getMajorNum() == null){
            return Result.error("专业评价不能为空");
        }
        if(bean.getServiceNum() == null){
            return Result.error("服务评价不能为空");
        }
        if(bean.getType() == null){
            return Result.error("类型不能为空");
        }

        bean.setUserId(msgOrder.getUserId());
        bean.setTerId(msgOrder.getTechnicianId());
        bean.setCreateTime(new Date());
        //把几个评价分数累加起来5分以下是差评5分到13分是中评13分以上是好
        int i = bean.getAttitudeNum() + bean.getResponseNum() + bean.getMajorNum() + bean.getServiceNum();
        if(i < 5){
            bean.setFraction(2);
        }else if(i >= 5 && i < 13){
            bean.setFraction(1);
        }else{
            bean.setFraction(0);
        }
        msgEvaluateService.save(bean);

        //修改订单状态为已评价
        if(bean.getType() == 0){
            msgOrder.setEvaluated(1);
        }else{
            msgOrder.setEvaluated(2);
        }





        msgOrderService.updateById(msgOrder);
        return Result.ok("评价成功");
    }


    //收藏技师
    @Override
    public Result<?> collectVipTechnician(String token, String tenId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        if(tenId == null){
            return Result.error("技师标识不能为空");
        }
        if(msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, tenId).one() != null){
            MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, tenId).one();
            if(msgTechnician.getCollectNum() == null){
                msgTechnician.setCollectNum(0);
            }
            msgTechnician.setCollectNum(msgTechnician.getCollectNum() + 1);
            msgTechnicianService.updateById(msgTechnician);
        }
        //添加收藏记录
        MsgCollect msgCollect = new MsgCollect();
        msgCollect.setTenId(tenId);
        msgCollect.setUserId(hanHaiMember.getId());
        if(msgCollectService.lambdaQuery().eq(MsgCollect::getTenId, tenId).eq(MsgCollect::getUserId, hanHaiMember.getId()).one() == null){
            msgCollectService.save(msgCollect);
            return Result.OK("收藏成功");
        }else{
            return Result.error("已经收藏过该技师");
        }
    }

    //收藏列表
    @Override
    public Result<?> getVipCollectList(String token, CollectPageBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        Page<MsgCollect> page = new Page<MsgCollect>(bean.getPageNo(), bean.getPageSize());
        IPage<MsgCollect> pageList = msgCollectService.lambdaQuery().eq(MsgCollect::getUserId, hanHaiMember.getId()).page(page);
        pageList.getRecords().forEach(item -> {
            MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, item.getTenId()).one();
            item.setTechnician(msgTechnician);
        });
        return Result.OK(pageList);
    }

    //分享生成签名
    @Override
    public Result<?> getVipShareSign(String url){
        try {
            Map<String, Object> signPackage = WeChatJSSDK.getSignPackage(url);
            return Result.OK("分享成功",signPackage);
        }catch (Exception e){
            e.printStackTrace();
        }
       return Result.OK();

    }

    //取消收藏接口
    @Override
    public Result<?> cancelCollect(String token, String tenId){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        if(msgCollectService.lambdaQuery().eq(MsgCollect::getTenId, tenId).eq(MsgCollect::getUserId, hanHaiMember.getId()).one() != null){
            msgCollectService.lambdaUpdate().eq(MsgCollect::getTenId, tenId).eq(MsgCollect::getUserId, hanHaiMember.getId()).remove();
            if(msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, tenId).one() != null){
                MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, tenId).one();
                msgTechnician.setCollectNum(msgTechnician.getCollectNum() - 1);
                msgTechnicianService.updateById(msgTechnician);
            }
            return Result.OK("取消收藏成功");
        }else{
            return Result.error("取消收藏失败");
        }
    }


    //技师端-获取技师个人信息
    @Override
    public Result<?> giveTenInfo(String token){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        //根据用户标识获取技师信息
        if(msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one() != null) {
            MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
            //根据技师中的用户标识获取用户钱包信息
            MsgBelece one = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
            Map map = new HashMap();
            map.put("msgTen",msgTechnician);
            map.put("belece", one);

            return Result.OK(map);
        }
        return Result.OK();
    }



    //技师端-资料上传
    @Override
    public Result<?> uploadTenInfo(String token, TenInfoBean bean){
        return Result.OK();
    }




    //技师顿-上下线
    @Override
    public Result<?> online(String token, OnlineBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        //经度不能为空
        if(bean.getLongitude() == null){
            return Result.error("经度不能为空");
        }
        if(bean.getLatitude() == null){
            return Result.error("纬度不能为空");
        }
        if(bean.getBookable() == null){
            return Result.error("是否可预约不能为空");
        }
        //根基传入经纬度更新技师信息状态
        if(msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one() != null){
            MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
            msgTechnician.setLatitude(bean.getLatitude());
            msgTechnician.setLongitude(bean.getLongitude());
            msgTechnician.setBookable(bean.getBookable());
            msgTechnicianService.updateById(msgTechnician);
            if(bean.getBookable().equals("Y")){
                return Result.OK("上线成功");
            }else{
                return Result.OK("下线成功");
            }
        }
        return Result.OK();
    }






    //技师端-提现-充值
    @Override
    public Result<?> giveWithdrawal(String token, WithdrawalBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        BigDecimal price = bean.getPrice();
        //类型不能为空
        if(bean.getType() == null){
            return Result.error("类型不能为空");
        }
        //充值
        if(bean.getType() == 0){
            //充值金额需大于0
            if(price.compareTo(new BigDecimal(0)) == -1){
                return Result.error("充值金额不能小于0");
            }

            //创建充值流水
            MsgWater water = new MsgWater();
            String l = System.currentTimeMillis()+"";

            water.setId(l);
            water.setTitle("普通充值");
            water.setType(0);
            water.setMoney(price);
            water.setCreateTime(new Date());
            water.setUserId(hanHaiMember.getId());
            water.setState(0);

            if(StringUtils.isBlank(bean.getId())){
                //充值套餐
                MsgPackage msgPackage = msgPackageService.lambdaQuery().eq(MsgPackage::getId, bean.getId()).one();
                if(msgPackage == null){
                    return Result.error("充值套餐不存在");
                }
                water.setTitle("套餐充值");
                price = msgPackage.getMoney();

                water.setMoney(msgPackage.getMoney());
                water.setType(0);
                water.setState(0);
            }
            log.info("当前充值金额======="+price);
            String s = price.multiply(new BigDecimal(100)).toString();

            log.info("当前充值金额======扩大一百倍======"+price);
            msgWaterService.save(water);
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createUserOrder(
                    "充值" ,
                    "127.0.0.1",
                    l,
                    i1,
                    l,
                    hanHaiMember.getOfficialOpenid(),
                    "{}");

            return Result.OK(appOrder);

        }else{

            //开户行不能为空
            if(StringUtils.isBlank(bean.getBank())){
                return Result.error("开户行不能为空");
            }
            //银行卡不能为空
            if(StringUtils.isBlank(bean.getCard())){
                return Result.error("银行卡不能为空");
            }

            //提现
            if(msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one() != null){
                MsgBelece one = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, hanHaiMember.getId()).one();
                if(one.getMoney().compareTo(price) == -1){
                    return Result.error("余额不足");
                }
                if(one.getMoney().compareTo(price) == 1){
                    one.setMoney(one.getMoney().subtract(price));
                    msgBeleceService.updateById(one);
                    MsgWater water = new MsgWater();
                    String l = System.currentTimeMillis()+"";
                    water.setId(l);
                    water.setTitle("提现");
                    water.setType(1);
                    water.setMoney(price);
                    water.setCreateTime(new Date());
                    water.setUserId(hanHaiMember.getId());
                    water.setState(0);
                    water.setBank(bean.getBank());
                    water.setCard(bean.getCard());
                    msgWaterService.save(water);

                    //修改当前提现的卡号
                    MsgTer one1 = msgTerService.lambdaQuery().eq(MsgTer::getUserId, hanHaiMember.getId())
                            .eq(MsgTer::getState,1)
                            .one();


//                    one1.setCard(bean.getCard());
//                    one1.setBank(bean.getBank());
//                    msgTerService.updateById(one1);



                }
                return Result.OK("提现成功");
            }

        }





        return Result.OK();
    }

    //公告
    @Override
    public Result<?> getTenNotice(String token){

        return Result.OK();
    }

    //获取首页订单
    @Override
    public Result<?> getTenOrderList(String token){
        return Result.OK();
    }


    //首页统计数据
    @Override
    public Result<?> getTenOrderStatistics(String token){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        //查询该用户关联的技师信息
        MsgTechnician technician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId())
                .one();
        //查询该技师的全部订单
        List<MsgOrder> technicianListAll = msgOrderService.lambdaQuery().eq(MsgOrder::getTechnicianId, technician.getId())
                .list();
        List list = new ArrayList<>();
        StatisBean statisBean = new StatisBean();
        statisBean.setStatus(0);
        statisBean.setName("全部订单");
        statisBean.setSize(technicianListAll.size());
        list.add(statisBean);

        //查询该技师未完成订单
        List<MsgOrder> technicianListNoFinish = msgOrderService.lambdaQuery().eq(MsgOrder::getTechnicianId, technician.getId())
                .eq(MsgOrder::getState,0)
                .list();


        StatisBean statisBean1 = new StatisBean();
        statisBean1.setStatus(1);
        statisBean1.setName("未完成");
        statisBean1.setSize(technicianListNoFinish.size());
        list.add(statisBean1);

        List<MsgOrder> technicianListFinish = msgOrderService.lambdaQuery().eq(MsgOrder::getTechnicianId, technician.getId())
                .eq(MsgOrder::getState,1)
                .list();

        StatisBean statisBean2 = new StatisBean();
        statisBean2.setStatus(2);
        statisBean2.setName("已完成");
        statisBean2.setSize(technicianListFinish.size());
        list.add(statisBean2);


        List<MsgOrder> technicianListAll1 = msgOrderService.lambdaQuery().eq(MsgOrder::getTechnicianId, technician.getId())
                .eq(MsgOrder::getState,2)
                .list();

        StatisBean statisBean3 = new StatisBean();
        statisBean3.setStatus(3);
        statisBean3.setName("已评价");
        statisBean3.setSize(technicianListAll1.size());
        list.add(statisBean3);



        return Result.OK(list);
    }


    //获取订单页订单
    @Override
    public Result<?> getTenOrderPageList(String token ,OrderPageBean pageBean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if (hanHaiMember == null) {
            return Result.error("用户信息失效，请重新登录");
        }
        //根据用户标识查询技师信息
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
        if (msgTechnician == null) {
            return Result.error("当前技师不存在");
        }
        //根据技师信息查询订单分页信息
        Page<MsgOrder> page = new Page<MsgOrder>(pageBean.getPageNo(), pageBean.getPageSize());
        IPage<MsgOrder> pageList = msgOrderService
                .lambdaQuery()
                .eq(MsgOrder::getTechnicianId, msgTechnician.getId())
                .eq(MsgOrder::getState, pageBean.getState())
                //根据服务时间查询
                .isNotNull(MsgOrder::getAddressId)
                .orderByDesc(MsgOrder::getCreateTime)
                .page(page);
        //如果服务日期不为空
        if(pageBean.getServiceDate() != null){
            pageList = msgOrderService
                    .lambdaQuery()
                    .eq(MsgOrder::getTechnicianId, msgTechnician.getId())
                    .eq(MsgOrder::getState, pageBean.getState())
                    //根据服务时间查询
                    .isNotNull(MsgOrder::getAddressId)
//                    .like(MsgOrder::getServiceDate, pageBean.getServiceDate())
                    .orderByDesc(MsgOrder::getCreateTime)
                   .page(page);
        }

        return Result.OK(pageList);
    }



    //根据用户手机号码验证码更换手机号码绑定信息
    @Override
    public Result<?> changePhone(String token, String phone, String code){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        //根据手机号码查询是否有用户以绑定
        HanHaiMember byPhone = hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getPhone, phone).one();
        if(byPhone != null){
            return Result.error("该手机号码已被绑定");
        }
        //从缓存总得到code
        if(StringUtils.isEmpty(code)){
            return Result.error("验证码不能为空");
        }
        if(!code.equals(redisUtil.get(phone))){
            return Result.error("验证码错误");
        }
        hanHaiMember.setPhone(phone);
        hanHaiMemberService.updateById(hanHaiMember);
        return Result.OK("绑定成功");
    }

    //支付回调
    @Override
    public Object createCzNotify(String requestBody){
        log.info("进入订单支付回回调-----------------------------");
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        log.info(notify.toString());
        String outTradeNo = notify.getOutTradeNo();
        log.info("订单标识"+outTradeNo);
        //开始处理业务逻辑
        MsgWater byId = msgWaterService.getById(outTradeNo);
        log.info("订单数据{}",byId);
        if(byId!=null){
            if(byId.getState()==0){
                //修改订单状态
                byId.setState(1);
                byId.setUpdateTime(new Date());
                msgWaterService.updateById(byId);

                //增加余额
                MsgBelece b = msgBeleceService.lambdaQuery().eq(MsgBelece::getUserId, byId.getUserId()).one();
                b.setMoney(b.getMoney().add(byId.getMoney()));
                msgBeleceService.updateById(b);


            }
        }
        return null;
    }


    //语音电话拨打  -- 来订单
    public void online(MsgOrder order){
        //根据订单标识查询技师信息
        MsgTechnician technician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getId, order.getTechnicianId()).one();
        //根据技师信息中的用户标识查询用户电话
        HanHaiMember member = hanHaiMemberService.lambdaQuery().eq(HanHaiMember::getId, technician.getUserId()).one();


        try {
            String appId = "61ZhAwDm";
            String appKey = "22JncSVX";
            String mobile = member.getPhone();
            String templateId = "1275466558320451584";


            String urlParameters = "appId=" + appId +
                    "&appKey=" + appKey +
                    "&mobile=" + mobile +
                    "&templateId=" + templateId;

            URL url = new URL("https://api.253.com/open/notify/batch-voice-notify");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", String.valueOf(urlParameters.length()));
            conn.setDoOutput(true);

            OutputStream os = conn.getOutputStream();
            os.write(urlParameters.getBytes());
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            br.close();

            System.out.println("Response: " + response.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }












    //认证
    @Override
    public Result<?> tenRealName(String token, TenRealNameBean bean){
        //判断当前用户是否存在
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        //姓名不能为空
        if(StringUtils.isEmpty(bean.getName())){
            return Result.error("姓名不能为空");
        }
        //证件号不能为空
        if(StringUtils.isEmpty(bean.getIdCard())){
            return Result.error("证件号不能为空");
        }
        //健康证不能为空
        if(StringUtils.isEmpty(bean.getIdImage())){
            return Result.error("健康证不能为空");
        }

        //营业证不能为空
        if(StringUtils.isEmpty(bean.getIdImage2())){
            return Result.error("营业证不能为空");
        }

        if(StringUtils.isEmpty(bean.getIdImg())){
            return Result.error("证件图片不能为空");
        }
        if(StringUtils.isEmpty(bean.getIdImg2())){
            return Result.error("证件图片不能为空");
        }
        //修改用户状态为实名
        hanHaiMember.setIdCardOpen("Y");
        hanHaiMemberService.updateById(hanHaiMember);

        //修改技师实名状态
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
        msgTechnician.setHealthCertificate(bean.getIdImage());
        msgTechnician.setBusinessLicense(bean.getIdImage2());
        msgTechnician.setRealOk("Y");

        msgTechnicianService.updateById(msgTechnician);

        //修改当前技师认证资料
        MsgTer msgTer = msgTerService.lambdaQuery()
                .eq(MsgTer::getUserId, hanHaiMember.getId())
                .eq(MsgTer::getState, 1)
                .one();

        //msgTer信息不能为空
        if(msgTer == null){
            return Result.error("当前技师认证资料不存在");
        }

        msgTer.setIdCard(bean.getIdCard());
        msgTer.setIdImg(bean.getIdImg());
        msgTer.setIdImg2(bean.getIdImg2());
        msgTer.setIdImage(bean.getIdImage());
        msgTer.setIdImage2(bean.getIdImage2());
        msgTer.setName(bean.getName());

        msgTerService.updateById(msgTer);

        return Result.OK("认证成功");
    }


    //获取实名认证信息
    @Override
    public Result<?> getTenRealName(String token){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        if(hanHaiMember == null){
            return Result.error("用户信息失效，请重新登录");
        }
        MsgTer one = msgTerService.lambdaQuery()
                .eq(MsgTer::getUserId, hanHaiMember.getId())
                .eq(MsgTer::getState, 1)
                .one();

        return Result.OK(one);

    }


    //修改技师相册
    @Override
    public Result<?> uploadTenImg(String token,String file){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
       //相册不能为空
        if(StringUtils.isEmpty(file)){
            return Result.error("相册不能为空");
        }
        MsgTechnician msgTechnician = msgTechnicianService.lambdaQuery().eq(MsgTechnician::getUserId, hanHaiMember.getId()).one();
        msgTechnician.setImages(file);
        msgTechnicianService.updateById(msgTechnician);
        return Result.OK("上传成功");
    }



    //获取我推荐的技师记录
    @Override
    public Result<?> getTenFans(String token){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        //查询当前用户
        List<MsgTer> list = msgTerService.lambdaQuery().eq(MsgTer::getUserId, hanHaiMember.getId()).list();

        return Result.OK(list);
    }


}
