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.utils.StringUtils;
import com.fs.kingbos.domian.*;
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.domain.FsStoreProduct;
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 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.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
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 sign = SignUtil.sign(param.toString(),sysConfig.getKingbosSecret());
        String url = UrlUtil.getUrl(sysConfig.getKingbosUrl(),sign);
        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 sign = SignUtil.sign(param.toString(),sysConfig.getKingbosSecret());
        String url = UrlUtil.getUrl(sysConfig.getKingbosUrl(),sign);
        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) throws ParseException {
        FsStoreOrder order=fsStoreOrderMapper.selectFsStoreOrderById(orderId);
        if(StringUtils.isEmpty(order.getExtendOrderId())&&order.getStatus()!=1){
            return;
        }
        //组装金博data
        KingbosOrderData data = new KingbosOrderData();
        data.setCordersource("中康未来智慧药房");
        data.setDorder_date(order.getCreateTime());
        data.setCshop_buyer_id("zkwlzhyf100");//传固定值不可变
        data.setCplatformtype("zkwlzhyfminiapp");
        data.setCshop_id("zkwlzhyf2024");//中康未来智慧药房
        data.setCshop_name("中康未来智慧药房");
        data.setCso_id(order.getOrderCode());
        String orderSn = IdUtil.getSnowflake(0, 0).nextIdStr();
        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.setCstatus("待发货");
        data.setFpostcost(BigDecimal.ZERO);
        data.setDmodified(new Date());
        String[] address=order.getUserAddress().split(" ");
        data.setCreceiver_state(address[0]);
        data.setCreceiver_city(address[1]);
        data.setCreceiver_district(address[2]);
        //处理地址多空隔问题
        if(address.length>3){
            StringBuffer addrs=new StringBuffer();
            for(int i=3;i<address.length;i++){
                addrs.append(address[i]);
            }
            data.setCreceiver_address(addrs.toString());
        }
        else if(address.length==3){
            data.setCreceiver_address(address[2]);
        }
        //处理地址字符问题
        data.setCreceiver_address(data.getCreceiver_address().replace("+","加"));
        data.setCreceiver_address(data.getCreceiver_address().replace("\n",""));
        data.setCreceiver_name(order.getRealName());
        data.setCreceiver_mobile(order.getUserPhone());
        data.setCexpress_name(order.getDeliveryName());
        data.setCexpress_code("SF");
        data.setCwarehouse_code("");
        data.setCwarehouse_name("");
        List<KingbosOrderD1Data> d1Datas = new ArrayList<>();
        FsStoreOrderItem itemMap=new FsStoreOrderItem();
        itemMap.setOrderId(order.getId());
        List<FsStoreOrderItem> orderItems=storeOrderItemService.selectFsStoreOrderItemList(itemMap);
        for (FsStoreOrderItem orderItem: orderItems){
            FsStoreCartDTO cartDTO= JSONUtil.toBean(orderItem.getJsonInfo(),FsStoreCartDTO.class);
            KingbosOrderD1Data item = new KingbosOrderD1Data();
            item.setCdo_id(data.getCdo_id());
            item.setCo_id(data.getCo_id());
            item.setCsku_id(cartDTO.getBarCode());
            item.setCgoodsid(cartDTO.getBarCode());
            item.setCname(cartDTO.getProductName());
            item.setCshop_sku_id(cartDTO.getBarCode());
            item.setIqty(new BigDecimal(orderItem.getNum()));
            item.setFprice(cartDTO.getPrice());
            item.setFamount(new BigDecimal(orderItem.getNum()).multiply(cartDTO.getPrice()));
            item.setCordersource(data.getCordersource());
            item.setIsreturn(0);
            item.setFpromoamount(BigDecimal.ZERO);
            d1Datas.add(item);
        }
        KingbosOrderRequest request = new KingbosOrderRequest();
        request.setData(data);
        request.setD1_data(d1Datas);
        KingbosOrderResponse response = this.addOrder(request);
    }
}
