package com.tmerclub.cloud.cuerecycle.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tmerclub.cloud.api.coupon.feign.CouponFeignClient;
import com.tmerclub.cloud.api.delivery.dto.CurOderReturnsDTO;
import com.tmerclub.cloud.api.delivery.feign.DeliveryFeignClient;
import com.tmerclub.cloud.api.order.constant.OrderStatus;
import com.tmerclub.cloud.api.order.dto.SaveOrderToMallDTO;
import com.tmerclub.cloud.api.order.feign.OrderAddrFeignClient;
import com.tmerclub.cloud.api.order.feign.OrderFeignClient;
import com.tmerclub.cloud.api.user.feign.UserAddrFeignClient;
import com.tmerclub.cloud.api.user.feign.UserBalanceLogFeignClient;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.order.vo.OrderAddrVO;
import com.tmerclub.cloud.common.order.vo.UserAddrVO;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.cuerecycle.mapper.CueOrderFlawMapper;
import com.tmerclub.cloud.cuerecycle.mapper.CueOrderMapper;
import com.tmerclub.cloud.cuerecycle.model.CueOrder;
import com.tmerclub.cloud.cuerecycle.model.CueOrderFlaw;
import com.tmerclub.cloud.cuerecycle.model.dto.*;
import com.tmerclub.cloud.cuerecycle.model.vo.CueOrderVO;
import com.tmerclub.cloud.cuerecycle.service.CueFlawService;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 确认订单管理器
 *
 * @author: frank
 * @create: 2025-04-15
 **/
@Component
public class CreateOrderManager {
    private final Logger log = LoggerFactory.getLogger(CreateOrderManager.class);

    @Resource
    CueFlawService cueFlawService;
    @Resource
    CueOrderMapper cueOrderMapper;
    @Resource
    CueOrderFlawMapper cueOrderFlawMapper;
    @DubboReference
    CouponFeignClient couponFeignClient;
    @DubboReference
    DeliveryFeignClient deliveryFeignClient;
    @DubboReference
    UserAddrFeignClient userAddrFeignClient;
    @DubboReference
    OrderAddrFeignClient orderAddrFeignClient;
    @DubboReference
    UserBalanceLogFeignClient userBalanceLogFeignClient;
    @DubboReference
    OrderFeignClient orderFeignClient;

    /**
     * 保存订单信息
     *
     * @param createOrderDTO 订单信息
     * @return 订单id
     */
    public Long saveOrder(CreateOrderDTO createOrderDTO) {
        // 保存订单信息
        CueOrder cueOrder = BeanUtil.toBean(createOrderDTO, CueOrder.class);
        cueOrder.setOrderStatus(OrderStatus.CUE_PENDING_AUDIT.value());
        cueOrder.setCreateTime(DateUtil.date());
        cueOrderMapper.save(cueOrder);
        return cueOrder.getOrderId();
    }

    /**
     * 添加瑕疵项
     *
     * @param createOrderDTO 订单信息
     */
    public Long addFlawItem(Long orderId, CreateOrderDTO createOrderDTO) {
        // 循环插入瑕疵信息并累计选择金额
        Long flawPrice = 0L;
        for (CreateOrderFlawDTO createOrderFlawDTO : createOrderDTO.getFlawList()) {
            if (createOrderFlawDTO.getIsFlaw() == 1) {
                // 累加瑕疵金额
                flawPrice += createOrderFlawDTO.getFlawPrice();
            }
            CueOrderFlaw cueOrderFlaw = BeanUtil.toBean(createOrderFlawDTO, CueOrderFlaw.class);
            cueOrderFlaw.setOrderId(orderId);
            cueOrderFlawMapper.save(cueOrderFlaw);
        }
        return flawPrice;
    }

    /**
     * 保存订单到mallOrder
     */
    public void saveOrderToMall(Long orderId, Long estimatedAmount, CreateOrderDTO createOrderDTO) {
        SaveOrderToMallDTO saveOrderToMallDTO = new SaveOrderToMallDTO();
        saveOrderToMallDTO.setUserId(createOrderDTO.getUserId());
        saveOrderToMallDTO.setEstimatedAmount(estimatedAmount);
        saveOrderToMallDTO.setProductName(createOrderDTO.getProductName());
        saveOrderToMallDTO.setProductImages(createOrderDTO.getProductImages());
        Long mallOrderId = orderFeignClient.saveOrderToMall(saveOrderToMallDTO);
        CueOrder cueOrder = new CueOrder();
        cueOrder.setOrderId(orderId);
        cueOrder.setMallOrderId(mallOrderId);
        cueOrder.setEstimatedAmount(estimatedAmount);
        cueOrderMapper.update(cueOrder);
    }

    /**
     * 修改mallOrder订单
     *
     * @param mallOrderId mallOrderId
     * @param orderStatus 状态
     */
    public void updateOrderMall(Long shopId, Long mallOrderId, Integer orderStatus) {
        orderFeignClient.updateOrderMall(shopId, mallOrderId, orderStatus);
    }

    public void agreeOrder(CueAgreeOrderDTO cueAgreeOrderDTO) {
        // 查询订单信息
        CueOrderVO cueOrderVO = cueOrderMapper.getById(cueAgreeOrderDTO.getOrderId());
        if (ObjectUtil.isNull(cueOrderVO)) {
            throw new LuckException("订单不存在,请检查!");
        }
        // 判断状态是否允许修改
        if (!Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_SUCCESS.value())) {
            throw new LuckException("状态已变更,请检查!");
        }
        DateTime date = DateUtil.date();
        CueOrder cueOrder = new CueOrder();
        cueOrder.setOrderId(cueAgreeOrderDTO.getOrderId());
        cueOrder.setCueOrderType(cueAgreeOrderDTO.getCueOrderType());
        cueOrder.setOrderStatus(OrderStatus.CUE_EVALUATION_SUCCESS_PAY.value());
        cueOrder.setUpdateTime(date);
        cueOrder.setFinallyTime(date);
        cueOrder.setPayTime(date);
        cueOrder.setIsPayed(1);
        // 根据回收类型进行不同操作
        switch (cueAgreeOrderDTO.getCueOrderType()) {
            case 1:
                // 回收
                cueOrder.setPayType(1);
                // 余额支付 直接向用户账户打款
                userBalanceLogFeignClient.sellCueUpdateBalance(cueOrderVO.getUserId(), cueOrderVO.getActualAmount());
                break;
            case 2:
                // 置换
                cueOrder.setPayType(2);
                // 代金卷支付
                couponFeignClient.sendUserCoupon(cueOrderVO.getShopId(), cueOrderVO.getUserId(), cueOrderVO.getVoucherAmount());
                break;
            case 3:
                // 寄售
                cueOrder.setPayType(1);
                // 余额支付 直接向用户账户打款
                Long actualAmount = cueOrderVO.getActualAmount() - cueOrderVO.getBrokerage() - cueOrderVO.getServiceCharge();
                userBalanceLogFeignClient.sellCueUpdateBalance(cueOrderVO.getUserId(), actualAmount);
                break;
            default:
                throw new LuckException("订单类型错误,请检查!");
        }
        cueOrderMapper.update(cueOrder);
        this.updateOrderMall(cueOrderVO.getShopId(), cueOrderVO.getMallOrderId(), OrderStatus.SUCCESS.value());
    }

    /**
     * 填写回邮地址
     *
     * @param cueFillAddrDTO 订单信息
     */
    public void fillAddr(CueFillAddrDTO cueFillAddrDTO) {
        Long orderId = cueFillAddrDTO.getOrderId();
        // 查询订单信息
        CueOrderVO cueOrderVO = cueOrderMapper.getById(orderId);
        if (ObjectUtil.isNull(cueOrderVO)) {
            throw new LuckException("订单不存在,请检查!");
        }
        // 两种情况会导致退货 5不合格 6价格不满意
        // 检查当前状态
        if (Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_FAIL.value()) || Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_SUCCESS.value())) {
            CueOrder cueOrder = new CueOrder();
            cueOrder.setOrderId(orderId);
            // 需要向order_addr插入一条数据
            ServerResponseEntity<UserAddrVO> userAddrVO = userAddrFeignClient.cueGetUserAddrByAddrId(cueFillAddrDTO.getAddrId(), cueOrderVO.getUserId());
            if (userAddrVO.isSuccess()) {
                // 将地址信息插入到order_addr中
                OrderAddrVO orderAddrVO = BeanUtil.toBean(userAddrVO.getData(), OrderAddrVO.class);
                orderAddrVO.setUserId(cueOrderVO.getUserId());
                ServerResponseEntity<Long> longServerResponseEntity = orderAddrFeignClient.addCueAddr(orderAddrVO);
                if (longServerResponseEntity.isSuccess()) {
                    cueOrder.setOrderAddrId(longServerResponseEntity.getData());
                }
            }
            if (Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_SUCCESS.value())) {
                cueOrder.setOrderStatus(OrderStatus.CUE_EVALUATION_SUCCESS_PRICE_DISCONTENT.value());
            } else {
                cueOrder.setOrderStatus(OrderStatus.CUE_EVALUATION_FAIL_FILLED_RETURN_ADDRESS.value());
            }

            cueOrder.setUpdateTime(DateUtil.date());
            cueOrderMapper.update(cueOrder);
            this.updateOrderMall(null, cueOrderVO.getMallOrderId(), cueOrder.getOrderStatus());
        } else {
            throw new LuckException("状态已变更,请检查!");
        }

    }

    /**
     * 后管操作球杆退回
     *
     * @param cueRetractedDTO 订单信息
     */
    public void cueRetracted(CueRetractedDTO cueRetractedDTO) {
        CueOrderVO cueOrderVO = cueOrderMapper.getById(cueRetractedDTO.getOrderId());
        if (ObjectUtil.isNull(cueOrderVO)) {
            throw new LuckException("订单不存在,请检查!");
        }
        if (Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_FAIL_FILLED_RETURN_ADDRESS.value()) || Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_SUCCESS_PRICE_DISCONTENT.value())) {

            CueOrder cueOrder = new CueOrder();
            cueOrder.setOrderId(cueRetractedDTO.getOrderId());
            cueOrder.setOutletConfigId(cueRetractedDTO.getOutletConfigId());
            cueOrder.setPrinterId(cueRetractedDTO.getPrinterId());
            CurOderReturnsDTO curOderReturnsDTO = new CurOderReturnsDTO();
            curOderReturnsDTO.setOrderId(cueOrderVO.getMallOrderId());
            curOderReturnsDTO.setOutletConfigId(cueRetractedDTO.getOutletConfigId());
            curOderReturnsDTO.setPrinterId(cueRetractedDTO.getPrinterId());
            curOderReturnsDTO.setOrderAddrId(cueOrderVO.getOrderAddrId());
            ServerResponseEntity<String> stringServerResponseEntity = deliveryFeignClient.curOderReturns(curOderReturnsDTO);
            if (stringServerResponseEntity.isSuccess()) {
                cueOrder.setBackTrackingNumber(stringServerResponseEntity.getData());
            }
            // 判断状态
            if (Objects.equals(cueOrderVO.getOrderStatus(), OrderStatus.CUE_EVALUATION_FAIL_FILLED_RETURN_ADDRESS.value())) {
                cueOrder.setOrderStatus(OrderStatus.CUE_EVALUATION_FAIL_COMPLETED.value());
            } else {
                cueOrder.setOrderStatus(OrderStatus.CUE_EVALUATION_SUCCESS_COMPLETED.value());
            }
            cueOrderMapper.update(cueOrder);
        } else {
            throw new LuckException("状态已变更,请检查!");
        }
    }
}