package cn.iocoder.yudao.module.payment.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.inspection.entity.*;
import cn.iocoder.yudao.module.inspection.service.*;
import cn.iocoder.yudao.module.partner.entity.PartnerWorker;
import cn.iocoder.yudao.module.partner.service.IPartnerWorkerService;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.payment.entity.OrderInfoDetail;
import cn.iocoder.yudao.module.payment.entity.commentVo;
import cn.iocoder.yudao.module.payment.mapper.OrderInfoMapper;
import cn.iocoder.yudao.module.payment.service.IOrderInfoDetailService;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import cn.iocoder.yudao.module.shop.entity.*;
import cn.iocoder.yudao.module.shop.service.*;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import cn.iocoder.yudao.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * (OrderInfo)表服务实现类
 *
 * @author makejava
 * @since 2023-07-24 18:30:29
 */
@Service("orderInfoService")
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    @Autowired
    private AppInspectionPartnerService partnerService;
    @Autowired
    private IOrderInfoDetailService orderInfoDetailService;
    @Autowired
    private IInspectionInfoService iInspectionInfoService;
    @Autowired
    private IUserBalanceService userBalanceService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private IShopCouponService shopCouponService;
    @Autowired
    private AdminUserService userService;
    @Autowired
    private IInspectionAppointmentService appointmentService;
    @Autowired
    private IInspectionPickCarService pickCarService;
    @Autowired
    private InspectionGoodsSkuService skuService;
    @Autowired
    private IShopInspectionGoodsService iShopInspectionService;
    @Autowired
    private IPartnerWorkerService workerService;
    @Autowired
    private IShopConfigService configService;
    @Autowired
    private IShopRepairGoodsService repairGoodsService;
    @Autowired
    private IShopMallPartnersService shopMallPartnersService;

    @Override
    public void reviewOrder(String orderId, Integer starLevel, String reviewStr) throws Exception {
        OrderInfo orderInfo = this.getById(orderId);
        if (!Objects.equals(orderInfo.getUserId(), SecurityFrameworkUtils.getLoginUserId())) {
            throw new Exception("禁止评价");
        }
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderInfo::getId, orderId)
                .set(OrderInfo::getCommentTime,new Date())
                .set(OrderInfo::getCommentStar, starLevel).set(OrderInfo::getCommentDesc, reviewStr)
                .set(OrderInfo::getOrderStatus, "3");
        this.update(wrapper);
        orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"评论订单",new Date(),0L,"1"));
        //计算当前店铺评分
        if (ObjectUtil.isNotEmpty(orderInfo.getPartnerId())) {
            Double score = baseMapper.avgPartnerScore(orderInfo.getPartnerId());
            ShopMallPartners partner = partnerService.getById(orderInfo.getPartnerId());
            partner.setAverageScore(score);
            partnerService.updateById(partner);
        }
    }
    @Override
    public IPage<OrderInfo> orderListApp(Page<OrderInfo> page,String status, String title, String type) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        return baseMapper.orderListApp(page,user.getId(), status, title, type);
    }

    @Override
    public List<InspectionInfo> workOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime) {
        if (StringUtils.isNotEmpty(startTime)){
            startTime = startTime+" 00:00:00";
        }
        if (StringUtils.isNotEmpty(endTime)){
            endTime = endTime+" 23:59:59";
        }
        return iInspectionInfoService.workOrder(partnerId,carNum,goodsTitle, customerSource, payType, startTime, roleId,endTime);
    }

    @Override
    public IPage<InspectionInfo> pageWorkOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime, Page<InspectionInfo> page) {
        if (StringUtils.isNotEmpty(startTime)){
            startTime = startTime+" 00:00:00";
        }
        if (StringUtils.isNotEmpty(endTime)){
            endTime = endTime+" 23:59:59";
        }

        return iInspectionInfoService.pageWorkOrder(partnerId,carNum,goodsTitle, customerSource, payType, startTime, roleId,endTime,page);
    }

    @Override
    public Map<String, Object> workOrderData(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime) {
        if (StringUtils.isNotEmpty(startTime)){
            startTime = startTime+" 00:00:00";
        }
        if (StringUtils.isNotEmpty(endTime)){
            endTime = endTime+" 23:59:59";
        }
        return iInspectionInfoService.workOrderData(partnerId,carNum,goodsTitle, customerSource, payType, startTime, roleId,endTime);
    }

    @Override
    public List<InspectionInfo> delworkOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime) {
        if (StringUtils.isNotEmpty(startTime)){
            startTime = startTime+" 00:00:00";
        }
        if (StringUtils.isNotEmpty(endTime)){
            endTime = endTime+" 23:59:59";
        }
        return iInspectionInfoService.delworkOrder(partnerId,carNum,goodsTitle, customerSource, payType, startTime, roleId,endTime);
    }

    @Override
    public IPage<InspectionInfo> pageDelworkOrder(Long partnerId, String carNum, String goodsTitle, String customerSource, String payType, String startTime, Long roleId, String endTime, Page<InspectionInfo> page) {
        if (StringUtils.isNotEmpty(startTime)){
            startTime = startTime+" 00:00:00";
        }
        if (StringUtils.isNotEmpty(endTime)){
            endTime = endTime+" 23:59:59";
        }
        return iInspectionInfoService.pageDelWorkOrder(partnerId,carNum,goodsTitle, customerSource, payType, startTime, roleId,endTime,page);
    }

    @Override
    public IPage<OrderInfo> orderListSystem(Page<OrderInfo> page,OrderInfo orderInfo) {
        return baseMapper.orderListSystem(page,orderInfo);
    }

    /**
     * 分页查询订单
     *
     * @param orderInfo OrderInfo实体
     * @param page      分页参数
     * @return com.baomidou.mybatisplus.core.metadata.IPage<cn.iocoder.yudao.module.payment.entity.OrderInfo>
     * @author PQZ
     * @date 0:02 2024/9/20
     **/
    @Override
    public IPage<OrderInfo> queryListPage(OrderInfo orderInfo, Page<OrderInfo> page) {
        return baseMapper.pageOrderListSystem(orderInfo,page);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(OrderInfo orderInfo) throws Exception {
        //获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(loginUser.getId());
        UserBalance shopUserBalance = userBalanceService.selectShopUserBalanceByUserId(user.getId());
        if (orderInfo.getBalance() > 0) {
            if (ObjectUtil.isEmpty(shopUserBalance) || ObjectUtil.isEmpty(shopUserBalance.getBalance())) {
                throw new Exception("积分不足!");
            }
            if (orderInfo.getBalance() > shopUserBalance.getBalance()) {
                throw new Exception("积分不足!");
            }
        }
        if ((orderInfo.getGoodsType().equals("qxmd") || orderInfo.getGoodsType().equals("jymd")) && orderInfo.getMdAmount() <= 0) {
            throw new Exception("请输入买单金额!");
        }

        if (StringUtils.isNotEmpty(orderInfo.getPayType())&&orderInfo.getPayType().equals("sz")){
            Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(user.getId());
            List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
            boolean flag = false;
            for (RoleDO role : roleList) {
                if (role.getCode().equals("jcdb")) {
                    flag = true;
                    break;
                }
            }
            if (!flag){
                throw new Exception("您不是代办 请不要选择赊账!");
            }
        }
        //优惠卷的积分
        Long couponAmount = 0L;
        String isCoupon = "0";
        ShopCoupon shopCoupon = null;
        if (null != orderInfo.getCouponId()) {
            //判断当前用户是否拥有此优惠卷
            shopCoupon = shopCouponService.selectShopCouponByCouponId(orderInfo.getCouponId());
            if (!ObjectUtil.isEmpty(shopCoupon)) {
                Lock lock = new ReentrantLock();
                lock.lock();
                try {
                    if (!shopCoupon.getCouponStatus().equals("0") || !shopCoupon.getUserId().equals(user.getId())) {
                        throw new Exception("优惠卷不存在");
                    }
                    //判断是否过期
                    boolean flag = shopCoupon.getStartTime().before(new Date()) && shopCoupon.getExpirationTime().after(new Date());
                    if (!flag) {
                        throw new Exception("优惠卷不在使用期限内");
                    }
                    //判断模块是否正确
                    if (shopCoupon.getCouponType().equals("cash")) {
                        //现金卷
                        if (shopCoupon.getBindMoudle().equals("检测项目现金券") && !orderInfo.getGoodsType().equals("jc")) {
                            throw new Exception("优惠卷不正确");
                        }
                        if (shopCoupon.getBindMoudle().equals("维修项目现金券") && !(orderInfo.getGoodsType().equals("qx") || orderInfo.getGoodsType().equals("qxmd"))) {
                            throw new Exception("优惠卷不正确");
                        }

                    }
                    //如果是抵扣券
                    if (shopCoupon.getCouponType().equals("offset")) {
                        //抵扣券 判断商品id是否正确
                        if (!shopCoupon.getBindGoodsIds().contains(orderInfo.getGoodsId().toString())) {
                            throw new Exception("优惠卷不匹配");
                        }
                    }
                    //冻结住优惠卷
                    shopCoupon.setCouponStatus("3");
                    shopCouponService.updateShopCoupon(shopCoupon);
                    couponAmount = shopCoupon.getDiscount();
                    isCoupon = "1";
                } finally {
                    lock.unlock();
                }
            }

        }
        JSONObject goods = this.getGoodsInfo(orderInfo);
        if (ObjectUtil.isNotEmpty(shopCoupon) && StringUtils.isNotEmpty(shopCoupon.getCouponType()) && shopCoupon.getCouponType().equals("offset")) {
            //如果是抵消卷 则匹配当前商品的价格
            couponAmount = goods.getLong("payMoney");
        }
        OrderInfo createOrder = new OrderInfo();
        createOrder.setOrderNo((orderInfo.getGoodsType().equals("qxmd") || orderInfo.getGoodsType().equals("jymd") ? orderInfo.getGoodsType() : goods.getString("goodsId")) + "-" + System.currentTimeMillis() + "-" + getRandomString6());
        createOrder.setGoodsId(goods.getLong("goodsId"));
        createOrder.setGoodsTitle(goods.getString("goodsName"));
        createOrder.setGoodsType(orderInfo.getGoodsType());
        createOrder.setSkuId(goods.getLong("skuId"));
        createOrder.setSkuName(goods.getString("skuName"));
        createOrder.setPartnerId(goods.getLong("partnerId"));
        createOrder.setPartnerName(goods.getString("partnerName"));
        createOrder.setRealName(user.getNickname());
        createOrder.setPhonenumber(user.getMobile());
        createOrder.setCreator(String.valueOf(user.getId()));
        createOrder.setDeptId(user.getDeptId());
        createOrder.setReduceMoney(goods.getLong("reduceMoney"));
        //待支付
        createOrder.setOrderStatus("0");
        createOrder.setGoodsPrice(goods.getLongValue("goodsPrice"));
        createOrder.setPayMoney(goods.getLong("payMoney") - orderInfo.getBalance() - couponAmount);
        createOrder.setBalance(orderInfo.getBalance());
        createOrder.setOrderTime(new Date());
        createOrder.setUserId(user.getId());
        createOrder.setIsCoupon(isCoupon);
        createOrder.setUserCarId(orderInfo.getUserCarId());
        createOrder.setOtherPhone(orderInfo.getOtherPhone());
        createOrder.setDriverLicenesImg(orderInfo.getDriverLicenesImg());
        createOrder.setIsPayOnline(orderInfo.getIsPayOnline());
        createOrder.setIsPickCar(orderInfo.getIsPickCar());

        if (isCoupon.equals("1")) {
            createOrder.setCouponId(orderInfo.getCouponId());
        }
        this.save(createOrder);
        //追加订单明细记录
        OrderInfoDetail detail =new OrderInfoDetail(createOrder.getId(),"创建订单",new Date(),0L,"0");
        orderInfoDetailService.save(detail);
        if (ObjectUtil.isNotEmpty(orderInfo.getAppointmentId())){
            //处理预约记录
            orderInfo.setId(createOrder.getId());
            this.dealAppointment(orderInfo);

        }
        if (ObjectUtil.isNotEmpty(orderInfo.getPickCarId())){
            //处理上门取车服务
            orderInfo.setId(createOrder.getId());
            this.dealPickCar(orderInfo);

        }
        if (goods.getLong("payMoney") - couponAmount - orderInfo.getBalance() <= 0) {
            Long userBalance = (goods.getLong("payMoney") - couponAmount) > 0 ? goods.getLong("payMoney") - couponAmount : 0L;
            //公共订单处理
            createOrder.setPayMoney(0L);
            createOrder.setBalance(userBalance);
            if (isCoupon.equals("1")) {
                //如果使用优惠卷
                //核销掉优惠卷
                shopCoupon.setCouponStatus("1");
                shopCoupon.setOrderId(createOrder.getId());
                shopCoupon.setUseTime(new Date());
                shopCouponService.updateShopCoupon(shopCoupon);
                createOrder.setCouponId(shopCoupon.getCouponId());
                createOrder.setCouponDiscount(shopCoupon.getDiscount() > goods.getLong("payMoney") ? goods.getLong("payMoney") : shopCoupon.getDiscount());

            }
            if (userBalance > 0) {
                //扣除积分
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("goodsType", orderInfo.getGoodsType());
                jsonObject.put("goodsTitle", orderInfo.getGoodsTitle());
                userBalanceService.subtractBalance(userBalance, user.getId(), jsonObject);
            }
            // 生成16位核销码
            UUID uuid = UUID.randomUUID();
            long mostSignificantBits = uuid.getMostSignificantBits();
            long leastSignificantBits = uuid.getLeastSignificantBits();
            String combinedBits = mostSignificantBits + String.valueOf(leastSignificantBits);
            String shortUuid = combinedBits.substring(combinedBits.length() - 16);
            createOrder.setAccessCode(shortUuid);
            createOrder.setOrderStatus("1");
            createOrder.setPayTime(new Date());
            //支付方式为余额支付
            createOrder.setPayType("balance");
            this.updateById(createOrder);
            //追加订单明细记录
            orderInfoDetailService.save(new OrderInfoDetail(createOrder.getId(),"支付成功",new Date(),createOrder.getPayMoney(),"0"));
            //店铺销量+1
            if (goods.getLong("partnerId") != null) {
                partnerService.addSalesNum(goods.getLong("partnerId"));
            }
            return 11111111L;

        } else if (StringUtils.isNotEmpty(createOrder.getPayType())&&createOrder.getPayType().equals("sz")){
            //赊账的情况
            //支付方式为余额支付
            createOrder.setPayType("sz");
            // 生成16位核销码
            UUID uuid = UUID.randomUUID();
            long mostSignificantBits = uuid.getMostSignificantBits();
            long leastSignificantBits = uuid.getLeastSignificantBits();
            String combinedBits = mostSignificantBits + String.valueOf(leastSignificantBits);
            String shortUuid = combinedBits.substring(combinedBits.length() - 16);
            createOrder.setAccessCode(shortUuid);
            this.updateById(createOrder);
            return 11111111L;
        } else {
            //支付方式为余额支付
            createOrder.setPayType("wx");
            if (isCoupon.equals("1")) {
                //如果使用优惠卷
                createOrder.setCouponId(shopCoupon.getCouponId());
                createOrder.setCouponDiscount(shopCoupon.getDiscount());
            }
            this.updateById(createOrder);
            //冻结积分
            userBalanceService.frozenBalance(orderInfo.getBalance(), user.getId());
        }
        return createOrder.getId();
    }

    //获取商品信息
    private JSONObject getGoodsInfo(OrderInfo orderInfo) throws Exception {
        JSONObject res = new JSONObject();
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO sysUser = userService.getUser(userId);
        Integer userLevel = sysUser.getUserLevel();
        res.put("skuId", null);
        res.put("skuName", "");
        res.put("partnerId", null);
        res.put("partnerName", "");
        Long reduceMoney = 0l;
        if (orderInfo.getGoodsType().equals("jc")) {
            Long priceFen = 0L;
            ShopInspectionGoods shopInspectionGoods = new ShopInspectionGoods();
            if (ObjectUtil.isNotEmpty(orderInfo.getSkuId())) {
                Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(sysUser.getId());
                List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
                List<String> roleKeys = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList());
                //汽车检测
                //规格处理
                InspectionGoodsSku skuInfo = skuService.getById(orderInfo.getSkuId());
                shopInspectionGoods = iShopInspectionService.selectShopInspectionGoodsById(Long.parseLong(skuInfo.getGoodsId().toString()));
                if (ObjectUtil.isEmpty(shopInspectionGoods)) {
                    throw new Exception("商品不存在");
                }
                ShopMallPartners partners = partnerService.getById(shopInspectionGoods.getPartnerId());
                if (ObjectUtil.isEmpty(partners)) {
                    throw new Exception("店铺不存在");
                }
                res.put("goodsId", skuInfo.getGoodsId());
                res.put("goodsName", shopInspectionGoods.getTitle());
                res.put("partnerId", shopInspectionGoods.getPartnerId());
                res.put("partnerName", partners.getPartnerName());

                //商品原价
                res.put("goodsPrice", skuInfo.getPrice());
                res.put("skuId", skuInfo.getId());
                res.put("skuName", skuInfo.getSkuName());
                priceFen = skuInfo.getPrice();
                try {
                    if (roleKeys.contains("jcdb")){
                        //先判断是否为代办
                        priceFen=skuInfo.getDbPrice();
                    }else if (roleKeys.contains("jcdwgly")){
                        //单位管理员
                        priceFen=skuInfo.getDwPrice();
                    }else if (roleKeys.contains("jcworker")||roleKeys.contains("jcshop")){
                        //检测工人
                        //判断是否为当前店铺的工人
                        LambdaQueryWrapper<PartnerWorker> queryWrapper1 =new LambdaQueryWrapper<>();
                        queryWrapper1.eq(PartnerWorker::getUserId,userId).eq(PartnerWorker::getPartnerId,shopInspectionGoods.getPartnerId()).last("limit 1");
                        PartnerWorker one = workerService.getOne(queryWrapper1);
                        if (ObjectUtils.isNotEmpty(one)){
                            priceFen=skuInfo.getYgPrice();
                        }
                    }

                }catch (Exception e){
                    log.error(e.getMessage());
                }
            } else {
                //汽车检测
                shopInspectionGoods = iShopInspectionService.selectShopInspectionGoodsById(orderInfo.getGoodsId());
                priceFen = shopInspectionGoods.getPrice();
                if (ObjectUtil.isEmpty(shopInspectionGoods)) {
                    throw new Exception("商品不存在");
                }
                ShopMallPartners partners = partnerService.getById(shopInspectionGoods.getPartnerId());
                if (ObjectUtil.isEmpty(partners)) {
                    throw new Exception("店铺不存在");
                }
                res.put("goodsId", orderInfo.getGoodsId());
                res.put("goodsName", shopInspectionGoods.getTitle());
                res.put("partnerId", shopInspectionGoods.getPartnerId());
                res.put("partnerName", partners.getPartnerName());
                //商品
                res.put("goodsPrice", shopInspectionGoods.getPrice());
            }
            //根据计算得到的实付金额
            ShopConfig shopConfig = configService.selectShopConfigById(1L);
            //原价单位分

            Double priceYuan = priceFen.doubleValue() / 100d;
            Long realPrice = 0L;
            if (StringUtils.isEmpty(shopInspectionGoods.getIsAttend()) || shopInspectionGoods.getIsAttend().equals("0") || shopInspectionGoods.getIsSpecial() == 1 || ObjectUtils.isEmpty(userLevel) || 0 == userLevel) {
                //直接计算原价
                realPrice = priceFen;
            }
            else if (userLevel == 1) {
                //白银会员
                //获取会员的优惠折扣
                BigDecimal inspectionPlatinum = shopConfig.getInspectionSilver();
                Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
                Double realPriceTemp = BigDecimal.valueOf(priceYuan * ratio).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                realPrice = realPriceTemp.longValue();

            } else if (userLevel == 2) {
                //黄金会员
                BigDecimal inspectionPlatinum = shopConfig.getInspectionGold();
                Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
                Double realPriceTemp = BigDecimal.valueOf(priceYuan * ratio).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                realPrice = realPriceTemp.longValue();
            } else if (userLevel == 3) {
                //白金会员
                BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
                Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
                Double realPriceTemp = BigDecimal.valueOf(priceYuan * ratio).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                realPrice = realPriceTemp.longValue();
            }
            reduceMoney = priceFen - realPrice;
            //追加汽车上门取车服务费用
            if (ObjectUtil.isNotEmpty(orderInfo.getPickCarId())){
                JSONObject jsonObject = pickCarDetail(orderInfo.getPickCarId());
                realPrice = realPrice +jsonObject.getLong("pickCarPrice");
            }
            res.put("payMoney", realPrice);
        } else if (orderInfo.getGoodsType().equals("qx")) {
            //汽车维修
            ShopRepairGoods repairGoods = repairGoodsService.selectShopRepairGoodsById(orderInfo.getGoodsId());
            if (ObjectUtil.isEmpty(repairGoods)) {
                throw new Exception("商品不存在");
            }
            res.put("goodsId", orderInfo.getGoodsId());
            res.put("goodsName", repairGoods.getTitle());
            //商品原价
            res.put("goodsPrice", repairGoods.getPrice());
            //根据计算得到的实付金额
            ShopConfig shopConfig = configService.selectShopConfigById(1L);
            //原价单位分
            Long priceFen = repairGoods.getPrice();
            Double priceYuan = priceFen.doubleValue() / 100d;
            Long realPrice = 0L;
            if (repairGoods.getIsSpecial() == 1 || ObjectUtils.isEmpty(userLevel) || 0 == userLevel) {
                //直接计算原价
                realPrice = priceFen;
            } else if (userLevel == 1) {
                //白银会员
                //获取会员的优惠折扣
                BigDecimal inspectionPlatinum = shopConfig.getInspectionSilver();
                Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
                Double realPriceTemp = BigDecimal.valueOf(priceYuan * ratio).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                realPrice = realPriceTemp.longValue();

            } else if (userLevel == 2) {
                //黄金会员
                BigDecimal inspectionPlatinum = shopConfig.getInspectionGold();
                Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
                Double realPriceTemp = BigDecimal.valueOf(priceYuan * ratio).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                realPrice = realPriceTemp.longValue();
            } else if (userLevel == 3) {
                //白金会员
                BigDecimal inspectionPlatinum = shopConfig.getInspectionPlatinum();
                Double ratio = inspectionPlatinum.divide(BigDecimal.valueOf(10)).doubleValue();
                Double realPriceTemp = BigDecimal.valueOf(priceYuan * ratio).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                realPrice = realPriceTemp.longValue();
            }
            res.put("payMoney", realPrice);
            reduceMoney = priceFen - realPrice;
        } else if (orderInfo.getGoodsType().equals("cz")) {
            //积分充值
            res.put("goodsId", orderInfo.getGoodsId());
            res.put("goodsName", "积分充值");
            //商品原价
            res.put("goodsPrice", orderInfo.getBalanceCz());
            res.put("payMoney", orderInfo.getBalanceCz());
        } else if (orderInfo.getGoodsType().equals("qxmd")) {
            //买单功能
            //原价单位分
            Long priceFen = orderInfo.getMdAmount();
            Long realPrice = 0L;
            //直接计算原价
            realPrice = priceFen;
            res.put("goodsId", null);
            res.put("goodsName", orderInfo.getGoodsTitle());
            //商品原价
            res.put("goodsPrice", orderInfo.getMdAmount());
            res.put("payMoney", realPrice);
            reduceMoney = priceFen - realPrice;
        } else if (orderInfo.getGoodsType().equals("jymd")) {
            //买单功能
            //原价单位分
            Long priceFen = orderInfo.getMdAmount();
            Long realPrice = 0L;
            //直接计算原价
            realPrice = priceFen;
            res.put("goodsId", null);
            res.put("goodsName", orderInfo.getGoodsTitle());
            //商品原价
            res.put("goodsPrice", orderInfo.getMdAmount());
            res.put("payMoney", realPrice);
            reduceMoney = priceFen - realPrice;
        }
        //会员折扣的金额
        res.put("reduceMoney", reduceMoney);
        return res;
    }

    /**
     * 6位随机数
     *
     * @return
     */
    public static String getRandomString6() {
        String str = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder buff = new StringBuilder();
        for (int i = 0; i < 6; ++i) {
            int number = random.nextInt(str.length());
            buff.append(str.charAt(number));
        }
        return buff.toString();
    }

    private void dealAppointment(OrderInfo orderInfo){
        if (orderInfo.getGoodsType().equals("jc")){
            InspectionAppointment appointment = appointmentService.getById(orderInfo.getAppointmentId());
            appointment.setOrderId(orderInfo.getId());
            appointmentService.updateById(appointment);
//            //处理短信
//            String[] phones ={"18715738382","18715738835","18162987866"};
//
//            try {
//                String carNum ="未知车牌号";
//                //开始检测短信发送
//                Long carId = orderInfo.getUserCarId();
//                if (ObjectUtil.isNotEmpty(carId)){
//                    ShopUserCar userCar = userCarService.getById(carId);
//                    carNum = userCar.getCarNo();
//                }
//                for (String phone : phones) {
//                    if (PhoneValidator.isValid(phone)){
//                        SendSmsUtil.sendMsgCommon(new String[]{carNum,appointment.getAppointmentDay()+(appointment.getAppointmentPeriod().equals("0")?"上午":"下午")},phone,"1400852709","机动车管家小程序","1962738");
//                    }
//                }
//            }catch (Exception ignored){
//                log.error(ignored.getMessage());
//            }

        }
    }
    private void dealPickCar(OrderInfo orderInfo){
        if (orderInfo.getGoodsType().equals("jc")){
            InspectionPickCar pickCarInfo = pickCarService.getById(orderInfo.getPickCarId());
            pickCarInfo.setOrderId(orderInfo.getId());
            pickCarService.updateById(pickCarInfo);
            //追加订单明细记录
            orderInfoDetailService.save(new OrderInfoDetail(orderInfo.getId(),"上门取车费用",new Date(),pickCarInfo.getNeedPrice(),"1"));

        }
    }
    @Override
    public JSONObject pickCarDetail(Long pickCarId) {
        JSONObject res =new JSONObject();
        InspectionPickCar pickCar = pickCarService.getById(pickCarId);
        res.put("pickCarPrice",Optional.ofNullable(pickCar.getNeedPrice()).orElse(0L));
        return res;
    }

    @Override
    public JSONObject orderDetail(Long goodsId, String type, String title, Integer amount) {
        JSONObject res = new JSONObject();
        //获取当前登录用户
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO sysUser = userService.getUser(user.getId());
        Integer userLevel = sysUser.getUserLevel();
        ShopConfig shopConfig = configService.selectShopConfigById(1L);
        UserBalance shopUserBalance = userBalanceService.selectShopUserBalanceByUserId(user.getId());
        res.put("balance", Optional.ofNullable(shopUserBalance).orElse(new UserBalance()).getBalance());
        res.put("userLevel", userLevel);
        if (type.equals("jc")) {
            ShopInspectionGoods shopInspectionGoods = iShopInspectionService.selectShopInspectionGoodsById(goodsId);
            res.put("goodsName", shopInspectionGoods.getTitle());
            res.put("goodsImage", shopInspectionGoods.getImage());
            res.put("goodsPrice", shopInspectionGoods.getPrice());
            res.put("isSpecial", shopInspectionGoods.getIsSpecial());
            res.put("silver", shopConfig.getInspectionSilver());
            res.put("gold", shopConfig.getInspectionGold());
            res.put("platinum", shopConfig.getInspectionPlatinum());
        } else if (type.equals("qx")) {
            ShopRepairGoods shopInspectionGoods = repairGoodsService.selectShopRepairGoodsById(goodsId);
            res.put("goodsName", shopInspectionGoods.getTitle());
            res.put("goodsImage", shopInspectionGoods.getImage());
            res.put("goodsPrice", shopInspectionGoods.getPrice());
            res.put("isSpecial", shopInspectionGoods.getIsSpecial());
            res.put("silver", shopConfig.getInspectionSilver());
            res.put("gold", shopConfig.getInspectionGold());
            res.put("platinum", shopConfig.getInspectionPlatinum());
        } else if (type.equals("qxmd")) {
            res.put("goodsName", title);
            res.put("goodsImage", "http://www.nuoyunr.com/lananRsc/mdqx.png");
            res.put("goodsPrice", amount);
            res.put("isSpecial", "1");
            res.put("silver", 10);
            res.put("gold", 10);
            res.put("platinum", 10);
        } else if (type.equals("jymd")) {
            res.put("goodsName", title);
            res.put("goodsImage", "http://www.nuoyunr.com/lanan/mdqx.png");
            res.put("goodsPrice", amount);
            res.put("isSpecial", "1");
        }
        return res;
    }

    @Override
    public void cancelPay(Long orderId) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        OrderInfo info = this.getById(orderId);
        if (ObjectUtil.isNotEmpty(info.getBalance()) && info.getBalance() > 0) {
            //打开相应的冻结积分
            userBalanceService.thawBalance(info.getBalance(), user.getId());
        }
        if (!ObjectUtil.isEmpty(info.getIsCoupon()) && info.getIsCoupon().equals("1")) {
            //打开相应的冻结优惠卷
            ShopCoupon shopCoupon = shopCouponService.selectShopCouponByCouponId(info.getCouponId());
            //处理优惠卷
            shopCoupon.setCouponStatus("0");
            shopCouponService.updateShopCoupon(shopCoupon);
        }
        LambdaUpdateWrapper<InspectionAppointment> queryWrapper =new LambdaUpdateWrapper<>();
        queryWrapper.set(InspectionAppointment::getOrderId,null).eq(InspectionAppointment::getOrderId,orderId);
        appointmentService.update(queryWrapper);

    }

    @Override
    public IPage<OrderInfo> orderList(Page<OrderInfo> page,String status, String title) {
        LoginUser user = SecurityFrameworkUtils.getLoginUser();

        return baseMapper.orderList(page,user.getId(), status, title);
    }

    /**
     * 核销功能
     *
     * @param accessCode
     * @return
     */
    @Override
    public String validation(String accessCode) {
        if (accessCode == null || accessCode.length() != 16) {
            return "核销码有误";
        }
        LoginUser sysUser = SecurityFrameworkUtils.getLoginUser();
        AdminUserDO user = userService.getUser(sysUser.getId());
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(sysUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        boolean isInsider = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList()).contains("insider");

        if (!isInsider) {
            return "非公司员工禁止使用";
        }

        OrderInfo orderInfo = getOrderByAccessCode(accessCode);
        if (orderInfo != null && "1".equals(orderInfo.getOrderStatus())) {
            orderInfo.setOrderStatus("2");
            orderInfo.setValidationUserId(sysUser.getId());
            orderInfo.setValidationRealName(user.getNickname());
            orderInfo.setValidationTime(new Date());
            int result = baseMapper.updateById(orderInfo);
            String message = (result > 0) ? "核销成功" : "核销失败";
            return message;
        } else {
            return "无此核销码或该订单已核销";
        }
    }

    @Override
    public OrderInfo getOrderByAccessCode(String accessCode) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getAccessCode, accessCode);
        OrderInfo one = this.getOne(queryWrapper);
        return one;
    }

    /**
     * 商城核销功能
     *
     * @param accessCode
     * @return
     */
    @Override
    public String validationMall(String accessCode) {
        if (accessCode == null || accessCode.length() != 16) {
            return "核销码有误";
        }
        AdminUserDO sysUser = userService.getUser(SecurityFrameworkUtils.getLoginUserId());
        Set<Long> userRoleIdListByUserId = permissionService.getUserRoleIdListByUserId(sysUser.getId());
        List<RoleDO> roleList = roleService.getRoleList(userRoleIdListByUserId);
        boolean isPartners = roleList.stream().map(RoleDO::getCode).collect(Collectors.toList()).contains("partners");

        if (!isPartners) {
            return "当前账号，非合作商，禁止使用";
        }

        OrderInfo orderInfo = getOrderByAccessCode(accessCode);


        if (orderInfo != null && "1".equals(orderInfo.getOrderStatus())) {
            ShopMallPartners shopMallPartners = shopMallPartnersService.selectShopMallPartnersByUserId(sysUser.getId(),"sc");
            if (!Objects.equals(orderInfo.getPartnerId(), shopMallPartners.getPartnerId())) {
                return "非本店铺核销码";
            }
            orderInfo.setOrderStatus("2");
            orderInfo.setValidationUserId(sysUser.getId());
            orderInfo.setValidationRealName(sysUser.getNickname());
            orderInfo.setValidationTime(new Date());
            int result = baseMapper.updateById(orderInfo);
            String message = (result > 0) ? "核销成功" : "核销失败";
            return message;
        } else {
            return "无此核销码或该订单已核销";
        }
    }

    @Override
    public IPage<OrderInfo> validationListWx(Page<OrderInfo> page) {
        return  baseMapper.validationListWx(page,SecurityFrameworkUtils.getLoginUserId());
    }

    // pc端核销记录 商城
    @Override
    public IPage<OrderInfo> validationListPc(Page<OrderInfo> page) {
        ShopMallPartners shopMallPartners = shopMallPartnersService.selectShopMallPartnersByUserId(SecurityFrameworkUtils.getLoginUserId(),"sc");
        Long partnerId = shopMallPartners.getPartnerId();
        return baseMapper.validationListPc(page,partnerId);
    }

    @Override
    public Integer commentOrder(OrderInfo orderInfo) {
        orderInfo.setOrderStatus("3");
        orderInfo.setCommentTime(new Date());
        return baseMapper.updateById(orderInfo);
    }

    @Override
    public Integer getNoCommentOrder() {
        //获取当前登录用户
        LoginUser user = SecurityFrameworkUtils.getLoginUser();
        return baseMapper.getNoCommentOrder(user.getId());
    }

    @Override
    public IPage<commentVo>  getCommentOrderList(Page<commentVo> page, Long partnerId) {
        return baseMapper.getCommentOrderList(page,partnerId);
    }

    @Override
    public IPage<OrderInfo> orderListPc(Page<OrderInfo> page, OrderInfo orderInfo) {
        return baseMapper.orderListPc(page,orderInfo);
    }

    @Override
    public OrderInfo getOrderByOrderNo(String orderNo) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        return this.getOne(queryWrapper);
    }

}

