package com.fs.erp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.erp.constant.AfterSalesOrderStatusEnum;
import com.fs.erp.constant.ErpQueryOrderStatusEnum;
import com.fs.erp.constant.OrderStatusEnum;
import com.fs.erp.domain.*;
import com.fs.erp.dto.*;
import com.fs.erp.http.JstErpHttpService;
import com.fs.erp.mapper.FsJstAftersalePushMapper;
import com.fs.erp.mapper.FsJstCodPushMapper;
import com.fs.erp.service.IErpOrderService;
import com.fs.erp.utils.SignUtil;
import com.fs.express.enums.TaskStatusEnum;
import com.fs.store.domain.FsStoreAfterSales;
import com.fs.store.domain.FsStoreDelivers;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStoreProduct;
import com.fs.store.mapper.FsStoreAfterSalesMapper;
import com.fs.store.mapper.FsStoreDeliversMapper;
import com.fs.store.service.IFsStoreOrderItemService;
import com.fs.store.service.IFsStoreOrderService;
import com.fs.store.service.IFsStoreProductService;
import com.fs.store.vo.FsStoreOrderItemVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class JSTErpOrderServiceImpl implements IErpOrderService {
    @Autowired
    private JstErpHttpService jstErpHttpService;

    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private FsJstAftersalePushMapper fsJstAftersalePushMapper;

    @Autowired
    private IFsStoreOrderItemService fsStoreOrderItemService;

    @Autowired
    private IFsStoreProductService fsStoreProductService;

    @Autowired
    private FsStoreDeliversMapper fsStoreDeliversMapper;

    @Autowired
    private FsStoreAfterSalesMapper fsStoreAfterSalesMapper;

    @Autowired
    private FsJstCodPushMapper fsJstCodPushMapper;

    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(order.getPlatform_code());

        ErpOrderPayment erpOrderPayment = order.getPayments().get(0);

        ShopOrderDTO shopOrderDTO = new ShopOrderDTO();

        shopOrderDTO.setShopId(Long.valueOf(order.getShop_code()));
        shopOrderDTO.setSoId(order.getPlatform_code());
        shopOrderDTO.setOrderDate(order.getDeal_datetime());
        // 待发货
        shopOrderDTO.setShopStatus(OrderStatusEnum.WAIT_SELLER_SEND_GOODS.name());
        // 买家账号
        shopOrderDTO.setShopBuyerId(order.getBuyer_account());
        // 收货人省份
        shopOrderDTO.setReceiverState(order.getReceiver_province());
        // 收货人城市
        shopOrderDTO.setReceiverCity(order.getReceiver_city());
        // 收货人区域
        shopOrderDTO.setReceiverDistrict(order.getReceiver_district());
        // 收货人详细地址
        shopOrderDTO.setReceiverAddress(order.getReceiver_address());
        // 收货人详细地址
        shopOrderDTO.setReceiverName(order.getReceiver_name());
        // 收货人电话
        shopOrderDTO.setReceiverPhone(order.getReceiver_mobile());
        // 支付金额
        shopOrderDTO.setPayAmount(erpOrderPayment.getPayment());
        // 运费
        if(ObjectUtil.isNull(fsStoreOrder.getPayPostage())) {
            shopOrderDTO.setFreight(Double.valueOf("0.00"));
        } else {
            shopOrderDTO.setFreight(fsStoreOrder.getPayPostage().doubleValue());
        }
        // 备注
        shopOrderDTO.setRemark(order.getBuyer_memo());
        // 买家留言
        shopOrderDTO.setBuyerMessage(order.getBuyer_memo());

        // 订单商品项列表
        List<OrderItemDTO> itemDTOList = new ArrayList<>();

        List<FsStoreOrderItemVO> fsStoreOrderItemVOS = fsStoreOrderItemService.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getId());
        for (FsStoreOrderItemVO item : fsStoreOrderItemVOS) {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());

            String barCode = jsonObject.getString("barCode");
            String productName = jsonObject.getString("productName");

            orderItemDTO.setSkuId(barCode);
            orderItemDTO.setShopSkuId(barCode);
            orderItemDTO.setName(productName);

            FsStoreProduct fsStoreProduct = fsStoreProductService.selectFsStoreProductById(item.getProductId());

            orderItemDTO.setAmount(fsStoreProduct.getPrice());

            orderItemDTO.setQty(item.getNum().intValue());
            orderItemDTO.setOuterOiId(String.format("%s%s",item.getOrderCode(),item.getItemId()));
            itemDTOList.add(orderItemDTO);
        }
        shopOrderDTO.setItems(itemDTOList);

        // 实际支付金额
        PaymentDTO paymentDTO = new PaymentDTO();
        paymentDTO.setAmount(fsStoreOrder.getPayMoney().doubleValue());
        paymentDTO.setOuterPayId(order.getPlatform_code());
        paymentDTO.setPayDate(order.getDeal_datetime());
        paymentDTO.setPayment("微信支付");
        paymentDTO.setBuyerAccount(order.getBuyer_account());
        paymentDTO.setSellerAccount("平台销售");
        shopOrderDTO.setPay(paymentDTO);


        // 如果是货到付款
        if("2".equals(fsStoreOrder.getPayType()) || "3".equals(fsStoreOrder.getPayType())){
            shopOrderDTO.setIsCod(true);
            // 货到付款金额 = 物流代收金额-优惠金额
            shopOrderDTO.setBuyerPaidAmount(fsStoreOrder.getPayDelivery());
            shopOrderDTO.setPayAmount(fsStoreOrder.getPayPrice().doubleValue());

            // 货到付款要推两次
            PaymentDTO paymentDTO2 = new PaymentDTO();
            // 物流代收金额
            paymentDTO2.setAmount(fsStoreOrder.getPayDelivery().doubleValue());
            paymentDTO2.setOuterPayId(String.format("%s%d",order.getPlatform_code(),1));
            paymentDTO2.setPayDate(order.getDeal_datetime());
            paymentDTO2.setPayment("货到付款");
            paymentDTO2.setBuyerAccount(order.getBuyer_account());
            paymentDTO2.setSellerAccount("平台销售");
            shopOrderDTO.setPay(paymentDTO2);

            FsJstCodPush fsJstCodPush = new FsJstCodPush();
            fsJstCodPush.setOrderId(fsStoreOrder.getOrderCode());
            fsJstCodPush.setType("0");
            fsJstCodPush.setParams(JSON.toJSONString(shopOrderDTO));
            fsJstCodPush.setRetryCount(0);
            fsJstCodPush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstCodPushMapper.insert(fsJstCodPush);

            shopOrderDTO.setPay(paymentDTO);
        }

        ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);

        if(CollectionUtils.isEmpty(upload.getDatas())) {
            log.info("推送ERP返回结果: {}",upload);
            throw new IllegalArgumentException("推送ERP返回数不应该为0");
        }
        ErpOrderResponseDTO.OrderData orderData = upload.getDatas().get(0);

        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        erpOrderResponse.setSuccess(true);
        erpOrderResponse.setCode(String.valueOf(orderData.getOId()));
        return erpOrderResponse;
    }



    @Override
    public ErpOrderResponse refundOrder(ErpRefundOrder order) {
        return null;
    }

    @Override
    public ErpDeliverysResponse getDeliver(ErpDeliverysRequest param) {
        return null;
    }

    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert param) {
        // 1. 构建查询请求DTO
        OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
        requestDTO.setOIds(Collections.singletonList(Long.valueOf(param.getCode())));


        // 2. 调用ERP服务查询订单
        OrderQueryResponseDTO query = jstErpHttpService.query(requestDTO);

        // 3. 构建响应对象
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();

        // 4. 设置基本响应信息

        // 5. 转换订单数据
        if (query.getOrders() != null && !query.getOrders().isEmpty()) {
            List<ErpOrderQuery> erpOrders = query.getOrders().stream()
                    .map(this::convertToErpOrderQuery)
                    .collect(Collectors.toList());

            response.setOrders(erpOrders);
        } else {
            response.setOrders(Collections.emptyList());
        }

        return response;
    }

    /**
     * 将OrderQueryResponseDTO.Order转换为ErpOrderQuery
     *
     * @param order 订单数据
     * @return ErpOrderQuery 转换后的订单数据
     */
    private ErpOrderQuery convertToErpOrderQuery(OrderQueryResponseDTO.Order order) {
        ErpOrderQuery erpOrder = new ErpOrderQuery();

        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(order.getSoId());
        Asserts.notNull(fsStoreOrder,"该订单号没有找到！");

        // 设置基本订单信息
        erpOrder.setCode(order.getSoId());

        // 计算订单总数量
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            int totalQty = order.getItems().stream()
                    .mapToInt(OrderQueryResponseDTO.OrderItem::getQty)
                    .sum();
            erpOrder.setQty(totalQty);
        }

        // 设置金额相关信息
        erpOrder.setAmount(order.getAmount() != null ? order.getAmount().doubleValue() : null);
        erpOrder.setPayment(order.getPaidAmount() != null ? order.getPaidAmount().doubleValue() : null);

        // 设置其他订单属性
        erpOrder.setCod(order.getIsCod());
        erpOrder.setPlatform_code(order.getOrderFrom());

        // 尝试解析创建时间
        try {
            if (order.getCreated() != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                erpOrder.setCreatetime(formatter.parse(order.getCreated()));
            }
        } catch (Exception e) {
            // 日期解析异常处理
            // 可以记录日志或保持为null
        }

        // 设置店铺信息
        erpOrder.setShop_name(order.getShopName());
        erpOrder.setShop_code(String.valueOf(order.getShopId()));

        // 设置物流信息
        erpOrder.setExpress_name(order.getLogisticsCompany());
        erpOrder.setExpress_code(order.getLId());

        // 设置收件人信息
        erpOrder.setReceiver_name(fsStoreOrder.getRealName());
        erpOrder.setReceiver_phone(fsStoreOrder.getUserPhone());
        erpOrder.setReceiver_mobile(fsStoreOrder.getUserPhone());

        // 构建完整地址
        erpOrder.setReceiver_address(fsStoreOrder.getUserAddress());

        // 如果是已发货
        if(ObjectUtil.equal(order.getStatus(), ErpQueryOrderStatusEnum.SENT.getCode())){
            List<ErpDeliverys> deliverysList = new ArrayList<>();

            ErpDeliverys delivery = new ErpDeliverys();
            delivery.setMail_no(order.getLId());
            delivery.setExpress_code(order.getLcId());
            delivery.setExpress_name(order.getLogisticsCompany());
            delivery.setDelivery(true);
            delivery.setCode(order.getSoId());

            deliverysList.add(delivery);
            erpOrder.setDeliverys(deliverysList);

            // 设置发货状态，假设有物流单号就是已发货状态
            erpOrder.setDelivery_state(1);
        } else {
            erpOrder.setDelivery_state(0);
        }

        return erpOrder;
    }


    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest param) {

        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(param.getTid());
        FsStoreDelivers byOrderCode = fsStoreDeliversMapper.findByOrderCode(fsStoreOrder.getOrderCode());

        // 发货后退款
        if(ObjectUtil.isNotNull(byOrderCode)){

        } else {
            // 如果是发货前退款，直接走取消订单流程
            // 如果是发货后退款，走售后流程
            OrderCancelRequestDTO requestDTO = new OrderCancelRequestDTO();
            requestDTO.setOIds(Collections.singletonList(Integer.valueOf(fsStoreOrder.getExtendOrderId())));
            requestDTO.setCancelType("用户退款");
            requestDTO.setRemark("用户退款");

            jstErpHttpService.cancel(requestDTO);
        }


        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setSuccess(true);

        return baseResponse;
    }
}

