package com.xiaoniu.system.order.storeorder.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoniu.common.core.constant.Constants;
import com.xiaoniu.common.core.resdata.RowsData;
import com.xiaoniu.common.core.utils.DateUtils;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.system.order.aftersales.domain.TbAfterSales;
import com.xiaoniu.system.order.aftersales.mapper.TbAfterSalesMapper;
import com.xiaoniu.system.order.storeorder.domain.TbOrderCoupon;
import com.xiaoniu.system.order.storeorder.domain.TbOrderInfo;
import com.xiaoniu.system.order.storeorder.domain.TbOrderMember;
import com.xiaoniu.system.order.storeorder.dto.*;
import com.xiaoniu.system.order.storeorder.mapper.TbOrderCouponMapper;
import com.xiaoniu.system.order.storeorder.mapper.TbOrderGoodsMapper;
import com.xiaoniu.system.order.storeorder.mapper.TbOrderInfoMapper;
import com.xiaoniu.system.order.storeorder.mapper.TbOrderMemberMapper;
import com.xiaoniu.system.order.storeorder.service.ITbOrderInfoService;
import com.xiaoniu.system.order.storeorder.vo.*;
import com.xiaoniu.system.platformusers.user.domain.TbClientUser;
import com.xiaoniu.system.platformusers.user.mapper.TbClientUserMapper;
import com.xiaoniu.system.platformusers.vehicle.domain.TbVehicleInfo;
import com.xiaoniu.system.platformusers.vehicle.mapper.TbVehicleInfoMapper;
import com.xiaoniu.system.store.store.domain.TbStoreInfo;
import com.xiaoniu.system.store.store.mapper.TbStoreInfoMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 订单信息表 服务实现类
 * </p>
 *
 * @author haoxuyang
 * @since 2024-10-16 09:11:47
 */
@Service
public class TbOrderInfoServiceImpl extends ServiceImpl<TbOrderInfoMapper, TbOrderInfo> implements ITbOrderInfoService {

    @Resource
    private TbClientUserMapper tbClientUserMapper;
    @Resource
    private TbOrderGoodsMapper tbOrderGoodsMapper;
    @Resource
    private TbStoreInfoMapper tbStoreInfoMapper;
    @Resource
    private TbVehicleInfoMapper tbVehicleInfoMapper;
    @Resource
    private TbOrderCouponMapper tbOrderCouponMapper;
    @Resource
    private TbOrderMemberMapper tbOrderMemberMapper;
    @Resource
    private TbAfterSalesMapper tbAfterSalesMapper;

    @Override
    public RowsData<StoreOrderListVO> storeOrderList(StoreOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<StoreOrderListVO> list = baseMapper.storeOrderList(dto);
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public RowsData<GroupOrderListVO> groupOrderList(GroupOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<GroupOrderListVO> list = baseMapper.groupOrderList(dto);
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }


    @Override
    public RowsData<ComplaintOrderListVO> complaintOrderList(ComplaintOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<ComplaintOrderListVO> list = baseMapper.complaintOrderList(dto);
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public RowsData<PointsOrderListVO> pointsOrderList(PointsOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<PointsOrderListVO> list = baseMapper.pointsOrderList(dto);
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public RowsData<MemberOrderListVO> memberOrderList(MemberOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<MemberOrderListVO> list = baseMapper.memberOrderList(dto);
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public RowsData<CouponOrderListVO> couponOrderList(CouponOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<CouponOrderListVO> list = baseMapper.couponOrderList(dto);
            if (!CollectionUtils.isEmpty(list)) {
                for (CouponOrderListVO couponOrderListVO : list) {
                    String discountResult = couponOrderListVO.getDiscountResult();
                    if (StringUtils.isNotEmpty(discountResult)) {
                        if (Constants.ONE.equals(couponOrderListVO.getDiscountMethod())) {
                            couponOrderListVO.setDiscountResult(discountResult);
                        } else if (Constants.TWO.equals(couponOrderListVO.getDiscountMethod())) {
                            JSONObject parse = JSONObject.parse(discountResult);
                            couponOrderListVO.setDiscountResult("满" + parse.getBigDecimal("full") + "减" + parse.getBigDecimal("minus"));
                        } else if (Constants.THREE.equals(couponOrderListVO.getDiscountMethod())) {
                            JSONObject parse = JSONObject.parse(discountResult);
                            couponOrderListVO.setDiscountResult(parse.getString("discount") + "折");
                        }
                    }
                }
            }
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public OrderDetailsVO orderDetails(Long orderId) {
        OrderDetailsVO orderDetailsVO = new OrderDetailsVO();
        TbOrderInfo tbOrderInfo = baseMapper.selectById(orderId);
        if (StringUtils.isNotNull(tbOrderInfo)) {
            orderDetailsVO.setOrderId(tbOrderInfo.getId());
            TbClientUser tbClientUser = tbClientUserMapper.selectById(tbOrderInfo.getUserId());
            if (StringUtils.isNotNull(tbClientUser)) {
                orderDetailsVO.setUserName(tbClientUser.getNickName());
                orderDetailsVO.setPhoneNumber(tbClientUser.getPhoneNumber());
            }
            orderDetailsVO.setOrderNo(tbOrderInfo.getOrderNo());
            orderDetailsVO.setCreateTime(tbOrderInfo.getCreateTime());
            orderDetailsVO.setPayTime(tbOrderInfo.getPayTime());
            //根据订单id获取商品信息
            OrderDetailsVO goodsInfo = tbOrderGoodsMapper.getGoodInfoByOrderId(orderId);
            if (StringUtils.isNotNull(goodsInfo)) {
                orderDetailsVO.setGoodsName(goodsInfo.getGoodsName());
                orderDetailsVO.setGoodsId(goodsInfo.getGoodsId());
                orderDetailsVO.setGoodsNum(goodsInfo.getGoodsNum());
                orderDetailsVO.setGoodsPrice(goodsInfo.getGoodsPrice());
                orderDetailsVO.setGoodsType(goodsInfo.getGoodsType());
            }
            orderDetailsVO.setStatus(String.valueOf(tbOrderInfo.getStatus()));
            orderDetailsVO.setPaymentAmount(tbOrderInfo.getActualAmount());
            orderDetailsVO.setDiscountAmount(tbOrderInfo.getOrderAmount().subtract(StringUtils.isNotNull(tbOrderInfo.getActualAmount()) ? tbOrderInfo.getActualAmount() : BigDecimal.ZERO));
            //获取订单优惠明细
            StringBuilder discountDetails = new StringBuilder();
            //获取会员权益优惠金额
            TbOrderMember tbOrderMember = tbOrderMemberMapper.selectOne(new LambdaQueryWrapper<TbOrderMember>().eq(TbOrderMember::getOrderId, orderId).eq(TbOrderMember::getGoodsId, goodsInfo.getGoodsId()).eq(TbOrderMember::getDelFlag, Constants.ZERO).eq(TbOrderMember::getStatus,Constants.TWO).last("limit 1"));
            if (StringUtils.isNotNull(tbOrderMember)) {
                discountDetails.append("会员权益：");
                discountDetails.append(tbOrderMember.getDiscountAmount());
                discountDetails.append(" ");
            }
            //获取优惠券优惠金额
            TbOrderCoupon tbOrderCoupon = tbOrderCouponMapper.selectOne(new LambdaQueryWrapper<TbOrderCoupon>().eq(TbOrderCoupon::getOrderId, orderId).eq(TbOrderCoupon::getGoodsId, goodsInfo.getGoodsId()).eq(TbOrderCoupon::getStatus,Constants.TWO).eq(TbOrderCoupon::getDelFlag, Constants.ZERO).last("limit 1"));
            if (StringUtils.isNotNull(tbOrderCoupon)) {
                discountDetails.append("优惠券：");
                discountDetails.append(tbOrderCoupon.getDiscountAmount());
            }
            orderDetailsVO.setDiscountDetails(discountDetails.toString());
            if (Constants.THREE.equals(tbOrderInfo.getStatus())) {
                TbStoreInfo tbStoreInfo = tbStoreInfoMapper.selectById(tbOrderInfo.getStoreId());
                if (StringUtils.isNotNull(tbStoreInfo)) {
                    orderDetailsVO.setStoreName(tbStoreInfo.getStoreName());
                    orderDetailsVO.setStoreInfo(tbStoreInfo.getPersonChargeName() + "/" + tbStoreInfo.getPersonChargePhone());
                }
            }
            //查询用户车辆信息
            if (StringUtils.isNotNull(tbOrderInfo.getUserCarId())) {
                TbVehicleInfo tbVehicleInfo = tbVehicleInfoMapper.selectById(tbOrderInfo.getUserCarId());
                if (StringUtils.isNotNull(tbVehicleInfo)) {
                    String vehicleBrand = tbVehicleInfo.getVehicleBrand();
                    String vehicleModel = tbVehicleInfo.getVehicleModel();
                    String vehicleMileage = tbVehicleInfo.getVehicleMileage();
                    String startTime = DateUtils.dateTime(tbVehicleInfo.getStartTime());
                    orderDetailsVO.setAssociatedVehicles("品牌：" + vehicleBrand + "；型号：" + vehicleModel + "；行驶里程：" + vehicleMileage + "；启程时间：" + startTime);
                }
            }
            if (tbOrderInfo.getType().equals(Constants.FIVE)) {
                orderDetailsVO.setGoodsType("优惠券");
            }
            if (tbOrderInfo.getStatus().equals(Constants.FIVE)) {
                TbAfterSales tbAfterSales = tbAfterSalesMapper.selectOne(new LambdaQueryWrapper<TbAfterSales>().eq(TbAfterSales::getOrderId, tbOrderInfo.getId()).eq(TbAfterSales::getGoodsId, goodsInfo.getGoodsId()).eq(TbAfterSales::getDelFlag, Constants.ZERO).last("limit 1"));
                if (StringUtils.isNotNull(tbAfterSales)) {
                    AfterSalesVO afterSalesVO = new AfterSalesVO();
                    afterSalesVO.setSubmissionTime(tbAfterSales.getCreateTime());
                    afterSalesVO.setOrderType(tbAfterSales.getOrderType());
                    afterSalesVO.setAfterSalesType(tbAfterSales.getAfterSalesType());
                    afterSalesVO.setApplyContent(tbAfterSales.getApplyContent());
                    afterSalesVO.setAfterSalesPicture(tbAfterSales.getAfterSalesPicture());
                    afterSalesVO.setStoreProcessStatus(String.valueOf(tbAfterSales.getStoreProcessStatus()));
                    afterSalesVO.setStoreRemark(tbAfterSales.getStoreRemark());
                    afterSalesVO.setPlatformProcessStatus(String.valueOf(tbAfterSales.getPlatformProcessStatus()));
                    afterSalesVO.setEstimatedRefundAmount(tbAfterSales.getEstimatedRefundAmount());
                    afterSalesVO.setRemark(tbAfterSales.getRemark());
                    orderDetailsVO.setAfterSalesVO(afterSalesVO);
                }
            }
        }
        return orderDetailsVO;
    }

    @Override
    public RowsData<FinancialOrderListVO> financialOrderList(FinancialOrderQueryDTO dto) {
        try (Page<Object> page = PageHelper.startPage(dto.getPageNum(), dto.getPageSize())) {
            List<FinancialOrderListVO> list = baseMapper.financialOrderList(dto);
            if (!CollectionUtils.isEmpty(list)) {
                for (FinancialOrderListVO financialOrderListVO : list) {
                    Double commissionRatio = financialOrderListVO.getCommissionRatio();
                    BigDecimal paymentAmount = financialOrderListVO.getPaymentAmount();
                    if (StringUtils.isNotNull(commissionRatio)) {
                        financialOrderListVO.setPlatformRevenue(paymentAmount.multiply(new BigDecimal(String.valueOf(commissionRatio)).divide(new BigDecimal(100))));
                        financialOrderListVO.setStoreRevenue(paymentAmount.subtract(financialOrderListVO.getPlatformRevenue()));
                    } else {
                        financialOrderListVO.setPlatformRevenue(paymentAmount);
                    }
                }
            }
            return new RowsData<>(list, page.getTotal(), dto.getPageNum());
        }
    }

    @Override
    public void reviewComplaintOrders(ReviewComplaintOrdersDTO dto) {
        TbAfterSales tbAfterSales = tbAfterSalesMapper.selectOne(new LambdaQueryWrapper<TbAfterSales>().eq(TbAfterSales::getOrderId, dto.getOrderId()).last("limit 1"));
        if (StringUtils.isNotNull(tbAfterSales)) {
            tbAfterSales.setPlatformProcessStatus(dto.getPlatformProcessStatus());
            tbAfterSales.setRemark(dto.getRemark());
            tbAfterSalesMapper.updateById(tbAfterSales);
            if (Constants.TWO.equals(dto.getPlatformProcessStatus())) {
                //todo 退款操作
            }
        }
    }
}
