package com.fs.kingbos.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.kingbos.domian.*;
import com.fs.kingbos.enums.OrderStatusEnum;
import com.fs.kingbos.service.K9OrderService;
import com.fs.kingbos.util.SignUtil;
import com.fs.kingbos.util.UrlUtil;
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 org.springframework.transaction.annotation.Transactional;


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

import static com.fs.kingbos.enums.OrderStatusEnum.CANCELLED;
import static com.fs.kingbos.enums.OrderStatusEnum.NO_DELIVERED;

@Service
@Slf4j
public class K9OrderServiceImpl implements K9OrderService {
    public final static Logger logger = LoggerFactory.getLogger(K9OrderServiceImpl.class);
    @Autowired
    FSSysConfig sysConfig;
    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;
    @Autowired
    private IFsStoreOrderItemService storeOrderItemService;
    @Autowired
    private FsStoreProductMapper productMapper;
    @Override
    public KingbosOrderResponse addOrder(KingbosOrderRequest request) {
        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 = SignUtil.sign(param.toString(),sysConfig.getKingbosSecret(), sysConfig.getKingbosan(), timeStep);
        String url = UrlUtil.getUrl(sysConfig.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 KingbosOrderResponse refundOrder(KingbosRefundOrderRequest request) {
        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 = SignUtil.sign(param.toString(),sysConfig.getKingbosSecret(), sysConfig.getKingbosan(), timeStep);
        String url = UrlUtil.getUrl(sysConfig.getKingbosUrl(),sign, timeStep);
        String result = HttpUtil.post(url, param.toString());
        logger.info("zyp \n【金博网络退货单】:"+result);
        KingbosOrderResponse response = JSONUtil.toBean(result, KingbosOrderResponse.class);
        return response;
    }


    @Override
    @Transactional
    public void createOmsOrder(Long orderId,String orderStatus){
        logger.info("【金博网络订单】开始创建订单，订单ID: {}", orderId);
        try {
            // 1. 获取订单信息并验证
            FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderById(orderId);
            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.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("【金博网络订单】创建订单失败，订单ID: {}, 错误信息: {}", orderId, e.getMessage(), e);
            throw e;
        }
    }


    private KingbosOrderData buildKingbosOrderData(FsStoreOrder order,String orderStatus) {
        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);

        // 设置金额信息
        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(sysConfig.getCwarehouseCode());
        data.setCwarehouse_name(sysConfig.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 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;
    }

    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 = this.addOrder(request);
            logger.info("【金博网络订单】订单请求发送成功，金博订单号: {}, 响应结果: {}", data.getCo_id(), response);
            return response;
        } catch (Exception e) {
            logger.error("【金博网络订单】订单请求发送失败，金博订单号: {}, 错误信息: {}", data.getCo_id(), e.getMessage(), e);
            throw e;
        }
    }
}
