package com.fs.erp.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fs.common.config.FSSysConfig;
import com.fs.common.exception.ServiceException;
import com.fs.common.utils.StringUtils;
import com.fs.erp.domain.*;
import com.fs.erp.dto.*;
import com.fs.erp.service.IErpOrderService;
import com.fs.erp.utils.SignUtils;
import com.fs.erp.utils.UrlUtils;
import com.fs.his.config.FsErpConfig;
import com.fs.his.utils.ConfigUtil;
import com.fs.store.domain.FsStoreOrder;
import com.fs.store.domain.FsStoreOrderItem;
import com.fs.store.dto.FsStoreCartDTO;
import com.fs.store.mapper.FsStoreOrderMapper;
import com.fs.store.mapper.FsStoreProductMapper;
import com.fs.store.service.IFsStoreOrderItemService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static com.fs.erp.enums.KbOrderStatusEnum.CANCELLED;
import static com.fs.erp.enums.KbOrderStatusEnum.NO_DELIVERED;


@Service
@Slf4j
public class K9OrderServiceImpl implements IErpOrderService {
    public final static Logger logger = LoggerFactory.getLogger(K9OrderServiceImpl.class);
    @Autowired
    ConfigUtil configUtil;
    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private IFsStoreOrderItemService storeOrderItemService;
    @Autowired
    private FsStoreProductMapper productMapper;
    @Override
    /**
     * 推送erp订单
     */
    public ErpOrderResponse addOrder(ErpOrder order) {
        return addOmsOrder(order.getPlatform_code());
    }


    /**
     * 退款
     * @param order
     * @return
     */
    @Override
    public ErpOrderResponse refundOrder(ErpRefundOrder order){
        if (order != null){
            String deliverySn = order.getDeliverySn();
            String orderCode = order.getTrade_platform_code();
            if (StringUtils.isNotBlank(orderCode)){
                if (StringUtils.isBlank(deliverySn)){
                    //未获取订单号
                    return refundOmsOrder2(orderCode);
                } else {
                    //已获取订单号
                    return refundOrder1(orderCode);
                }
            }
        }
        return null;
    }

    private KingbosRefundOrderRequest getKingbosRefundOrderRequest(String orderCode) {
        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
        if (order != null){
            logger.debug("【金博网络退货单】开始构建订单数据，订单号: {}", orderCode);
            KingbosRefundOrderRequest request = new KingbosRefundOrderRequest();
            KingbosRefundOrderData data = new KingbosRefundOrderData();
            data.setCorderSource("MALL");
            String extendOrderId = order.getExtendOrderId();
            data.setCasId(extendOrderId);
            data.setCoId(extendOrderId);
            request.setData(data);
            // 3. 构建订单明细数据
            List<KingbosRefundOrderD1Data> d1Datas = new ArrayList<>();


            List<KingbosRefundOrderD1Data> d1_data = new ArrayList<>();
            FsStoreOrderItem query = new FsStoreOrderItem();
            query.setOrderId(order.getId());
            List<FsStoreOrderItem> orderItems = storeOrderItemService.selectFsStoreOrderItemList(query);


            d1_data = orderItems.stream()
                    .map(item -> buildRefundOrderDetailItem(extendOrderId))
                    .collect(Collectors.toList());
            request.setD1_data(d1_data);
            logger.info("【金博网络退货单】订单明细数据构建完成，明细数量: {}", d1Datas.size());
        }
        return null;
    }

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

    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert param) {
        return null;
    }

    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest param) {
        return null;
    }


    /**
     * 退款 运单号已获取到
     * @param orderCode
     * @return
     */
    private ErpOrderResponse refundOrder1(String orderCode) {
        KingbosRefundOrderRequest request = getKingbosRefundOrderRequest(orderCode);
        FsErpConfig erpConfig = configUtil.getErpConfig();
        JSONObject param = JSONUtil.createObj();
        param.set("key", "WR");
        param.set("data", request.getData());
        param.set("d1_data", request.getD1_data());
        String timeStep = System.currentTimeMillis() + "";
        String sign = SignUtils.sign(param.toString(),erpConfig.getKingbosSecret(), erpConfig.getKingbosan(), timeStep);
        String url = UrlUtils.getUrl(erpConfig.getKingbosUrl(),sign, timeStep);
        String result = HttpUtil.post(url, param.toString());
        logger.info("zyp \n【金博网络退货单】:"+result);
        KingbosOrderResponse response = JSONUtil.toBean(result, KingbosOrderResponse.class);
        log.info("订单推送成功: {}", response);
        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        erpOrderResponse.setCode(response.getCbilid());
        return erpOrderResponse;
    }




    /**
     * 退款 运单号未获取到  改状态
     * @param orderCode 订单编号
     * @return
     */
    private ErpOrderResponse refundOmsOrder2(String orderCode) {
        try {
            KingbosOrderResponse response = createOmsOrder(orderCode, CANCELLED.getCode());
            if (response.getIsSuccess()){
                log.info("订单推送成功: {}", response);
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(response.getCbilid());
                return erpOrderResponse;
            }else {
                throw new RuntimeException(String.format("订单推送失败,原因: %s",response.getErrmsg()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    /**
     * 通过订单编号推送订单 解析金博结果
     * @param orderCode
     * @return
     */
    private ErpOrderResponse addOmsOrder(String orderCode) {
        try {
            KingbosOrderResponse response = this.createOmsOrder(orderCode, NO_DELIVERED.getCode());
            if (response.getIsSuccess()){
                log.info("订单推送成功: {}", response);
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(response.getCbilid());
                return erpOrderResponse;
            }else {
                throw new RuntimeException(String.format("订单推送失败,原因: %s",response.getErrmsg()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }


    /**
     * 组装参数得到金博结果
     * @param orderCode
     * @param orderStatus
     * @return
     */
    private KingbosOrderResponse createOmsOrder(String orderCode,String orderStatus){
        logger.info("【金博网络订单】开始创建订单，订单Code: {}", orderCode);
        try {
            // 1. 获取订单信息并验证
            FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
            logger.info("【金博网络订单】订单信息获取成功，订单id: {}", order.getId());
            logger.info("【金博网络订单】订单信息获取成功，订单号: {}", order.getOrderCode());

            // 2. 构建金博订单数据
            KingbosOrderData data = buildKingbosOrderData(order,orderStatus);
            logger.info("【金博网络订单】订单数据构建完成，金博订单号: {}", data.getCo_id());

            // 3. 构建订单明细数据
            List<KingbosOrderD1Data> d1Datas = buildOrderDetailData(order, data.getCdo_id());
            logger.info("【金博网络订单】订单明细数据构建完成，明细数量: {}", d1Datas.size());

            // 4. 发送订单请求
            KingbosOrderResponse response = sendOrderRequest(data, d1Datas);
            if (response.getCbilid()==null){
                response.setCbilid(order.getExtendOrderId());
            }
            return response;
//            if (response.getIsSuccess()){
//                FsStoreOrder order1 = new FsStoreOrder();
//                order1.setId(order.getId());
//                order1.setExtendOrderId(response.getCbilid());
//                fsStoreOrderMapper.updateFsStoreOrder(order1);
//                logger.info("【金博网络订单】订单创建完成，订单ID: {}", orderId);
//            }else {
//                logger.error("【金博网络订单】创建订单失败，订单ID: {}, 错误信息: {}", orderId, response.getErrmsg());
//            }
        } catch (Exception e) {
            logger.error("【金博网络订单】创建订单失败，订单Code: {}, 错误信息: {}", orderCode, e.getMessage(), e);
            throw e;
        }
    }


    /**
     * 组装订单推送参数
     * @param order
     * @param orderStatus
     * @return
     */
    private KingbosOrderData buildKingbosOrderData(FsStoreOrder order,String orderStatus) {
        FsErpConfig erpConfig = configUtil.getErpConfig();
        logger.debug("【金博网络订单】开始构建订单数据，订单号: {}", order.getOrderCode());
        KingbosOrderData data = new KingbosOrderData();
        // 设置基础信息
        data.setCordersource("MALL");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        data.setDorder_date(sdf.format(order.getCreateTime()));
//        data.setCshop_buyer_id("zk2025");
        data.setCplatformtype("99");
        data.setCshop_id("zk2025");
        data.setCshop_name("自建商城");
        String orderSn = "";
        // 设置订单编号
        if (orderStatus.equals(NO_DELIVERED.getCode())){
            orderSn= IdUtil.getSnowflake(0, 0).nextIdStr();
        }else if (orderStatus.equals(CANCELLED.getCode())){
            orderSn = order.getExtendOrderId();
        }

        data.setCso_id(order.getOrderCode());
        data.setCo_id(orderSn);
        data.setCdo_id(orderSn);
        //同步订单信息
        order.setExtendOrderId(orderSn);

        // 设置金额信息
        data.setFpay_amount(order.getPayPrice());
        data.setFpaid_amount(order.getPayMoney());
        data.setFfreight(order.getTotalPostage());
        data.setFfree_amount(order.getCouponPrice());
        data.setFpostcost(BigDecimal.ZERO);

        // 设置状态和时间
        data.setCstatus(orderStatus);//未发货
        data.setDmodified(sdf.format(order.getUpdateTime()));

        // 设置收货信息
        setReceiverInfo(data, order);

        // 设置仓库信息
        data.setCwarehouse_code(erpConfig.getCwarehouseCode());
        data.setCwarehouse_name(erpConfig.getCwarehouseName());

        // 设置货到付款信息
        if (!order.getPayType().equals("1")) {
            data.setBis_cod(1);
            data.setFshouldpaymoney(order.getDeliveryPayMoney());
        }

        return data;
    }

    private void setReceiverInfo(KingbosOrderData data, FsStoreOrder order) {
        logger.debug("【金博网络订单】开始处理收货信息，订单号: {}", order.getOrderCode());
        String[] address = order.getUserAddress().split(" ");
        if (address.length < 3) {
            logger.error("【金博网络订单】收货地址格式不正确，订单号: {}, 地址: {}", order.getOrderCode(), order.getUserAddress());
            throw new ServiceException("收货地址格式不正确");
        }

        data.setCreceiver_state(address[0]);
        data.setCreceiver_city(address[1]);
        data.setCreceiver_district(address[2]);

        // 处理详细地址
        String detailAddress = address.length > 3 ?
            String.join("", Arrays.copyOfRange(address, 3, address.length)) :
            address[2];

        // 处理特殊字符
        detailAddress = detailAddress.replace("+", "加")
                                   .replace("\n", "");

        data.setCreceiver_address(detailAddress);
        data.setCreceiver_name(order.getRealName());
        data.setCreceiver_mobile(order.getUserPhone());

    }

    private List<KingbosOrderD1Data> buildOrderDetailData(FsStoreOrder order, String orderId) {
        logger.debug("【金博网络订单】开始构建订单明细，订单号: {}", order.getOrderCode());
        FsStoreOrderItem query = new FsStoreOrderItem();
        query.setOrderId(order.getId());
        List<FsStoreOrderItem> orderItems = storeOrderItemService.selectFsStoreOrderItemList(query);

        List<KingbosOrderD1Data> d1Datas = orderItems.stream()
            .map(item -> buildOrderDetailItem(item, orderId))
            .collect(Collectors.toList());

        logger.debug("【金博网络订单】订单明细构建完成，订单号: {}, 明细数量: {}", order.getOrderCode(), d1Datas.size());
        return d1Datas;
    }

    private KingbosRefundOrderD1Data buildRefundOrderDetailItem(String orderId) {
        KingbosRefundOrderD1Data item = new KingbosRefundOrderD1Data();
        item.setCasId(orderId);
        item.setCorderSource("MALL");
        return item;
    }

    private KingbosOrderD1Data buildOrderDetailItem(FsStoreOrderItem orderItem, String orderId) {
        FsStoreCartDTO cartDTO = JSONUtil.toBean(orderItem.getJsonInfo(), FsStoreCartDTO.class);
        BigDecimal quantity = new BigDecimal(orderItem.getNum());

        KingbosOrderD1Data item = new KingbosOrderD1Data();
        item.setCdo_id(orderId);
        item.setCo_id(orderId);
        item.setCsku_id(cartDTO.getBarCode());
        item.setCgoodsid(cartDTO.getBarCode());
        item.setCname(cartDTO.getProductName());
        item.setCshop_sku_id(cartDTO.getSku());
        item.setIqty(quantity);
        item.setFprice(cartDTO.getPrice());
        item.setFamount(quantity.multiply(cartDTO.getPrice()));
        item.setCordersource("MALL");
        item.setFpromoamount(BigDecimal.ZERO);

        return item;
    }

    /**
     * 发送请求
     * @param data
     * @param d1Datas
     * @return
     */
    private KingbosOrderResponse sendOrderRequest(KingbosOrderData data, List<KingbosOrderD1Data> d1Datas) {
        logger.info("【金博网络订单】开始发送订单请求，金博订单号: {}", data.getCo_id());
        KingbosOrderRequest request = new KingbosOrderRequest();
        request.setData(data);
        request.setD1_data(d1Datas);

        try {
            KingbosOrderResponse response = addErpOrder(request);
            logger.info("【金博网络订单】订单请求发送成功，金博订单号: {}, 响应结果: {}", data.getCo_id(), response);
            return response;
        } catch (Exception e) {
            logger.error("【金博网络订单】订单请求发送失败，金博订单号: {}, 错误信息: {}", data.getCo_id(), e.getMessage(), e);
            throw e;
        }
    }

    private KingbosOrderResponse addErpOrder(KingbosOrderRequest request) {
        FsErpConfig erpConfig = configUtil.getErpConfig();
        JSONObject param = JSONUtil.createObj();
        param.set("key", "OL");
        param.set("data", request.getData());
        param.set("d1_data", request.getD1_data());
        String timeStep = System.currentTimeMillis() + "";
        logger.info("zyp \n【金博网络订单推送参数】:"+param);
        String sign = SignUtils.sign(param.toString(),erpConfig.getKingbosSecret(), erpConfig.getKingbosan(), timeStep);
        String url = UrlUtils.getUrl(erpConfig.getKingbosUrl(),sign, timeStep);
        String json = param.toString();
        String result = HttpUtil.post(url, json);
        logger.info("zyp \n【金博网络订单推送返回】:"+result);
        KingbosOrderResponse response = JSONUtil.toBean(result, KingbosOrderResponse.class);
        return response;
    }


    @Override
    public ErpOrderResponse finishOrder(ErpOrder order) {
        return null;
    }
}
