package cn.pluss.platform.yt;

import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.device.DeviceSpecService;
import cn.pluss.platform.entity.DeviceMerchantBuy;
import cn.pluss.platform.entity.DeviceSpec;
import cn.pluss.platform.entity.MercOrderDetail;
import cn.pluss.platform.entity.MercOrderNew;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.util.XmlUtil;
import cn.pluss.platform.yt.constant.YtConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 *
 *圆通相关处理业务类
 *@author: bzg
 *@time: 2022/2/24 16:33
 */
@Slf4j
@Component
public class YtLogistHandler {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DeviceSpecService deviceSpecService;

    /**
     * 圆通订单创建接口
     * @date: 2022/2/24 16:37
     * @param order:
     * @return com.alibaba.fastjson.JSONObject
     */
    public DeviceMerchantBuy createYtOrder(DeviceMerchantBuy order){
        if(order == null){
            return null;
        }
        if(!"1".equals(order.getStatus())){
            return null;
        }
        if(StringUtils.isNotEmpty(order.getExpressNo())){
            return null;
        }
        String logisticsNo =  "YT" + DateUtils.currentYourDate("yyyyMMddHHmmssSSS") + StringUtil.generateMixStr(2).toUpperCase(Locale.ROOT);
        order.setLogistNo(logisticsNo);
        YtCreateOrder reqData = new YtCreateOrder();
        reqData.setRecipientName(order.getLinkName());
        reqData.setRecipientMobile(order.getLinkPhone());
        reqData.setRecipientAddress(order.getAddress());
        reqData.setRecipientProvinceName(order.getProvinces().split("-")[0]);
        reqData.setRecipientCityName(order.getProvinces().split("-")[1]);
        reqData.setRecipientCountyName(order.getProvinces().split("-")[2]);
        reqData.setLogisticsNo(logisticsNo);
        YtLogisticsRequest request = new YtLogisticsRequest(reqData,YtConstant.CUSTOMER_KEY, YtConstant.YT_CREATE_METHOD, YtConstant.CUSTOMER_CODE);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> header = new HttpEntity<>(JSON.toJSONString(request), headers);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(request.getReqUrl(), header, JSONObject.class);
        if(HttpStatus.OK.equals(response.getStatusCode())){
            JSONObject body = response.getBody();
            String mailNo = body.getString("mailNo");
            order.setExpressNo(mailNo);
            return order;
        }else{
            log.info("【圆通】下单接口请求异常,异常信息:{}",response.getBody());
            return null;
        }
    }

    /**
     * 解析圆通物流业务参数
     * @param reqData
     * @return
     */
    public YtUpdateInfo resolvXml(String reqData) {
        Map<String, String> params = XmlUtil.readXml(reqData);
        return JSONObject.parseObject(JSON.toJSONString(params),YtUpdateInfo.class);
    }

    /**
     * 推送圆通物流信息V2
     * @param list
     * @return
     */
    public JSONObject createYtOrderV2(List<MercOrderDetail> list, MercOrderNew order) {
        String logisticsNo = "YT" + DateUtils.currentYourDate("yyyyMMddHHmmssSSS") + StringUtil.generateMixStr(2).toUpperCase(Locale.ROOT);
        YtCreateOrder reqData = new YtCreateOrder();
        reqData.setRecipientName(order.getReceiver());
        reqData.setRecipientMobile(order.getPhone());
        reqData.setRecipientAddress(order.getAddress());
        reqData.setRecipientProvinceName(order.getAreaName().split("-")[0]);
        reqData.setRecipientCityName(order.getAreaName().split("-")[1]);
        reqData.setRecipientCountyName(order.getAreaName().split("-")[2]);
        reqData.setLogisticsNo(logisticsNo);
        List<YtGood> ytGoods = new ArrayList<>(list.size());
        for (MercOrderDetail detail:list) {
            YtGood ytGood = new YtGood();
            ytGood.setName(detail.getName());
            ytGood.setPrice(detail.getPrice());
            ytGood.setQuantity(detail.getNum());
            DeviceSpec spec = deviceSpecService.getByCodeAndSpec(detail.getCode(), detail.getType());
            MsgException.checkNull(spec,"商品规格信息异常");
            ytGood.setWeight(spec.getWeight().multiply(BigDecimal.valueOf(detail.getNum())));
            ytGoods.add(ytGood);
        }
        reqData.setGoods(ytGoods);
        YtLogisticsRequest request = new YtLogisticsRequest(reqData,YtConstant.CUSTOMER_KEY, YtConstant.YT_CREATE_METHOD, YtConstant.CUSTOMER_CODE);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> header = new HttpEntity<>(JSON.toJSONString(request), headers);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(request.getReqUrl(), header, JSONObject.class);
        if(HttpStatus.OK.equals(response.getStatusCode())){
            JSONObject body = response.getBody();
            String mailNo = body.getString("mailNo");
            JSONObject params = new JSONObject(2);
            params.put("logistNo",logisticsNo);
            params.put("expressNo",mailNo);
            return ResultGenerator.genSuccessJsonResult("下单成功",params);
        }else{
            log.info("【圆通】下单接口请求异常,异常信息:{}",response.getBody());
            return ResultGenerator.genFailJsonResult(response.getBody().toJSONString());
        }
    }
}
