package com.sqx.modules.errand.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.address.dao.AddressDao;
import com.sqx.modules.address.entity.Address;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.dao.ErrandEvaluateDao;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.ErrandAddress;
import com.sqx.modules.errand.entity.ErrandEvaluate;
import com.sqx.modules.errand.entity.ErrandRedPacket;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.errand.service.TbIndentService;
import com.sqx.modules.errand.util.LonLatUtil;
import com.sqx.modules.goods.dao.GoodsShopDao;
import com.sqx.modules.goods.dao.GoodsShopRelevancyDao;
import com.sqx.modules.goods.entity.GoodsShop;
import com.sqx.modules.goods.entity.GoodsShopRelevancy;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.message.service.MessageService;
import com.sqx.modules.order.dao.OrderGoodsDao;
import com.sqx.modules.order.entity.OrderGoods;
import com.sqx.modules.order.entity.TbOrder;
import com.sqx.modules.order.service.AppOrderService;
import com.sqx.modules.pay.controller.app.AliPayController;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.WxService;
import com.sqx.modules.utils.HttpClientUtil;
import com.sqx.modules.utils.SenInfoCheckUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Service
@Slf4j
public class TbIndentServiceImpl extends ServiceImpl<TbIndentDao, TbIndent> implements TbIndentService {

    @Autowired
    private TbIndentDao tbIndentDao;
    @Autowired
    private GoodsShopDao goodsShopDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    @Autowired
    private ErrandEvaluateDao errandEvaluateDao;
    @Autowired
    private OrderGoodsDao orderGoodsDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PayDetailsDao payDetailsDao;
    @Autowired
    private WxService wxService;
    @Autowired
    private AliPayController aliPayController;
    @Lazy
    @Autowired
    private AppOrderService appOrderService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private GoodsShopRelevancyDao goodsShopRelevancyDao;
    private ReentrantReadWriteLock reentrantReadWriteLock=new ReentrantReadWriteLock(true);

    @Override
    public TbIndent findIndentByPayOrdersNo(String ordersNo) {
        return baseMapper.selectOne(new QueryWrapper<TbIndent>().eq("pay_orders_no", ordersNo));
    }

    @Override
    public void sendNewIndentMsg(TbIndent indent){
        try{
            //开关 是否开启推送
            String value1 = commonInfoService.findOne(340).getValue();
            if("是".equals(value1)){
                //新订单通知
                //查询附近指定公里范围内的骑手
                String value = commonInfoService.findOne(339).getValue();
                String lat,lng;
                if("1".equals(indent.getIndentType()) || "2".equals(indent.getIndentType())){
                    lat=String.valueOf(indent.getShopLat());
                    lng=String.valueOf(indent.getShopLng());
                }else{
                    lat=String.valueOf(indent.getUserLat());
                    lng=String.valueOf(indent.getUserLng());
                }
                BigDecimal multiply = new BigDecimal(value).multiply(BigDecimal.valueOf(1000));
                List<UserEntity> userEntityList = userDao.selectRiderUserByOnLineFlag(String.valueOf(multiply), lng, lat);
                if(userEntityList.size()>0){
                    String templateId = commonInfoService.findOne(338).getValue();
                    for(UserEntity userEntity:userEntityList){
                        if(userEntity.getIsSendMsg()==null || userEntity.getIsSendMsg()==1){
                            String indentType;
                            if("1".equals(indent.getIndentType())){
                                indentType="帮我送";
                            }else if("2".equals(indent.getIndentType())){
                                indentType="帮我取";
                            }else if("3".equals(indent.getIndentType())){
                                indentType="同城帮买";
                            }else if("4".equals(indent.getIndentType())){
                                indentType="同城服务";
                            }else{
                                indentType="外卖";
                            }
                            if(StringUtils.isNotEmpty(userEntity.getRiderOpenId())){
                                List<String> msgList=new ArrayList<>();
                                //1：帮我送；2：帮我取；3：同城帮买；4：同城服务
                                msgList.add(indentType);
                                if("5".equals(indent.getIndentType())){
                                    TbOrder order = appOrderService.selectOrderByNum(indent.getIndentNumber());
                                    msgList.add(String.valueOf(order.getPayMoney()));
                                }else{
                                    msgList.add(String.valueOf(indent.getIndentMoney()));
                                }

                                String address;
                                if("1".equals(indent.getIndentType()) || "2".equals(indent.getIndentType())){
                                    address=indent.getShopProvince()+indent.getShopCity()+indent.getShopDistrict()+indent.getShopAddressDetail();
                                }else{
                                    address=indent.getUserProvince()+indent.getUserCity()+indent.getUserDistrict()+indent.getUserAddressDetail();
                                }
                                if(address.length()>15){
                                    address=address.substring(0,15)+"...";
                                }
                                msgList.add(address);
                                msgList.add(indent.getCreateTime());
                                SenInfoCheckUtil.sendRiderMsg(userEntity.getRiderOpenId(),templateId,msgList,6);
                            }
                            if(StringUtils.isNotEmpty(userEntity.getRiderClientid())){
                                userService.pushToSingleRider("新订单通知",indentType,userEntity.getRiderClientid());
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("新订单骑手通知异常："+e.getMessage(),e);
        }

    }



    @Override
    public Result insertIndent(TbOrder order) {
        Integer integer = tbIndentDao.selectCount(new QueryWrapper<TbIndent>().eq("order_id", order.getOrderId()));
        if(integer>=1){
            return Result.error("请勿重复生成订单！");
        }
        GoodsShop goodsShop = goodsShopDao.selectById(order.getShopId());
        Address address = addressDao.selectById(order.getAddressId());
        TbIndent tbIndent = new TbIndent();
        tbIndent.setItemCodeFlag(1);
        tbIndent.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        tbIndent.setOrderId(order.getOrderId());
        tbIndent.setIndentType("5");
        tbIndent.setIndentNumber(order.getOrderNumber());
        tbIndent.setShopName(goodsShop.getShopName());
        tbIndent.setShopPhone(goodsShop.getPhone());
        tbIndent.setShopProvince(goodsShop.getProvince());
        tbIndent.setShopCity(goodsShop.getCity());
        tbIndent.setShopDistrict(goodsShop.getDistrict());
        tbIndent.setShopLng(goodsShop.getShopLng());
        tbIndent.setShopLat(goodsShop.getShopLat());
        tbIndent.setShopAddressDetail(goodsShop.getDetailedAddress());
        if(order.getOrderType()==2){
            tbIndent.setUserName(address.getUserName());
            tbIndent.setUserPhone(address.getUserPhone());
            tbIndent.setUserProvince(address.getProvince());
            tbIndent.setUserCity(address.getCity());
            tbIndent.setUserDistrict(address.getDistrict());
            tbIndent.setUserLng(address.getLng());
            tbIndent.setUserLat(address.getLat());
            tbIndent.setUserAddressDetail(address.getAddressDetail());
        }

        tbIndent.setOrderCode(order.getOrderCode());
        tbIndent.setRemarks(order.getRemark());
        BigDecimal errandMoney = goodsShop.getErrandMoney();
        BigDecimal platformMoney=BigDecimal.ZERO;
        if(errandMoney!=null && errandMoney.doubleValue()>0){
            //平台扣除骑手佣金 具体金额
            String value = commonInfoService.findOne(333).getValue();
            //平台佣金
            platformMoney = new BigDecimal(value);
            //骑手最终可得金额
            errandMoney = errandMoney.subtract(platformMoney);
        }
        tbIndent.setErrandMoney(errandMoney);
        tbIndent.setRiderMoney(errandMoney);
        tbIndent.setPlatformMoney(platformMoney);
        tbIndent.setIndentState("11");
        tbIndent.setUserId(order.getUserId());
        tbIndent.setShopId(order.getShopId());
        baseMapper.insert(tbIndent);
        return Result.success();
    }

    //根据双方经纬度计算距离
    @Override
    public Result distance(double ol, double od, double dl, double dd) {
        GlobalCoordinates source = new GlobalCoordinates(ol, od);
        GlobalCoordinates target = new GlobalCoordinates(dl, dd);
        Integer meter = (int) LonLatUtil.getDistanceMeter(source, target, Ellipsoid.Sphere);
        return Result.success().put("data", meter);
    }

    @Transactional
    @Override
    public Result addUserAddress(Long userId, ErrandAddress errandAddress) {
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        if("1".equals(errandAddress.getAddressDefault())){
            tbIndentDao.updateDefault(userId);
        }
        errandAddress.setUserId(userId);
        errandAddress.setCreateTime(datetime);
        tbIndentDao.addUserAddress(errandAddress);
        return Result.success().put("data", errandAddress.getAddressId());
    }

    @Transactional
    @Override
    public Result updateAddress(Long userId, ErrandAddress errandAddress) {
        if("1".equals(errandAddress.getAddressDefault())){
            tbIndentDao.updateDefault(userId);
        }
        String datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        tbIndentDao.updateAddress(userId,errandAddress.getUserName(), errandAddress.getUserPhone(), errandAddress.getAddress(), errandAddress.getAddressDetail(),
                errandAddress.getAddressLongitude(), errandAddress.getAddressLatitude(), datetime, errandAddress.getAddressDefault(), errandAddress.getAddressId());

        return Result.success();
    }

    @Override
    public Result findUserAddress(Long userId) {
        List<ErrandAddress> userAddress = tbIndentDao.findUserAddress(userId);
        return Result.success().put("data", userAddress);
    }

    @Override
    public Result findAddressById(Long userId, Integer addressId) {
        ErrandAddress addressById = tbIndentDao.findAddressById(userId, addressId);
        return Result.success().put("data", addressById);
    }

    @Transactional
    @Override
    public Result addDefaultAddress(Long userId, Integer addressId) {
        tbIndentDao.updateDefault(userId);
        tbIndentDao.addDefaultAddress(userId, addressId);

        return Result.success();
    }

    @Override
    public Result delUserAddress(Long userId, Integer addressId) {
        tbIndentDao.delUserAddress(userId, addressId);
        return Result.success();
    }

    @Override
    public TbIndent basicsMoney(TbIndent indent) {
        BigDecimal price1 = new BigDecimal(0);
        if(indent.getIndentType().equals("1")||indent.getIndentType().equals("2")){
            //帮我送的初始订单价格计算
            //根据距离和重量计算具体价格/admin/dataCentre
            Integer aitemWeight = 1;
            if("25斤以内".equals(indent.getItemWeight())){
                aitemWeight = Integer.parseInt(commonInfoService.findOne(343).getValue());
            }else if("26-30斤".equals(indent.getItemWeight())){
                aitemWeight = Integer.parseInt(commonInfoService.findOne(344).getValue());
            }else if("31-40斤".equals(indent.getItemWeight())){
                aitemWeight = Integer.parseInt(commonInfoService.findOne(345).getValue());
            }else if("41-50斤".equals(indent.getItemWeight())){
                aitemWeight = Integer.parseInt(commonInfoService.findOne(346).getValue());
            }
            CommonInfo one = commonInfoService.findOne(276);
            Double a =  indent.getDistance() * aitemWeight / Double.valueOf(one.getValue());
            CommonInfo oneUser = commonInfoService.findOne(277);
            Double value = Double.valueOf(oneUser.getValue());
            if(a<value){
                a = value;
            }
            //初始订单价格;
            price1 = BigDecimal.valueOf(a);//20
            //计算保价费
            //判断用户是否需要保价费
            if("50元以下".equals(indent.getItemValue())){
                indent.setCargoInsurance(new BigDecimal(commonInfoService.findOne(347).getValue()));
            }else if("50-150元".equals(indent.getItemValue())){
                indent.setCargoInsurance(new BigDecimal(commonInfoService.findOne(348).getValue()));
            }else if("150-350元".equals(indent.getItemValue())){
                indent.setCargoInsurance(new BigDecimal(commonInfoService.findOne(349).getValue()));
            }else if("350-500元".equals(indent.getItemValue())){
                indent.setCargoInsurance(new BigDecimal(commonInfoService.findOne(350).getValue()));
            }else if("500-1000元".equals(indent.getItemValue())){
                indent.setCargoInsurance(new BigDecimal(commonInfoService.findOne(351).getValue()));
            }
            // price1 = price1.add(indent.getCargoInsurance());
            //计算骑手的跑腿费
            CommonInfo oneUser1 = commonInfoService.findOne(278);
            Double value1 = Double.valueOf(oneUser1.getValue());
            BigDecimal multiply = BigDecimal.valueOf(a).multiply(BigDecimal.valueOf(value1));
            //跑腿费四舍五入保存两位小数
            BigDecimal bigDecimal = multiply.setScale(2, BigDecimal.ROUND_HALF_DOWN);
            indent.setErrandMoney(bigDecimal);
        }else if(indent.getIndentType().equals("3")){
            CommonInfo one = commonInfoService.findOne(279);
            //计算用户要支付的跑腿费
            Double a = indent.getDistance()/Double.valueOf(one.getValue());
            //如果本订单支付价格不足10元，则提升到10元
            CommonInfo oneUser = commonInfoService.findOne(280);
            Double value = Double.valueOf(oneUser.getValue());
            if(a<value){
                a = value;
            }
            //计算用户需支付金额
            price1 = price1.add(BigDecimal.valueOf(a));
            //计算骑手的跑腿费（为该订单跑腿费的1/2）
            CommonInfo oneUser1 = commonInfoService.findOne(281);
            Double value1 = Double.valueOf(oneUser1.getValue());
            BigDecimal multiply = (BigDecimal.valueOf(a)).multiply(BigDecimal.valueOf(value1));
            //四舍五入保存两位小数
            BigDecimal bigDecimal = multiply.setScale(2, BigDecimal.ROUND_HALF_DOWN);
            indent.setErrandMoney(bigDecimal);
        }else if (indent.getIndentType().equals("4")){
            //同城服务的初始订单价格
            CommonInfo oneUser = commonInfoService.findOne(282);
            Double value = Double.valueOf(oneUser.getValue());
            price1 = price1.add(BigDecimal.valueOf(value));
            //计算同城师傅上门费
            CommonInfo oneUser1 = commonInfoService.findOne(283);
            Double value1 = Double.valueOf(oneUser1.getValue());
            BigDecimal multiply = (BigDecimal.valueOf(value)).multiply(BigDecimal.valueOf(value1));
            //四舍五入保存两位小数
            BigDecimal bigDecimal = multiply.setScale(2, BigDecimal.ROUND_HALF_DOWN);
            indent.setErrandMoney(bigDecimal);
        }
        price1 = price1.setScale(2, BigDecimal.ROUND_HALF_DOWN);

        indent.setIndentBasicsMoney(price1);
        //计算用户取消订单要扣除的违约金
        CommonInfo oneUser = commonInfoService.findOne(284);
        String valueUser = oneUser.getValue();
        BigDecimal userFine = price1.multiply(new BigDecimal(valueUser)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        indent.setUserFine(userFine);
        //计算骑手取消订单要扣除的违约金
        CommonInfo riderOne = commonInfoService.findOne(285);
        String valueRider = riderOne.getValue();
        BigDecimal riderFine = indent.getErrandMoney().multiply(new BigDecimal(valueRider)).setScale(2, BigDecimal.ROUND_HALF_DOWN);
        indent.setRiderFine(riderFine);
        return indent;
    }

    @Transactional
    @Override
    public Result addIndentBuy( TbIndent indent) {
        BigDecimal price1 = basicsMoney(indent).getIndentBasicsMoney();
        if (indent.getRedPacketId() != null) {
            //根据红包id查询红包 判断红包是否是自己的  是否使用  金额是否满足
            ErrandRedPacket red = tbIndentDao.findRed(indent.getRedPacketId());
            if(red.getUserId().equals(indent.getUserId())&&//判断红包是否是登录用户的
                    (red.getRedPacketType().equals(indent.getIndentType())||red.getRedPacketType().equals("0"))&&//判断该订单能否使用该红包
                    red.getDeleteFlag().equals("0")&&//判断红包是否已被使用过
                    red.getExpirationTime().after(new Date())&&//判断红包是否已经过期
                    red.getMinimumAmount().compareTo(price1)!=1){//判断订单价格是否大于红包最小使用额度
                //把红包改为已使用
                tbIndentDao.delRedPacket(indent.getRedPacketId());
                //红包可用，用刚才计算的价格减去红包金额
                price1 = price1.subtract(red.getRedPacketAmount());
                if(price1.doubleValue()<=0){
                    price1 = BigDecimal.valueOf(0.01);
                }
            }else {
                return Result.error("红包使用异常，请刷新重试！");
            }
        }
        if(("1".equals(indent.getIndentType())||"2".equals(indent.getIndentType()))&&indent.getCargoInsuranceFlag()==0){
            //用户选择要保价费，则给订单基础价格加上保价费
            price1=price1.add(indent.getCargoInsurance());
        }else if(("1".equals(indent.getIndentType())||"2".equals(indent.getIndentType()))&& indent.getCargoInsuranceFlag()==1){
            //用户默认不要保价费，则不改变订单价格，并将保价费改为0
            indent.setCargoInsurance(new BigDecimal(0));
        }
        if(indent.getIndentType().equals("3")&&indent.getPrepayMoney()!=null){
            //帮我买订单再加上商品预付费
            price1 =price1.add(indent.getPrepayMoney());
        }
        if(indent.getTip() != null){
            //加小费
            price1 = price1.add(indent.getTip());
        }
        //最终订单价格
        indent.setIndentMoney(price1);
        //生成取货码
        if(("1".equals(indent.getIndentType())||"2".equals(indent.getIndentType())||"3".equals(indent.getIndentType()))&&indent.getItemCodeFlag()==0){
            int a = (int)((Math.random()*9+1)*10000);
            indent.setOrderCode(String.valueOf(a));
        }
        //生成订单号
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String format = sdf.format(new Date());
        Random random=new Random();
        int i   = (int) ((Math.random()*9+1)*10000);
        String indentNumber = format + i;
        indent.setIndentNumber(indentNumber);
        indent.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //用户生成订单，默认为未支付状态
        indent.setIndentState("0");
        //计算骑手本单收入（配送费+小费）
        indent.setRiderMoney(indent.getErrandMoney());
        if(indent.getTip()!=null){
            BigDecimal riderMoney = indent.getErrandMoney().add(indent.getTip());
            indent.setRiderMoney(riderMoney);
        }
        //计算骑手本单收入（+商品费）
        if(indent.getPrepayMoney()!=null){
            BigDecimal riderMoney = indent.getRiderMoney().add(indent.getPrepayMoney());
            indent.setRiderMoney(riderMoney);
        }
        //计算平台本单收入（订单价格-骑手跑腿费-商品费）
        BigDecimal subtract = indent.getIndentMoney().subtract(indent.getErrandMoney());
        if(indent.getPrepayMoney()==null){
            indent.setPrepayMoney(BigDecimal.valueOf(0));
        }
        if("3".equals(indent.getIndentType())){
            subtract = subtract.subtract(indent.getPrepayMoney());
        }
        indent.setPlatformMoney(subtract);
        //前端传了默认的支付方式，在后端改为null
        indent.setModeOfPayment(null);
        tbIndentDao.insert(indent);
        TbIndent indent1 = tbIndentDao.selectIndentByIndentNumber(indentNumber);
        return Result.success().put("data", indent1);
    }

    @Override
    public TbIndent findIndentByIndentNumber(String indentNumber){
        return baseMapper.selectIndentByIndentNumber(indentNumber);
    }

    @Override
    public Result findNewIndent(Long userId, String receivingPettern, Integer page, Integer limit, double riderLng, double riderLat, String indentType, String buyType) {
        Page<TbIndent> pages=new Page<>(page,limit);
        IPage<TbIndent> indent = null;
        String address = "";
        if(receivingPettern.equals("1")){
            CommonInfo one = commonInfoService.findOne(274);
            Integer value =Integer.valueOf(one.getValue());
            double distances = value;
            indent = baseMapper.findNewIndent(pages, riderLng, riderLat, distances, indentType);
            for (int i = 0;i<indent.getRecords().size();i++){
                if("4".equals(indent.getRecords().get(i).getIndentType())){
                    Result distance = distance(riderLng, riderLat, indent.getRecords().get(i).getUserLng(), indent.getRecords().get(i).getUserLat());
                    Object data = distance.get("data");
                    indent.getRecords().get(i).setDistancess(Double.valueOf(data.toString()));
                }
            }
        }else if("2".equals(receivingPettern)){
            String way = commonInfoService.findOne(416).getValue();
            if("1".equals(way)){
                //根据骑手经纬度获取骑手所在城市
                CommonInfo one = commonInfoService.findOne(235);
                String url="https://apis.map.qq.com/ws/geocoder/v1/";
                Map<String,String> maps=new HashMap<>();
                maps.put("location",riderLat+","+riderLng);
                maps.put("key",one.getValue());
                String data = HttpClientUtil.doGet(url, maps);
                JSONObject jsonObject = JSON.parseObject(data);
                log.error("jsonObject的值："+jsonObject);
                String status = jsonObject.getString("status");
                if("0".equals(status)){
                    JSONObject result = jsonObject.getJSONObject("result");
                    JSONObject adInfo = result.getJSONObject("ad_info");
                    if(adInfo!=null){
                        String province = String.valueOf(adInfo.get("province"));
                        String city = String.valueOf(adInfo.get("city"));
                        address = city;
                    }

                }else{
                    log.error("转换失败！！！原因:"+jsonObject.getString("message"));
                }
            }else{
                String value = commonInfoService.findOne(417).getValue();
                String url="http://api.tianditu.gov.cn/geocoder";
                Map<String,String> param=new HashMap<>();
                JSONObject postStr=new JSONObject();
                postStr.put("lon",riderLng);
                postStr.put("lat",riderLat);
                postStr.put("ver","1");
                param.put("postStr",postStr.toJSONString());
                param.put("type","geocode");
                param.put("tk",value);
                String s = HttpClientUtil.doGet(url,param);
                JSONObject jsonObject = JSONObject.parseObject(s);
                String status = jsonObject.getString("status");
                if("0".equals(status)){
                    JSONObject result = jsonObject.getJSONObject("result");
                    JSONObject addressComponent = result.getJSONObject("addressComponent");
                    String province = addressComponent.getString("province");
                    String city = addressComponent.getString("city");
                    if(com.baomidou.mybatisplus.core.toolkit.StringUtils.isEmpty(city)){
                        if("新疆维吾尔自治区".equals(province) || "台湾省".equals(province)){
                            city = addressComponent.getString("county");
                        }else{
                            city = addressComponent.getString("province");
                        }
                    }
                    address=city;
                }
            }

            indent = baseMapper.findNewIndentcity(pages, riderLng, riderLat, address, indentType);
            for (int i = 0;i<indent.getRecords().size();i++){
                if("4".equals(indent.getRecords().get(i).getIndentType())){
                    Result distance = distance(riderLng, riderLat, indent.getRecords().get(i).getUserLng(), indent.getRecords().get(i).getUserLat());
                    Object data1 = distance.get("data");
                    indent.getRecords().get(i).setDistancess(Double.valueOf(data1.toString()));
                }
            }
        }
        return Result.success().put("data",new PageUtils(indent));
    }


    @Override
    public Result indentReceiving(Long userId, String indentNumber) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            //判断骑手状态是否被封号
            UserEntity userEntity1 = userService.selectUserById(userId);
            if(userEntity1.getStatus()!=1){
                return Result.error("您的帐号已被封禁，请联系客服解封！");
            }
            //判断骑手保证金是否大于可接单金额
            UserEntity userMessage = userService.selectUserById(userId);
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            CommonInfo one1 = commonInfoService.findOne(273);
            Double cashDeposit = Double.valueOf(one1.getValue());
            if(userMessage.getCashDeposit().compareTo(BigDecimal.valueOf(cashDeposit)) > 0 ||userMessage.getCashDeposit().compareTo(BigDecimal.valueOf(cashDeposit))==0){
                //  tbIndentDao.indentReceiving(userId, indentNumber, format);
                //判断骑手是否超过最大接单数量
                String maxNumStr = commonInfoService.findOne(342).getValue();
                Integer maxNum=Integer.parseInt(maxNumStr);
                int i = tbIndentDao.selectIndentByRiderUserCount(userId);
                if(i>=maxNum){
                    return Result.error("您已达最大接单数量，请先完成订单后再进行接单");
                }
                TbIndent tbIndent = tbIndentDao.findIndentByNumber(indentNumber);
                log.error("抢单："+userId+"     "+tbIndent.getIndentState());
                if(!"2".equals(tbIndent.getIndentState())){
                    return Result.error("订单已被抢走！");
                }
                if("4".equals(tbIndent.getIndentType())){
                    tbIndentDao.indentReceiv(userId, indentNumber, format,"4");
                }else {
                    tbIndentDao.indentReceiving(userId, indentNumber, format);
                }
                //消息推送（以前写的在下面放着）
                CommonInfo five = commonInfoService.findOne(310);
                List<String> msgList=new ArrayList<>();
                msgList.add("接单项目");
                msgList.add(userEntity1.getNickName());
                msgList.add(format);
                msgList.add("接单成功，请及时取货！");
                SenInfoCheckUtil.sendRiderMsg(userEntity1.getRiderOpenId(),five.getValue(),msgList,4);
                userService.pushToSingleRider("接单成功", "您已接单成功，请及时派送", userEntity1.getRiderClientid());

                //用户推送
                CommonInfo msg = commonInfoService.findOne(269);
                UserEntity userEntity = userService.selectUserById(tbIndent.getUserId());
                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("骑手已接单");
                messageInfo.setTitle("订单状态通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);


                List<String> msgListUser = new ArrayList<>();
                String value = commonInfoService.findOne(12).getValue();
                msgListUser.add("骑手已接单");
                msgListUser.add(tbIndent.getIndentNumber());
                if(tbIndent.getOrderId()!=null){
                    TbOrder order = appOrderService.getById(tbIndent.getOrderId());
                    if(order!=null){
                        Long shopId = order.getShopId();
                        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
                        msgListUser.add(goodsShop.getShopName());
                    }else{
                        msgListUser.add(value);
                    }
                }else{
                    msgListUser.add(value);
                }
                msgListUser.add(DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), msg.getValue(), msgListUser, 1);
                if(tbIndent.getOrderId()!=null){
                    TbOrder order = appOrderService.getById(tbIndent.getOrderId());
                    String shopTemplate = commonInfoService.findOne(354).getValue();
                    List<String> msgListShop = new ArrayList<>();
                    msgListShop.add(tbIndent.getIndentNumber());
                    log.error("打印："+tbIndent.getIndentNumber());
                    msgListShop.add("骑手接单");
                    msgListShop.add(DateUtils.format(new Date()));
                    log.error("打印："+msgListShop.toString());
                    GoodsShop goodsShop = goodsShopDao.selectById(order.getShopId());
                    UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
                    SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate, msgListShop, 9);
                }
            }else {
                return Result.error("你的保证金不足，请缴纳保证金后再接单");
            }
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("骑手接单 异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");

    }

    @Override
    public Result riderBuyGoods(TbIndent indent) {
        if("4".equals(indent.getIndentState())){
            TbIndent tbIndent= baseMapper.selectById(indent.getIndentId());
            if(!"3".equals(tbIndent.getIndentState())){
                return Result.error("订单状态变更，请刷新页面后重试！");
            }
            //用户推送
            CommonInfo msg = commonInfoService.findOne(269);
            UserEntity userEntity = userService.selectUserById(tbIndent.getUserId());
            if(userEntity!=null){

                MessageInfo messageInfo = new MessageInfo();
                messageInfo.setContent("骑手已取货，正在为您配送");
                messageInfo.setTitle("订单状态通知");
                messageInfo.setState(String.valueOf(5));
                messageInfo.setUserName(userEntity.getUserName());
                messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
                messageInfo.setCreateAt(DateUtils.format(new Date()));
                messageInfo.setIsSee("0");
                messageService.saveBody(messageInfo);


                List<String> msgList = new ArrayList<>();
                String value = commonInfoService.findOne(12).getValue();
                msgList.add("骑手已取货");
                msgList.add(tbIndent.getIndentNumber());
                if(tbIndent.getOrderId()!=null){
                    TbOrder order = appOrderService.getById(tbIndent.getOrderId());
                    if(order!=null){
                        Long shopId = order.getShopId();
                        GoodsShop goodsShop = goodsShopDao.selectById(shopId);
                        msgList.add(goodsShop.getShopName());
                    }else{
                        msgList.add(value);
                    }
                }else{
                    msgList.add(value);
                }
                msgList.add(DateUtils.format(new Date()));
                SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), msg.getValue(), msgList, 1);
            }
        }
        tbIndentDao.updateById(indent);
        return Result.success();
    }

    @Override
    public Result findRiderIndent(Long userId, Integer page, Integer limit, String indentState) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(tbIndentDao.findRiderIndent(pages, userId, indentState));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public TbIndent indentMessage(String indentNumber, double riderLng, double riderLat) {
        TbIndent tbIndent = tbIndentDao.indentRiderMessage(indentNumber, riderLng, riderLat);
        return tbIndent;
    }

    @Override
    public TbIndent indentMessageByOrderId(Long orderId, double riderLng, double riderLat) {
        TbIndent tbIndent = tbIndentDao.indentMessageByOrderId(orderId, riderLng, riderLat);
        return tbIndent;
    }


    @Transactional
    @Override
    public Result riderCancleIndent(String indentNumber,Integer type) {
        TbIndent tbIndent = baseMapper.selectOne(new QueryWrapper<TbIndent>().eq("indent_number", indentNumber));
        Long userId = tbIndent.getRiderUserId();
        UserEntity userInfo = userService.selectUserById(userId);
        CommonInfo one = commonInfoService.findOne(275);
        BigDecimal riderFine = tbIndent.getErrandMoney().multiply(BigDecimal.valueOf(Double.valueOf(one.getValue())));
        if(type==1){
            if(userInfo.getCashDeposit().doubleValue()<=riderFine.doubleValue()){
                return Result.error("您的保证金不足，不能取消该订单！");
            }
        }
        //把订单改为未接单状态
        tbIndentDao.riderCancleIndent(userId, indentNumber);
        //返回订单对象
        //骑手取消订单后，从骑手的保证金里暂扣罚金
        BigDecimal cashDeposit = userInfo.getCashDeposit().subtract(riderFine);
        tbIndentDao.updateRiderCashDeposit(cashDeposit, userId);
        //将扣款明细添加到钱包明细表里
        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        userMoneyDetails.setMoney(riderFine);
        userMoneyDetails.setUserId(userId);
        userMoneyDetails.setContent("骑手取消订单扣除保证金："+riderFine);
        userMoneyDetails.setTitle("骑手取消接单");
        userMoneyDetails.setType(2);
        userMoneyDetails.setClassify(1);
        userMoneyDetails.setState(2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(new Date());
        userMoneyDetails.setCreateTime(time);
        userMoneyDetailsService.save(userMoneyDetails);

        //用户推送
        CommonInfo msg = commonInfoService.findOne(269);
        UserEntity userEntity = userService.selectUserById(tbIndent.getUserId());

        if(userEntity!=null){

            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setContent("骑手取消接单，正在为您重新匹配骑手");
            messageInfo.setTitle("订单状态通知");
            messageInfo.setState(String.valueOf(5));
            messageInfo.setUserName(userEntity.getUserName());
            messageInfo.setUserId(String.valueOf(userEntity.getUserId()));
            messageInfo.setCreateAt(DateUtils.format(new Date()));
            messageInfo.setIsSee("0");
            messageService.saveBody(messageInfo);

            List<String> msgList = new ArrayList<>();
            String value = commonInfoService.findOne(12).getValue();
            msgList.add("骑手已取消");
            msgList.add(tbIndent.getIndentNumber());
            if(tbIndent.getOrderId()!=null){
                TbOrder order = appOrderService.getById(tbIndent.getOrderId());
                if(order!=null){
                    Long shopId = order.getShopId();
                    GoodsShop goodsShop = goodsShopDao.selectById(shopId);
                    msgList.add(goodsShop.getShopName());
                }else{
                    msgList.add(value);
                }
            }else{
                msgList.add(value);
            }
            msgList.add(time);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(), msg.getValue(), msgList, 1);

            if(tbIndent.getOrderId()!=null){
                TbOrder order = appOrderService.getById(tbIndent.getOrderId());
                String shopTemplate = commonInfoService.findOne(354).getValue();
                List<String> msgListShop = new ArrayList<>();
                msgListShop.add(tbIndent.getIndentNumber());
                msgListShop.add("骑手取消");
                msgListShop.add(DateUtils.format(new Date()));
                GoodsShop goodsShop = goodsShopDao.selectById(order.getShopId());
                UserEntity shopUser = userService.selectUserById(goodsShop.getUserId());
                SenInfoCheckUtil.sendShopMsg(shopUser.getShopOpenId(), shopTemplate, msgListShop, 9);
            }

        }

        return Result.success();
    }

    @Override
    public Result riderDelivery(Long userId, String indentNumber, String itemCode) {
        reentrantReadWriteLock.writeLock().lock();
        try{
            return finshOrder(userId, indentNumber, itemCode);
        }catch (Exception e){
            e.printStackTrace();
            log.error("完成订单异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Transactional
    public Result finshOrder(Long userId, String indentNumber, String itemCode){
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        TbIndent indentByNumber = tbIndentDao.findIndentByNumber(indentNumber);
        if("6".equals(indentByNumber.getIndentState())){
            return Result.success();
        }
        if("4".equals(indentByNumber.getIndentState())){
            if("5".equals(indentByNumber.getIndentType())){
                log.info("操作完成订单1："+indentByNumber.getOrderId());
                appOrderService.accomplishOrder(indentByNumber.getOrderId());
            }else{
                if(indentByNumber.getItemCodeFlag()!=null && indentByNumber.getItemCodeFlag()==0){
                    if(indentByNumber.getOrderCode().equals(itemCode)){
                        tbIndentDao.riderDelivery(indentByNumber.getIndentId(), date);
                        finshIndent(userId, indentNumber);
                    }else {
                        return Result.error("收货码错误！");
                    }
                }else {
                    tbIndentDao.riderDelivery(indentByNumber.getIndentId(), date);
                    finshIndent(userId, indentNumber);
                }
            }

            return Result.success();
        }
        return Result.error("订单已完成！");
    }


    @Override
    public Result userDelivery(Long userId, String indentNumber) {
        reentrantReadWriteLock.writeLock().lock();
        try{
            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            TbIndent indentByNumber = tbIndentDao.findIndentByNumber(indentNumber);
            tbIndentDao.userDelivery(userId, indentNumber, date);
            finshIndent(userId, indentNumber);
            log.info("操作完成订单5："+indentByNumber.getOrderId());
            appOrderService.accomplishOrders(indentByNumber.getOrderId(),1);
            return Result.success();
        }catch (Exception e){
            e.printStackTrace();
            log.error("用户确认收货异常："+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    public Result userEvaluate(ErrandEvaluate errandEvaluate) {
        errandEvaluateDao.insert(errandEvaluate);
        return Result.success();
    }

    @Override
    public Result findallIndent(Integer page, Integer limit, Long userId, Long riderUserId, Long shopId,Integer indentType,String ordersNo,Integer status,String riderPhone) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(tbIndentDao.findallIndent(pages, userId, riderUserId, shopId,indentType,ordersNo,status,riderPhone));
        return Result.success().put("data", pageUtils);
    }

    @Override
    @Transactional
    public void finshIndent(Long userId, String indentNumber){

        //用户确认送达以后，将配送费加到骑手余额账户
        TbIndent tbIndent = tbIndentDao.selectIndentByIndentNumber(indentNumber);
        UserEntity userMessage = userService.selectUserById(tbIndent.getRiderUserId());
        BigDecimal balance = userMessage.getBalance().add(tbIndent.getRiderMoney());
        tbIndentDao.updateRiderBalance(balance, tbIndent.getRiderUserId());
        //将接单明细添加到钱包明细表里
        UserMoneyDetails userMoneyDetails=new UserMoneyDetails();
        userMoneyDetails.setMoney(tbIndent.getRiderMoney());
        userMoneyDetails.setUserId(tbIndent.getRiderUserId());
        userMoneyDetails.setTitle("[接单收入]接单ID："+tbIndent.getIndentNumber());
        userMoneyDetails.setContent("接单收入:"+tbIndent.getRiderMoney());
        userMoneyDetails.setType(1);
        userMoneyDetails.setClassify(3);
        userMoneyDetails.setState(2);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        //tbIndentDao.insertUserMoneyDetails(userMoneyDetails.getUserId(), userMoneyDetails.getTitle(), userMoneyDetails.getType(), userMoneyDetails.getMoney(), userMoneyDetails.getContent(), userMoneyDetails.getCreateTime());
        userMoneyDetailsService.save(userMoneyDetails);
        String riderTemplate = commonInfoService.findOne(311).getValue();
        List<String> msgList = new ArrayList<>();
        msgList.add(indentNumber);
        msgList.add(tbIndent.getCreateTime());
        msgList.add("已完成");
        msgList.add(DateUtils.format(new Date()));
        UserEntity riderUser = userService.selectUserById(tbIndent.getRiderUserId());
        SenInfoCheckUtil.sendRiderMsg(riderUser.getRiderOpenId(), riderTemplate, msgList, 2);
    }

    @Override
    public Result findAllIndent(String indentType, String phone, String indentState, Integer page, Integer limit, String date, String dateType,String riderPhone) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findAllIndent(pages, indentType, phone, indentState, date, dateType,riderPhone));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result findAllIndents(String indentType, String phone, String indentState, Integer page, Integer limit, String date, String dateType,String riderPhone) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(baseMapper.findAllIndents(pages, indentType, phone, indentState, date, dateType,riderPhone));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result IndentCenter(Integer page, Integer limit, String indentType, String indentNumber, String indentState, String phone, String date, String dateType) {
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(baseMapper.IndentCenter(pages,indentType, indentNumber, indentState, phone, date, dateType));
        return Result.success().put("data", pageUtils);
    }

    @Override
    public Result updateIndentState(String indentNumber, String indentState) {
        baseMapper.updateIndentState(indentNumber, indentState);
        return Result.success();
    }

    @Override
    public Result adminSoldOutIndent(String indentNumber) {
        baseMapper.adminSoldOutIndent(indentNumber);
        return Result.success();
    }

    @Override
    public Result findDataCenter() {
        String format = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date());
        HashMap dataCenter = new HashMap();
        //总用户数
        int allCount = tbIndentDao.findAllCount();
        //今日新增用户数
        int dayAddUser = tbIndentDao.findDayAddUser(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        //本月新增用户数
        int monthAddUser = tbIndentDao.findMonthAddUser(new SimpleDateFormat("yyyy-MM-01 00:00:00").format(new Date()));
        //本年新增用户数
        int yearAddUser = tbIndentDao.findYearAddUser(new SimpleDateFormat("yyyy-01-01 00:00:00").format(new Date()));
        //今日收入
        BigDecimal dayIncome = tbIndentDao.findDayIncome(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        //本月收入
        BigDecimal monthIncome = tbIndentDao.findMonthIncome(new SimpleDateFormat("yyyy-MM-01 00:00:00").format(new Date()));
        //本年收入
        BigDecimal yearIncome = tbIndentDao.findYearIncome(new SimpleDateFormat("yyyy-01-01 00:00:00").format(new Date()));
        //今日接单数量
        int indentCount = tbIndentDao.findIndentCount(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        dataCenter.put("allCount", allCount);
        dataCenter.put("dayAddUser", dayAddUser);
        dataCenter.put("monthAddUser", monthAddUser);
        dataCenter.put("yearAddUser", yearAddUser);
        dataCenter.put("dayIncome", dayIncome);
        dataCenter.put("monthIncome", monthIncome);
        dataCenter.put("yearIncome", yearIncome);
        dataCenter.put("indentCount", indentCount);
        return Result.success().put("data", dataCenter);
    }

    @Override
    public Result taskAnalysis(String dateType, String date, Integer page, Integer limit, String indentState) {
        HashMap hashMap = new HashMap();
        //发单总金额
        BigDecimal billMoney = tbIndentDao.billMoney(dateType,date);
        //接单总金额
        BigDecimal receivingMoney = tbIndentDao.receivingMoney(dateType,date);
        //发单数量
        int billCount = tbIndentDao.billCount(dateType,date);
        //接单数量
        int reveivingCount = tbIndentDao.reveivingCount(dateType,date);
        //任务收入分析
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils taskAnalysisMoney = new PageUtils(baseMapper.taskAnalysisMoney(pages, dateType, date, indentState));
        hashMap.put("billMoney", billMoney);
        hashMap.put("receivingMoney", receivingMoney);
        hashMap.put("billCount", billCount);
        hashMap.put("reveivingCount", reveivingCount);
        hashMap.put("taskAnalysisMoney", taskAnalysisMoney);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result selectOrderByStatus(String date, String dateType) {
        HashMap hashMap = new HashMap();
        //全部
        int i = tbIndentDao.selectOrderByStatus(date, dateType, null);
        // 付款
        int i1 = tbIndentDao.selectOrderByStatus(date, dateType, 2);
        // 接单
        int i2 = tbIndentDao.selectOrderByStatus(date, dateType, 3);
        // 进行中
        int i3 = tbIndentDao.selectOrderByStatus(date, dateType, 4);
        // 已完成
        int i4 = tbIndentDao.selectOrderByStatus(date, dateType, 6);
        //用户已取消
        int i5 = tbIndentDao.selectOrderByStatus(date, dateType, 8);
        //骑手已取消
        int i6 = tbIndentDao.selectOrderByStatus(date, dateType, 9);
        //平台取消
        int i7 = tbIndentDao.selectOrderByStatus(date, dateType, 10);
        hashMap.put("i", i);
        hashMap.put("i1", i1);
        hashMap.put("i2", i2);
        hashMap.put("i3", i3);
        hashMap.put("i4", i4);
        hashMap.put("i5", i5+i6+i7);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result findIncome(Long userId, String date, String dateType, Integer page, Integer limit) {
        HashMap hashMap = new HashMap();
        //收益统计
        BigDecimal incomeday = tbIndentDao.findAdminIncomeday(userId, date, dateType);
        BigDecimal prepayMoney = tbIndentDao.findPrepayMoney(userId, date, dateType);
        BigDecimal subtract = incomeday.subtract(prepayMoney);
        //接单数量
        int indentCount = tbIndentDao.findAdminIndentCount(userId, date, dateType);
        //接单详情
        Page<TbIndent> pages=new Page<>(page,limit);
        PageUtils pageUtils = new PageUtils(tbIndentDao.selectIndentById(pages, userId, date, dateType));

        hashMap.put("incomeday",subtract);
        hashMap.put("indentCount",indentCount);
        hashMap.put("pageUtils",pageUtils);
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result findUserIndent(Long userId, Integer page, Integer limit, String indentState) {
        Page<TbIndent> pages=new Page<>(page,limit);

        return Result.success().put("data",new PageUtils(tbIndentDao.findUserIndent(pages, userId,indentState)));
    }

    @Override
    public TbIndent userIndentMessage(String indentNumber) {

        return tbIndentDao.indentMessage(indentNumber);
    }

    @Override
    public Result find5KmRider(double lng, double lat) {
        List<UserEntity> kmRider = tbIndentDao.find5KmRider(lng, lat);
        return Result.success().put("data", kmRider);
    }

    @Override
    public Result updateCoordinate(Long userId, double lng, double lat) {
        tbIndentDao.updateCoordinate(userId, lng, lat);
        return Result.success();
    }

    @Override
    public UserEntity findUserInfoById(Long userId) {

        return tbIndentDao.findUserInfoById(userId);
    }

    @Transactional
    @Override
    public Result getNewUserRedPacket(Long userId) {
        //查看该用户是否是新用户
        UserEntity userInfoById = userDao.selectUserById(userId);
        if(1==userInfoById.getNewUserFlag()){
            ErrandRedPacket redPacket = new ErrandRedPacket();
            //如果是新用户，则可以领取新人红包
            //红包数额
            CommonInfo one = commonInfoService.findOne(297);
            BigDecimal redPacketAmount = new BigDecimal(one.getValue());
            //红包数量
            CommonInfo one1 = commonInfoService.findOne(298);
            Integer integer = Integer.valueOf(one1.getValue());
            //红包过期时间
            CommonInfo one2 = commonInfoService.findOne(299);
            Integer integer1 = Integer.valueOf(one2.getValue());

            Date date = new Date();
            Date addDate = addDate(integer1);
            String expirationTime = new SimpleDateFormat("yyyy-MM-dd").format(addDate);
            String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
            redPacket.setRedPacketType("0");
            redPacket.setRedPacketTitle("跑腿专用红包");
            redPacket.setMinimumAmount(new BigDecimal(0));
            for(int i = 0;i<integer; i++){
                userDao.addRedPacket(userId, redPacket.getRedPacketType(), redPacket.getMinimumAmount(), redPacketAmount, redPacket.getRedPacketTitle(), expirationTime, createTime);
            }
            //修改用户为非新用户
            int i = userDao.updateOldUser(userId);
            return Result.success();
        }
        return Result.error("本福利仅新用户可领取！");
    }


    public static Date addDate (int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, num);
        Date date = calendar.getTime();
        return date;
    }

    @Override
    public List<ErrandRedPacket> findAllRedPacket(Long userId) {
        String expirationTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        return tbIndentDao.findAllRedPacket(userId, expirationTime);
    }

    @Override
    public List<ErrandRedPacket> findRedPacket(Long userId, TbIndent indent) {

        return tbIndentDao.findRedPacket(userId, indent.getIndentType(), indent.getIndentBasicsMoney(), new Date());
    }

    @Transactional
    @Override
    public Result userCancleIndent(Long userId, String indentNumber) {
        //返回订单对象
        TbIndent indent1 = tbIndentDao.indentMessage(indentNumber);
        if("2".equals(indent1.getIndentState())){
            //退款给用户余额
            PayDetails payDetails = payDetailsDao.selectOne(new QueryWrapper<PayDetails>().eq("order_id", indent1.getPayOrdersNo()));
            if (payDetails.getType().equals(4)) {
                String code=AliPayController.alipayRefund(payDetails);
                if(StringUtils.isNotBlank(code)){
                    log.error(code);
                    JSONObject jsonObject = JSON.parseObject(code);
                    JSONObject alipay_trade_refund_response = jsonObject.getJSONObject("alipay_trade_refund_response");
                    String code1 = alipay_trade_refund_response.getString("code");
                    if(!"10000".equals(code1)){
                        return Result.error("退款失败！"+alipay_trade_refund_response.getString("sub_msg"));
                    }
                }else{
                    return Result.error("退款失败！");
                }
            } else {
                boolean flag = wxService.wxRefund(payDetails);
                if(!flag){
                    return Result.error("退款失败，请联系客服！");
                }
            }
        }
        int i = tbIndentDao.userCancleIndent(userId, indentNumber, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //将红包修改为未使用状态
        if (indent1.getRedPacketId() != null) {
            tbIndentDao.updateRedPaclet(indent1.getRedPacketId());
        }
        if(indent1.getOrderId()!=null){
            TbOrder order = appOrderService.getById(indent1.getOrderId());

            MessageInfo messageInfo1 = new MessageInfo();
            messageInfo1.setTitle("用户取消订单");
            messageInfo1.setCreateAt(DateUtils.format(new Date()));
            messageInfo1.setContent("用户取消订单，订单号："+order.getOrderNumber());
            messageInfo1.setShopId(order.getShopId());
            messageInfo1.setReadFlag(2);
            messageInfo1.setIsSee("1");
            messageService.save(messageInfo1);

            List<OrderGoods> orderGoodsList = orderGoodsDao.selectList(new QueryWrapper<OrderGoods>().eq("order_id", indent1.getOrderId()));
            for(int a = 0;a<orderGoodsList.size();a++){
                OrderGoods orderGoods = orderGoodsList.get(a);
                Integer goodsNum =orderGoods .getGoodsNum();
                Long goodsId = orderGoodsList.get(a).getGoodsId();
                GoodsShopRelevancy goodsShopRelevancy = goodsShopRelevancyDao.selectOne(new QueryWrapper<GoodsShopRelevancy>()
                        .eq("shop_id", order.getShopId()).eq("goods_id", goodsId));
                GoodsShopRelevancy goodsShopRelevancy1 = new GoodsShopRelevancy();
                goodsShopRelevancy1.setId(goodsShopRelevancy.getId());
                goodsShopRelevancy1.setSales(goodsShopRelevancy.getSales()-goodsNum);//加销量
                goodsShopRelevancy1.setInventory(goodsShopRelevancy.getInventory()+goodsNum);//减库存
                goodsShopRelevancyDao.updateById(goodsShopRelevancy1);
                goodsShopDao.updateShopSales(2,goodsNum, goodsShopRelevancy.getShopId());
            }
        }



        return Result.success().put("data", indent1);
    }


}





/*//小程序消息推送
            UserEntity userEntity = userService.selectUserById(indentByNumber.getUserId());
            UserEntity riderEntity = userService.selectUserById(userId);
            CommonInfo one = commonInfoService.findOne(268);
            List<String> msgList=new ArrayList<>();
            //服务项目
            String indentType="";
            if("1".equals(indentByNumber.getIndentType())){
                indentType = "帮我送";
            }else if("2".equals(indentByNumber.getIndentType())){
                indentType = "帮我取";
            }else if("3".equals(indentByNumber.getIndentType())){
                indentType = "同城帮买";
            }else if("4".equals(indentByNumber.getIndentType())){
                indentType = "同城服务";
            }
            msgList.add(0,indentType);
            //接单人员
            String nickName = userMessage.getNickName();
            msgList.add(1,nickName);
            //接单时间
            msgList.add(2,format);
            //备注
            String content="";
            if("1".equals(indentByNumber.getIndentType())||"2".equals(indentByNumber.getIndentType())){
                content = indentByNumber.getRemarks();
            }else if("3".equals(indentByNumber.getIndentType())){
                content = indentByNumber.getProductDetails();
            }else if("4".equals(indentByNumber.getIndentType())){
                content = indentByNumber.getServiceDetails();
            }
            if(content.length()>20){
                content=content.substring(0,15)+"...";
            }
            msgList.add(3,content);
            SenInfoCheckUtil.sendMsg(userEntity.getOpenId(),one.getValue(),msgList,1);
            SenInfoCheckUtil.sendMsg(riderEntity.getOpenId(),one.getValue(),msgList,1);
            //app端用户消息推送
            if(StringUtils.isNotEmpty(userEntity.getClientid())){
                String title = "";
                if("1".equals(indentByNumber.getIndentType())){
                    title = "帮我送";
                }else if("2".equals(indentByNumber.getIndentType())){
                    title = "帮我取";
                }else if("3".equals(indentByNumber.getIndentType())){
                    title = "同城帮买";
                }else if("4".equals(indentByNumber.getIndentType())){
                    title = "同城服务";
                }
                String contents = "亲爱的顾客，诚邀您为本次服务进行评价";
                userService.pushToSingle(title, contents, userEntity.getClientid());
            }
            //app端骑手消息推送
            if(StringUtils.isNotEmpty(riderEntity.getClientid())){
                String title = "";
                if("1".equals(indentByNumber.getIndentType())){
                    title = "帮我送";
                }else if("2".equals(indentByNumber.getIndentType())){
                    title = "帮我取";
                }else if("3".equals(indentByNumber.getIndentType())){
                    title = "同城帮买";
                }else if("4".equals(indentByNumber.getIndentType())){
                    title = "同城服务";
                }
                String contents = "订单已完成，服务费将在稍后返回到您的账户";
                userService.pushToSingle(title, contents, riderEntity.getClientid());
            }*/