package com.ruoyi.frequency.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.code.DictConstant;
import com.ruoyi.code.PublicCommon;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.enums.CoreExceptionEnum;
import com.ruoyi.common.page.PageResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.controller.req.*;
import com.ruoyi.controller.resp.AppealDetailResp;
import com.ruoyi.controller.resp.OrderDataResp;
import com.ruoyi.controller.resp.OrderDetailResp;
import com.ruoyi.controller.resp.OrderPageResp;
import com.ruoyi.enums.IntegralDetailEnums;
import com.ruoyi.enums.PlatformRecordEnums;
import com.ruoyi.enums.WalletDetailEnums;
import com.ruoyi.enums.message.OrderMessageEnums;
import com.ruoyi.enums.order.OrderPriceEnums;
import com.ruoyi.enums.order.OrderStatusEnums;
import com.ruoyi.enums.process.ProcessResultEnums;
import com.ruoyi.enums.user.UserEnums;
import com.ruoyi.frequency.appeal.entity.Appeal;
import com.ruoyi.frequency.appeal.service.AppealService;
import com.ruoyi.frequency.appealdetail.entity.AppealDetail;
import com.ruoyi.frequency.appealdetail.service.AppealDetailService;
import com.ruoyi.frequency.auth.entity.Auth;
import com.ruoyi.frequency.auth.service.AuthService;
import com.ruoyi.frequency.block.entity.Block;
import com.ruoyi.frequency.block.service.BlockService;
import com.ruoyi.frequency.customer.mapper.CustomerMapper;
import com.ruoyi.frequency.customer.service.CustomerService;
import com.ruoyi.frequency.customer.service.UserService;
import com.ruoyi.frequency.givewallerecord.service.GiveWalletRecordService;
import com.ruoyi.frequency.highendauth.entity.HighendAuth;
import com.ruoyi.frequency.highendauth.service.HighendAuthService;
import com.ruoyi.frequency.integralrecord.service.IntegralRecordService;
import com.ruoyi.frequency.onlinerecord.service.OnlineRecordService;
import com.ruoyi.frequency.order.entity.Order;
import com.ruoyi.frequency.order.mapper.OrderMapper;
import com.ruoyi.frequency.order.model.result.OrderCount;
import com.ruoyi.frequency.order.service.OrderService;
import com.ruoyi.frequency.orderchangerecord.entity.OrderChangeRecord;
import com.ruoyi.frequency.orderchangerecord.service.OrderChangeRecordService;
import com.ruoyi.frequency.orderevaluate.entity.OrderEvaluate;
import com.ruoyi.frequency.orderevaluate.service.OrderEvaluateService;
import com.ruoyi.frequency.orderextensionrecord.entity.OrderExtensionRecord;
import com.ruoyi.frequency.orderextensionrecord.service.OrderExtensionRecordService;
import com.ruoyi.frequency.ordermessage.service.OrderMessageService;
import com.ruoyi.frequency.orderoperatorhistory.entity.OrderOperatorHistory;
import com.ruoyi.frequency.orderoperatorhistory.service.OrderOperatorHistoryService;
import com.ruoyi.frequency.orderpanorama.entity.OrderPanorama;
import com.ruoyi.frequency.orderpanorama.service.OrderPanoramaService;
import com.ruoyi.frequency.orderpricerecord.service.OrderPriceRecordService;
import com.ruoyi.frequency.orderreceiving.entity.OrderReceiving;
import com.ruoyi.frequency.orderreceiving.service.OrderReceivingService;
import com.ruoyi.frequency.platformrecord.service.PlatformRecordService;
import com.ruoyi.frequency.refereeuser.entity.RefereeUser;
import com.ruoyi.frequency.refereeuser.service.RefereeUserService;
import com.ruoyi.frequency.store.entity.Store;
import com.ruoyi.frequency.store.mapper.StoreMapper;
import com.ruoyi.frequency.store.service.StoreService;
import com.ruoyi.frequency.wallerecord.service.WalletRecordService;
import com.ruoyi.frequency.works.entity.Works;
import com.ruoyi.frequency.works.service.WorksService;
import com.ruoyi.frequency.workspanorama.entity.WorksPanorama;
import com.ruoyi.frequency.workspanorama.service.WorksPanoramaService;
import com.ruoyi.pay.enums.PayEnums;
import com.ruoyi.pay.enums.PaySourceEnums;
import com.ruoyi.pay.utils.AlipayCore;
import com.ruoyi.pay.utils.HttpRequestUtil;
import com.ruoyi.pay.utils.PayUtil;
import com.ruoyi.response.ResponseData;
import com.ruoyi.utils.BusinessUtil;
import com.ruoyi.vo.BodyIdReq;
import com.ruoyi.vo.PayVo;
import com.ruoyi.vo.UserInfo;
import com.ruoyi.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.ruoyi.enums.message.OrderMessageEnums.EVALUATE_ORDER;

/**
 * 订单主Service业务层处理
 *
 * @author zj
 * @date 2023-10-13
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderEvaluateService orderEvaluateService;

    @Autowired
    private AppealDetailService appealDetailService;


    /**
     * 查询订单主
     *
     * @param id 订单主主键
     * @return 订单主
     */
    @Override
    public Order selectOrderById(Long id) {
        Order order = orderMapper.selectOrderById(id);

        if (order != null) {

            Set<UserVo> userVoSet = new HashSet<>();
            userVoSet.add(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()));
            userVoSet.add(new UserVo(UserEnums.store.getCode(), order.getStoreId()));

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            order.setStoreInfo(userMap.get(new UserVo(UserEnums.store.getCode(), order.getStoreId())));
            order.setCustomerInfo(userMap.get(new UserVo(UserEnums.customer.getCode(), order.getCustomerId())));

            //查询3D图
            List<OrderPanorama> panoramaList = orderPanoramaService.list(new QueryWrapper<OrderPanorama>().lambda()
                    .eq(OrderPanorama::getDelFlag, PublicCommon.启用)
                    .eq(OrderPanorama::getOrderId, id).orderByDesc(BaseEntity::getCreateTime));
            order.setPanoramaList(panoramaList);

            //查询最新一条申诉
            Appeal appeal = appealService.getOne(new QueryWrapper<Appeal>().lambda()
                    .eq(Appeal::getOrderId, id).orderByDesc(BaseEntity::getCreateTime).last("limit 1"));

            if (appeal != null) {
                AppealDetailResp appealDetailResp = appealService.appealDetail(appeal.getId(), null).getData();

                List<AppealDetail> appealDetailList = appealDetailService.list(new QueryWrapper<AppealDetail>().lambda()
                        .eq(AppealDetail::getDelFlag, PublicCommon.启用)
                        .eq(AppealDetail::getAppealId, appeal.getId())
                        .orderByDesc(BaseEntity::getCreateTime)
                );
                appealDetailResp.setAppealDetailList(appealDetailList);

                order.setAppeal(appealDetailResp);
            }

            //查询表现师评价
            if (order.getIsStoreEvaluate() == 2) {
                OrderEvaluate storeEvaluate = orderEvaluateService.getOne(new QueryWrapper<OrderEvaluate>().lambda()
                        .eq(OrderEvaluate::getOrderId, id)
                        .eq(OrderEvaluate::getUserType, UserEnums.store.getCode())
                        .eq(OrderEvaluate::getUserId, order.getStoreId())
                );
                order.setStoreEvaluate(storeEvaluate);
            }

            //查询设计师评价
            if (order.getIsCustomerEvaluate() == 2) {
                OrderEvaluate customerEvaluate = orderEvaluateService.getOne(new QueryWrapper<OrderEvaluate>().lambda()
                        .eq(OrderEvaluate::getOrderId, id)
                        .eq(OrderEvaluate::getUserType, UserEnums.customer.getCode())
                        .eq(OrderEvaluate::getUserId, order.getCustomerId())
                );
                order.setCustomerEvaluate(customerEvaluate);
            }


        }
        return order;
    }

    private List<Order> orderList(Order order) {
        List<Order> orders = orderMapper.selectOrderList(order);
        return orders;
    }

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

        List<Order> orders = orderList(order);

        if (orders != null && orders.size() > 0) {
            Set<UserVo> userVoSet = new HashSet<>();
            orders.stream().forEach(s -> {
                userVoSet.add(new UserVo(UserEnums.customer.getCode(), s.getCustomerId()));
                userVoSet.add(new UserVo(UserEnums.store.getCode(), s.getStoreId()));
            });

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, null);

            orders.stream().forEach(s -> {
                s.setCustomerInfo(userMap.get(new UserVo(UserEnums.customer.getCode(), s.getCustomerId())));
                s.setStoreInfo(userMap.get(new UserVo(UserEnums.store.getCode(), s.getStoreId())));
            });
        }


        return orders;
    }

    @Override
    public OrderCount statistics(Order order) {
        List<Order> orders = orderList(order);

        List<Long> orderIdList = orders.stream().map(x -> x.getId()).collect(Collectors.toList());
        orderIdList.add(-1L);
        return orderMapper.statistics(orderIdList);
    }

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

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

    /**
     * 批量删除订单主
     *
     * @param ids 需要删除的订单主主键
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] ids) {
        this.lambdaUpdate().set(Order::getDelFlag, PublicCommon.删除).in(Order::getId, ids).update();
        return ids.length;
    }

    /**
     * 删除订单主信息
     *
     * @param id 订单主主键
     * @return 结果
     */
    @Override
    public int deleteOrderById(Long id) {
        this.lambdaUpdate().set(Order::getDelFlag, PublicCommon.删除).eq(Order::getId, id).update();
        return 1;
    }

    @Autowired
    private PayUtil payUtil;

    @Autowired
    private OrderReceivingService orderReceivingService;

    @Autowired
    private BusinessUtil businessUtil;

    @Autowired
    private OrderMessageService orderMessageService;

    @Autowired
    private PlatformRecordService platformRecordService;

    @Override
    public ResponseData orderRelease(OrderReleaseReq req, UserVo userVo) {

        if (UserEnums.enterprise.getCode().equals(userVo.getUserType())) {
            return ResponseData.error("企业不可以发布订单");
        }

        //首款支付占比
        BigDecimal ratio = firstPayRatio();

        if (UserEnums.store.getCode().equals(userVo.getUserType())) {
            //表现师发布订单
            return storeReleaseOrder(req, userVo, ratio);
        } else if (UserEnums.customer.getCode().equals(userVo.getUserType()) && ObjectUtil.isNotEmpty(req.getStoreId())) {
            //设计师在表现师主页发布订单
            return customerReleaseDefaultStoreOrder(req, userVo, ratio);
        } else {
            //设计师发布订单
            return customerReleaseOrder(req, userVo, ratio);
        }
    }

    /**
     * 设计师在表现师主页发布订单
     *
     * @param req
     * @param userVo
     * @param ratio
     * @return
     */
    private ResponseData customerReleaseDefaultStoreOrder(OrderReleaseReq req, UserVo userVo, BigDecimal ratio) {

        //判断屏蔽关系
        checkUserRelation(userVo, new UserVo(UserEnums.store.getCode(), req.getStoreId()));


        //余额支付判断
        judgeBlancePay(req, userVo, ratio);

        //组装订单
        Order order = assembleOrder(req, userVo, ratio);
        order.setStoreId(req.getStoreId());
        this.save(order);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "设计师在表现师主页发布订单", "设计师在表现师主页发布订单", userVo));
        //支付
        ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), order.getFirstTripartitePrice(), order.getFirstGivePrice(), order.getFirstPayOrderNo(), PaySourceEnums.order_pay, WalletDetailEnums.ORDER_PAY);

        if (responseData.getSuccess() || responseData.getCode().equals(210)) {
            //余额支付/苹果支付
            if (PayEnums.balance.getCode().equals(req.getPayType()) || PayEnums.apple.getCode().equals(req.getPayType())) {
                after(order);
            }
        }

        return responseData;
    }

    /**
     * 获取字典首款支付占比
     *
     * @return
     */
    private BigDecimal firstPayRatio() {
        SysDictData dict = businessUtil.getDict(DictConstant.OrderDict.首款支付占比);
        //首款支付比例
        BigDecimal ratio = BigDecimal.ZERO;

        if (dict != null && ObjectUtil.isNotEmpty(dict.getDictValue())) {
            ratio = new BigDecimal(dict.getDictValue());
        }
        return ratio;
    }


    /**
     * 设计师发布订单
     *
     * @param req
     * @param userVo
     * @return
     */
    private ResponseData customerReleaseOrder(OrderReleaseReq req, UserVo userVo, BigDecimal ratio) {

        //余额支付判断
        judgeBlancePay(req, userVo, ratio);

        //组装订单
        Order order = assembleOrder(req, userVo, ratio);

        this.save(order);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "设计师发布订单", "设计师发布订单", userVo));
        //支付
        ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), order.getFirstTripartitePrice(), order.getFirstGivePrice(), order.getFirstPayOrderNo(), PaySourceEnums.order_pay, WalletDetailEnums.ORDER_PAY);


        if (responseData.getSuccess() || responseData.getCode().equals(210)) {
            //余额支付/苹果支付
            if (PayEnums.balance.getCode().equals(req.getPayType()) || PayEnums.apple.getCode().equals(req.getPayType())) {
                after(order);
            }
        }

        return responseData;

    }

    @Autowired
    private BlockService blockService;


    private void checkUserRelation(UserVo self, UserVo other) {
        List<Block> userVos = blockService.list(new QueryWrapper<Block>().lambda().eq(Block::getUserId, self.getUserId())
                .eq(Block::getUserType, self.getUserType()).eq(Block::getDelFlag, PublicCommon.启用));

        for (Block cur : userVos) {
            if (cur.getBlockUserId().equals(other.getUserId()) && cur.getBlockUserType().equals(other.getUserType())) {
                throw new ServiceException("你已将对方拉黑");
            }
        }
        userVos = blockService.list(new QueryWrapper<Block>().lambda().eq(Block::getUserId, other.getUserId())
                .eq(Block::getUserType, other.getUserType()).eq(Block::getDelFlag, PublicCommon.启用));
        for (Block cur : userVos) {
            if (cur.getBlockUserId().equals(self.getUserId()) && cur.getBlockUserType().equals(self.getUserType())) {
                throw new ServiceException("对方已将你拉黑");
            }
        }

        //屏蔽
        List<UserVo> userVosShield = userService.shieldUserList(self);
        for (UserVo cur : userVosShield) {
            if (cur.getUserId().equals(other.getUserId()) && cur.getUserType().equals(other.getUserType())) {
                throw new ServiceException("你已将对方屏蔽");
            }
        }

        userVosShield = userService.shieldUserList(other);
        for (UserVo cur : userVosShield) {
            if (cur.getUserId().equals(self.getUserId()) && cur.getUserType().equals(self.getUserType())) {
                throw new ServiceException("对方已将你屏蔽");
            }
        }

    }

    /**
     * 表现师发布订单
     *
     * @param req
     * @param userVo
     * @return
     */
    private ResponseData storeReleaseOrder(OrderReleaseReq req, UserVo userVo, BigDecimal ratio) {
        //判断表现师认证情况
        checkStoreAuthType(userVo, req.getIfHighend());

        //设计师id是否存在
        if (ObjectUtil.isNull(req.getCustomerId())) {
            return ResponseData.error("请选择设计师");
        }

        //判断屏蔽关系
        checkUserRelation(userVo, new UserVo(UserEnums.customer.getCode(), req.getCustomerId()));

        //组装订单
        Order order = assembleOrder(req, userVo, ratio);

        this.save(order);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "表现师发布订单", "表现师发布订单", userVo));

        //关联记录
        OrderReceiving orderReceiving = new OrderReceiving()
                .setOrderId(order.getId())
                .setStoreId(userVo.getUserId())
                .setReceivingStatus(PublicCommon.OrderReceiving.接单成功);
        orderReceivingService.save(orderReceiving);

        //表现师发布订单 给设计师发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.STORE_RELEASE_ORDER);


        Map<String, Object> map = new HashMap<>();
        map.put("orderId", order.getId());
        return ResponseData.success(map);
    }

    @Autowired
    private OrderOperatorHistoryService orderOperatorHistoryService;

    /**
     * 余额支付判断
     *
     * @param req
     * @param userVo
     */
    private void judgeBlancePay(OrderReleaseReq req, UserVo userVo, BigDecimal ratio) {

        //表现师创建订单不需要判断
        if (userVo.getUserType().equals(UserEnums.store.getCode())) {
            return;
        }
        //余额支付 验证密码
        if (req.getPayType().equals(PayEnums.balance.getCode())) {

            //支付密码验证
            Boolean isTrue = businessUtil.payPwdTrue(userVo, req.getPayPwd());
            if (!isTrue) {
                throw new CustomException(CoreExceptionEnum.PWD_ERROR);
            }
            //判断余额
            BigDecimal userBalance = businessUtil.getUserBalance(userVo);
            if (userBalance.compareTo(req.getAmount().multiply(ratio)) == -1) {
                throw new CustomException(CoreExceptionEnum.BALANCE_INSUFFICIENT);
            }

        }
    }


    /**
     * 组装订单
     *
     * @param req
     * @param userVo
     * @param ratio
     * @return
     */
    private Order assembleOrder(OrderReleaseReq req, UserVo userVo, BigDecimal ratio) {

        Order order = new Order();

        BeanUtil.copyProperties(req, order);

        order.setOriginAmount(req.getAmount());
        order.setOriginDeliverTime(order.getDeliverTime());

        //订单来源 1 设计师自己下单 2 表现师帮设计师下单
        order.setSourceUserType(userVo.getUserType());


        //计算首款支付金额
        order.setFirstPrice(req.getAmount().multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP));

        //计算首款赠送支付金额
        BigDecimal maxGivePrice = businessUtil.userMaxGivePrice(userVo, order.getFirstPrice());
        order.setFirstGivePrice(maxGivePrice);

        //三方支付金额（支付宝，微信）
        order.setFirstTripartitePrice(order.getFirstPrice().subtract(maxGivePrice));

        //订单号
        order.setOrderNo(generateOrderNo(1));

        //订单状态
        order.setStatus(OrderStatusEnums.to_be_confirm.getCode());

        order.setDrawingNum(req.getDrawingNum());

        //表现师发布订单 默认选中
        if (UserEnums.store.getCode().equals(userVo.getUserType())) {
            //默认接单
            order.setStoreId(userVo.getUserId());
            //设计师ID
            order.setCustomerId(req.getCustomerId());
        } else {
            order.setCustomerId(userVo.getUserId());

            //首款支付单号
            order.setFirstPayOrderNo(generateOrderNo(2));

            //首款支付类型
            order.setFirstPayType(req.getPayType());
        }

        return order;
    }

    @Override
    public ResponseData customerPay(CustomerPayReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.to_be_confirm.getCode(), order.getStatus()) &&
                ObjectUtil.notEqual(PublicCommon.Pay.未支付, order.getFirstStatus())) {
            return ResponseData.error("订单状态错误");
        }

        String firstPayOrderNo = "";
        //如果支付单号 不为空 重新生成支付单号 payOrderNo_次数
        if (StringUtils.isNotBlank(order.getFirstPayOrderNo())) {

            if (order.getFirstPayOrderNo().split("_").length > 1) {
                firstPayOrderNo = order.getFirstPayOrderNo().split("_")[0] + "_" + (Integer.valueOf(order.getFirstPayOrderNo().split("_")[1]) + 1);
            } else {
                firstPayOrderNo = order.getFirstPayOrderNo().concat("_") + 1;
            }
        } else {
            firstPayOrderNo = generateOrderNo(2);
        }

        //重新计算支付金额
        BigDecimal maxGivePrice = businessUtil.userMaxGivePrice(userVo, order.getFirstPrice());


        BigDecimal firstTripartitePrice = order.getFirstPrice().subtract(maxGivePrice);
        //支付单号
        this.lambdaUpdate()
                .set(Order::getFirstGivePrice, maxGivePrice)
                .set(Order::getFirstTripartitePrice, firstTripartitePrice)
                .set(Order::getFirstPayOrderNo, firstPayOrderNo)
                .eq(Order::getId, order.getId()).update();

        //支付
        ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), firstTripartitePrice, maxGivePrice, firstPayOrderNo, PaySourceEnums.order_pay, WalletDetailEnums.ORDER_PAY);

        if (responseData.getSuccess() || responseData.getCode().equals(210)) {
            //余额支付
            if (req.getPayType().equals(PayEnums.balance.getCode()) || req.getPayType().equals(PayEnums.apple.getCode())) {
                after(order);
            }
        }


        return responseData;
    }

    @Autowired
    private OrderPriceRecordService orderPriceRecordService;

    /**
     * 支付成功
     *
     * @param order
     */
    private void after(Order order) {


        Integer status = null;


        if (UserEnums.store.getCode().equals(order.getSourceUserType())) {
            //表现师发布订单
            status = OrderStatusEnums.ongoing.getCode();
            //发送消息提醒用户
            orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.FIRST_PRICE_PAY);

        } else if (UserEnums.customer.getCode().equals(order.getSourceUserType()) && ObjectUtil.isNotEmpty(order.getStoreId())) {
            //设计师在表现师主页发布订单
            status = OrderStatusEnums.ongoing.getCode();
            //发送消息提醒用户
            orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), "", PublicCommon.Order.订单, OrderMessageEnums.CUSTOMER_CHOOSE_STORE);

        } else {
            //设计师发布订单
            status = OrderStatusEnums.to_be_confirm.getCode();
        }

        //修改状态
        LambdaUpdateChainWrapper<Order> wrapper = this.lambdaUpdate().set(Order::getStatus, status)
                .set(Order::getFirstStatus, PublicCommon.Pay.已支付)
                .set(Order::getFirstPayTime, new Date())
                .eq(Order::getId, order.getId());
        wrapper.update();
        //平台流水
        platformRecordService.addPlatformRecord(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getFirstPrice(), PlatformRecordEnums.ORDER_PAY);

        //订单支付金额
        orderPriceRecordService.addOrderPriceRecord(OrderPriceEnums.first_pay, order.getId(), order.getFirstPrice());

    }

    @Autowired
    private UserService userService;

    @Override
    public ResponseData<PageResult<Page<OrderPageResp>>> orderPage(OrderPageReq req, UserVo userVo) {

        //项目大厅订单要晒去拉黑屏蔽
        if (req.getIsHall()) {
            //筛去拉黑与被拉黑用户
            List<UserVo> blockUserList = userService.blockUserList(userVo);
            req.setBlockUserList(blockUserList);

            //筛去屏蔽用户
            List<UserVo> shieldUserList = userService.shieldUserList(userVo);
            req.setShieldUserList(shieldUserList);
        }

        //查询设计师和表现师互相之间的订单
        if (req.getIsEachOther() != null && req.getIsEachOther()) {
            if (userVo.getUserType().equals(UserEnums.customer.getCode())) {
                req.setOtherUserType(UserEnums.store.getCode());
            } else if (userVo.getUserType().equals(UserEnums.store.getCode())) {
                req.setOtherUserType(UserEnums.customer.getCode());
            }
        }

        Page<OrderPageResp> page = orderMapper.orderPage(new Page<>(req.getPageNo(), req.getPageSize()), req, userVo);

        if (!page.getRecords().isEmpty()) {

            Set<UserVo> userVoSet = new HashSet<>();
            page.getRecords().stream().forEach(orderPageResp -> {
                userVoSet.add(new UserVo(UserEnums.customer.getCode(), orderPageResp.getCustomerId()));
                userVoSet.add(new UserVo(UserEnums.store.getCode(), orderPageResp.getStoreId()));
            });

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, userVo);

            page.getRecords().stream().forEach(orderPageResp -> {
                orderPageResp.setCustomerInfo(userMap.get(new UserVo(UserEnums.customer.getCode(), orderPageResp.getCustomerId())));
                orderPageResp.setStoreInfo(userMap.get(new UserVo(UserEnums.store.getCode(), orderPageResp.getStoreId())));
            });
        }

        return ResponseData.success(new PageResult<>(page));
    }

    @Override
    public ResponseData<OrderDetailResp> orderDetail(Long id, UserVo userVo) {
        OrderDetailResp orderDetailResp = orderMapper.orderDetail(id, userVo);
        if (orderDetailResp != null) {

            Set<UserVo> userVoSet = new HashSet<>();
            userVoSet.add(new UserVo(UserEnums.customer.getCode(), orderDetailResp.getCustomerId()));
            userVoSet.add(new UserVo(UserEnums.store.getCode(), orderDetailResp.getStoreId()));

            //查询用户信息
            Map<UserVo, UserInfo> userMap = userService.selectUserInfoMap(userVoSet, userVo);

            orderDetailResp.setStoreInfo(userMap.get(new UserVo(UserEnums.store.getCode(), orderDetailResp.getStoreId())));
            orderDetailResp.setCustomerInfo(userMap.get(new UserVo(UserEnums.customer.getCode(), orderDetailResp.getCustomerId())));

            //查询3D图
            List<OrderPanorama> panoramaList = orderPanoramaService.list(new QueryWrapper<OrderPanorama>().lambda()
                    .eq(OrderPanorama::getDelFlag, PublicCommon.启用)
                    .eq(OrderPanorama::getOrderId, id).orderByDesc(BaseEntity::getCreateTime));
            orderDetailResp.setPanoramaList(panoramaList);

            //查询接单表现师
            List<OrderReceiving> orderReceivingList = orderReceivingService.list(new QueryWrapper<OrderReceiving>().lambda()
                    .eq(OrderReceiving::getOrderId, id).eq(OrderReceiving::getDelFlag, PublicCommon.启用).orderByDesc(BaseEntity::getCreateTime));
            Set<UserVo> storeVoSet = orderReceivingList.stream().map(orderReceiving -> new UserVo(UserEnums.store.getCode(), orderReceiving.getStoreId())).collect(Collectors.toSet());

            //查询表现师信息
            Map<UserVo, UserInfo> storeMap = userService.selectUserInfoMap(storeVoSet, userVo);

            orderReceivingList.stream().forEach(orderReceiving -> orderReceiving.setUserInfo(storeMap.get(new UserVo(UserEnums.store.getCode(), orderReceiving.getStoreId()))));

            orderDetailResp.setOrderReceivingList(orderReceivingList);
            if (orderReceivingList.size() > 0) {
                StringBuffer stringBuffer = new StringBuffer();
                orderReceivingList.stream().forEach(x -> {
                    stringBuffer.append(x.getId());
                });
                orderDetailResp.setRecentlyReceiveStr(stringBuffer.toString());
            }

            //调价信息
            OrderChangeRecord changeRecord = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda()
                    .eq(OrderChangeRecord::getDelFlag, PublicCommon.启用)
                    .eq(OrderChangeRecord::getOrderId, id)
                    .eq(OrderChangeRecord::getStatus, PublicCommon.OrderChange.已确认)
                    .orderByDesc(BaseEntity::getCreateTime)
                    .last("LIMIT 1")
            );
            orderDetailResp.setOrderChangeRecord(changeRecord);

            //延期信息
            OrderExtensionRecord orderExtensionRecord = orderExtensionRecordService.getOne(new QueryWrapper<OrderExtensionRecord>().lambda()
                    .eq(OrderExtensionRecord::getDelFlag, PublicCommon.启用)
                    .eq(OrderExtensionRecord::getOrderId, id)
                    .eq(OrderExtensionRecord::getStatus, PublicCommon.OrderChange.已确认)
                    .orderByDesc(BaseEntity::getCreateTime)
                    .last("LIMIT 1")
            );
            orderDetailResp.setOrderExtensionRecord(orderExtensionRecord);

            //评价信息
            List<OrderEvaluate> orderEvaluates = orderEvaluateService.list(new QueryWrapper<OrderEvaluate>().lambda()
                    .eq(OrderEvaluate::getDelFlag, PublicCommon.启用)
                    .eq(OrderEvaluate::getOrderId, id)
            );

            if (orderEvaluates.size() > 0) {
                orderEvaluates.stream().forEach(s -> {
                    if (ObjectUtil.equal(UserEnums.customer.getCode(), s.getUserType())) {
                        s.setUserInfo(orderDetailResp.getCustomerInfo());
                        orderDetailResp.setCustomerOrderEvaluate(s);
                    } else {
                        s.setUserInfo(orderDetailResp.getCustomerInfo());
                        orderDetailResp.setStoreOrderEvaluate(s);
                    }
                });
            }

            BigDecimal depositAmount = depositChangeAmount(orderDetailResp.getAmount(), orderDetailResp.getChangeAmount(),orderDetailResp.getFirstPrice(),orderDetailResp.getFirstStatus());
            orderDetailResp.setDepositAmount(depositAmount);
        }
        return ResponseData.success(orderDetailResp);
    }

    /**
     * 表现师接单
     *
     * @param orderId
     * @param userVo
     * @return
     */
    @Override
    public ResponseData storeOrderReceiving(Long orderId, UserVo userVo) {

        //企业不能接单
        if (UserEnums.enterprise.getCode().equals(userVo.getUserType())) {
            return ResponseData.error("企业不能接单");
        }

        //订单
        Order order = this.getById(orderId);
        //判断表现师认证情况
        checkStoreAuthType(userVo, order.getIfHighend());

        //判断屏蔽关系
        checkUserRelation(userVo, new UserVo(UserEnums.customer.getCode(), order.getCustomerId()));


        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.to_be_confirm.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断表现师是否接单
        int count = orderReceivingService.count(new QueryWrapper<OrderReceiving>().lambda()
                .eq(OrderReceiving::getDelFlag, PublicCommon.启用)
                .eq(OrderReceiving::getOrderId, orderId)
                .eq(OrderReceiving::getStoreId, userVo.getUserId()));
        if (count > 0) {
            return ResponseData.error("订单已接取 请勿重复接单");
        }

        //添加表现师接单记录
        OrderReceiving orderReceiving = new OrderReceiving();
        orderReceiving.setOrderId(orderId)
                .setStoreId(userVo.getUserId());
        orderReceivingService.save(orderReceiving);

        //发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.RECEIVING_ORDER);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "表现师接单", "表现师接单", userVo));

        return ResponseData.success();
    }

    @Autowired
    private AuthService authService;

    @Autowired
    private HighendAuthService highendAuthService;

    /**
     * 判断表现师是否认证
     *
     * @param userVo
     * @return
     */
    private Boolean isAuth(UserVo userVo) {
        //判断认证状态
        Boolean isAuth = authService.count(new QueryWrapper<Auth>().lambda()
                .eq(Auth::getStoreId, userVo.getUserId())
                .eq(Auth::getResult, ProcessResultEnums.APPROVED.getCode())
                .eq(Auth::getDelFlag, PublicCommon.启用)) > 0;

        //判断认证状态
        Boolean ishigHendAuth = highendAuthService.count(new QueryWrapper<HighendAuth>().lambda()
                .eq(HighendAuth::getStoreId, userVo.getUserId())
                .eq(HighendAuth::getStatus, 3)
                .eq(HighendAuth::getDelFlag, PublicCommon.启用)) > 0;

        return isAuth || ishigHendAuth;
    }

    /**
     * 判断表现师是否认证
     *
     * @param userVo
     * @return
     */
    private void checkStoreAuthType(UserVo userVo, Integer ifHighend) {

        if (ifHighend == null) {
            return;
        }

        //高端认证可以接高端和酷家乐，酷家乐认证可以接酷家乐，普通只能接普通

        //普通认证
        Boolean commonAuth = authService.count(new QueryWrapper<Auth>().lambda()
                .eq(Auth::getStoreId, userVo.getUserId())
                .eq(Auth::getType, 1)
                .eq(Auth::getResult, ProcessResultEnums.APPROVED.getCode())
                .eq(Auth::getDelFlag, PublicCommon.启用)) > 0;

        //酷家乐认证
        Boolean kujialeAuth = authService.count(new QueryWrapper<Auth>().lambda()
                .eq(Auth::getStoreId, userVo.getUserId())
                .eq(Auth::getType, 3)
                .eq(Auth::getResult, ProcessResultEnums.APPROVED.getCode())
                .eq(Auth::getDelFlag, PublicCommon.启用)) > 0;

        //高端认证
        Boolean ishigHendAuth = highendAuthService.count(new QueryWrapper<HighendAuth>().lambda()
                .eq(HighendAuth::getStoreId, userVo.getUserId())
                .ge(HighendAuth::getStatus, 3)
                .eq(HighendAuth::getDelFlag, PublicCommon.启用)) > 0;

        //1普通 2 高端 3酷家乐
        if (ifHighend == 1) {
            if (!commonAuth && !ishigHendAuth) {
                throw new ServiceException("请先进行普通认证");
            }

        } else if (ifHighend == 2) {
            if (!ishigHendAuth) {
                throw new ServiceException("请先进行高端认证");
            }
        } else if (ifHighend == 3) {
            if (!kujialeAuth) {
                throw new ServiceException("请先进行酷家乐认证");
            }
        }

    }


    @Override
    public ResponseData orderCancel(Long orderId, UserVo userVo) {

        //订单
        Order order = this.getById(orderId);

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.to_be_confirm.getCode(), order.getStatus()) || ObjectUtil.equal(OrderStatusEnums.cancel.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        switch (UserEnums.getUserEnums(userVo.getUserType())) {
            case customer:
                //设计师
                //修改状态
                this.lambdaUpdate().set(Order::getStatus, OrderStatusEnums.cancel.getCode())
                        .eq(Order::getId, orderId).update();

                if (order.getFirstStatus().equals(PublicCommon.Pay.已支付)) {
                    //退款
                    payUtil.refund(userVo, orderId, order.getFirstPayType(), order.getFirstTripartitePrice(), order.getFirstTripartitePrice(), order.getFirstPayOrderNo(), order.getAliBusinessId(), order.getFirstGivePrice());

                    //平台流水
                    platformRecordService.addPlatformRecord(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getFirstPrice().negate(), PlatformRecordEnums.ORDER_RETURN);
                }

                break;
            case store:
                //表现师取消，删除对应的接单记录
                orderReceivingService.lambdaUpdate().set(OrderReceiving::getDelFlag, PublicCommon.删除)
                        .eq(OrderReceiving::getOrderId, orderId)
                        .eq(OrderReceiving::getStoreId, userVo.getUserId()).update();
                //如果是表现师发布的订单 并且设计师未支付取消订单
                if (ObjectUtil.isNotEmpty(order.getStoreId()) && !order.getFirstStatus().equals(PublicCommon.Pay.已支付)) {
                    this.lambdaUpdate().set(Order::getStatus, OrderStatusEnums.cancel.getCode())
                            .eq(Order::getId, orderId).update();

                    //消息推送给用户
                    orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ORDER_STORE_CANCEL);
                }

                break;
        }

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "取消订单", "取消订单", userVo));


        return ResponseData.success();
    }

    @Override
    public ResponseData confirmStore(ConfirmStoreReq req, UserVo userVo) {
        //订单
        Order order = this.getById(req.getOrderId());

        //判断屏蔽关系
        checkUserRelation(userVo, new UserVo(UserEnums.store.getCode(), req.getStoreId()));

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.to_be_confirm.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断表现师是否已取消接单
        OrderReceiving orderReceiving = orderReceivingService.getOne(new QueryWrapper<OrderReceiving>().lambda()
                .eq(OrderReceiving::getOrderId, req.getOrderId())
                .eq(OrderReceiving::getStoreId, req.getStoreId())
                .orderByDesc(BaseEntity::getCreateTime).last(" limit 1"));
        if (orderReceiving == null) {
            return ResponseData.error("表现师不存在");
        }
        if (!orderReceiving.getDelFlag().equals(PublicCommon.启用)) {
            return ResponseData.error("表现师已取消接单");
        }

        //修改关联表现师接单状态
        orderReceivingService.lambdaUpdate()
                .set(OrderReceiving::getReceivingStatus, PublicCommon.OrderReceiving.接单成功)
                .eq(OrderReceiving::getOrderId, req.getOrderId())
                .eq(OrderReceiving::getStoreId, req.getStoreId())
                .update();

        //其他接单失败
        orderReceivingService.lambdaUpdate()
                .set(OrderReceiving::getReceivingStatus, PublicCommon.OrderReceiving.接单失败)
                .eq(OrderReceiving::getOrderId, req.getOrderId())
                .ne(OrderReceiving::getStoreId, req.getStoreId())
                .update();

        //修改状态
        this.lambdaUpdate().set(Order::getStatus, OrderStatusEnums.ongoing.getCode())
                .set(Order::getStoreId, req.getStoreId())
                .eq(Order::getId, req.getOrderId()).update();

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "客户确定表现师", "客户确定表现师", userVo));


        CompletableFuture.runAsync(() -> {
            List<OrderReceiving> list = orderReceivingService.list(new QueryWrapper<OrderReceiving>().lambda()
                    .eq(OrderReceiving::getDelFlag, PublicCommon.启用)
                    .eq(OrderReceiving::getOrderId, req.getOrderId()));
            list.stream().forEach(s -> {

                //接单状态;1等待接单 2接单成功 3接单失败
                if (s.getReceivingStatus().equals(PublicCommon.OrderReceiving.接单成功)) {
                    //发送消息
                    orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), s.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.CONFIRM);
                } else {
                    //发送消息
                    orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), s.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.NOT_CONFIRM);

                }
            });
        });

        return ResponseData.success();
    }

    @Autowired
    private AppealService appealService;

    @Override
    public ResponseData orderAppeal(OrderAppealReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());


        //判断申诉价格
        if (ObjectUtil.isNotEmpty(req.getAppeal().getAmount()) && req.getAppeal().getAmount().compareTo(order.getAmount()) >= 0) {
            return ResponseData.error("申诉价格要低于订单价格!");
        }

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断是否申诉过
        if (ObjectUtil.equal(order.getAppealStatus(), PublicCommon.Appeal.申诉中)) {
            return ResponseData.error("订单已申诉!");
        }

        //判断是否调价
        if (ObjectUtil.equal(order.getChangeStatus(), PublicCommon.OrderChange.待确认)) {
            return ResponseData.error("订单已调价 请先确认!");
        }

        this.lambdaUpdate().set(Order::getAppealStatus, PublicCommon.Appeal.申诉中)
                .set(Order::getAppealUserType, userVo.getUserType())
                .eq(Order::getId, req.getOrderId()).update();

        //生成申诉记录
        Appeal appeal = req.getAppeal();
        appeal.setOrderId(req.getOrderId())
                .setAppealUserType(userVo.getUserType())
                .setAppealUserId(userVo.getUserId())
                .setPassiveAppealUserType(userVo.getUserType().equals(UserEnums.store.getCode()) ? UserEnums.customer.getCode() : UserEnums.store.getCode())
                .setPassiveAppealUserId(userVo.getUserType().equals(UserEnums.store.getCode()) ? order.getCustomerId() : order.getStoreId());
        appealService.save(appeal);

        //发送消息
        orderMessageService.addOrderMessage(new UserVo(appeal.getPassiveAppealUserType(), appeal.getPassiveAppealUserId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.APPEAL);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "发起申诉", "发起申诉", userVo));


        return ResponseData.success();
    }

    @Override
    public ResponseData cancelOrderAppeal(BodyIdReq req, UserVo userVo) {
        Appeal appeal = appealService.getById(req.getId());
        if (appeal == null || !appeal.getDelFlag().equals(PublicCommon.启用)) {
            return ResponseData.error("投诉已取消");
        }
        //只有投诉方才可以取消投诉
        Order order = getById(appeal.getOrderId());
        if (!order.getAppealUserType().equals(userVo.getUserType())) {
            return ResponseData.error("您无权取消投诉");
        }
        //投诉处理中才可以取消投诉
        if (!appeal.getAppealResult().equals(1)) {
            return ResponseData.error("投诉已处理,不可取消");
        }
        //48小时内才可以取消投诉
//        if (DateUtil.offsetHour(appeal.getCreateTime(), 48).getTime() < System.currentTimeMillis()) {
//            return ResponseData.error("48小时内方可取消投诉");
//        }
        appeal.setDelFlag(PublicCommon.删除);
        appealService.updateById(appeal);

        this.lambdaUpdate().set(Order::getAppealStatus, PublicCommon.Appeal.无申诉)
                .set(Order::getAppealUserType, null)
                .eq(Order::getId, appeal.getOrderId()).update();
        //发送消息
        orderMessageService.addOrderMessage(new UserVo(appeal.getPassiveAppealUserType(), appeal.getPassiveAppealUserId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.CANCEL_APPEAL);


        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "取消申诉", "取消申诉", userVo));


        return ResponseData.success();
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseData getLakalaPaySuccess(LakalaPaySuccessReq req) {

        return ResponseData.success(redisTemplate.hasKey(req.getOutOrderNo()));
    }

    @Override
    public ResponseData sampleImagesAddendum(SampleImagesUploadReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.to_be_evaluated.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //修改订单
        this.lambdaUpdate().set(Order::getCoverImage, req.getCoverImage()).set(Order::getImages, req.getImages())
                .eq(Order::getId, req.getOrderId()).update();

        List<OrderPanorama> orderPanoramaList = req.getOrderPanoramaList().stream().filter(s -> ObjectUtil.isAllNotEmpty(s.getPanorama(), s.getPanoramaImage())).collect(Collectors.toList());

        if (orderPanoramaList.isEmpty() && ObjectUtil.isEmpty(req.getImages())) {
            return ResponseData.error("请上传大图");
        }

        //清除原有的数据
        orderPanoramaService.remove(new QueryWrapper<OrderPanorama>().lambda().eq(OrderPanorama::getOrderId, req.getOrderId()));

        //关联添加 3D图
        req.getOrderPanoramaList().stream().forEach(s -> s.setOrderId(req.getOrderId()));
        orderPanoramaService.saveBatch(req.getOrderPanoramaList());


        //发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.UPLOAD_LARGE_IMAGES);

        //查询3D图
        List<WorksPanorama> worksPanoramas = req.getOrderPanoramaList().stream().map(s -> new WorksPanorama(s)).collect(Collectors.toList());

        Works works = worksService.getOne(new QueryWrapper<Works>().lambda().eq(Works::getOrderId, order.getId()));
        works.setCoverImage(req.getCoverImage());
        works.setImages(req.getImages());
        worksService.updateById(works);

        //清除原有的数据
        worksPanoramaService.remove(new QueryWrapper<WorksPanorama>().lambda().eq(WorksPanorama::getWorksId, works.getId()));

        //关联3D图
        if (worksPanoramas != null && !worksPanoramas.isEmpty()) {

            List<WorksPanorama> saveList = worksPanoramas.stream().filter(s -> ObjectUtil.isAllNotEmpty(s.getPanorama(), s.getPanoramaImage())).collect(Collectors.toList());

            if (saveList.size() > 0) {
                saveList.stream().forEach(w -> w.setWorksId(works.getId()));
                worksPanoramaService.saveBatch(saveList);
            }
        }

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "追加大图", "追加大图", userVo));

        return ResponseData.success();
    }

    @Autowired
    private WorksPanoramaService worksPanoramaService;

    @Autowired
    private OrderChangeRecordService orderChangeRecordService;

    @Override
    public ResponseData<PayVo> orderAdjustPricePayCount(OrderAdjustPricePayCountReq req, UserVo userVo) {
        //订单
        Order order = this.getById(req.getOrderId());

        if (order.getAmount().compareTo(req.getAmount()) >= 0) {
            return ResponseData.success(new PayVo());
        }

        //计算调价后还需支付定金金额
        PayVo payVo = depositAmountCount(order, req.getAmount());

        return ResponseData.success(payVo);
    }

    @Override
    public ResponseData orderAdjustPrice(OrderAdjustPriceReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断是否调价
        if (ObjectUtil.equal(order.getChangeStatus(), PublicCommon.OrderChange.待确认)) {
            return ResponseData.error("订单已调价 请先确认!");
        }

        //判断是否申诉过
        if (ObjectUtil.equal(order.getAppealStatus(), PublicCommon.Appeal.申诉中)) {
            return ResponseData.error("订单已申诉!");
        }

        /*if(order.getAmount().compareTo(req.getAmount()) == 0){
            return ResponseData.error("新价不能和原价一样!");
        }*/

        if (ObjectUtil.equal(UserEnums.customer.getCode(), userVo.getUserType())) {
            //设计师调价
            //调价分为两种情况 1 调价后价格大于原价格(先支付) 2 调价后价格小于等于原价格(对方确认后：需要退款)
            if (order.getAmount().compareTo(req.getAmount()) >= 0) {
                return orderAdjustPriceNoPay(order, req, userVo);
            } else {
                return orderAdjustPricePay(order, req, userVo);
            }
        } else {
            //表现师调价 设计师确认后 需要支付或退款
            return orderAdjustPriceNoPay(order, req, userVo);
        }


    }

    /**
     * 调价后价格小于等于原价格(对方确认后：需要退款)
     *
     * @param order
     * @param req
     * @param userVo
     * @return
     */
    private ResponseData orderAdjustPriceNoPay(Order order, OrderAdjustPriceReq req, UserVo userVo) {

        //计算调价后还需支付定金金额
        PayVo payVo = depositAmountCount(order, req.getAmount());

        //生成调价记录
        OrderChangeRecord record = new OrderChangeRecord();
        record.setChangeAmount(req.getAmount())
                .setOriginAmount(order.getAmount())
                .setRemark(req.getRemark())
                .setOrderId(req.getOrderId())
                .setUserType(userVo.getUserType())
                .setPayPrice(payVo.getPrice())
                .setGivePrice(payVo.getMaxGivePrice())
                .setUserId(userVo.getUserId());
        orderChangeRecordService.save(record);

        //修改
        this.lambdaUpdate().set(Order::getChangeStatus, PublicCommon.OrderChange.待确认)
                .set(Order::getChangeAmount, req.getAmount())
                .set(Order::getChangeRemark, req.getRemark())
                .set(Order::getChangeUserType, userVo.getUserType())
                .eq(Order::getId, req.getOrderId()).update();

        //发送消息
        Long userId = userVo.getUserType().equals(UserEnums.store.getCode()) ? order.getCustomerId() : order.getStoreId();
        Integer userType = userVo.getUserType().equals(UserEnums.store.getCode()) ? UserEnums.customer.getCode() : UserEnums.store.getCode();
        orderMessageService.addOrderMessage(new UserVo(userType, userId), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ADJUST_PRICE);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "申请调价", "申请调价", userVo));


        return ResponseData.success();
    }


    /**
     * 调价后价格大于原价格(对方确认后：需要追加首付款)
     * @param order
     * @param req
     * @param userVo
     * @return
     */
    private ResponseData orderAdjustPricePay(Order order, OrderAdjustPriceReq req, UserVo userVo) {

        //计算调价后还需支付定金金额
        PayVo payVo = depositAmountCount(order, req.getAmount());

        //生成调价记录
        OrderChangeRecord record = new OrderChangeRecord();
        record.setChangeAmount(req.getAmount())
                .setOriginAmount(order.getAmount())
                .setRemark(req.getRemark())
                .setOrderId(req.getOrderId())
                .setPayOrderNo(generateOrderNo(4))
                .setPayPrice(payVo.getPrice())
                .setGivePrice(payVo.getMaxGivePrice())
                .setUserType(userVo.getUserType())
                .setUserId(userVo.getUserId());
        orderChangeRecordService.save(record);

        //支付
        ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), record.getPayPrice().subtract(record.getGivePrice()), record.getGivePrice(), record.getPayOrderNo(), PaySourceEnums.adjust_price_pay, WalletDetailEnums.ADJUST_PRICE_PAY);

        if (responseData.getSuccess() || responseData.getCode().equals(210)) {
            //余额支付
            if (req.getPayType().equals(PayEnums.balance.getCode()) || req.getPayType().equals(PayEnums.apple.getCode())) {
                record.setPayType(req.getPayType());
                afterAdjustPricePay(record);
            }
        }
        return responseData;
    }


    /**
     * 计算金额
     *
     * @return
     */
    private PayVo depositAmountCount(Order order, BigDecimal adjustAmount) {

        PayVo payVo = new PayVo();

        //还需要支付定金
        BigDecimal depositPrice = depositChangeAmount(order.getAmount(), adjustAmount,order.getFirstPrice(),order.getFirstStatus());
        payVo.setPrice(depositPrice);

        //查询赠送金额最大支付比例
        BigDecimal maxGivePrice = businessUtil.userMaxGivePrice(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), depositPrice);

        //赠送金额支付最大值
        payVo.setMaxGivePrice(maxGivePrice);

        return payVo;
    }

    /**
     * 获取条件之后的定金差额
     *
     * @param originAmount
     * @param changeAmount
     * @return
     */
    private BigDecimal depositChangeAmount(BigDecimal originAmount, BigDecimal changeAmount, BigDecimal firstPrice,Integer firstStatus) {
        //超出金额
        //BigDecimal amount = originAmount.subtract(changeAmount == null ? originAmount : changeAmount);

        //查询定金支付比例
        BigDecimal ratio = firstPayRatio();

        if (ObjectUtil.isNull(changeAmount)){
            //还需要支付定金/需要退还定金
            return originAmount.multiply(ratio).setScale(2, RoundingMode.HALF_UP);
        }

        //还需要支付定金/需要退还定金
        BigDecimal depositPrice = changeAmount.multiply(ratio).setScale(2, RoundingMode.HALF_UP);

        if(firstStatus == 2){
            //减去首付
            return depositPrice.subtract(firstPrice);
        }
        return depositPrice;
    }

    /**
     * 获取条件之后的抵用金差额
     *
     * @param originAmount
     * @param changeAmount
     * @return
     */
    private BigDecimal depositChangeGiveAmount(BigDecimal originAmount, BigDecimal changeAmount, BigDecimal firstOriginGiveAmount) {
        //超出金额
        BigDecimal amount = originAmount.subtract(changeAmount == null ? originAmount : changeAmount);

        //查询定金支付比例
        BigDecimal ratio = firstPayRatio();

        //还需要支付定金/需要退还定金
        BigDecimal depositPrice = amount.multiply(ratio).setScale(2, RoundingMode.HALF_UP);
        return firstOriginGiveAmount.multiply(depositPrice.divide(originAmount, 2, BigDecimal.ROUND_HALF_UP));
    }

    /**
     * 调价定金支付（超出原有价格）
     *
     * @param record
     */
    private void afterAdjustPricePay(OrderChangeRecord record) {

        //支付后修改
        boolean update = orderChangeRecordService.lambdaUpdate().set(OrderChangeRecord::getPayStatus, PublicCommon.Pay.已支付)
                .set(OrderChangeRecord::getPayType, record.getPayType())
                .eq(OrderChangeRecord::getPayStatus, PublicCommon.Pay.未支付)
                .eq(OrderChangeRecord::getId, record.getId())
                .update();
        if (update) {

            Order order = this.getById(record.getOrderId());

            //修改
            boolean update1 = this.lambdaUpdate().set(Order::getChangeStatus, PublicCommon.OrderChange.待确认)
                    .set(Order::getChangeAmount, record.getChangeAmount())
                    .set(Order::getChangeRemark, record.getRemark())
                    .set(Order::getChangeUserType, record.getUserType())
                    .eq(Order::getId, record.getOrderId()).update();

            //发送消息
            Long userId = record.getUserType().equals(UserEnums.store.getCode()) ? order.getCustomerId() : order.getStoreId();
            Integer userType = record.getUserType().equals(UserEnums.store.getCode()) ? UserEnums.customer.getCode() : UserEnums.store.getCode();
            orderMessageService.addOrderMessage(new UserVo(userType, userId), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ADJUST_PRICE);


            //订单支付金额
            orderPriceRecordService.addOrderPriceRecord(OrderPriceEnums.change, order.getId(), record.getPayPrice());

            //记录订单操作日志
            orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "申请调价", "申请调价,原价：" + order.getAmount() + "; 申请调价后金额：" + record.getChangeAmount(), new UserVo(record.getUserType(), record.getUserId())));


        }
    }

    @Override
    public ResponseData orderAdjustPriceConfirm(OrderAdjustPriceConfirmReq req, UserVo userVo) {

        //订单id
        Long orderId = req.getId();

        //订单
        Order order = this.getById(orderId);

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断调价状态
        if (ObjectUtil.notEqual(order.getChangeStatus(), PublicCommon.OrderChange.待确认)) {
            return ResponseData.error("调价状态错误!");
        }

        //调价后的价格 小于原价
        if (order.getChangeAmount().compareTo(order.getAmount()) < 0) {
            //小于原价退款(退还部分定金到余额)
            orderAdjustPriceConfirmRefund(order, userVo);

        } else if (order.getChangeAmount().compareTo(order.getAmount()) > 0) {
            //高于原价
            return orderAdjustPriceConfirmPay(order, req, userVo);
        } else {
            //等于原价 不需要支付定金
            //修改订单
            boolean update = this.lambdaUpdate().set(Order::getChangeStatus, PublicCommon.OrderChange.已确认)
                    .set(Order::getAmount, order.getChangeAmount())
                    .eq(Order::getId, order.getId()).update();

            if (update) {
                //发送消息
                Long userId = userVo.getUserType().equals(UserEnums.store.getCode()) ? order.getCustomerId() : order.getStoreId();
                Integer userType = userVo.getUserType().equals(UserEnums.store.getCode()) ? UserEnums.customer.getCode() : UserEnums.store.getCode();
                orderMessageService.addOrderMessage(new UserVo(userType, userId), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ADJUST_PRICE_CONFIRM);

                //记录订单操作日志
                orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "同意调价", "同意调价,调价后金额：" + order.getChangeAmount(), userVo));

            }
        }
        return ResponseData.success();
    }

    /**
     * 调价确认（设计师申请，表现师确认） 退款
     */
    private void orderAdjustPriceConfirmRefund(Order order, UserVo userVo) {

        //修改调价记录状态
        boolean update = orderChangeRecordService.lambdaUpdate().set(OrderChangeRecord::getStatus, PublicCommon.OrderChange.已确认)
                .eq(OrderChangeRecord::getStatus, PublicCommon.OrderChange.待确认)
                .eq(OrderChangeRecord::getOrderId, order.getId()).update();

        if (update) {

            //计算退还定金  负数转为正数
            BigDecimal refundPrice = depositChangeAmount(order.getAmount(), order.getChangeAmount(),order.getFirstPrice(),order.getFirstStatus()).negate();
            //计算退还抵用金
            BigDecimal refundGivePrice = order.getFirstGivePrice().multiply(refundPrice.divide(order.getFirstPrice(), 8, RoundingMode.HALF_UP)).setScale(2, RoundingMode.HALF_UP);

            //退还定金到余额
            walletRecordService.updateBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.DEPOSIT_REFUND, order.getId(), refundPrice.subtract(refundGivePrice), PublicCommon.Wallet.可提现);
            //退还抵用金到余额
            giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.DEPOSIT_REFUND, order.getId(), refundGivePrice, PublicCommon.Wallet.可提现);


            //修改订单
            LambdaUpdateChainWrapper<Order> updateChainWrapper = this.lambdaUpdate().set(Order::getChangeStatus, PublicCommon.OrderChange.已确认)
                    .set(Order::getAmount, order.getChangeAmount())
                    .eq(Order::getId, order.getId());

            BigDecimal firstPrice = order.getFirstPrice().subtract(refundPrice);
            updateChainWrapper.set(Order::getFirstPrice, firstPrice);

            BigDecimal fistGivePrice = order.getFirstGivePrice().subtract(refundGivePrice);
            updateChainWrapper.set(Order::getFirstGivePrice, fistGivePrice);
            updateChainWrapper.update();

            //订单支付金额
            orderPriceRecordService.addOrderPriceRecord(OrderPriceEnums.change, order.getId(), refundPrice);

            //发送消息
            Long userId = userVo.getUserType().equals(UserEnums.store.getCode()) ? order.getCustomerId() : order.getStoreId();
            Integer userType = userVo.getUserType().equals(UserEnums.store.getCode()) ? UserEnums.customer.getCode() : UserEnums.store.getCode();
            orderMessageService.addOrderMessage(new UserVo(userType, userId), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ADJUST_PRICE_CONFIRM);

            //记录订单操作日志
            orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "同意调价", "同意调价，调价后金额：" + order.getChangeAmount(), userVo));


        }
    }

    /**
     * 调价确认（表现师申请，设计师确认） 支付
     */
    private ResponseData orderAdjustPriceConfirmPay(Order order, OrderAdjustPriceConfirmReq req, UserVo userVo) {


        OrderChangeRecord orderChangeRecord = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getOrderId, req.getId())
                .eq(OrderChangeRecord::getStatus, PublicCommon.OrderChange.待确认).eq(OrderChangeRecord::getDelFlag, PublicCommon.启用)
                .orderByDesc(BaseEntity::getCreateTime).last(" limit 1"));
        if (orderChangeRecord == null) {
            throw new ServiceException("调价记录不存在");
        }

        //表现师发起，设计师确认时需要支付
        if (orderChangeRecord.getUserType().equals(UserEnums.store.getCode())) {
            //调价支付订单号
            String payOrderNo = generateOrderNo(4);

            /*//差值（超出原价的金额）
            BigDecimal excessAmount = order.getChangeAmount().subtract(order.getAmount());
            //定金比例
            BigDecimal ratio = firstPayRatio();*/

            //需要支付定金金额
            BigDecimal payPrice = depositChangeAmount(order.getOriginAmount(), order.getChangeAmount(), order.getFirstPrice(), order.getFirstStatus());

            //最大使用赠送金额
            BigDecimal maxGivePrice = businessUtil.userMaxGivePrice(userVo, payPrice);

            //修改调价记录状态
            boolean update = orderChangeRecordService.lambdaUpdate()
                    .set(OrderChangeRecord::getPayOrderNo, payOrderNo)
                    .eq(OrderChangeRecord::getStatus, PublicCommon.OrderChange.待确认)
                    .eq(OrderChangeRecord::getOrderId, order.getId()).update();

            //支付
            ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), payPrice.subtract(maxGivePrice), maxGivePrice, payOrderNo, PaySourceEnums.store_adjust_price_pay, WalletDetailEnums.ADJUST_PRICE_PAY);

            if (responseData.getSuccess() || responseData.getCode().equals(210)) {
                //余额支付
                if (req.getPayType().equals(PayEnums.balance.getCode()) || req.getPayType().equals(PayEnums.apple.getCode())) {
                    afterAdjustPriceConfirmPay(orderChangeRecordService.getById(orderChangeRecord.getId()));
                }
            }

            return responseData;
        } else {
            afterAdjustPriceConfirmPay(orderChangeRecordService.getById(orderChangeRecord.getId()));
        }
        return ResponseData.success();
    }

    private void afterAdjustPriceConfirmPay(OrderChangeRecord record) {

        //支付后修改
        boolean update = orderChangeRecordService.lambdaUpdate().set(OrderChangeRecord::getPayStatus, PublicCommon.Pay.已支付)
                .set(OrderChangeRecord::getStatus, PublicCommon.OrderChange.已确认)
                .eq(OrderChangeRecord::getStatus, PublicCommon.OrderChange.待确认)
                .eq(OrderChangeRecord::getId, record.getId())
                .update();

        if (update) {

            Order order = this.getById(record.getOrderId());
            BigDecimal newPayPrice = order.getFirstPrice().add(record.getPayPrice());
            BigDecimal newGivePrice = order.getFirstGivePrice().add(record.getGivePrice());

            boolean update1 = this.lambdaUpdate().set(Order::getChangeStatus, PublicCommon.OrderChange.已确认)
                    .set(Order::getAmount, record.getChangeAmount())
                    .set(Order::getFirstPrice, newPayPrice)
                    .set(Order::getFirstGivePrice, newGivePrice)
//                    .setSql("first_price = first_price + " + record.getPayPrice())
//                    .setSql("first_give_price = first_give_price + " + record.getGivePrice())
                    .eq(Order::getId, record.getOrderId()).update();

            if (update1) {

                if (ObjectUtil.equal(UserEnums.store.getCode(), record.getUserType())) {
                    //订单支付金额
                    orderPriceRecordService.addOrderPriceRecord(OrderPriceEnums.change, record.getOrderId(), record.getPayPrice());
                }

                //发送消息
                orderMessageService.addOrderMessage(new UserVo(record.getUserType(), record.getUserId()), record.getOrderId(), "", PublicCommon.Order.订单, OrderMessageEnums.ADJUST_PRICE_CONFIRM);

                //记录订单操作日志
                orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(record.getOrderId(), "同意调价", "同意调价,调价后金额：" + record.getChangeAmount(), new UserVo(record.getUserType(), record.getUserId())));

            }
        }
    }

    @Override
    public ResponseData orderAdjustPriceRefuse(RefuseReq req, UserVo userVo) {

        Long orderId = req.getId();
        //订单
        Order order = this.getById(orderId);

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断调价状态
        if (ObjectUtil.notEqual(order.getChangeStatus(), PublicCommon.OrderChange.待确认)) {
            return ResponseData.error("调价状态错误!");
        }

        //修改调价记录状态
        boolean update = orderChangeRecordService.lambdaUpdate().set(OrderChangeRecord::getStatus, PublicCommon.OrderChange.拒绝)
                .set(OrderChangeRecord::getReason, req.getReason())
                .eq(OrderChangeRecord::getStatus, PublicCommon.OrderChange.待确认)
                .eq(OrderChangeRecord::getOrderId, orderId).update();

        if (update) {
            //修改订单
            LambdaUpdateChainWrapper<Order> updateChainWrapper = this.lambdaUpdate().set(Order::getChangeStatus, PublicCommon.OrderChange.拒绝)
                    .eq(Order::getId, orderId);

            //调价价格大于原价 拒绝退还已支付定金到余额
            if (ObjectUtil.equal(UserEnums.customer.getCode(), order.getChangeUserType()) && order.getChangeAmount().compareTo(order.getAmount()) > 0) {

                OrderChangeRecord orderChangeRecord = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda()
                        .eq(OrderChangeRecord::getDelFlag, PublicCommon.启用)
                        .eq(OrderChangeRecord::getOrderId, orderId)
                        .orderByDesc(BaseEntity::getCreateTime)
                        .last("limit 1")
                );


                walletRecordService.updateBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.DEPOSIT_REFUND, order.getId(), orderChangeRecord.getPayPrice().subtract(orderChangeRecord.getGivePrice()), PublicCommon.Wallet.可提现);
                giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.DEPOSIT_REFUND, order.getId(), orderChangeRecord.getGivePrice(), PublicCommon.Wallet.可提现);


                //订单支付金额
                orderPriceRecordService.addOrderPriceRecord(OrderPriceEnums.change, order.getId(), orderChangeRecord.getPayPrice().negate());
            }

            updateChainWrapper.update();


            //发送消息
            Long userId = userVo.getUserType().equals(UserEnums.store.getCode()) ? order.getCustomerId() : order.getStoreId();
            Integer userType = userVo.getUserType().equals(UserEnums.store.getCode()) ? UserEnums.customer.getCode() : UserEnums.store.getCode();
            orderMessageService.addOrderMessage(new UserVo(userType, userId), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.ADJUST_PRICE_REFUSE);

            //记录订单操作日志
            orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "拒绝调价", "拒绝调价", userVo));


        }


        return ResponseData.success();
    }

    @Autowired
    private GiveWalletRecordService giveWalletRecordService;

    @Autowired
    private OrderExtensionRecordService orderExtensionRecordService;

    @Override
    public ResponseData orderExtension(OrderExtensionReq req, UserVo userVo) {
        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断是否延期
        if (ObjectUtil.equal(order.getChangeStatus(), PublicCommon.Extension.待确认)) {
            return ResponseData.error("订单已延期 请先确认!");
        }

        //判断延期时间
        if (req.getExtensionTime().getTime() < order.getDeliverTime().getTime()) {
            return ResponseData.error(String.format("延期时间不能小于%s", DateUtil.format(order.getDeliverTime(), "yyyy-MM-dd HH:mm")));
        }


        //生成延期记录
        OrderExtensionRecord record = new OrderExtensionRecord();
        record.setChangeTime(req.getExtensionTime())
                .setOriginTime(order.getDeliverTime())
                .setRemark(req.getRemark())
                .setOrderId(req.getOrderId())
                .setUserType(userVo.getUserType())
                .setUserId(userVo.getUserId());
        orderExtensionRecordService.save(record);

        //修改
        this.lambdaUpdate().set(Order::getExtensionStatus, PublicCommon.Extension.待确认)
                .set(Order::getExtensionDeliverTime, req.getExtensionTime())
                .set(Order::getExtensionRemark, req.getRemark())
                .set(Order::getExtensionUserType, userVo.getUserType())
                .eq(Order::getId, req.getOrderId()).update();
        //发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.EXTENSION);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "订单申请延期", "订单申请延期,延期至:" + DateUtil.formatDateTime(req.getExtensionTime()), userVo));


        return ResponseData.success();
    }

    @Override
    public ResponseData orderExtensionCancel(Long orderId) {

        //延期信息
        OrderExtensionRecord orderExtensionRecord = orderExtensionRecordService.getOne(new QueryWrapper<OrderExtensionRecord>().lambda()
                .eq(OrderExtensionRecord::getDelFlag, PublicCommon.启用)
                .eq(OrderExtensionRecord::getOrderId, orderId)
                .eq(OrderExtensionRecord::getStatus, PublicCommon.OrderChange.待确认)
                .orderByDesc(BaseEntity::getCreateTime)
                .last("LIMIT 1")
        );

        //判断延期 设计师是否已操作
        if (orderExtensionRecord == null || ObjectUtil.notEqual(orderExtensionRecord.getStatus(), PublicCommon.Extension.待确认)) {
            return ResponseData.error("订单已延期 请不要重复操作!");
        }

        boolean update = orderExtensionRecordService.lambdaUpdate().set(OrderExtensionRecord::getDelFlag, PublicCommon.删除)
                .eq(OrderExtensionRecord::getId, orderExtensionRecord.getId())
                .update();
        if (update) {
            //同步修改订单中延期信息
            this.lambdaUpdate().set(Order::getExtensionStatus, PublicCommon.Extension.取消)
                    .eq(Order::getId, orderExtensionRecord.getOrderId()).update();

            //记录订单操作日志
            orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(orderExtensionRecord.getOrderId(), "订单延期取消", "订单延期取消", new UserVo(orderExtensionRecord.getUserType(), orderExtensionRecord.getUserId())));

        }

        return ResponseData.success();
    }

    @Override
    public ResponseData orderExtensionConfirm(Long orderId, UserVo userVo) {
        //订单
        Order order = this.getById(orderId);

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断延期状态
        if (ObjectUtil.notEqual(order.getExtensionStatus(), PublicCommon.OrderChange.待确认)) {
            return ResponseData.error("延期状态错误!");
        }

        //修改延期记录状态
        orderExtensionRecordService.lambdaUpdate().set(OrderExtensionRecord::getStatus, PublicCommon.Extension.已确认)
                .eq(OrderExtensionRecord::getStatus, PublicCommon.OrderChange.待确认)
                .eq(OrderExtensionRecord::getOrderId, orderId).update();

        //修改订单
        this.lambdaUpdate().set(Order::getExtensionStatus, PublicCommon.Extension.已确认)
                .set(Order::getDeliverTime, order.getExtensionDeliverTime())
                .eq(Order::getId, orderId).update();

        //发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.EXTENSION_CONFIRM);


        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "同意订单延期", "同意订单延期", userVo));


        return ResponseData.success();
    }

    @Override
    public ResponseData orderExtensionRefuse(RefuseReq req, UserVo userVo) {

        Long orderId = req.getId();
        //订单
        Order order = this.getById(orderId);

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断延期状态
        if (ObjectUtil.notEqual(order.getExtensionStatus(), PublicCommon.Extension.待确认)) {
            return ResponseData.error("延期状态错误!");
        }

        //修改延期记录状态
        orderExtensionRecordService.lambdaUpdate().set(OrderExtensionRecord::getStatus, PublicCommon.Extension.拒绝)
                .set(OrderExtensionRecord::getReason, req.getReason())
                .eq(OrderExtensionRecord::getStatus, PublicCommon.Extension.待确认)
                .eq(OrderExtensionRecord::getOrderId, orderId).update();

        //修改订单
        this.lambdaUpdate().set(Order::getExtensionStatus, PublicCommon.Extension.拒绝)
                .eq(Order::getId, orderId).update();

        //发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.EXTENSION_REFUSE);


        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "拒绝订单延期", "拒绝订单延期", userVo));


        return ResponseData.success();
    }

    @Autowired
    private OrderPanoramaService orderPanoramaService;

    @Override
    public ResponseData sampleImagesUpload(SampleImagesUploadReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.pending_drawings.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }


        List<OrderPanorama> orderPanoramaList = req.getOrderPanoramaList().stream().filter(s -> ObjectUtil.isAllNotEmpty(s.getPanorama(), s.getPanoramaImage())).collect(Collectors.toList());

        if (orderPanoramaList.isEmpty() && ObjectUtil.isEmpty(req.getImages())) {
            return ResponseData.error("请上传大图");
        }

        //关联添加 3D图
        req.getOrderPanoramaList().stream().forEach(s -> s.setOrderId(req.getOrderId()));
        orderPanoramaService.saveBatch(req.getOrderPanoramaList());

        //修改订单
        boolean update = this.lambdaUpdate().set(Order::getCoverImage, req.getCoverImage()).set(Order::getImages, req.getImages())
                .set(Order::getStatus, OrderStatusEnums.to_be_evaluated.getCode())
                .set(Order::getConfirmDate, new Date())
                .eq(Order::getId, req.getOrderId()).update();

        if (update) {
            //发送消息
            orderMessageService.addOrderMessage(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.UPLOAD_LARGE_IMAGES);
        }

        //生成表现师作品
        WorksReleaseReq worksReleaseReq = new WorksReleaseReq()
                .setOrderId(order.getId())
                .setWorksTypeId(order.getWorksTypeId())
                .setCoverImage(req.getCoverImage())
                .setImages(req.getImages())
                .setTitle(order.getTitle())
                .setPrice(order.getAmount())
                .setCustomerId(order.getCustomerId())
                .setSource(2);//来源 1 手动创建 2 订单同步"

        //查询3D图
        List<OrderPanorama> panoramaList = req.getOrderPanoramaList();

        List<WorksPanorama> worksPanoramas = panoramaList.stream().map(s -> new WorksPanorama(s)).collect(Collectors.toList());
        worksReleaseReq.setWorksPanoramaList(worksPanoramas);

        worksService.worksRelease(worksReleaseReq, new UserVo(UserEnums.store.getCode(), order.getStoreId()));

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "上传大图", "上传大图", userVo));


        return ResponseData.success();
    }

    @Override
    public ResponseData receiveDrawingsAndPay(ReceiveDrawingsAndPayReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.ongoing.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断是否申诉
        if (ObjectUtil.equal(order.getAppealStatus(), PublicCommon.Appeal.申诉中)) {
            return ResponseData.error("订单申诉中! 请联系平台关闭申诉");
        }

        //判断是否延期
        if (ObjectUtil.equal(order.getExtensionStatus(), PublicCommon.Extension.待确认)) {
            String msg = "订单延期中 请先确认!";
            if (ObjectUtil.equal(userVo.getUserType(), order.getExtensionUserType())) {
                msg = "订单延期中 请等待对方确认!";
            }
            return ResponseData.error(msg);
        }

        //判断调价状态
        if (ObjectUtil.equal(order.getChangeStatus(), PublicCommon.OrderChange.待确认)) {
            String msg = "订单调价中 请先确认!";
            if (ObjectUtil.equal(userVo.getUserType(), order.getChangeUserType())) {
                msg = "订单调价中 请等待对方确认!";
            }
            return ResponseData.error(msg);
        }


        //三方支付金额
        BigDecimal secondPayPrice = order.getAmount().subtract(order.getFirstPrice());

        BigDecimal maxGivePrice = businessUtil.userMaxGivePrice(userVo, secondPayPrice);

        //余额支付 验证密码
        if (req.getPayType().equals(PayEnums.balance.getCode())) {
            //支付密码验证
            Boolean isTrue = businessUtil.payPwdTrue(userVo, req.getPayPwd());
            if (!isTrue) {
                return ResponseData.error(CoreExceptionEnum.PWD_ERROR);
            }

            //判断余额
            BigDecimal userBalance = businessUtil.getUserBalance(userVo);
            if (userBalance.compareTo(secondPayPrice.subtract(maxGivePrice)) == -1) {
                return ResponseData.error(CoreExceptionEnum.BALANCE_INSUFFICIENT);
            }

        }


        //尾款支付单号
        String secondPayOrderNo = "";

        //如果尾款支付单号 不为空 重新生成尾款支付单号 payOrderNo_次数
        if (StringUtils.isNotBlank(order.getSecondPayOrderNo())) {

            if (order.getSecondPayOrderNo().split("_").length > 1) {
                secondPayOrderNo = order.getSecondPayOrderNo().split("_")[0] + "_" + (Integer.valueOf(order.getSecondPayOrderNo().split("_")[1]) + 1);
            } else {
                secondPayOrderNo = order.getSecondPayOrderNo().concat("_") + 1;
            }
        } else {
            secondPayOrderNo = generateOrderNo(3);
        }

        //修改订单
        this.lambdaUpdate()
                .set(Order::getIsAgree, req.getIsAgree())
                .set(Order::getSecondPayType, req.getPayType())
                .set(Order::getSecondPayOrderNo, secondPayOrderNo)
                .set(Order::getSecondTripartitePrice, secondPayPrice.subtract(maxGivePrice))
                .set(Order::getSecondGivePrice, maxGivePrice)
                .eq(Order::getId, req.getOrderId()).update();

        //支付
        ResponseData responseData = payUtil.pay(userVo, order.getId(), req.getPayType(), secondPayPrice.subtract(maxGivePrice), maxGivePrice, secondPayOrderNo, PaySourceEnums.order_second_pay, WalletDetailEnums.ORDER_PAY);

        if (responseData.getSuccess() || responseData.getCode().equals(210)) {
            //余额支付
            if (req.getPayType().equals(PayEnums.balance.getCode()) || req.getPayType().equals(PayEnums.apple.getCode())) {
                endPayAfter(order, req.getIsAgree() == 1 ? false : true);
            }
        }

        return responseData;
    }

    @Autowired
    private WalletRecordService walletRecordService;


    @Autowired
    private WorksService worksService;

    @Autowired
    private RefereeUserService refereeUserService;

    @Autowired
    private StoreMapper storeMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private IntegralRecordService integralRecordService;

    /**
     * 收图支付后操作
     *
     * @param order
     */
    private void endPayAfter(Order order, boolean isAddWorks) {


        //平台流水
        platformRecordService.addPlatformRecord(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), order.getAmount().subtract(order.getFirstPrice()), PlatformRecordEnums.ORDER_SECOND_PAY);

        //判断销售是否分佣
        RefereeUser refereeUser = refereeUserService.getOne(new QueryWrapper<RefereeUser>().lambda()
                .eq(RefereeUser::getDelFlag, PublicCommon.启用)
                .eq(RefereeUser::getUserId, order.getCustomerId())
                .eq(RefereeUser::getUserType, UserEnums.customer.getCode())
                .orderByDesc(BaseEntity::getCreateTime));


        //销售分佣
        BigDecimal commission = BigDecimal.ZERO;

        Order dbOrder = getById(order.getId());

        //订单用来分佣的钱(实际支付金额=订单总金额-抵用金)
        BigDecimal canCommission = order.getAmount().subtract(order.getFirstGivePrice()).subtract(dbOrder.getSecondGivePrice());

        //邀请销售id
        Long saleId = null;

        //销售邀请（销售分佣）
        if (refereeUser != null && ObjectUtil.equal(UserEnums.sale.getCode(), refereeUser.getParentUserType())) {

            //获取销售分佣比例
            SysDictData commissionRatio = businessUtil.getDict(DictConstant.推广师分佣比例);

            //计算销售分佣金额
            commission = canCommission.multiply(new BigDecimal(commissionRatio.getDictValue()));

            saleId = refereeUser.getParentUserId();
        }

        //表现师分佣
        Store store = storeService.getById(order.getStoreId());
        BigDecimal storeCommissionRatio = store.getCommissionRatio();
        if (storeCommissionRatio == null) {
            storeCommissionRatio = new BigDecimal(businessUtil.getDict(DictConstant.表现师分佣比例).getDictValue());
        }

        BigDecimal storeCommission = canCommission.multiply(storeCommissionRatio).setScale(2, RoundingMode.HALF_UP);


        //修改状态
        this.lambdaUpdate().set(Order::getStatus, OrderStatusEnums.pending_drawings.getCode())
                .set(Order::getSecondStatus, PublicCommon.Pay.已支付)
                .set(Order::getSecondPayTime, new Date())
                .set(saleId != null, Order::getSaleId, saleId)
                .set(saleId != null, Order::getSaleAmount, commission)
                .eq(Order::getId, order.getId()).update();


        //修改用户余额，添加余额记录 (表现师)
        walletRecordService.updateBalance(new UserVo(UserEnums.store.getCode(), order.getStoreId()), WalletDetailEnums.ORDER_INCOME, order.getId(), storeCommission, PublicCommon.Wallet.可提现);

        if (refereeUser != null) {

            switch (UserEnums.getUserEnums(refereeUser.getParentUserType())) {
                case sale:
                    //销售分佣
                    walletRecordService.updateBalance(new UserVo(UserEnums.sale.getCode(), refereeUser.getParentUserId()), WalletDetailEnums.TEAM_COMMISSION, order.getId(), commission, PublicCommon.Wallet.可提现);

                    //平台流水
                    platformRecordService.addPlatformRecord(new UserVo(UserEnums.sale.getCode(), refereeUser.getParentUserId()), order.getId(), commission.negate(), PlatformRecordEnums.TEAM_COMMISSION);

                    break;
                default:
                    //赠送积分比例
                    SysDictData dict = businessUtil.getDict(DictConstant.OrderDict.邀请用户下单获取积分与消费额的比例);

                    BigDecimal ratio = BigDecimal.ZERO;
                    if (dict != null) {
                        ratio = new BigDecimal(dict.getDictValue());
                    }

                    //赠送积分
                    BigDecimal integral = ratio.multiply(canCommission).setScale(2, BigDecimal.ROUND_HALF_UP);

                    //积分记录
                    integralRecordService.updateIntegral(new UserVo(refereeUser.getParentUserType(), refereeUser.getParentUserId()),
                            order.getId(), integral, IntegralDetailEnums.SHARE_TEAM_COMMISSION,null);

                    break;
            }
        }

        //平台流水
        platformRecordService.addPlatformRecord(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), storeCommission.negate(), PlatformRecordEnums.STORE_ORDER_INCOME);

        //表现师累计收益
        storeMapper.addIncome(order.getStoreId(), storeCommission);

        //设计师累计消费额
        customerMapper.addConsumptionAmount(order.getCustomerId(), order.getAmount());

        //订单支付金额
        orderPriceRecordService.addOrderPriceRecord(OrderPriceEnums.second_pay, order.getId(), order.getAmount().subtract(order.getFirstPrice()));

        //发送消息
        orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, OrderMessageEnums.FINAL_PAY);

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "支付尾款", "支付尾款,尾款金额：" + order.getAmount().subtract(order.getFirstPrice()), new UserVo(UserEnums.customer.getCode(), order.getCustomerId())));


    }

    @Autowired
    private CustomerService customerService;

    @Autowired
    private StoreService storeService;


    @Override
    public ResponseData evaluate(EvaluateReq req, UserVo userVo) {

        //订单
        Order order = this.getById(req.getOrderId());

        //判断订单状态
        if (ObjectUtil.notEqual(OrderStatusEnums.to_be_evaluated.getCode(), order.getStatus())) {
            return ResponseData.error("订单状态错误");
        }

        //判断是否已经评价过 是否评价 1 没有 2 评价
        if (ObjectUtil.equal(UserEnums.customer.getCode(), userVo.getUserType()) ?
                ObjectUtil.equal(2, order.getIsCustomerEvaluate()) : ObjectUtil.equal(2, order.getIsStoreEvaluate())) {
            return ResponseData.error("订单已评价");
        }

        //添加评价记录
        OrderEvaluate evaluate = new OrderEvaluate();
        evaluate.setUserId(userVo.getUserId())
                .setUserType(userVo.getUserType())
                .setOrderId(req.getOrderId())
                .setEfficiencyStar(req.getEfficiencyStar())
                .setServiceStar(req.getServiceStar())
                .setQualityStar(req.getQualityStar());

        //根据配置的权重--->计算总评分
        BigDecimal quality_ratio = new BigDecimal(businessUtil.getDict(DictConstant.质量评分占比).getDictValue());
        BigDecimal efficiency_ratio = new BigDecimal(businessUtil.getDict(DictConstant.效率评分占比).getDictValue());
        BigDecimal service_ratio = new BigDecimal(businessUtil.getDict(DictConstant.服务评分占比).getDictValue());

        BigDecimal star = quality_ratio.multiply(evaluate.getQualityStar())
                .add(efficiency_ratio.multiply(evaluate.getEfficiencyStar()))
                .add(service_ratio.multiply(evaluate.getServiceStar()));

        evaluate.setStar(star);

        orderEvaluateService.save(evaluate);

        //修改订单
        this.lambdaUpdate().set(Order::getStatus, OrderStatusEnums.to_be_evaluated.getCode())
                .set(ObjectUtil.equal(UserEnums.customer.getCode(), userVo.getUserType()), Order::getIsStoreEvaluate, 2)
                .set(ObjectUtil.equal(UserEnums.customer.getCode(), userVo.getUserType()), Order::getIsCustomerEvaluate, 2)
                .eq(Order::getId, req.getOrderId()).update();


        //评价对象
        UserVo evaluateUserVo = new UserVo();
        if (ObjectUtil.equal(UserEnums.store.getCode(), userVo.getUserType())) {
            evaluateUserVo.setUserType(UserEnums.customer.getCode());
            evaluateUserVo.setUserId(order.getCustomerId());
        } else {
            evaluateUserVo.setUserType(UserEnums.store.getCode());
            evaluateUserVo.setUserId(order.getStoreId());
        }

        //计算评分
        BigDecimal userStar = orderEvaluateService.getUserStar(evaluateUserVo);

        switch (UserEnums.getUserEnums(evaluateUserVo.getUserType())) {
            case store:
                //表现师评分
                storeService.update().set("star", userStar).eq("id", evaluateUserVo.getUserId()).update();

                //消息通知
                orderMessageService.addOrderMessage(new UserVo(UserEnums.store.getCode(), order.getStoreId()), order.getId(), order.getOrderNo(), PublicCommon.Order.订单, EVALUATE_ORDER);

                break;
            case customer:
                //设计师评分
                customerService.update().set("star", userStar).eq("id", evaluateUserVo.getUserId()).update();
                break;
            default:
                break;
        }

        //记录订单操作日志
        orderOperatorHistoryService.insertOrderOperatorHistory(OrderOperatorHistory.addAppHistory(order.getId(), "订单评价", "订单评价", userVo));


        return ResponseData.success();
    }


    @Override
    public ResponseData evaluateCountStar(EvaluateReq req, UserVo userVo) {

        //根据配置的权重--->计算总评分
        BigDecimal quality_ratio = new BigDecimal(businessUtil.getDict(DictConstant.质量评分占比).getDictValue());
        BigDecimal efficiency_ratio = new BigDecimal(businessUtil.getDict(DictConstant.效率评分占比).getDictValue());
        BigDecimal service_ratio = new BigDecimal(businessUtil.getDict(DictConstant.服务评分占比).getDictValue());

        BigDecimal star = quality_ratio.multiply(req.getQualityStar())
                .add(efficiency_ratio.multiply(req.getEfficiencyStar()))
                .add(service_ratio.multiply(req.getServiceStar()));

        return ResponseData.success(star);
    }

    @Override
    public ResponseData<OrderDataResp> orderData(OrderPageReq orderPageReq, UserVo userVo) {
        OrderDataResp orderDataResp = new OrderDataResp();
        LambdaQueryWrapper<Order> lambdaQueryWrapper = new QueryWrapper<Order>().lambda()
                .eq(userVo.getUserType().equals(UserEnums.store.getCode()), Order::getStoreId, userVo.getUserId())
                .eq(userVo.getUserType().equals(UserEnums.customer.getCode()), Order::getCustomerId, userVo.getUserId())
                .eq(Order::getFirstStatus, PublicCommon.Pay.已支付)
                .eq(Order::getDelFlag, PublicCommon.启用);

        if (orderPageReq != null && orderPageReq.getIsEachOther() != null && orderPageReq.getIsEachOther()) {
            if (userVo.getUserType().equals(UserEnums.customer.getCode())) {
                lambdaQueryWrapper.eq(Order::getStoreId, orderPageReq.getOtherUserId());
            } else if (userVo.getUserType().equals(UserEnums.store.getCode())) {
                lambdaQueryWrapper.eq(Order::getCustomerId, orderPageReq.getOtherUserId());
            }
        }
        List<Order> list = this.list(lambdaQueryWrapper);
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal income = BigDecimal.ZERO;

        for (Order order : list) {
            amount = amount.add(order.getAmount());
            if (
                    (order.getStatus().equals(OrderStatusEnums.to_be_confirm.getCode())
                            || order.getStatus().equals(OrderStatusEnums.ongoing.getCode()))
                            && order.getSourceUserType() == 1
            ) {
                income = income.add(order.getFirstPrice());
            } else if (order.getStatus().equals(OrderStatusEnums.ongoing.getCode()) && order.getSourceUserType() == 2) {
                income = income.add(order.getFirstPrice());
            } else {
                income = income.add(order.getAmount());
            }
        }

        orderDataResp.setIncome(income);
        orderDataResp.setAmount(amount);

        if (orderPageReq.getIsEachOther()) {
            if (userVo.getUserType().equals(UserEnums.customer.getCode())) {
                orderPageReq.setOtherUserType(UserEnums.store.getCode());
            } else if (userVo.getUserType().equals(UserEnums.store.getCode())) {
                orderPageReq.setOtherUserType(UserEnums.customer.getCode());
            }
        }

        //订单数量
        Integer orderNum = this.baseMapper.orderCount(userVo, orderPageReq);
        orderDataResp.setOrderNum(orderNum);

        return ResponseData.success(orderDataResp);
    }

    /**
     * 生成订单号
     *
     * @param type 1订单号 2 首款支付单号 3 尾款支付单号 4调价支付定金
     * @return
     */
    private String generateOrderNo(Integer type) {
        String orderNo;
        String prefix = type == 1 ? "HT" : type == 2 ? "HTS" : "HTW";
        if (type == 4) {
            prefix = "TJ";

            while (true) {
                orderNo = prefix + DateUtil.format(new Date(), "MMdd" + RandomUtil.randomNumbers(6));
                OrderChangeRecord old = orderChangeRecordService.getBaseMapper().selectOne(new QueryWrapper<OrderChangeRecord>().lambda()
                        .eq(OrderChangeRecord::getPayOrderNo, orderNo)
                );
                if (old == null) {
                    break;
                }
            }
            return orderNo;
        }

        while (true) {
            orderNo = prefix + DateUtil.format(new Date(), "MMdd" + RandomUtil.randomNumbers(6));
            Order old = this.getBaseMapper().selectOne(new QueryWrapper<Order>().lambda()
                    .eq(type == 1, Order::getOrderNo, orderNo)
                    .eq(type == 2, Order::getFirstPayOrderNo, orderNo)
                    .eq(type == 3, Order::getSecondPayOrderNo, orderNo)

            );
            if (old == null) {
                break;
            }
        }
        return orderNo;
    }


    @Override
    public ResponseData orderAliNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("******************************进入支付宝支付回调");
        //接收参数进行校验
        Map<String, String> paramsMap = AlipayCore.updateMap(request);
        //流水号
        String payId = paramsMap.get("out_trade_no");
        // 支付宝订单号
        String orderNo = paramsMap.get("trade_no");
        //付款状态
        String tradeStatus = paramsMap.get("trade_status");
        log.info("******************************payId=" + payId);

        Order cur = baseMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getFirstPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getFirstStatus() == 2) {
            log.error("支付宝回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }
        if (cur.getFirstStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getFirstTripartitePrice(), cur.getFirstTripartitePrice(), cur.getFirstPayOrderNo(), orderNo, cur.getFirstGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getOrderNo());
            }
            return responseData;
        }
        if ("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getFirstGivePrice()) && cur.getFirstGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(),
                            cur.getFirstGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getFirstTripartitePrice(), cur.getFirstTripartitePrice(), cur.getFirstPayOrderNo(), orderNo, cur.getFirstGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getOrderNo());
                    }
                    return responseData;
                }
            }

            this.lambdaUpdate().set(Order::getAliBusinessId, orderNo).eq(Order::getId, cur.getId()).update();

            after(cur);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setFirstStatus(3);
            baseMapper.updateById(cur);
            log.error("支付失败");
        }
        return ResponseData.error("");
    }

    @Override
    public ResponseData orderWxNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> requestMap = HttpRequestUtil.parseXml(request);
        // 微信中的订单号
        String transactionId = requestMap.get("transaction_id");
        // 用户唯一标识
        String openid = requestMap.get("openid");
        //流水号
        String payId = requestMap.get("out_trade_no");

        Order cur = baseMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getFirstPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getFirstStatus() == 2) {
            log.error("微信回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }
        if (cur.getFirstStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getFirstTripartitePrice(), cur.getFirstTripartitePrice(), cur.getFirstPayOrderNo(), cur.getAliBusinessId(), cur.getFirstGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getOrderNo());
            }
            return responseData;
        }

        if ("SUCCESS".equals(requestMap.get("result_code"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getFirstGivePrice()) && cur.getFirstGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getFirstGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getFirstTripartitePrice(), cur.getFirstTripartitePrice(), cur.getFirstPayOrderNo(), cur.getAliBusinessId(), cur.getFirstGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getOrderNo());
                    }
                    return responseData;
                }
            }


            after(cur);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setFirstStatus(3);
            baseMapper.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Autowired
    private OnlineRecordService onlineRecordService;

    @Override
    public ResponseData orderLakalaNotify(Map<String, String> requestMap) {
        //商户订单号
        String payId = requestMap.get("out_order_no");

        Order cur = baseMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getFirstPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getFirstStatus() == 2) {
            log.error("拉卡拉回调已经开始 回去吧");
            return ResponseData.error("拉卡拉回调已经开始 回去吧");
        }

        //order_status 聚合收银台订单状态 	0:待支付 1:支付中 2:支付成功 3:支付失败 4:已过期 5:已取消 6：部分退款或者全部退款
        if (("2").equals(requestMap.get("order_status"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getFirstGivePrice()) && cur.getFirstGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getFirstGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getFirstTripartitePrice(), cur.getFirstTripartitePrice(), cur.getFirstPayOrderNo(), cur.getAliBusinessId(), cur.getFirstGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getOrderNo());
                    }
                    return responseData;
                }
            }


            after(cur);//支付后逻辑处理
            log.info("正常");

            //设置成功标识
            businessUtil.setOutTradeNo(payId);

            //添加支付记录
            onlineRecordService.addOnlineRecord(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstTripartitePrice(), WalletDetailEnums.ORDER_PAY);

            return ResponseData.success();
        } else {
            cur.setFirstStatus(3);
            baseMapper.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData secondOrderAliNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("******************************进入支付宝支付回调");
        //接收参数进行校验
        Map<String, String> paramsMap = AlipayCore.updateMap(request);
        //流水号
        String payId = paramsMap.get("out_trade_no");
        // 支付宝订单号
        String orderNo = paramsMap.get("trade_no");
        //付款状态
        String tradeStatus = paramsMap.get("trade_status");
        log.info("******************************payId=" + payId);

        Order cur = baseMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getSecondPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getSecondStatus() == 2) {
            log.error("支付宝回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }
        if (cur.getSecondStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getSecondPayType(), cur.getSecondTripartitePrice(), cur.getSecondTripartitePrice(), cur.getSecondPayOrderNo(), orderNo, cur.getSecondGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getOrderNo());
            }
            return responseData;
        }
        if ("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getSecondGivePrice()) && cur.getSecondGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getSecondGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getSecondTripartitePrice(), cur.getSecondTripartitePrice(), cur.getSecondPayOrderNo(), orderNo, cur.getSecondGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getOrderNo());
                    }
                    return responseData;
                }
            }

            this.lambdaUpdate().set(Order::getSecondAliBusinessId, orderNo).eq(Order::getId, cur.getId()).update();

            endPayAfter(cur, cur.getIsAgree() == 1 ? false : true);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setSecondStatus(3);
            baseMapper.updateById(cur);
            log.error("支付失败");
        }
        return ResponseData.error("");
    }

    @Override
    public ResponseData secondOrderWxNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> requestMap = HttpRequestUtil.parseXml(request);
        // 微信中的订单号
        String transactionId = requestMap.get("transaction_id");
        // 用户唯一标识
        String openid = requestMap.get("openid");
        //流水号
        String payId = requestMap.get("out_trade_no");

        Order cur = baseMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getSecondPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getSecondStatus() == 2) {
            log.error("微信回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }
        if (cur.getSecondStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getSecondPayType(), cur.getSecondTripartitePrice(), cur.getSecondTripartitePrice(), cur.getSecondPayOrderNo(), cur.getSecondAliBusinessId(), cur.getSecondGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getOrderNo());
            }
            return responseData;
        }

        if ("SUCCESS".equals(requestMap.get("result_code"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getSecondGivePrice()) && cur.getSecondGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getSecondGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getSecondTripartitePrice(), cur.getSecondTripartitePrice(), cur.getSecondPayOrderNo(), cur.getAliBusinessId(), cur.getSecondGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getOrderNo());
                    }
                    return responseData;
                }
            }


            endPayAfter(cur, cur.getIsAgree() == 1 ? false : true);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setSecondStatus(3);
            baseMapper.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData secondOrderLakalaNotify(Map<String, String> requestMap) {
        //商户订单号
        String payId = requestMap.get("out_order_no");
        Order cur = baseMapper.selectOne(new QueryWrapper<Order>().lambda().eq(Order::getSecondPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getSecondStatus() == 2) {
            log.error("拉卡拉回调已经开始 回去吧");
            return ResponseData.error("拉卡拉回调已经开始 回去吧");
        }

        //order_status 聚合收银台订单状态 	0:待支付 1:支付中 2:支付成功 3:支付失败 4:已过期 5:已取消 6：部分退款或者全部退款
        if (("2").equals(requestMap.get("order_status"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getSecondGivePrice()) && cur.getSecondGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getSecondGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getFirstPayType(), cur.getSecondTripartitePrice(), cur.getSecondTripartitePrice(), cur.getSecondPayOrderNo(), cur.getAliBusinessId(), cur.getSecondGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getOrderNo());
                    }
                    return responseData;
                }
            }


            endPayAfter(cur, cur.getIsAgree() == 1 ? false : true);//支付后逻辑处理
            log.info("正常");

            //设置成功标识
            businessUtil.setOutTradeNo(payId);

            //添加支付记录
            onlineRecordService.addOnlineRecord(new UserVo(UserEnums.customer.getCode(), cur.getCustomerId()), cur.getId(), cur.getSecondTripartitePrice(), WalletDetailEnums.ORDER_PAY);

            return ResponseData.success();
        } else {
            cur.setSecondStatus(3);
            baseMapper.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData orderAdjustPricePayAliNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("******************************进入支付宝支付回调");
        //接收参数进行校验
        Map<String, String> paramsMap = AlipayCore.updateMap(request);
        //流水号
        String payId = paramsMap.get("out_trade_no");
        // 支付宝订单号
        String orderNo = paramsMap.get("trade_no");
        //付款状态
        String tradeStatus = paramsMap.get("trade_status");
        log.info("******************************payId=" + payId);

        OrderChangeRecord cur = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getPayStatus() == 2) {
            log.error("支付宝回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }

        Order order = this.getById(cur.getOrderId());


        BigDecimal tripartitePrice = cur.getPayPrice().subtract(cur.getGivePrice());

        if (cur.getPayStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), orderNo, cur.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getPayOrderNo());
            }
            return responseData;
        }
        if ("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getGivePrice()) && cur.getGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //赠送余额
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getPayOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), cur.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), orderNo, cur.getGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getPayOrderNo());
                    }
                    return responseData;
                }
            }

            orderChangeRecordService.lambdaUpdate().set(OrderChangeRecord::getAliBusinessId, orderNo).eq(OrderChangeRecord::getId, cur.getId()).update();
            cur.setPayType(PayEnums.app_alipay.getCode());
            afterAdjustPricePay(cur);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setPayStatus(3);
            orderChangeRecordService.updateById(cur);
            log.error("支付失败");
        }
        return ResponseData.error("");
    }

    @Override
    public ResponseData orderAdjustPricePayWxNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> requestMap = HttpRequestUtil.parseXml(request);
        // 微信中的订单号
        String transactionId = requestMap.get("transaction_id");
        // 用户唯一标识
        String openid = requestMap.get("openid");
        //流水号
        String payId = requestMap.get("out_trade_no");

        OrderChangeRecord cur = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getPayStatus() == 2) {
            log.error("微信回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }

        Order order = this.getById(cur.getOrderId());

        BigDecimal tripartitePrice = cur.getPayPrice().subtract(cur.getGivePrice());

        if (cur.getPayStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getPayOrderNo());
            }
            return responseData;
        }

        if ("SUCCESS".equals(requestMap.get("result_code"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getGivePrice()) && cur.getGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getPayOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), cur.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getPayOrderNo());
                    }
                    return responseData;
                }
            }
            cur.setPayType(PayEnums.app_weChat.getCode());
            afterAdjustPricePay(cur);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setPayStatus(3);
            orderChangeRecordService.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData orderAdjustPricePayLakalaNotify(Map<String, String> requestMap) {
        //流水号
        String payId = requestMap.get("out_order_no");

        OrderChangeRecord cur = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getPayStatus() == 2) {
            log.error("拉卡拉回调已经开始 回去吧");
            return ResponseData.error("拉卡拉回调已经开始 回去吧");
        }

        Order order = this.getById(cur.getOrderId());

        BigDecimal tripartitePrice = cur.getPayPrice().subtract(cur.getGivePrice());

        if (cur.getPayStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getPayOrderNo());
            }
            return responseData;
        }

        //order_status 聚合收银台订单状态 	0:待支付 1:支付中 2:支付成功 3:支付失败 4:已过期 5:已取消 6：部分退款或者全部退款
        if (("2").equals(requestMap.get("order_status"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getGivePrice()) && cur.getGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getPayOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), cur.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getPayOrderNo());
                    }
                    return responseData;
                }
            }
            cur.setPayType(PayEnums.lakala_ccss.getCode());
            afterAdjustPricePay(cur);//支付后逻辑处理
            log.info("正常");

            //设置成功标识
            businessUtil.setOutTradeNo(payId);

            //添加支付记录
            onlineRecordService.addOnlineRecord(new UserVo(UserEnums.customer.getCode(), cur.getUserId()), cur.getId(), cur.getPayPrice(), WalletDetailEnums.ADJUST_PRICE_PAY);

            return ResponseData.success();
        } else {
            cur.setPayStatus(3);
            orderChangeRecordService.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData orderAdjustPriceConfirmPayAliNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("******************************进入支付宝支付回调");
        //接收参数进行校验
        Map<String, String> paramsMap = AlipayCore.updateMap(request);
        //流水号
        String payId = paramsMap.get("out_trade_no");
        // 支付宝订单号
        String orderNo = paramsMap.get("trade_no");
        //付款状态
        String tradeStatus = paramsMap.get("trade_status");
        log.info("******************************payId=" + payId);

        OrderChangeRecord cur = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getPayStatus() == 2) {
            log.error("支付宝回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }

        Order order = this.getById(cur.getOrderId());


        BigDecimal tripartitePrice = cur.getPayPrice().subtract(cur.getGivePrice());

        if (cur.getPayStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), orderNo, cur.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getPayOrderNo());
            }
            return responseData;
        }
        if ("TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getGivePrice()) && cur.getGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getPayOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), cur.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), orderNo, cur.getGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getPayOrderNo());
                    }
                    return responseData;
                }
            }

            orderChangeRecordService.lambdaUpdate().set(OrderChangeRecord::getAliBusinessId, orderNo).eq(OrderChangeRecord::getId, cur.getId()).update();

            afterAdjustPriceConfirmPay(cur);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setPayStatus(3);
            orderChangeRecordService.updateById(cur);
            log.error("支付失败");
        }
        return ResponseData.error("");
    }

    @Override
    public ResponseData orderAdjustPriceConfirmPayWxNotify(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> requestMap = HttpRequestUtil.parseXml(request);
        // 微信中的订单号
        String transactionId = requestMap.get("transaction_id");
        // 用户唯一标识
        String openid = requestMap.get("openid");
        //流水号
        String payId = requestMap.get("out_trade_no");

        OrderChangeRecord cur = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getPayStatus() == 2) {
            log.error("微信回调已经开始 回去吧");
            return ResponseData.error("支付宝回调已经开始 回去吧");
        }

        Order order = this.getById(cur.getOrderId());

        BigDecimal tripartitePrice = cur.getPayPrice().subtract(cur.getGivePrice());

        if (cur.getPayStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getPayOrderNo());
            }
            return responseData;
        }

        if ("SUCCESS".equals(requestMap.get("result_code"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getGivePrice()) && cur.getGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getPayOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), cur.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getPayOrderNo());
                    }
                    return responseData;
                }
            }
            afterAdjustPriceConfirmPay(cur);//支付后逻辑处理
            log.info("正常");
            return ResponseData.success();
        } else {
            cur.setPayStatus(3);
            orderChangeRecordService.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData orderAdjustPriceConfirmPayLakalaNotify(Map<String, String> requestMap) {
        //流水号
        String payId = requestMap.get("out_order_no");

        OrderChangeRecord cur = orderChangeRecordService.getOne(new QueryWrapper<OrderChangeRecord>().lambda().eq(OrderChangeRecord::getPayOrderNo, payId));
        if (cur == null) {
            log.error("支付信息丢失");
            return ResponseData.error("支付信息丢失");
        }
        if (cur.getPayStatus() == 2) {
            log.error("拉卡拉回调已经开始 回去吧");
            return ResponseData.error("拉卡拉回调已经开始 回去吧");
        }

        Order order = this.getById(cur.getOrderId());

        BigDecimal tripartitePrice = cur.getPayPrice().subtract(cur.getGivePrice());

        if (cur.getPayStatus() == 3) {
            //退款
            ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), order.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
            if (!responseData.getSuccess()) {
                log.error("退款失败：" + cur.getPayOrderNo());
            }
            return responseData;
        }

        //order_status 聚合收银台订单状态 	0:待支付 1:支付中 2:支付成功 3:支付失败 4:已过期 5:已取消 6：部分退款或者全部退款
        if (("2").equals(requestMap.get("order_status"))) {

            //是否使用抵用金支付
            if (ObjectUtil.isNotEmpty(cur.getGivePrice()) && cur.getGivePrice().compareTo(BigDecimal.ZERO) > 0) {
                //抵用金
                try {
                    giveWalletRecordService.updateGiveBalance(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), WalletDetailEnums.GIVE_ORDER_PAY, cur.getId(), cur.getGivePrice().negate(), PublicCommon.Wallet.可提现);
                } catch (CustomException c) {
                    log.error("抵用金支付失败：" + cur.getPayOrderNo());

                    //退款
                    ResponseData responseData = payUtil.refund(new UserVo(UserEnums.customer.getCode(), order.getCustomerId()), cur.getId(), cur.getPayType(), tripartitePrice, tripartitePrice, cur.getPayOrderNo(), cur.getAliBusinessId(), cur.getGivePrice());
                    if (!responseData.getSuccess()) {
                        log.error("退款失败：" + cur.getPayOrderNo());
                    }
                    return responseData;
                }
            }
            afterAdjustPriceConfirmPay(cur);//支付后逻辑处理
            log.info("正常");

            //设置成功标识
            businessUtil.setOutTradeNo(payId);

            //添加支付记录
            onlineRecordService.addOnlineRecord(new UserVo(UserEnums.customer.getCode(), cur.getUserId()), cur.getId(), cur.getPayPrice(), WalletDetailEnums.ADJUST_PRICE_PAY);

            return ResponseData.success();
        } else {
            cur.setPayStatus(3);
            orderChangeRecordService.updateById(cur);
            log.error("支付失败");
        }

        return ResponseData.error("");
    }

    @Override
    public ResponseData<Boolean> isNeedGetOrderDetail(IsNeedGetOrderDetailReq req) {
        //查询接单表现师
        List<OrderReceiving> orderReceivingList = orderReceivingService.list(new QueryWrapper<OrderReceiving>().lambda()
                .eq(OrderReceiving::getOrderId, req.getOrderId()).eq(OrderReceiving::getDelFlag, PublicCommon.启用).orderByDesc(BaseEntity::getCreateTime));

        if (StringUtils.isBlank(req.getDate()) && orderReceivingList.size() > 0) {
            return ResponseData.success(true);
        }
        if (StringUtils.isNotBlank(req.getDate())) {
            if (orderReceivingList.size() == 0) {
                return ResponseData.success(true);
            }

            StringBuffer stringBuffer = new StringBuffer();
            orderReceivingList.stream().forEach(x -> {
                stringBuffer.append(x.getId());
            });
            if (!stringBuffer.toString().equals(req.getDate())) {
                return ResponseData.success(true);
            }
        }
        return ResponseData.success(false);
    }


}
