package com.cyksj.service.order.post.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.*;
import com.cyksj.mapper.OrderDonMapper;
import com.cyksj.mapper.order.OrderDonPostMapper;
import com.cyksj.model.entity.OrderDon;
import com.cyksj.service.order.post.AbstractPostDataService;
import com.cyksj.service.order.post.PostDataFactory;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.net.URLDecoder;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Optional;

/**
 * 360点睛回传
 *
 * @author chan
 * @date 2023-07-10 14:20
 */
@Slf4j
@Service("djPostDataService")
@RequiredArgsConstructor
public class djPostDataService extends AbstractPostDataService{

    //key: 6px6m643y9zoadccx4n1
    //Secret: omgdr7q9bxw0rsyb634wnhk1fjow7o4j
    private static final String APP_KEY = "6px6m643y9zoadccx4n1";

    private static final String APP_SECRET = "omgdr7q9bxw0rsyb634wnhk1fjow7o4j";

    @Override
    public void postData(Long orderId, String callback, String evenType) throws Exception {
        callback = callback.replaceAll("#", "");
        log.info("360广告回传入参id：{}", orderId);

        callback = URLDecoder.decode(callback, IoKit.Charsets.UTF_8.getCharset());

        Map<String, String> paramMap = HttpUtil.decodeParamMap(callback, StandardCharsets.UTF_8);
        OrderDon orderDon = orderDonMapper.selectById(orderId);
        //临时处理 只回传奈飞，其他不回传。
        if(orderDon.getGoodsId() != 1){
            log.info("360 只回传奈飞. 该订单商品id:{}",orderDon.getGoodsId());
            return;
        }
        String qhclickid = Optional.ofNullable(paramMap.get("qhclickid")).orElse("");
        if (StringUtil.isBlank(qhclickid)) {
            throw new BusinessRuntimeException("360回传错误. qhclickid为空 orderId:" + orderId);
        }
        JSONObject params = new JSONObject();
        DianJingPostData dianJingPostData = new DianJingPostData();

        if(orderDon.getIsWebPay()){
            //ocpc_ms_convert[移动搜索]
            //ocpc_ps_convet[PC搜索推广]
            dianJingPostData.setData_industry("ocpc_ps_convert");
        }else {
            dianJingPostData.setData_industry("ocpc_ms_convert");
        }
        DianJingPostDataDetail dianJingPostDataDetail = new DianJingPostDataDetail();
        dianJingPostDataDetail.setQhclickid(qhclickid);
        dianJingPostDataDetail.setEvent(evenType);
        dianJingPostDataDetail.setTrans_id(orderId.toString());
        dianJingPostData.setData_detail(dianJingPostDataDetail);
        params.putOpt("data",dianJingPostData);


        String url = "https://convert.dop.360.cn/uploadWebConvert";
        String postData = Jsons.toJson(params);
        log.info("360广告api回传 参数params：{}", postData);
        String sign = Codec.DoDigest.custom()
                .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
                .setStringData(APP_SECRET + postData).toHexString();
        HttpResponse<byte[]> res =
                J11HttpC.custom()
                        .ofPost()
                        .url(url)
                        .headers(J11HttpC.ReqType.raw_json, J11HttpC.ofHeader("App-Key",APP_KEY), J11HttpC.ofHeader("App-Sign",sign))
                        .body(HttpRequest.BodyPublishers.ofString(postData, IoKit.Charsets.UTF_8.getCharset()))
                        .send(HttpResponse.BodyHandlers.ofByteArray());


        Map<String, Object> resMap = Jsons.parseObject(res.body(), Map.class);
        log.info("360广告api回传：{}", resMap);

        String result = StringUtil.getString(resMap.get("errno"));
        if ("0".equals(result)) {
            //修改记录状态
            orderPostMapper.updateStatus(orderId);
            log.info("回传记录修改状态");

        } else {
            //错误
            log.error("360广告回传错误 msg:{}, orderId:{}", StringUtil.getString(resMap.get("error")), orderId);
        }

    }

    @PostConstruct
    public void init() {
       PostDataFactory.add(this, this.getClass().getSimpleName());
    }

    @Data
    static class DianJingPostData{

        private String data_industry;

        private DianJingPostDataDetail data_detail;
    }

    @Data
    static class DianJingPostDataDetail{
        private String qhclickid;

        private String event;

        private String trans_id;
    }
}
