package com.seer.teach.mall.app.order.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.enums.AfterSaleStatusEnum;
import com.seer.teach.common.enums.ResultCodeEnum;
import com.seer.teach.common.utils.AssertUtils;
import com.seer.teach.common.utils.OrderIdGenerator;
import com.seer.teach.mall.app.order.service.IAppAfterSaleService;
import com.seer.teach.mall.convert.AdminAfterSaleConvert;
import com.seer.teach.mall.entity.OrderChildEntity;
import com.seer.teach.mall.entity.OrderGoodsEntity;
import com.seer.teach.mall.entity.TradeAfterSaleEntity;
import com.seer.teach.mall.request.AfterSalePageReq;
import com.seer.teach.mall.request.AppAfterSaleCreateReq;
import com.seer.teach.mall.request.AppAfterSaleDeliveryReq;
import com.seer.teach.mall.response.AfterSaleResp;
import com.seer.teach.mall.service.IAfterSaleService;
import com.seer.teach.mall.service.IOrderChildService;
import com.seer.teach.mall.service.IOrderGoodsService;
import com.seer.teach.mall.service.IOrderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


/**
 * 售后服务类
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AppAfterSaleServiceImpl implements IAppAfterSaleService {


    private final IAfterSaleService afterSaleService;

    private final IOrderService orderService;

    private final IOrderChildService orderChildService;

    private final IOrderGoodsService orderGoodsService;


    @Override
    public PageListBean<AfterSaleResp> queryPageList(AfterSalePageReq pageReqVO) {
        log.info("查询售后列表，参数: {}", pageReqVO);
        int userId = StpUtil.getLoginIdAsInt();
        pageReqVO.setUserId(userId);
        PageListBean<AfterSaleResp> result = afterSaleService.queryPageList(pageReqVO);
        return result;
    }

    @Override
    public AfterSaleResp getAfterSale(Integer id) {
        log.info("查询售后详情，ID: {}", id);
        int userId = StpUtil.getLoginIdAsInt();
        AfterSaleResp tradeAfterSaleOrderDetail = afterSaleService.getTradeAfterSaleOrderDetail(id, null);
        AssertUtils.isTrue(tradeAfterSaleOrderDetail.getUserId() == userId, ResultCodeEnum.AFTER_SALE_NO_UNAUTHORIZED);
        log.info("查询售后详情完成，ID: {}, 用户ID: {}", id, userId);
        return tradeAfterSaleOrderDetail;
    }

    @Override
    public boolean createAfterSale(AppAfterSaleCreateReq createReqVO) {
        log.info("开始创建售后单: {}", createReqVO);
        // 设置订单编号
        OrderChildEntity childOrder = orderChildService.checkOrderChild(createReqVO.getChildOrderId());
        AssertUtils.notNull(childOrder, ResultCodeEnum.ORDER_NOT_FOUND);
        // 检查是否已经申请过售后
        TradeAfterSaleEntity queryAfterSale = afterSaleService.getListBySkuIdAndOrderId(createReqVO.getSkuId(), createReqVO.getOrderId());

        AssertUtils.isNull(queryAfterSale, ResultCodeEnum.AFTER_SALE_EXIST);

        // 获取订单商品信息
        OrderGoodsEntity orderGoods = orderGoodsService.getOne(
                new LambdaQueryWrapper<OrderGoodsEntity>()
                        .eq(OrderGoodsEntity::getOrderId, createReqVO.getOrderId())
                        .eq(OrderGoodsEntity::getSkuId, createReqVO.getSkuId())
        );
        AssertUtils.notNull(orderGoods, ResultCodeEnum.ORDER_NOT_FOUND);

        OrderChildEntity orderChildEntity = orderChildService.getById(createReqVO.getChildOrderId());
        AssertUtils.notNull(orderChildEntity, ResultCodeEnum.ORDER_NOT_FOUND);

        // 创建售后单
        TradeAfterSaleEntity afterSale = AdminAfterSaleConvert.INSTANCE.convert(createReqVO);
        afterSale.setOrderSn(childOrder.getChildOrderSn());
        afterSale.setAfterSaleSn(OrderIdGenerator.generateOrderId(OrderIdGenerator.MALL_ORDER_PREFIX));
        afterSale.setStatus(AfterSaleStatusEnum.APPLY.getStatus());
        afterSale.setUserId(childOrder.getUserId());
        afterSale.setChildOrderId(orderChildEntity.getId());
        afterSale.setChildOrderSn(orderChildEntity.getChildOrderSn());
        afterSale.setPayChannelCode(childOrder.getPayChannelCode());
        afterSale.setMerchantUserId(orderChildEntity.getMerchantUserId());
        afterSale.setSpuName(orderGoods.getGoodsName());
        afterSale.setRefundCoin(childOrder.getOrderTotalCoin());
        afterSale.setRefundPrice(childOrder.getActualPrice());
        afterSale.setPicUrl(orderGoods.getPicUrl());
        // 设置申请时间
        afterSale.setApplyTime(LocalDateTime.now());

        boolean result = afterSaleService.save(afterSale);
        log.info("创建售后单结果: {}，售后单号: {}", result, afterSale.getAfterSaleSn());
        afterSaleService.logAfterSaleOperation(afterSale.getId(), "用户创建售后单", "用户创建售后单，结果:" + result + "，售后单号:" + afterSale.getAfterSaleSn());
        return result;
    }

    @Override
    public boolean deliveryAfterSale(AppAfterSaleDeliveryReq deliveryReq) {
        log.info("用户发货退货商品，请求参数: {}", deliveryReq);
        int userId = StpUtil.getLoginIdAsInt();
        TradeAfterSaleEntity afterSaleEntity = afterSaleService.checkAfterSaleOrder(deliveryReq.getId().intValue());
        AssertUtils.notNull(afterSaleEntity, ResultCodeEnum.AFTER_SALE_NOT_FOUND);
        AssertUtils.isTrue(afterSaleEntity.getUserId() == userId, ResultCodeEnum.AFTER_SALE_NO_UNAUTHORIZED);
        AssertUtils.isTrue(AfterSaleStatusEnum.SELLER_AGREE.getStatus().intValue() == afterSaleEntity.getStatus(), ResultCodeEnum.AFTER_SALE_STATUS_ERROR);

        boolean updated = afterSaleService.update(new LambdaUpdateWrapper<>(TradeAfterSaleEntity.class)
                .set(TradeAfterSaleEntity::getLogisticsNo, deliveryReq.getLogisticsNo())
                .set(TradeAfterSaleEntity::getStatus, AfterSaleStatusEnum.BUYER_DELIVERY.getStatus())
                .eq(TradeAfterSaleEntity::getId, deliveryReq.getId()));

        log.info("退回货物更新售后单状态结果：{}，ID: {}, 用户ID: {}", updated, deliveryReq.getId(), userId);
        afterSaleService.logAfterSaleOperation(deliveryReq.getId().intValue(), "用户发货退货商品", "用户发货退货商品，结果:" + updated);
        return updated;
    }

    @Override
    public boolean cancelAfterSale(Integer id) {
        log.info("用户取消售后申请，ID: {}", id);
        int userId = StpUtil.getLoginIdAsInt();

        TradeAfterSaleEntity afterSaleEntity = afterSaleService.checkAfterSaleOrder(id);
        AssertUtils.notNull(afterSaleEntity, ResultCodeEnum.AFTER_SALE_NOT_FOUND);
        AssertUtils.isTrue(afterSaleEntity.getUserId() == userId, ResultCodeEnum.AFTER_SALE_NO_UNAUTHORIZED);

        boolean updated = afterSaleService.update(new LambdaUpdateWrapper<>(TradeAfterSaleEntity.class)
                .set(TradeAfterSaleEntity::getStatus, AfterSaleStatusEnum.BUYER_CANCEL.getStatus())
                .eq(TradeAfterSaleEntity::getId, id));

        log.info("取消售后更新售后单状态结果：{}，ID: {}, 用户ID: {}", updated, id, userId);
        afterSaleService.logAfterSaleOperation(id, "用户取消售后申请", "用户取消售后申请，结果:" + updated);
        return updated;
    }

    @Override
    public boolean deleteAfterSale(Integer id) {
        log.info("用户删除售后单，ID: {}", id);
        int userId = StpUtil.getLoginIdAsInt();

        TradeAfterSaleEntity afterSaleEntity = afterSaleService.checkAfterSaleOrder(id);
        AssertUtils.notNull(afterSaleEntity, ResultCodeEnum.AFTER_SALE_NOT_FOUND);
        AssertUtils.isTrue(afterSaleEntity.getUserId() == userId, ResultCodeEnum.AFTER_SALE_NO_UNAUTHORIZED);

        boolean removed = afterSaleService.removeById(id);

        log.info("删除售后单结果：{}，ID: {}, 用户ID: {}", removed, id, userId);
        afterSaleService.logAfterSaleOperation(id, "用户删除售后单", "用户删除售后单，结果:" + removed);
        return removed;
    }
}