package cn.com.ctop.track.controller;

import cn.com.ctop.track.entity.ClickInfo;
import cn.com.ctop.track.entity.ConvertInfo;
import cn.com.ctop.track.service.ClickInfoService;
import cn.com.ctop.track.service.ConvertInfoService;
import cn.com.ctop.track.service.TaobaoNoticeService;
import cn.com.ctop.track.service.impl.TaobaoNoticeServiceImpl;
import cn.com.ctop.track.utils.HttpUtils;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;

@Controller
@RequestMapping("/")
public class TrackController {
    private static Logger logger = Logger.getLogger(TrackController.class);
    @Autowired
    private ClickInfoService clickInfoService;
    @Autowired
    private TaobaoNoticeService taobaoNoticeService;
    @Autowired
    private ConvertInfoService convertInfoService;
    @ResponseBody
    @RequestMapping(value = "/convert")
    public String convert(HttpServletRequest request,
                        HttpServletResponse response){
        logger.info(request.getQueryString());
        try {
            //test
            String clickId = request.getParameter("click_id");
            String clickIdStr = request.getParameter("click_id_str");
            String spaceId = request.getParameter("space_id");
            String accountId = request.getParameter("account_id");
            String os = request.getParameter("os_type");
            String platform = request.getParameter("platform");
            String advertisor = request.getParameter("advertisor");
            String groupId = request.getParameter("group_id");
            String campaignId = request.getParameter("compaign_id");
            String creativeId = request.getParameter("creative_id");
            String campaignName = request.getParameter("campaign_name");
            String mac = request.getParameter("mac");
            String macMd5 = request.getParameter("mac_md5");
            String ts = request.getParameter("ts");
            String osString = request.getParameter("os");
            String ip = request.getParameter("ip");
            String sence = request.getParameter("sence");
            String imeiMd5 = null;
            String idfaMd5 = null;
            String oaid = null;
            if(os != null){
                if (os.equals("Android")){
                    imeiMd5 = request.getParameter("imei_md5");
                    oaid = request.getParameter("oaid");
                }else if(os.equals("IOS")){
                    idfaMd5 = request.getParameter("idfa_md5");
                }
            }
            String callbackUrl = request.getParameter("callback_url");
            String transformType = request.getParameter("transformType");
            if (transformType != null){
                if(platform !=null && platform.equals("sigmob")){
                    String e = request.getParameter("e");
                    String p = request.getParameter("p");
                    callbackUrl = callbackUrl+"&e="+e+"&p="+p;
                }
                if (transformType.equals("1")){
                    if(platform !=null && platform.equals("bytedance")){
                        callbackUrl = "https://ad.oceanengine.com/track/activate/?callback="+callbackUrl;
                        callbackUrl = callbackUrl+"&event_type=0&conv_time="+new Date().getTime()+"&imei="+imeiMd5+"&oaid="+oaid;
                    }else if(platform !=null && platform.equals("kuaishou")){
                        callbackUrl = callbackUrl+"&event_type=1&event_time="+new Date().getTime();
                    }

                }else if (transformType.equals("2")){
                    if(platform !=null && platform.equals("bytedance")){
                        callbackUrl = "https://ad.oceanengine.com/track/activate/?callback="+callbackUrl;
                        callbackUrl = callbackUrl+"&event_type=1&conv_time="+new Date().getTime()+"&imei="+imeiMd5+"&oaid="+oaid;
                    }else if(platform !=null && platform.equals("kuaishou")){
                        callbackUrl = callbackUrl+"&event_type=2&event_time="+new Date().getTime();
                    }

                }
            }
            String result = HttpUtils.httpGetRequest(callbackUrl);
            ConvertInfo convertInfo = new ConvertInfo();
            convertInfo.setCallbackUrl(callbackUrl);
            try {
                convertInfo.setClickId(Long.parseLong(clickId));
            }catch (Exception e){

            }
            convertInfo.setClickIdStr(clickIdStr);
            convertInfo.setTransformType(transformType);
            convertInfo.setResponse(result);
            convertInfo.setAdvertisor(advertisor);
            convertInfo.setCampaignId(campaignId);
            convertInfo.setCampaignName(campaignName);
            convertInfo.setCreativeId(creativeId);
            convertInfo.setGroupId(groupId);
            convertInfo.setIdfaMd5(idfaMd5);
            convertInfo.setImeiMd5(imeiMd5);
            convertInfo.setIp(ip);
            convertInfo.setMac(mac);
            convertInfo.setMacMd5(macMd5);
            convertInfo.setOaid(oaid);
            convertInfo.setOsType(os);
            convertInfo.setPlatform(platform);
            convertInfo.setSence(sence);
            convertInfo.setSpaceId(spaceId);
            convertInfo.setAccountId(accountId);
            try {
                convertInfo.setTs(new Date(Long.parseLong(ts)));
            } catch (NumberFormatException e) {

            }
            convertInfoService.save(convertInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"code\":200,\"result\":\"success\"}";
    }

    @ResponseBody
    @RequestMapping(value = "/convert2")
    public String convert2(HttpServletRequest request,
                          HttpServletResponse response){
        logger.info(request.getQueryString());
        try {
            //test
            String clickId = request.getParameter("click_id");
            String spaceId = request.getParameter("space_id");
            String accountId = request.getParameter("account_id");
            String os = request.getParameter("os_type");
            String platform = request.getParameter("platform");
            String advertisor = request.getParameter("advertisor");
            String groupId = request.getParameter("group_id");
            String campaignId = request.getParameter("compaign_id");
            String creativeId = request.getParameter("creative_id");
            String campaignName = request.getParameter("campaign_name");
            String mac = request.getParameter("mac");
            String macMd5 = request.getParameter("mac_md5");
            String ts = request.getParameter("ts");
            String osString = request.getParameter("os");
            String ip = request.getParameter("ip");
            String sence = request.getParameter("sence");
            String imeiMd5 = null;
            String idfaMd5 = null;
            String oaid = null;
            if(os != null){
                if (os.equals("Android")){
                    imeiMd5 = request.getParameter("imei_md5");
                    oaid = request.getParameter("oaid");
                }else if(os.equals("IOS")){
                    idfaMd5 = request.getParameter("idfa_md5");
                }
            }
            String callbackUrl = request.getParameter("callback_url");
            String transformType = request.getParameter("transformType");
            String result = null;
            if (transformType != null){
                if (transformType.equals("2")) {
                    if (platform != null && platform.equals("bytedance")) {
                        callbackUrl = "https://ad.oceanengine.com/track/activate/?callback=" + callbackUrl;
                        callbackUrl = callbackUrl + "&event_type=0&conv_time=" + new Date().getTime() + "&imei=" + imeiMd5 + "&oaid=" + oaid;
                    } else if (platform != null && platform.equals("kuaishou")) {
                        callbackUrl = callbackUrl + "&event_type=1&event_time=" + new Date().getTime();
                    }
                    result = HttpUtils.httpGetRequest(callbackUrl);
                }
//                }else if (transformType.equals("2")){
//                    if(platform !=null && platform.equals("bytedance")){
//                        callbackUrl = "https://ad.oceanengine.com/track/activate/?callback="+callbackUrl;
//                        callbackUrl = callbackUrl+"&event_type=1&conv_time="+new Date().getTime()+"&imei="+imeiMd5+"&oaid="+oaid;
//                    }else if(platform !=null && platform.equals("kuaishou")){
//                        callbackUrl = callbackUrl+"&event_type=2&event_time="+new Date().getTime();
//                    }
//
//                }
            }

            ConvertInfo convertInfo = new ConvertInfo();
            convertInfo.setCallbackUrl(callbackUrl);
            try {
                convertInfo.setClickId(Long.parseLong(clickId));
            }catch (Exception e){

            }
            convertInfo.setTransformType(transformType);
            convertInfo.setResponse(result);
            convertInfo.setAdvertisor(advertisor);
            convertInfo.setCampaignId(campaignId);
            convertInfo.setCampaignName(campaignName);
            convertInfo.setCreativeId(creativeId);
            convertInfo.setGroupId(groupId);
            convertInfo.setIdfaMd5(idfaMd5);
            convertInfo.setImeiMd5(imeiMd5);
            convertInfo.setIp(ip);
            convertInfo.setMac(mac);
            convertInfo.setMacMd5(macMd5);
            convertInfo.setOaid(oaid);
            convertInfo.setOsType(os);
            convertInfo.setPlatform(platform);
            convertInfo.setSence(sence);
            convertInfo.setSpaceId(spaceId);
            convertInfo.setAccountId(accountId);
            try {
                convertInfo.setTs(new Date(Long.parseLong(ts)));
            } catch (NumberFormatException e) {

            }
            convertInfoService.save(convertInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"code\":200,\"result\":\"success\"}";
    }

    @ResponseBody
    @RequestMapping(value = "/click")
    public String click(HttpServletRequest request,
                        HttpServletResponse response){
        try {
            logger.info(request.getQueryString());
            String os = request.getParameter("os_type");
            String spaceId = request.getParameter("space_id");
            String advertisor = request.getParameter("advertisor");
            String campaignId = request.getParameter("compaign_id");
            String creativeId = request.getParameter("creative_id");
            String campaignName = request.getParameter("campaign_name");
            String dpaId = request.getParameter("dpa_id");
            String dpaType = request.getParameter("dpa_type");
            String imeiMd5 = null;
            String idfaMd5 = null;
            String oaid = null;
            if(os != null){
                if (os.equals("Android")){
                    imeiMd5 = request.getParameter("imei_md5");
                    oaid = request.getParameter("oaid");
                }else if(os.equals("IOS")){
                    idfaMd5 = request.getParameter("idfa_md5");
                }
            }
            if(spaceId == null || spaceId.equals("")){
                spaceId = "11709";
            }
            if (advertisor!= null && advertisor.equals("taobao")){
                try {
                    String convertUrl = "https://track.c-top.com.cn/convert?"+request.getQueryString();
                    logger.info(convertUrl);
                    taobaoNoticeService.sendNotice(spaceId,campaignId,campaignName,creativeId,imeiMd5,idfaMd5,oaid,dpaId,dpaType,convertUrl);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return "{\"code\":200,\"result\":\"success\"}";
    }
}
