package com.fs.erp.service.impl;

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.service.IErpOrderService;
import com.fs.erp.utils.SignUtil;
import com.fs.store.service.IFsStoreOrderService;
import lombok.extern.slf4j.Slf4j;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

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

    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        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(ObjectUtils.isEmpty(order.getPost_fee())) {
            shopOrderDTO.setFreight(Double.valueOf("0.00"));
        }
        // 备注
        shopOrderDTO.setRemark(order.getBuyer_memo());
        // 买家留言
        shopOrderDTO.setBuyerMessage(order.getBuyer_memo());

        // 订单商品项列表
        List<ErpOrderItem> details = order.getDetails();
        List<OrderItemDTO> itemDTOList = new ArrayList<>();
        for (ErpOrderItem detail : details) {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            orderItemDTO.setSkuId("105220");
            orderItemDTO.setShopSkuId(detail.getItem_code());
            orderItemDTO.setName(detail.getItem_code());
            orderItemDTO.setAmount(Double.valueOf(detail.getPrice()));
            if(detail.getOrigin_price() != null) {
                orderItemDTO.setBasePrice(Double.valueOf(detail.getOrigin_price()));
            }
            orderItemDTO.setQty(detail.getQty());
            orderItemDTO.setOuterOiId(order.getPlatform_code());
            itemDTOList.add(orderItemDTO);
        }
        shopOrderDTO.setItems(itemDTOList);


        PaymentDTO paymentDTO = new PaymentDTO();
        paymentDTO.setAmount(erpOrderPayment.getPayment());
        paymentDTO.setOuterPayId(order.getPlatform_code());
        paymentDTO.setPayDate(order.getDeal_datetime());
        paymentDTO.setPayment("微信");
        paymentDTO.setBuyerAccount(order.getBuyer_account());
        paymentDTO.setSellerAccount("平台销售");
        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();

        // 设置基本订单信息
        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(order.getReceiverName());
        erpOrder.setReceiver_phone(order.getReceiverPhone());
        erpOrder.setReceiver_mobile(order.getReceiverMobile());

        // 构建完整地址
        StringBuilder addressBuilder = new StringBuilder();
        if (StringUtils.hasText(order.getReceiverAddress())) {
            addressBuilder.append(order.getReceiverAddress());
        }
        if (StringUtils.hasText(order.getReceiverDistrict())) {
            if (addressBuilder.length() > 0) addressBuilder.append(", ");
            addressBuilder.append(order.getReceiverDistrict());
        }
        if (StringUtils.hasText(order.getReceiverCity())) {
            if (addressBuilder.length() > 0) addressBuilder.append(", ");
            addressBuilder.append(order.getReceiverCity());
        }
        if (StringUtils.hasText(order.getReceiverState())) {
            if (addressBuilder.length() > 0) addressBuilder.append(", ");
            addressBuilder.append(order.getReceiverState());
        }
        if (StringUtils.hasText(order.getReceiverCountry())) {
            if (addressBuilder.length() > 0) addressBuilder.append(", ");
            addressBuilder.append(order.getReceiverCountry());
        }
        if (StringUtils.hasText(order.getReceiverZip())) {
            if (addressBuilder.length() > 0) addressBuilder.append(" ");
            addressBuilder.append(order.getReceiverZip());
        }
        erpOrder.setReceiver_address(addressBuilder.toString());

        // 处理发货相关信息
        if (order.getShipment() != null && StringUtils.hasText(order.getShipment())) {
            List<ErpDeliverys> deliverysList = new ArrayList<>();

            ErpDeliverys delivery = new ErpDeliverys();
            delivery.setMail_no(order.getShipment());
            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) {
        OrderCancelRequestDTO requestDTO = new OrderCancelRequestDTO();
        requestDTO.setOIds(Collections.singletonList(Integer.valueOf(param.getTid())));
        requestDTO.setCancelType("用户退款");
        requestDTO.setRemark("用户退款");

        jstErpHttpService.cancel(requestDTO);

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

        return baseResponse;
    }
}
