package com.prolog.cs.biz.outbound.service.impl.faceorder;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.prolog.cs.basic.common.model.BaseCommonDict;
import com.prolog.cs.biz.outbound.model.OmsDoBillHDO;
import com.prolog.cs.biz.outbound.model.dto.FaceOrderPickTaskDDTO;
import com.prolog.cs.biz.outbound.model.dto.faceorder.JDKdFaceOrderAddDTO;
import com.prolog.cs.biz.outbound.model.dto.faceorder.JdBmdFaceOrder;
import com.prolog.cs.biz.outbound.model.dto.faceorder.JdBmdFaceOrderAddDto;
import com.prolog.cs.biz.outbound.model.dto.faceorder.JdKyFaceOrderAddDTO;
import com.prolog.cs.biz.outbound.model.entity.WaveBillDDO;
import com.prolog.cs.biz.outbound.model.entity.WmsFaceOrder;
import com.prolog.cs.biz.outbound.model.vo.faceorder.JDKdOrderAddVO;
import com.prolog.cs.biz.outbound.model.vo.faceorder.JdKyOrderAddVO;
import com.prolog.cs.biz.outbound.resource.CommonClient;
import com.prolog.cs.biz.outbound.resource.StrategyResource;
import com.prolog.cs.biz.outbound.utils.HttpClientUtils;
import com.prolog.framework.common.message.RestMessage;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.utils.StringUtils;
import com.prolog.upcloud.base.strategy.model.BusinessControl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 京东 医药零担
 */
@Slf4j
@Component
public class JdKdFaceOrderHandler extends KyBaseFaceOrderHandler{

    @Autowired
    private StrategyResource strategyResource;

    @Autowired
    private CommonClient commonClient;

    public String generateCreateFaceOrderParam(OmsDoBillHDO omsDoBillHDO, List<FaceOrderPickTaskDDTO> list, List<WaveBillDDO> waveBillDDOS,Integer count){
        JDKdOrderAddVO faceOrderAddVO = new JDKdOrderAddVO();
        faceOrderAddVO.setCarrierCode("JD_QINGNIU_YYKD");
        List<JDKdOrderAddVO.ParamsBean2> params = new ArrayList<>();

        JDKdOrderAddVO.ParamsBean2 paramsBean = new JDKdOrderAddVO.ParamsBean2();
        JDKdOrderAddVO.ParamsBean2.CargoesRequestBean cargosContactDTO = new JDKdOrderAddVO.ParamsBean2.CargoesRequestBean();
        JDKdOrderAddVO.ParamsBean2.SenderContactRequestBean senderContactDTO = new JDKdOrderAddVO.ParamsBean2.SenderContactRequestBean();
        JDKdOrderAddVO.ParamsBean2.ReceiverContactRequestBean receiverContactDTO = new JDKdOrderAddVO.ParamsBean2.ReceiverContactRequestBean();

        paramsBean.setOrderId(omsDoBillHDO.getBillno());
        String customerCode = null; // 商家编码
        RestMessage<Map<String, BusinessControl>> rest = strategyResource.getControlByCodes(new String[]{"JD_QINGNIU_YYKD_CUSTOMER_CODE"}, omsDoBillHDO.getBranchid(), null, omsDoBillHDO.getEnterpriseId(), null);
        if (rest.isSuccess() && rest.getData() != null) {
            Map<String,BusinessControl> conMap = rest.getData();
            if (conMap.containsKey("JD_QINGNIU_YYKD_CUSTOMER_CODE")) {
                customerCode = String.valueOf(conMap.get("JD_QINGNIU_YYKD_CUSTOMER_CODE").getRegValue());
            }
        }
        if(StringUtils.isBlank(customerCode)){
            throw new BizException("请配置商家编码!");
        }
        paramsBean.setCustomerCode(customerCode);
        paramsBean.setRemark(omsDoBillHDO.getRemark());
        paramsBean.setSalePlatform("0030001");
        paramsBean.setPromiseTimeType(29);
        paramsBean.setGoodsType(24);

        senderContactDTO.setSenderAddress("江西省赣州市章贡区经济技术开发区凤凰路7号");
        senderContactDTO.setSenderCompany("青牛医药");
        senderContactDTO.setSenderMobile("4009158120");
        senderContactDTO.setSenderPhone("4009158120");
        senderContactDTO.setSenderName("青牛医药");
        senderContactDTO.setSenderPostcode("341002");

        receiverContactDTO.setReceiverCompany("京东");
        //receiverContactDTO.setReceiverProvince(omsDoBillHDO.getReceiveProvinceName());
        //receiverContactDTO.setReceiverCounty(omsDoBillHDO.getReceiveDistrictName());
        //receiverContactDTO.setReceiverCity(omsDoBillHDO.getReceiveCityName());
        receiverContactDTO.setReceiverPhone(omsDoBillHDO.getCustPersonTel());
        receiverContactDTO.setReceiverProvinceName(omsDoBillHDO.getReceiveProvinceName());
        //receiverContactDTO.setReceiverTown(omsDoBillHDO.getReceiveTownName());
        receiverContactDTO.setReceiverName(omsDoBillHDO.getCustPerson());
        receiverContactDTO.setReceiverMobile(omsDoBillHDO.getCustPersonTel());
        receiverContactDTO.setReceiverAddress(omsDoBillHDO.getReceiveAddress());
        receiverContactDTO.setReceiverCityName(omsDoBillHDO.getReceiveCityName());
        receiverContactDTO.setReceiverTownName(omsDoBillHDO.getReceiveDistrictName());
        receiverContactDTO.setReceiverCountyName(omsDoBillHDO.getReceiveDistrictName());
        receiverContactDTO.setReceiverOAID("1");

        cargosContactDTO.setVolume(omsDoBillHDO.getTotVolume().setScale(2, RoundingMode.HALF_UP).doubleValue());
        cargosContactDTO.setWeight(omsDoBillHDO.getTotWeight().setScale(2, RoundingMode.HALF_UP).doubleValue());
        cargosContactDTO.setGoodsCount(count);
        cargosContactDTO.setDescription("药品");
        cargosContactDTO.setGoodsName("药品");
        cargosContactDTO.setPackageQty(count);

        paramsBean.setCargoesRequest(cargosContactDTO);
        paramsBean.setReceiverContactRequest(receiverContactDTO);
        paramsBean.setSenderContactRequest(senderContactDTO);

        params.add(paramsBean);
        faceOrderAddVO.setParams(params);
        omsDoBillHDO.setAttrStr8("JD_QINGNIU_YYKD");
        log.info("京东快递生成下单参数 + {} + {}", JSONObject.toJSONString(faceOrderAddVO), JSONObject.toJSONString(omsDoBillHDO));
        return JSONObject.toJSONString(faceOrderAddVO);

    }

    @Override
    String getUrl() {
        BaseCommonDict baseCommonDict = getRequestUrls().stream().filter(item -> "JDYYKD".equals(item.getDictCode())).findFirst().orElse(null);
        if(baseCommonDict == null){
            throw new BizException("请配置京东快运医药快递创建面单请求地址！");
        }
        return baseCommonDict.getDictName();
    }

    @Override
    public List<WmsFaceOrder> convertResult(JSONObject result, OmsDoBillHDO omsDoBillHDO) {
//        RestMessage<JdFaceOrderAddDTO> restMessage = JSON.parseObject(result.toJSONString(), RestMessage.class);
//        if(restMessage == null || !restMessage.isSuccess() || restMessage.getData() == null){
//            throw new BizException("请求面单失败!");
//        }
//
//        List<WmsFaceOrder> wmsFaceOrders = new ArrayList<>();
//
//        Object data1 = restMessage.getData();
//        JSONArray jsonArray = JSON.parseArray(JSON.toJSONString(data1));
//        Object obj = jsonArray.get(0);
//        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(obj));
//        Object carrierJdResultInfo = jsonObject.get("carrierJdResultInfo");
//        String orderNo = jsonObject.getJSONObject("data").getString("orderNo");
//
//        JdFaceOrderAddDTO dto = JSON.parseObject(JSON.toJSONString(carrierJdResultInfo),JdFaceOrderAddDTO.class);
//        String createOrderInfo = dto.getGetPlainTextInfo();
//        JSONObject object = JSON.parseObject(createOrderInfo);
//        JSONArray jsonArray1 = object.getJSONArray("printDatas");
//
//        for (Object o : jsonArray1) {
//            JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(o));
//            String printData = jsonObject1.getString("printData");
//            JdFaceOrderInfo jdFaceOrderInfo = JSONObject.parseObject(printData, JdFaceOrderInfo.class);
//
//
//            WmsFaceOrder faceOrder = new WmsFaceOrder();
//            faceOrder.setWaybillCode(jdFaceOrderInfo.getPackageCode());
//            faceOrder.setTransportMode(jdFaceOrderInfo.getTransportMode());
//            faceOrder.setTransportType(jdFaceOrderInfo.getTransportType());
//            faceOrder.setFreshType(jdFaceOrderInfo.getFreshType());
//            faceOrder.setPackageCode(jdFaceOrderInfo.getWaybillCode());
//            faceOrder.setPackageCodeSuffix(jdFaceOrderInfo.getPackageCodeSuffix());
//            faceOrder.setSourceSortCenterName(jdFaceOrderInfo.getSourceSortCenterName());
//            faceOrder.setTargetSortCenterName(jdFaceOrderInfo.getTargetSortCenterName());
//            faceOrder.setSourceCrossCodeSourceTabletrolleyCode(jdFaceOrderInfo.getSourceTabletrolleyCode());
//            faceOrder.setTargetCrossCodeSourceTabletrolleyCode(jdFaceOrderInfo.getTargetTabletrolleyCode());
//            faceOrder.setPreSortSiteName(jdFaceOrderInfo.getPreSortSiteName());
//            faceOrder.setRemark(orderNo);
//            wmsFaceOrders.add(faceOrder);
//        }

        Boolean success = (Boolean) result.get("success");
        if(!success){
            throw new BizException("请求面单失败!");
        }

        JSONObject jsonObject = result.getJSONObject("data");
        if(jsonObject == null ){
            throw new BizException("请求面单数据失败");
        }
        String jsonString = JSONArray.toJSONString(jsonObject);
        JDKdFaceOrderAddDTO.DataBean jdKdFaceOrderAddDTO = JSONArray.parseObject(jsonString, JDKdFaceOrderAddDTO.DataBean.class);
        log.info("解析JDKD请求面单返回结果：{}",JSON.toJSONString(jdKdFaceOrderAddDTO));
        List<WmsFaceOrder> wmsFaceOrders = new ArrayList<>();
        String wayBillNo = jdKdFaceOrderAddDTO.getWaybillNo();

        BaseCommonDict baseCommonDict = getRequestUrls().stream().filter(item -> "JDBMD".equals(item.getDictCode())).findFirst().orElse(null);
        if(baseCommonDict == null){
            throw new BizException("请配置京东快运白名单请求地址！");
        }
        //配置信息
        RestMessage<List<BaseCommonDict>> restMessage = commonClient.getDictBasicListByCodes("Face_Order_Config", null);
        if(restMessage == null || !restMessage.isSuccess() || restMessage.getData() == null || restMessage.getData().size() <= 0){
            throw new BizException("获取配置失败!");
        }
        List<BaseCommonDict> data = restMessage.getData();
        BaseCommonDict baseCommonDict1 = data.stream().filter(item -> omsDoBillHDO.getAttrStr8().equals(item.getDictCode())).findFirst().orElse(null);
        if(baseCommonDict1 == null){
            throw new BizException("京东承运商客户编码未配置!");
        }

        String url = baseCommonDict.getDictName();
        String[] split = wayBillNo.split(",");
        //京东白名单接口调用
        JdBmdFaceOrder jdbmd = new JdBmdFaceOrder();
        List<JdBmdFaceOrder.JdBmdParamsDTO> param = new ArrayList<>();
        JdBmdFaceOrder.JdBmdParamsDTO jdBmdParamsDTO = new JdBmdFaceOrder.JdBmdParamsDTO();
        jdbmd.setCarrierCode(omsDoBillHDO.getAttrStr8());
        jdbmd.setCompanyCode("jdcloudprint");
        if (ObjectUtil.isEmpty(split[0])) {
            throw new BizException("获取面单失败");
        }
        jdBmdParamsDTO.setBillCodeValue(split[0]);
        jdBmdParamsDTO.setBillCodeType("waybillCode");
        jdBmdParamsDTO.setCustomerCode(baseCommonDict1.getAttr1());

        jdBmdParamsDTO.setScene(4);
        param.add(jdBmdParamsDTO);
        jdbmd.setParams(param);

        String jdbmdParam = JSONObject.toJSONString(jdbmd);
        log.info("请求创建面单url：{}", JSON.toJSONString(url));
        //String param = JSON.toJSONString(param);
        log.info("请求创建面单param：{}", jdbmd);
        JSONObject result1 = HttpClientUtils.postByJson(url, jdbmdParam);
        log.info("请求创建面单返回结果：{}",JSON.toJSONString(result1));

        // 假设result1是您的JSONObject对象
        JSONArray printDatas = result1.getJSONArray("printDatas");

        List<JdBmdFaceOrderAddDto> jdBmdFaceOrderAddDtoList = JSON.parseArray(printDatas.toJSONString(), JdBmdFaceOrderAddDto.class);
        if(CollectionUtil.isEmpty(jdBmdFaceOrderAddDtoList)){
            throw new BizException("获取白名单数据失败");
        }
        for (JdBmdFaceOrderAddDto jdBmdFaceOrderAddDto : jdBmdFaceOrderAddDtoList) {
            WmsFaceOrder faceOrder = new WmsFaceOrder();
            JdBmdFaceOrderAddDto.PrintDataDTO printData = jdBmdFaceOrderAddDto.getPrintData();

            faceOrder.setWaybillCode(jdBmdFaceOrderAddDto.getPackageCode());
            faceOrder.setRemark(wayBillNo);
            faceOrder.setTransportMode(printData.getTransportMode());
            faceOrder.setTransportType(printData.getTransportType());
            faceOrder.setFreshType(printData.getFreshType());
            faceOrder.setPackageCode(printData.getWaybillCode());
            faceOrder.setPackageCodeSuffix(printData.getPackageCodeSuffix());
            faceOrder.setSourceSortCenterName(printData.getSourceSortCenterName());
            faceOrder.setTargetSortCenterName(printData.getTargetSortCenterName());
            faceOrder.setSourceCrossCodeSourceTabletrolleyCode(printData.getSourceTabletrolleyCode());
            faceOrder.setTargetCrossCodeSourceTabletrolleyCode(printData.getTargetTabletrolleyCode());
            faceOrder.setPreSortSiteName(printData.getPreSortSiteName());
            faceOrder.setSenderName(printData.getSenderName());
            faceOrder.setSenderMobile(printData.getSenderMobile());
            faceOrder.setSenderAddress(printData.getSenderAddress());
            faceOrder.setReceiverAddress(printData.getReceiverAddress());
            faceOrder.setReceiverMobile(printData.getReceiverMobile());
            faceOrder.setReceiverName(printData.getReceiverName());
            faceOrder.setParentWaybillCode(printData.getWaybillCodeFirst());
            wmsFaceOrders.add(faceOrder);
        }

/*
        String bmdtoString = JSONArray.toJSONString(bmdsj);
        JdBmdFaceOrderAddDto jdKyBmdAddDto = JSONArray.parseObject(bmdtoString, JdBmdFaceOrderAddDto.class);
        log.info("京东快运请求白名单返回结果：{}",JSON.toJSONString(jdKyBmdAddDto));
        String waybillCode = jdKyBmdAddDto.getPackageCode()

        for (int i = 0; i < split.length; i++) {
            WmsFaceOrder faceOrder = new WmsFaceOrder();
            faceOrder.setWaybillCode(split[i]);
            faceOrder.setRemark(jdKyFaceOrderAddDTO.getOrderNo());
            wmsFaceOrders.add(faceOrder);
        }
*/

        return wmsFaceOrders;
    }
}
