package com.duiba.tuia.youtui.web.controller;/**
 * Created by chengdeman .
 * 17/6/28 .
 */

import cn.com.duiba.tuia.activity.center.api.constant.BalanceType;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.constant.Constants;
import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.constant.InnerLogCode;
import com.duiba.tuia.youtui.web.exception.ActivityException;
import com.duiba.tuia.youtui.web.log.InnerLogService;
import com.duiba.tuia.youtui.web.model.Result;
import com.duiba.tuia.youtui.web.model.req.*;
import com.duiba.tuia.youtui.web.model.toutiao.TouTiaoData;
import com.duiba.tuia.youtui.web.service.ThirPartyService;
import com.duiba.tuia.youtui.web.tool.DomainUtil;
import com.duiba.tuia.youtui.web.tool.RequestLocal;
import com.duiba.tuia.youtui.web.tool.RequestTool;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 第三方接口controller
 *
 * @author chengdeman
 * @create 2017-06-28 下午3:13
 **/
@RestController
@RequestMapping("/thirdParty")
public class ThirdPartyController extends BaseController {


    @Autowired
    private ThirPartyService thirPartyService;

    /**
     * 今日头条首页初始化.
     *
     * @throws ActivityException the activity exception
     * @author
     * @since JDK 1.6
     */
    @RequestMapping(value = "/Tindex", method = RequestMethod.GET)
    ModelAndView index(HttpServletRequest request) {
        try {
            ModelAndView model = new ModelAndView("headline/index");
            model.addObject("host", DomainUtil.getHost(request));
            model.addObject("pageHost", "//" + request.getHeader("host"));
            return model;
        } catch (Exception e) {
            logger.warn("今日头条首页初始化页面失败，请检查 :", e);
            return new ModelAndView(Constants.MODEL_ERROR);
        }
    }


    /**
     * 获取今日头条信息列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTdata", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTdata(HttpServletRequest request, String category, String refreshTime) {
        try {
            return successResult(thirPartyService.getTdata(request, category, refreshTime));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 今日头条搜索新闻接口
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTsearch", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTsearch(HttpServletRequest request, String keyword) {

        try {
            return successResult(thirPartyService.getTsearch(request, keyword));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 上报头条用户文章点击事件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTclick", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTclick(HttpServletRequest request, TclickReq req) {
        try {
            return successResult(thirPartyService.getTclick(request, req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 上报头条用户文章点击事件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTshow", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTshow(HttpServletRequest request, TclickReq req) {
        try {
            // 打印本地inner日志
            req.setConsumerId(RequestLocal.get().getCid());
            req.setAppId(RequestLocal.get().getAppId());
            String json = JSONObject.toJSONString(req);
            InnerLogService.innerJsonObject(InnerLogCode.INNER_GROUP, InnerLogCode.TOUTIAO_NEWS_INNER_TYPE, JSONObject.parseObject(json));
            return successResult("ok");
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 上报头条用户文章点击事件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTAdshow", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTAdshow(HttpServletRequest request, TAdclickReq req) {

        try {
            // 构建请求参数
            req.setClient_ip(RequestTool.getIpAddr(request));
            req.setOs(RequestTool.getOSNew(request));
            req.setLabel("show");
            req.setLanguage("simplified");
            return successResult(thirPartyService.getTAdclick(request, req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 上报头条用户广告点击事件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTAdclick", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTAdclick(HttpServletRequest request, TAdclickReq req) {
        try {
            // 构建请求参数
            req.setClient_ip(RequestTool.getIpAddr(request));
            req.setOs(RequestTool.getOSNew(request));
            req.setLabel("click");
            req.setLanguage("simplified");
            return successResult(thirPartyService.getTAdclick(request, req));
        } catch (Exception e) {
            return failResult(e);
        }
    }


    /**
     * 今日头条用户不喜欢的文章
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTdislike", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTdislike(HttpServletRequest request, TdislikeReq req) {
        try {
            req.setAction("dislike");
            return successResult(thirPartyService.getTdislike(request, req));
        } catch (Exception e) {
            return failResult(e);
        }
    }


    /**
     * 网易考拉回调接口
     *
     * @param request
     * @param kaolaCallBackReq
     * @return
     */
    @RequestMapping(value = "/kaola", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONObject kaolaCallBack(HttpServletRequest request, KaolaCallBackReq kaolaCallBackReq) {

        JSONObject jsonObject = new JSONObject();
        try {
            if (null != kaolaCallBackReq) {
                JSONObject json = new JSONObject();
                json.put("clickId", kaolaCallBackReq.getClickId());
                json.put("idfa", kaolaCallBackReq.getIdfa());
                json.put("ip", kaolaCallBackReq.getIp());
                json.put("subchannel", "kaola");
                InnerLogService.innerJsonObject(InnerLogCode.INNER_GROUP, InnerLogCode.KAOLA_INNER_TYPE, json);
            }
            jsonObject.put("record", 200);
            jsonObject.put("redesc", "成功");
            return jsonObject;
        } catch (Exception e) {
            jsonObject.put("record", 9999);
            jsonObject.put("redesc", "发生错误");
            return jsonObject;
        }
    }

    /**
     * 获取今日头条信息列表（直投页中展示）
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTNewdata", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getNewTdata(HttpServletRequest request, String category, String refreshTime) {
        try {
            return successResult(thirPartyService.getTNewdata(request, category, refreshTime));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 上报头条用户文章点击事件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTNewAdshow", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTNewAdshow(HttpServletRequest request, String showUrl, Integer pageId) {

        try {
            if (StringUtils.isEmpty(showUrl)) {
                logger.info("[param] error, because of showUrl is empty");
                throw new ActivityException(ErrorCode.E0000001.geteCode(), "param[showUrl] is empty");
            }
            String action = "show";
            return successResult(thirPartyService.getTNewAdReport(request, showUrl, pageId, action));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 上报头条用户广告点击事件
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/getTNewAdclick", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<String> getTNewAdclick(HttpServletRequest request, String clickUrl, Integer pageId) {
        try {
            // 构建请求参数
            if (StringUtils.isEmpty(clickUrl)) {
                logger.info("[param] error, because of clickUrl is empty");
                throw new ActivityException(ErrorCode.E0000001.geteCode(), "param[clickUrl] is empty");
            }
            String action = "click";
            return successResult(thirPartyService.getTNewAdReport(request, clickUrl, pageId, action));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    @RequestMapping(value = "/rechargeCash", method = RequestMethod.POST)
    @ApiOperation(value = "rechargeCash", httpMethod = "POST", notes = "虚拟奖品充值接口")
    public Map<String, String> rechargeCash(HttpServletRequest request, @RequestParam Map<String, String> map) {
        return thirPartyService.rechargeCash(map, BalanceType.CASH);
    }

    @RequestMapping(value = "/rechargeGame", method = RequestMethod.POST)
    @ApiOperation(value = "rechargeGame", httpMethod = "POST", notes = "虚拟奖品充值接口")
    public Map<String, String> rechargeGame(HttpServletRequest request, @RequestParam Map<String, String> map) {
        return thirPartyService.rechargeCash(map, BalanceType.GAME);
    }

    /**
     * 获取今日头条信息列表（直投页中展示）
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getTNewdata2", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<TouTiaoData> getNewTdata2(HttpServletRequest request, String category, String refreshTime) {
        try {
            return successResult(thirPartyService.getTNewdata2(request, category, refreshTime));
        } catch (Exception e) {
            return failResult(e);
        }
    }
}
