package com.younike.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.younike.common.core.domain.AjaxResult;
import com.younike.hlpay.dto.PaymentParam;
import org.apache.commons.lang3.StringUtils;
import com.younike.common.utils.bean.BeanUtils;
import com.younike.common.utils.geo.DistanceUtil;
import com.younike.common.utils.id.OrderIndexGenerate;
import com.younike.hlpay.constant.PayType;
import com.younike.hlpay.dto.OrderParam;
import com.younike.hlpay.service.IPayService;
import com.younike.system.domain.*;
import com.younike.system.domain.vo.*;
import com.younike.system.enums.OrderRefundStateEnum;
import com.younike.system.enums.OrderStateEnum;
import com.younike.system.enums.ServerLevelEnum;
import com.younike.system.mapper.*;
import com.younike.system.param.OrderQueryParam;
import com.younike.system.param.OredrRefundParam;
import com.younike.system.service.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单主Service业务层处理
 *
 * @author elev
 * @date 2022-01-07
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderAddressMapper orderAddressMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private SysCodeMapper sysCodeMapper;

    @Autowired
    private OrderRefundMapper orderRefundMapper;

    @Autowired
    private MerchantMapper merchantMapper;


    /**
     * 会员地址
     */
    @Autowired
    private MemberAddressMapper memberAddressMapper;

    /**
     * 商品数据
     */
    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 订单商品
     */
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    /**
     * 服务人员
     */
    @Autowired
    private IServerUserService serverUserService;

    /**
     * 订单服务人员
     */
    @Autowired
    private IOrderGoodsServerService orderGoodsServerService;
    /**
     * 订单记录
     */
    @Autowired
    private IOrderRecordService orderRecordService;

    @Autowired
    private CategoryMapper categoryMapper;
    /**商家*/
    @Autowired
    private IMerchantService merchantService;

    @Autowired
    private CoinService coinService;
    @Autowired
    private ServerTimeSectionMapper serverTimeSectionMapper;
    @Autowired
    private IOrderRefundService orderRefundService;

    @Autowired
    private ISysCodeService sysCodeService;


    @Value("${wechat.xcx.openidUrl}")
    private String xcxOpenIdUrl;

    @Value("${wechat.xcx.appid}")
    private String xcxAppId;

    @Value("${wechat.xcx.secret}")
    private String xcxAppSecret;

    @Autowired
    private IPayService payService;

    /**
     * 商家结算
     */
    @Autowired
    private IMerchantSettleInfoService settleInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult doRefund(OrderRefund orderRefund) {
        if (orderRefund == null || StringUtils.isEmpty(orderRefund.getStatus()) || StringUtils.isEmpty(orderRefund.getRefundResult())) {
            return AjaxResult.error("参数错误");
        }
        System.err.println(JSONObject.toJSONString(orderRefund));
        OrderRefund oldRefund = orderRefundService.selectOrderRefundByOrderRefundId(orderRefund.getOrderRefundId());
        if (oldRefund == null) {
            return AjaxResult.error("退款数据不存在");
        }
        if (!"001".equals(oldRefund.getStatus())) {
            return AjaxResult.error("退款数据状态为已处理");
        }

        OrderRefund updateRefund = new OrderRefund();
        updateRefund.setOrderRefundId(orderRefund.getOrderRefundId());
        updateRefund.setStatus(orderRefund.getStatus());
        updateRefund.setRefundReply(orderRefund.getRefundReply());
        updateRefund.setUpdateTime(LocalDateTime.now());

        Order updateOrder = new Order();
        updateOrder.setOrderId(oldRefund.getOrderId());
        if (updateRefund.getStatus().equals("003")) {
            // 驳回
            updateOrder.setOrderState("007");
        } else if (updateRefund.getStatus().equals("004")) {
            // 同意
            updateRefund.setRefundMoney(orderRefund.getRefundMoney());
            Order order = orderMapper.selectOrderByOrderId(orderRefund.getOrderId());
            if (order == null) {
                return AjaxResult.error("数据错误");
            }
            if (updateRefund.getRefundMoney() == null) {
                return AjaxResult.error("退款金额不能为空");
            }
            if (updateRefund.getRefundMoney().compareTo(new BigDecimal(0)) < 1) {
                return AjaxResult.error("退款金额不能小余0");
            }
            if (updateRefund.getRefundMoney().compareTo(order.getTotalAmount()) == 1) {
                return AjaxResult.error("退款金额不能大于实付金额");
            }

            updateOrder.setOrderState("006");
        } else {
            return AjaxResult.error("数据异常");
        }
        this.updateOrder(updateOrder);
        orderRefundService.updateOrderRefund(updateRefund);

        /**
         * 数据库更新完成之后，再处理外部退款
         */
        if (updateRefund.getStatus().equals("004")) {
            //todo 退钱，退优金豆
            System.err.println("退钱，退优金豆");
        }
        return AjaxResult.success();
    }

    @Override
    public List<OrderVo> orderList(OrderQueryParam param) {
        return orderMapper.orderList(param);
    }

    /**
     * 查询订单主
     *
     * @param orderId 订单主主键
     * @return 订单主
     */
    @Override
    public Order selectOrderByOrderId(Long orderId) {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    /**
     * 查询订单主列表
     *
     * @param order 订单主
     * @return 订单主
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单主
     *
     * @param order 订单主
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        order.setCreateTime(LocalDateTime.now());
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改订单主
     *
     * @param order 订单主
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        order.setUpdateTime(LocalDateTime.now());
        return orderMapper.updateOrder(order);
    }


    /**
     * 批量删除订单主
     *
     * @param orderIds 需要删除的订单主主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(Long[] orderIds) {
        return orderMapper.deleteOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单主信息
     *
     * @param orderId 订单主主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(Long orderId) {
        return orderMapper.deleteOrderByOrderId(orderId);
    }

    /**
     * 修改订单主
     *
     * @param order 订单主
     * @return 结果
     */
    @Override
    public int updateOrderCustom(Order order) {
        // todo 如果是待服务   1.需要获取当前经纬度存下来
        // todo              2.判断距离客户地址是否200米范围内 ，若在范围内才允许更改状态
        //配送范围
//        BigDecimal maxDeliverDistance = BigDecimal.valueOf(merchant.getServiceDistance());
        if("002".equals(order.getOrderState())){

            BigDecimal maxDeliverDistance = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("home.server.maxDistance").getConfigValue());
            //商家与会员距离
            BigDecimal shortestDistance = null;
            OrderAddress orderAddress = orderAddressMapper.selectOrderAddressByOrderId(order.getOrderId());
            // 计算距离
            shortestDistance = DistanceUtil.getShortestDistance(order.getServiceLatitude(),
                    order.getServiceLongitude(), orderAddress.getAddressLatitude(), orderAddress.getAddressLongitude());

            //验证坐标是否超出范围
            if(shortestDistance.compareTo(maxDeliverDistance)>0){
                //超出配送范围
                return 999;
            }
        }
        order.setUpdateTime(LocalDateTime.now());
//        order.setUpdateBy(getUsername());
        return orderMapper.updateOrderCustom(order);
    }

    /**
     * 查询近days天的特定订单状态（orderStates）订单列表
     *
     * @param days 天数
     * @param orderStates 订单状态
     * @return 订单列表
     */
    @Override
    public List<OrderStat> listLastOrders(int days, String[] orderStates) {
        return orderMapper.listLastOrders(days, StringUtils.join(orderStates, ","));
    }

    /**
     * 查询会员端订单分页列表
     *
     * @param order
     * @return
     */
    @Override
    public List<MemberOrderVo> listMemberOrderByOrderState(Order order) {
        String[] orderStateArr = new String[]{};
        if (StringUtils.isNotEmpty(order.getOrderState())) {
            orderStateArr = order.getOrderState().split(",");
        }

        // 查询会员订单列表
        List<MemberOrderVo> memberOrderVoList = orderMapper.listMemberOrderByOrderState(order, Arrays.asList(orderStateArr));
        if (StringUtils.isNotEmpty(order.getOrderState()) && Objects.equals("004", order.getOrderState())) {
            // 筛选出待评价订单
            memberOrderVoList = memberOrderVoList.stream()
                    .filter(vo -> Objects.equals("001", vo.getCommentState())).collect(Collectors.toList());
        }
        // 查询订单状态等字典值
        if (CollectionUtils.isNotEmpty(memberOrderVoList)) {
            for (MemberOrderVo vo : memberOrderVoList) {
                // 获取订单状态名称
                vo.setOrderStateName(OrderStateEnum.getDescription(vo.getOrderState()));
                // 获取家政等级名称
                vo.setServerLevelName(ServerLevelEnum.getDescription(vo.getServerLevel()));
                // 查询商品单位名称
                SysCode sysCode = sysCodeMapper.getByCodeIdAndDecodeId("011", vo.getGoodsUnit());
                vo.setGoodsUnitName(sysCode == null ? StringUtils.EMPTY : sysCode.getDecodeValue());
            }
        }
        return memberOrderVoList;
    }

    /**
     * 会员下单
     *
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult addOrder(OrderParam param) {

        if(param.getGoodsCoin()!=null) {
            if(param.getGoodsCoin()>500){
                throw new ArithmeticException("优金豆使用不得超过500");
            }

            //如果使用优金豆或者优惠券，调用远程接口减少用户优金豆数量
            if (param.getGoodsCoin() > 0) {
                FamilyParam familyParam = new FamilyParam();
                familyParam.setNum(BigDecimal.valueOf(-param.getGoodsCoin()));
                familyParam.setPhone(param.getPhone());
                String jsonCode = coinService.increasePoints(familyParam);
                if (!jsonCode.equals("200")) {
                    throw new ArithmeticException("预约失败，优金豆扣除失败");
                }
            }
        }
        BigDecimal multiply = new BigDecimal(param.getGoodsCounts()).multiply(param.getSingleTime());
        param.setAppointmentEndTime(param.getAppointmentStartTime().plusHours(multiply.longValue()));
        //创建订单对象
        Order order = new Order();
        BeanUtils.copyProperties(param, order);
        // 校验订单时间是否以及被预约
        List<Order> orders = orderMapper.getOrderList(param);
        if(orders.size()>0){
            throw new ArithmeticException("预约失败，超出可预约时间范围");
        }
        //验证预约结束世界是否超出服务人员工作时间
        //星期几
        //验证预约结束世界是否超出服务人员工作时间
        //星期几
        int week = param.getAppointmentEndTime().getDayOfWeek().getValue();
        //时间：时分秒
        LocalTime localTime = param.getAppointmentEndTime().toLocalTime();
        ServerTimeSection serverTimeSection = new ServerTimeSection();
        serverTimeSection.setSectionId(param.getServerId());
        serverTimeSection.setWeeks(String.valueOf(week));
        //查询工作人员工作时间
        ServerTimeSection section =serverTimeSectionMapper.selectSectionWeek(serverTimeSection);

        if(ObjectUtils.isEmpty(section)){
            throw new ArithmeticException("预约失败,超出可预约时间范围");
        }
        if(localTime.isAfter(section.getHoursEnd())){
            throw new ArithmeticException("预约失败,超出可预约时间范围");
        }
        Merchant merchant = merchantService.selectMerchantByMerchantId(param.getMerchantId());
        if (ObjectUtils.isEmpty(merchant)) {
            //抛出异常
            throw new ArithmeticException("商家不存在");
        }
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        order.setOrderState("000");
        order.setCommentState("001");

        //平台抽成百分比
        BigDecimal percaent = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("platform.commission.rate").getConfigValue());
        //商家可得到 实付总价减去平台抽成
        BigDecimal shopAmount= param.getTotalAmount().subtract(param.getTotalAmount().multiply(percaent).divide(new BigDecimal(100),2,BigDecimal.
                ROUND_HALF_UP));
        //判断优金豆抵扣金额
        if(order.getBeanAmount()!=null){
            shopAmount.add(new BigDecimal(order.getBeanAmount()));
        }
        order.setShopAmount(shopAmount);

        order.setMerchantName(merchant.getMerchantName());
        if (orderMapper.addOrder(order) < 1) {
            throw new ArithmeticException("添加订单失败");
        }
        //生成订单编号
        String index = OrderIndexGenerate.getIndexByOrderId(order.getOrderId());
        //更新数据
        Order orderIndex = new Order();
        orderIndex.setOrderId(order.getOrderId());
        orderIndex.setOrderIndex(index);
        orderIndex.setUpdateTime(LocalDateTime.now());
        if (orderMapper.updateOrderCustom(orderIndex) < 1) {
            throw new ArithmeticException("更新订单编号失败");
        }

        //order表添加数据
        //order_address 订单地址添加
        //根据地址id查询地址数据
        MemberAddress memberAddress = memberAddressMapper.selectMemberAddressByAddressId(param.getAddressId());
        if (ObjectUtils.isEmpty(memberAddress)) {
            //抛出异常
            throw new ArithmeticException("没有此会员地址");
        }

        //商家与会员距离
        BigDecimal shortestDistance = null;
        // 计算距离
        shortestDistance = DistanceUtil.getShortestDistance( merchant.getLatitude(), merchant.getLongitude(),memberAddress.getLatitude(),
                memberAddress.getLongitude());

        BigDecimal maxDeliverDistance =null;
        if(merchant.getServiceDistance()==null){
            maxDeliverDistance = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("home.server.distance").getConfigValue());

        }else {
            maxDeliverDistance  = new BigDecimal(String.valueOf(merchant.getServiceDistance()));
        }

        //验证坐标是否超出范围
        if(shortestDistance.compareTo(maxDeliverDistance)>0){
            //超出配送范围
            throw new ArithmeticException("下单失败订单地址超出服务范围");
        }


        //订单服务地址表
        OrderAddress orderAddress = new OrderAddress();
        BeanUtils.copyProperties(memberAddress, orderAddress);
        orderAddress.setCreateTime(LocalDateTime.now());
        orderAddress.setUpdateTime(LocalDateTime.now());
        orderAddress.setOrderId(order.getOrderId());
        orderAddress.setAddressLongitude(memberAddress.getLongitude());
        orderAddress.setAddressLatitude(memberAddress.getLatitude());
        if (orderAddressMapper.insertOrderAddress(orderAddress) < 1) {
            throw new ArithmeticException("添加订单服务地址表失败");
        }
        //查询商品数据
        Goods goods = goodsMapper.selectGoodsByGoodsId(param.getGoodsId());
        if (ObjectUtils.isEmpty(goods)) {
            throw new ArithmeticException("商品不存在");
        }
        if (goods.getIsSale() == 2) {
            throw new ArithmeticException("商品已售空");
        }
        //order_goods 订单商品添加数据
        OrderGoods orderGoods = new OrderGoods();
        BeanUtils.copyProperties(goods, orderGoods);
        orderGoods.setOrderId(order.getOrderId());
        orderGoods.setServerId(param.getServerId());
        orderGoods.setGoodsCounts(param.getGoodsCounts());
        orderGoods.setPrice(param.getPrice());
        orderGoods.setCreateTime(LocalDateTime.now());
        orderGoods.setUpdateTime(LocalDateTime.now());
        if (orderGoodsMapper.insertOrderGoods(orderGoods) < 1) {
            throw new ArithmeticException("添加订单商品失败");
        }

        //查询服务人员数据
        ServerUser serverUser = serverUserService.selectServerUserByServerId(param.getServerId());
        if (ObjectUtils.isEmpty(serverUser)) {
            throw new ArithmeticException("服务人员不存在");
        }
        //order_goodes_server 订单服务人员添加数据
        OrderGoodsServer orderGoodsServer = new OrderGoodsServer();
        BeanUtils.copyProperties(param, orderGoodsServer);
        //订单id
        orderGoodsServer.setOrderId(order.getOrderId());
        //商品名称
        orderGoodsServer.setGoodsName(goods.getName());
        //商品服务人员单价
        orderGoodsServer.setGoodsServerPrice(param.getPrice());
        //商品单位
        orderGoodsServer.setGoodsUnit(goods.getGoodsUnit());
        //服务人员姓名
        orderGoodsServer.setServerName(serverUser.getRealName());
        //服务人员性别
        orderGoodsServer.setServerSex(serverUser.getSex());
        //工龄
        orderGoodsServer.setServerAge(serverUser.getAge());
        //服务人员头像
        orderGoodsServer.setServerAvatar(serverUser.getAvatar());
        //创建时间
        orderGoodsServer.setCreateTime(LocalDateTime.now());
        orderGoodsServer.setUpdateTime(LocalDateTime.now());
        if (orderGoodsServerService.insertOrderGoodsServer(orderGoodsServer) < 1) {
            throw new ArithmeticException("添加订单服务人员关联数据失败");
        }

        //order_record 添加订单记录
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setOrderId(order.getOrderId());
        orderRecord.setPreState("000");
        orderRecord.setNowState("000");
        orderRecord.setCreateTime(LocalDateTime.now());
        orderRecord.setUpdateTime(LocalDateTime.now());
        orderRecord.setOperateInfo(sysCodeService.getDecodeValue("003","000"));
        if (orderRecordService.insertOrderRecord(orderRecord) < 1) {
            throw new ArithmeticException("添加订单记录失败");
        }


        return AjaxResult.success();
    }


    /**
     * 查询会员订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public MemberOrderDetailVo getMemberOrderByOrderId(Long orderId) {
        // 查询会员订单详情
        MemberOrderDetailVo memberOrderDetailVo = orderMapper.getMemberOrderByOrderId(orderId);
        if (memberOrderDetailVo == null) {
            return null;
        }
        // 获取商家电话
        Merchant merchant = merchantMapper.selectMerchantByMerchantId(memberOrderDetailVo.getMerchantId());
        memberOrderDetailVo.setMerchantPhone(merchant == null ? StringUtils.EMPTY : merchant.getMerchantPhone());
        // 获取订单状态名称
        memberOrderDetailVo.setOrderStateName(OrderStateEnum.getDescription(memberOrderDetailVo.getOrderState()));
        // 获取家政等级名称
        memberOrderDetailVo.setServerLevelName(ServerLevelEnum.getDescription(memberOrderDetailVo.getServerLevel()));
        // 获取服务类别名称
        if (!Objects.isNull(memberOrderDetailVo.getCateId())) {
            Category category = categoryMapper.selectCategoryByCategoryId(memberOrderDetailVo.getCateId());
            memberOrderDetailVo.setCateName(category == null ? StringUtils.EMPTY : category.getCategoryName());
            if (!Objects.isNull(category) && !Objects.isNull(category.getParentId())) {
                // 查询父级分类名称
                Category parentCategory = categoryMapper.selectCategoryByCategoryId(Long.valueOf(category.getParentId()));
                memberOrderDetailVo.setParentCateName(parentCategory == null ? StringUtils.EMPTY : parentCategory.getCategoryName());
            }
        }
        // 获取商品单位名称
        if (StringUtils.isNotBlank(memberOrderDetailVo.getGoodsUnit())) {
            SysCode sysCode = sysCodeMapper.getByCodeIdAndDecodeId("011", memberOrderDetailVo.getGoodsUnit());
            memberOrderDetailVo.setGoodsUnitName(sysCode == null ? StringUtils.EMPTY : sysCode.getDecodeValue());
        }
        // 已申请退款/已退款
        if (Objects.equals(OrderStateEnum.PENDING_REFUNDED.getCode(), memberOrderDetailVo.getOrderState())
                || Objects.equals(OrderStateEnum.REFUNDED.getCode(), memberOrderDetailVo.getOrderState()) ) {
            // 查询退款信息
            OrderRefund orderRefund = orderRefundMapper.getByOrderId(orderId);
            if (orderRefund != null) {
                memberOrderDetailVo.setPayMoney(orderRefund.getPayMoney());
                memberOrderDetailVo.setRefundReason(orderRefund.getRefundReason());
                memberOrderDetailVo.setRefundMoney(orderRefund.getRefundMoney());
                memberOrderDetailVo.setRefundState(orderRefund.getStatus());
                memberOrderDetailVo.setRefundStateName(OrderRefundStateEnum.getDescription(orderRefund.getStatus()));
            }
        }

        return memberOrderDetailVo;
    }

    /**
     * 订单支付
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult editOrder(PaymentParam param) {
        String qrcode = null;
        //根据订单id查询订单数据
        Order order = orderMapper.selectOrderByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(order)){
            return AjaxResult.error("订单不存在");
        }

        if(param.getTotalAmount().compareTo(order.getOrderAmount()) != 0){
            return AjaxResult.error("付款金额与订单金额不符");
        }
        //验证订单状态000（提交订单待支付）
        if(!"000".equals(order.getOrderState())){
            return AjaxResult.error("订单非支付状态");
        }
        //查询订单商品的商家信息
        Merchant merchant = merchantMapper.selectMerchantByMerchantId(order.getMerchantId());
        if(ObjectUtils.isEmpty(merchant)){
            return AjaxResult.error("商品商家不存在");
        }
        param.setMerchantType(merchant.getMerchantType());
        //商家
        if(merchant.getMerchantType().equals(0)){
            //查询商家合利宝邮箱
            MerchantSettleInfo merchantSettleInfo = settleInfoService.selectMerchantSettleInfoByMerchantId(merchant.getMerchantId());
            if(ObjectUtils.isEmpty(merchantSettleInfo)) {
                return AjaxResult.error("商品合利宝账户不存在");
            }
            param.setEmail(merchantSettleInfo.getEmail());
        }

        //平台抽成百分比
        BigDecimal percaent = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("platform.commission.rate").getConfigValue());
        BigDecimal shopAmount= order.getTotalAmount().subtract(order.getTotalAmount().multiply(percaent).divide(new BigDecimal(100),2,BigDecimal.
                ROUND_HALF_UP));
       //判断有无使用优金豆，如果有，加上优金豆优惠金额
        //判断优金豆抵扣金额
        if(order.getBeanAmount()!=null){
            shopAmount.add(new BigDecimal(order.getBeanAmount()));
        }
        //商家可得金额
        param.setShopAmount(shopAmount);

        //进行支付
        // 001微信 002支付宝
        if("001".equals(param.getPayWay()) && StringUtils.equals(param.getPayType(), PayType.APPLET.name())){
            // 获取用户openId
            String openId = getOpenId(param.getCode());
            if (StringUtils.isBlank(openId)) {
                return AjaxResult.error("OpenId获取异常");
            }
            Map<String, Object> resultMap = payService.hlbPay(param, openId);

            // 支付结果
            if (resultMap != null && (Integer) resultMap.get("statusCode") == HttpStatus.SC_OK) {
                String resultMsg = (String) resultMap.get("response");
                AppPayPublicOrderResponseVo orderResponseVo = JSONObject.parseObject(resultMsg, AppPayPublicOrderResponseVo.class);
                if (StringUtils.isBlank(orderResponseVo.getRt10_payInfo())) {
                    return AjaxResult.error(orderResponseVo.getRt3_retMsg());
                }

            }
        }else if("002".equals(param.getPayWay()) && StringUtils.equals(param.getPayType(), PayType.SDK.name())){
//            log.info("APP（SDK）预下单 -- 支付宝");
            Map<String, Object> resultMap = payService.hlbPay(param, null);

            String resultMsg = (String) resultMap.get("response");
            CreateOrderResponseVo orderResponseVo = JSONObject.parseObject(resultMsg, CreateOrderResponseVo.class);
            qrcode = orderResponseVo.getRt8_qrcode();
            if (StringUtils.isBlank(qrcode)) {
                return AjaxResult.error(orderResponseVo.getRt3_retMsg());
            }
        }else {
            return AjaxResult.error("支付方式不正确");
        }

        //支付成功后
        order.setUpdateTime(LocalDateTime.now());
        order.setOrderState("001");
        order.setIsSettle(1);
        order.setPayWay(param.getPayWay());
        order.setTotalAmount(param.getTotalAmount());
        order.setShopAmount(shopAmount);
        if(orderMapper.updateOrderCustom(order)<0){
            throw new ArithmeticException("更新订单信息失败");
        }
        //根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordService.selectRefunfd(order.getOrderId());
        OrderRecord record = new OrderRecord();
        if(!ObjectUtils.isEmpty(orderRecord)){
            record.setPreState(orderRecord.getNowState());
        }
        record.setOrderId(order.getOrderId());
        record.setNowState("001");
        record.setOperateInfo(sysCodeService.getDecodeValue("003","001"));
        if(orderRecordService.insertOrderRecord(record)<1){
            throw new ArithmeticException("添加订单追踪信息失败");
        }
        return AjaxResult.success(StringUtils.EMPTY, qrcode);
    }

    /**
     * 申请平台退款
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult applyForRefund(OredrRefundParam param) {
        //根据订单id查询订单数据
        Order order = orderMapper.selectOrderByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(order)){
            return AjaxResult.error("订单不存在");
        }
        //查询申请退款记录
        OredrRefundParam refund = orderRefundService.selectOrderId(param.getOrderId());
        if(!ObjectUtils.isEmpty(refund)){
            return AjaxResult.error("请务重复提交申请");
        }

        order.setOrderState("005");
        order.setUpdateTime(LocalDateTime.now());
        if(orderMapper.updateOrderCustom(order)<0){
            throw new ArithmeticException("更新订单信息失败");
        }

        //根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordService.selectRefunfd(order.getOrderId());
        OrderRecord record = new OrderRecord();
        if(!ObjectUtils.isEmpty(orderRecord)){
            record.setPreState(orderRecord.getNowState());
        }
        record.setOrderId(order.getOrderId());
        record.setNowState("005");
        record.setOperateInfo(sysCodeService.getDecodeValue("003","005"));
        if(orderRecordService.insertOrderRecord(record)<1){
            throw new ArithmeticException("添加订单追踪信息失败");
        }

        //添加一条退款处理
        OredrRefundParam oredrRefundParam = new OredrRefundParam();
        BeanUtils.copyProperties(param,oredrRefundParam);
        //需要退回金额是实际付款金额
        oredrRefundParam.setPayMoney(order.getTotalAmount());
        //退款状态
        oredrRefundParam.setStatus("001");
        if(orderRefundService.insertOrderRefund(oredrRefundParam)<1){
            throw new ArithmeticException("添加退款处理记录失败");
        }


        return AjaxResult.success();
    }

    /**
     * 取消订单
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult cancal (OredrRefundParam param) {
        //根据订单id查询订单数据
        Order order = orderMapper.selectOrderByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(order)){
            return AjaxResult.error("订单不存在");
        }
        if(!"000".equals(order.getOrderState())){
            return AjaxResult.error("订单待服务，不可取消");
        }

        order.setOrderState("099");
        order.setUpdateTime(LocalDateTime.now());
        if(orderMapper.updateOrderCustom(order)<0){
            throw new ArithmeticException("更新订单信息失败");
        }
        //根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordService.selectRefunfd(order.getOrderId());
        OrderRecord record = new OrderRecord();
        if(!ObjectUtils.isEmpty(orderRecord)){
            record.setPreState(orderRecord.getNowState());
        }
        record.setOrderId(order.getOrderId());
        record.setNowState("099");
        record.setOperateInfo(sysCodeService.getDecodeValue("003","099"));
        if(orderRecordService.insertOrderRecord(record)<1){
            throw new ArithmeticException("添加订单追踪信息失败");
        }
        return AjaxResult.success();
    }

    /**
     * 追加服务
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult addServer(OrderParam param) {

        //根据订单id查询订单数据
        Order order = orderMapper.selectOrderByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(order)){
            return AjaxResult.error("订单不存在");
        }
        //进行付款付款
        Integer addCounts = param.getAddCounts();
        //追加时间（小时）
        BigDecimal multiply = new BigDecimal(param.getAddCounts()).multiply(param.getSingleTime());
        //计算追加时长

        //付款成功后
        Order orderAdd = new Order();
        orderAdd.setOrderId(param.getOrderId());
        orderAdd.setAddAmount(param.getAddAmount());
        orderAdd.setAddPayStatus(1);
        orderAdd.setAddPayWay(param.getAddPayWay());
        orderAdd.setAppointmentEndTime(order.getAppointmentEndTime().plusHours(multiply.longValue()));
        orderAdd.setTotalAmount(order.getTotalAmount().add(param.getAddAmount()));
        //商家可得金额进行更改
        //平台抽成百分比
        BigDecimal percaent = new BigDecimal(sysConfigMapper.checkConfigKeyUnique("platform.commission.rate").getConfigValue());
        //商家可得到 实付总价减去平台抽成
        BigDecimal shopAmount= orderAdd.getTotalAmount().subtract(orderAdd.getTotalAmount().multiply(percaent).divide(new BigDecimal(100),2,BigDecimal.
                ROUND_HALF_UP));
        orderAdd.setShopAmount(shopAmount);

        orderAdd.setUpdateTime(LocalDateTime.now());
        //更新订单数据
        if(orderMapper.updateOrderCustom(orderAdd)<1){
            throw new ArithmeticException("订单更新失败");
        }
        OrderGoods orderGoods = orderGoodsMapper.selectOrderGoodsByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(orderGoods)){
            throw new ArithmeticException("订单商品表不存在失败");
        }
        orderGoods.setAddCounts(param.getAddCounts());
        orderGoods.setUpdateTime(LocalDateTime.now());
        if(orderGoodsMapper.updateOrderGoods(orderGoods)<1){
            throw new ArithmeticException("订单商品表更新失败");
        }

        //订单变更记录
        //根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordService.selectRefunfd(order.getOrderId());
        OrderRecord record = new OrderRecord();
        if(!ObjectUtils.isEmpty(orderRecord)){
            record.setPreState(orderRecord.getNowState());
            record.setNowState(orderRecord.getNowState());
        }
        record.setOrderId(order.getOrderId());
        record.setOperateInfo("追加服务");
        if(orderRecordService.insertOrderRecord(record)<1){
            throw new ArithmeticException("添加订单追踪信息失败");
        }
        return AjaxResult.success();

    }

    /**
     * 确认完成
     * @param param
     * @return
     */
    @Override
    @Transactional
    public AjaxResult affirm(OredrRefundParam param) {

        //根据订单id查询订单数据
        Order order = orderMapper.selectOrderByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(order)){
            return AjaxResult.error("订单不存在");
        }
        if(!"003".equals(order.getOrderState())){
            return AjaxResult.error("订单不可点击完成");
        }
        order.setUpdateTime(LocalDateTime.now());
        order.setOrderState("004");
        //更新订单数据
        if(orderMapper.updateOrderCustom(order)<1){
            throw new ArithmeticException("订单更新失败");
        }

        //根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordService.selectRefunfd(order.getOrderId());
        OrderRecord record = new OrderRecord();
        if(!ObjectUtils.isEmpty(orderRecord)){
            record.setPreState(orderRecord.getNowState());
        }
        record.setOrderId(order.getOrderId());
        record.setNowState("004");
        record.setOperateInfo(sysCodeService.getDecodeValue("003","004"));
        if(orderRecordService.insertOrderRecord(record)<1){
            throw new ArithmeticException("添加订单追踪信息失败");
        }
        return AjaxResult.success();
    }

    /**
     * 取消申请平台介入
     * @param param
     * @return
     */
    @Override
    public AjaxResult cancelRefund(OrderParam param) {

        //根据订单id查询订单数据
        Order order = orderMapper.selectOrderByOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(order)){
            return AjaxResult.error("订单不存在");
        }
        //查询
        OredrRefundParam refund = orderRefundService.selectOrderId(param.getOrderId());
        if(ObjectUtils.isEmpty(refund)){
            return AjaxResult.error("退款申请不存在");
        }
        if(!"005".equals(refund.getStatus())){
            return AjaxResult.error("退款申请已处理，不可取消");
        }

        order.setUpdateTime(LocalDateTime.now());
        order.setOrderState("002");
        //更新订单数据
        if(orderMapper.updateOrderCustom(order)<1){
            throw new ArithmeticException("订单更新失败");
        }
        //删除
        if(orderRefundService.deleteOrderRefundByOrderRefundId(refund.getOrderRefundId())<1){
            throw new ArithmeticException("取消申请平台介入失败");
        }

        //根据订单id查询最近一条订单记录数据
        OrderRecord orderRecord = orderRecordService.selectRefunfd(order.getOrderId());
        OrderRecord record = new OrderRecord();
        if(!ObjectUtils.isEmpty(orderRecord)){
            record.setPreState(orderRecord.getNowState());
        }
        record.setOrderId(order.getOrderId());
        record.setNowState("002");
        record.setOperateInfo(sysCodeService.getDecodeValue("003","002"));
        if(orderRecordService.insertOrderRecord(record)<1){
            throw new ArithmeticException("添加订单追踪信息失败");
        }
        return AjaxResult.success();

    }

    /**
     * @param settleDate 结算截止时间
     */
    @Override
    public Map<Long, List<Order>> selectPreSettleOrders(Date settleDate) {
        List<Order> list = orderMapper.selectPreSettleOrders(settleDate);
        if (list != null && list.size() > 0) {
            return list.stream().collect(Collectors.groupingBy(Order::getMerchantId));
        }
        return null;
    }

    @Override
    public boolean updateBatchById(List<Order> updated) {
        return orderMapper.updateBatchById(updated);
    }

    /**
     * 获取微信OpenID
     *
     * @param code 微信授权code
     */
    private String getOpenId(String code) {
        //微信的接口url地址
        String url = xcxOpenIdUrl + "?appid=" + xcxAppId +
                "&secret=" + xcxAppSecret + "&js_code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        //进行网络请求,访问url接口
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        if (responseEntity.getStatusCode() == org.springframework.http.HttpStatus.OK) {
            String sessionData = responseEntity.getBody();
            //下面是把拿到的json字符串转成 json对象
            com.alibaba.fastjson.JSONObject jsStr = com.alibaba.fastjson.JSONObject.parseObject(sessionData);
            //解析从微信服务器获得的openid和session_key;获取用户的唯一标识
            return jsStr.getString("openid");
        }
//        log.error("获取OpenId失败, code：" + code + "，\n 返回："  + JSON.toJSONString(responseEntity));
        return null;
    }
}
