package com.duiba.tuia.youtui.web.controller;


import cn.com.duiba.tuia.activity.center.api.log.InnerLog;
import cn.com.duiba.wolf.utils.UrlUtils;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.bo.ActivityBO;
import com.duiba.tuia.youtui.web.constant.Constants;
import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.constant.PreSource;
import com.duiba.tuia.youtui.web.log.InnerLogService;
import com.duiba.tuia.youtui.web.model.req.AdvertEffectReq;
import com.duiba.tuia.youtui.web.model.req.InnerLogReq;
import com.duiba.tuia.youtui.web.service.LogService;
import com.duiba.tuia.youtui.web.tool.DsmInfo;
import com.duiba.tuia.youtui.web.tool.PathUtil;
import com.duiba.tuia.youtui.web.tool.RequestLocal;
import com.duiba.tuia.youtui.web.tool.ResultUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.json.MappingJacksonValue;
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.net.URLDecoder;
import java.util.Map;
import java.util.UUID;

/**
 * ClassName: LogController <br/>
 * Function: 日志http接口. <br/>
 * date: 2017年2月20日 下午3:08:34 <br/>
 *
 * @author wubo
 * @since JDK 1.7
 */
@Controller
@RequestMapping("/log")
@Api("广告落地页日志API")
public class LogController extends BaseController {

    @Autowired
    private LogService logService;

    @Autowired
    private ActivityBO activityBO;


    /**
     * Inner log. 广告落地页曝光，点击日志接口 日志文档：http://cf.dui88.com/pages/viewpage.action?pageId=4513014
     *
     * @param req the req
     * @param callback the callback
     * @param request the request
     * @return the object
     */
    @ResponseBody
    @RequestMapping(value = "/inner", method = {RequestMethod.GET, RequestMethod.POST})
    public Object innerLog(InnerLogReq req, String callback, HttpServletRequest request) {
        try {
            // 1 校验参数
            String json = req.getJson();
            Integer type = req.getType();

            if (StringUtils.isBlank(json)) {
                return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "json不能为空");
            }
            if (type == null) {
                return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "type不能为空");
            }
            if (type > 8 || type < 7) {
                return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "type值不存在");
            }

            // jssdk  落地页处理
            logService.landPageLog(req,request);

            // 5 跨域json接口 返回
            return success(callback);

        } catch (JSONException e) {
            logger.info("解析json出错", e);
            return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "json格式异常");
        } catch (Exception e) {
            this.logger.error("日志记录出错", e);
            return failResult(e);
        }
    }


    @ResponseBody
    @RequestMapping(value = "/redirect", method = {RequestMethod.GET, RequestMethod.POST})
    public void redirect(HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.获取跳转链接
            String url = StringEscapeUtils.unescapeHtml3(request.getParameter("url"));
            String dsm = request.getParameter("dsm");
            Long slotId = Long.valueOf(RequestLocal.get().getSlotId());
            Long consumerId = RequestLocal.get().getCid();
            String orderId = UUID.randomUUID().toString();

            //2.记录内部日志，统计落地页访问日志
            JSONObject data = new JSONObject();
            data.put("appId", RequestLocal.get().getAppId());
            data.put("slotId", slotId);
            data.put("consumerId", consumerId);
            data.put("dsm", dsm);
            data.put("url", url);
            data.put("tuiaId", orderId);
            InnerLogService.log(new InnerLog().group(1).type(41).put("json", data).toJSONString());

            //3.更新反抗者拦截次数
            String dsmA = DsmInfo.getParamFromDsm(dsm, 1);
            if (PreSource.BACK.getType() == Integer.valueOf(dsmA)) {
                activityBO.updateReturnTimes(slotId, request);
            }

            //4.重定向
            Map<String, String> params = Maps.newHashMap();
            params.put(Constants.THE_TUIA_ID, orderId);
            params.put(Constants.THE_ORDER_ID, orderId);
            params.put(Constants.THE_CONSUMER_ID, String.valueOf(consumerId));
            String urlNew = UrlUtils.appendParams(url, params);
            response.sendRedirect(PathUtil.processUrl(urlNew, request));

        } catch (Exception e) {
            this.logger.error("日志记录出错", e);
        }
    }

    /**
     *  落地页转化效果回传
     * @param request
     * @param a_tuiaId   订单ID
     * @param a_cid      用户ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/effect/v1", method = {RequestMethod.GET,RequestMethod.POST})
    public JSONObject advertEffect(HttpServletRequest request,HttpServletResponse response, AdvertEffectReq advertEffectReq) {
        try {
            /**
             * 不同的域名记录转化，允许跨域
             */
            response.setHeader(Constants.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            response.setHeader(Constants.ACCESS_CONTROL_ALLOW_METHODS, Constants.MSG_POST_GET);
            response.setHeader(Constants.ACCESS_CONTROL_MAX_AGE, "3600");
            response.setHeader(Constants.ACCESS_CONTROL_ALLOW_HEADERS, Constants.MSG_X_REQUESTED_WITH);
            response.setHeader(Constants.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
            return logService.advertEffect(request,advertEffectReq);
        } catch (Exception e) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("record",999999);
            jsonObject.put("redesc","发生未知错误");
            return  jsonObject;
        }
    }


    /**
     *  记录所有的落地页点击曝光
     * @param request
     * @param a_tuiaId   订单ID
     * @param a_cid      用户ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/landLog", method = {RequestMethod.GET,RequestMethod.POST})
    public Object landLog(InnerLogReq req, String callback, HttpServletRequest request) {
        try {
            // 1 校验参数
            String json = req.getJson();
            Integer type = req.getType();

            if (StringUtils.isBlank(json)) {
                return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "json不能为空");
            }
            if (type == null) {
                return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "type不能为空");
            }
            if (type > 50 || type < 49) {
                return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "type值不存在");
            }

            // jssdk  落地页处理
            logService.allLandPageLog(req,request);

            // 5 跨域json接口 返回
            return success(callback);

        } catch (JSONException e) {
            logger.info("解析json出错", e);
            return ResultUtil.fail(ErrorCode.E0000001.geteCode(), "json格式异常");
        } catch (Exception e) {
            this.logger.error("日志记录出错", e);
            return failResult(e);
        }
    }


    /*
     * 返回成功
     */
    private MappingJacksonValue success(String callback) {
        MappingJacksonValue jacksonValue = new MappingJacksonValue(successResult());
        jacksonValue.setJsonpFunction(callback);
        return jacksonValue;
    }

}
