package com.kmall.manager.manager.tocus;

import com.kmall.common.constant.Dict;
import com.kmall.manager.entity.CusReqRecordEntity;
import com.kmall.manager.entity.pay.data.open.PayExInfo;
import com.kmall.manager.entity.pay.data.open.ResponseMsg;
import com.kmall.common.utils.JacksonUtils;
import com.kmall.common.utils.OkHttpUtils;
import com.kmall.manager.manager.pay.data.open.cus.CusPropertiesBuilder;
import com.kmall.manager.manager.pay.data.open.websocket.WebsocketPropertiesBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 向海关发送支付原始数据
 *
 * @author Scott Chen
 * @since 1.0
 * 2018-12-25
 */
public class CusPayDataSender {
    private static final Logger logger = LoggerFactory.getLogger(CusPayDataSender.class);

    /**
     * 发送海关数据
     * @param payExInfo
     * @param signValue
     * @return
     */
    public static String send(PayExInfo payExInfo, String signValue) {

        // 发送数据中增加证书序号和签名值
        payExInfo.setCertNo(WebsocketPropertiesBuilder.instance().getCardNo());
        payExInfo.setSignValue(signValue);

        String payExInfoStr = JacksonUtils.toJson(payExInfo);

        //payExInfoStr = "{\"sessionID\":\"7c73b9-962f45c2-348439e5\",\"payExchangeInfoHead\":{\"guid\":\"C4B0E1DB-7EFE-4C9D-9CE8-2FFB3884619A\",\"initalRequest\":\"request data\",\"initalResponse\":\"response data\",\"ebpCode\":\"4403160Z3Y\",\"payCode\":\"440316T004\",\"payTransactionId\":\"EMATO201812200305\",\"totalAmount\":100.01,\"currency\":\"142\",\"verDept\":\"3\",\"payType\":\"1\",\"tradingTime\":\"2018-12-20 13:33:20\",\"note\":\"批量订单，测试订单优化,生成多个so订单\"},\"payExchangeInfoLists\":[{\"orderNo\":\"EMATO201812200305\",\"goodsInfo\":[{\"gname\":\"Nivea90g\",\"itemLink\":\"http://ai.k1net.com/search/index.htm?key=aaa\"},{\"gname\":\"Nivea2100g\",\"itemLink\":\"http://ai.k1net.com/search/index.htm?key=bbb\"}],\"recpAccount\":\"20000032506200012146872\",\"recpCode\":\"91440300MA5DGG1J0R\",\"recpName\":\"abccc\"}],\"serviceTime\":\"1545646340365\",\"certNo\":\"00f2f3e3\",\"signValue\":\"" + signValue + "\"}";
        logger.debug("payExInfoStr: {}", payExInfoStr);


        Map<String, Object> map = new HashMap<>();
        map.put("payExInfoStr", payExInfoStr);

        String contents = JacksonUtils.toJson(map);
        logger.debug("send pay data: {}", contents);

        String resp = OkHttpUtils.post(map, CusPropertiesBuilder.instance().getPayDateUrl(), "SSL");
        return resp;
    }

    /**
     * 处理海关返回消息
     * @param result
     */
    public static CusReqRecordEntity response(String result, CusReqRecordEntity record) {
        if (StringUtils.isBlank(result)) {
            String str = "发送海关支付原始数据返回空";
            logger.error(str);

            // 更新状态
            record.setStatus(Dict.cusDateOpenStatus.item_20000.getItem());
            record.setMessage(str);
            record.setModTime(new Date());
            return record;
        }

        ResponseMsg resp = JacksonUtils.fromStringJson(result, ResponseMsg.class);
        String code = resp.getCode();
        if (ResponseMsg.SUCCESS_CODE.equals(code)) {
            logger.info("发送海关成功，返回消息: {}", result);

            // 更新状态
            record.setStatus(Dict.cusDateOpenStatus.item_10000.getItem());
            record.setMessage(resp.getMessage());
            record.setModTime(new Date());
            return record;
        } else {
            logger.error("发送海关失败，返回消息: {}", result);

            // 更新状态
            record.setStatus(code);
            record.setMessage(resp.getMessage());
            record.setModTime(new Date());
            return record;
        }
    }

}
