package com.duiba.tuia.youtui.web.controller;
/**
 * Created by chengdeman .
 * 17/5/9 .
 */

import cn.com.duiba.wolf.utils.UrlUtils;
import cn.com.duibaboot.ext.autoconfigure.accesslog.AccessLogFilter;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.bo.JoinActivityBO;
import com.duiba.tuia.youtui.web.constant.Constants;
import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.exception.ActivityException;
import com.duiba.tuia.youtui.web.exception.BusinessException;
import com.duiba.tuia.youtui.web.model.Result;
import com.duiba.tuia.youtui.web.model.UserAccount;
import com.duiba.tuia.youtui.web.model.req.DoJoinActivityReq;
import com.duiba.tuia.youtui.web.model.req.PluginToolsReq;
import com.duiba.tuia.youtui.web.model.rsp.PluginToolsRsp;
import com.duiba.tuia.youtui.web.service.PluginToolsService;
import com.duiba.tuia.youtui.web.tool.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
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 org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Map;

/**
 * 插件工具controller
 *
 * @author chengdeman
 * @create 2017-05-09 上午11:37
 **/
@Controller
@RequestMapping("/pluginTools")
public class PluginToolsController extends BaseController {

    /**
     * The plugin tools Service.
     */
    @Autowired
    private PluginToolsService pluginToolsService;

    @Autowired
    private JoinActivityBO joinActivityBO;


    /**
     * @param : a
     * @return :  a
     * @Description :
     * @author :  chengdeman
     * @Date :  17/5/
     */
    @ResponseBody
    @RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<PluginToolsRsp> pluginToolsIndex(PluginToolsReq req, HttpServletRequest request, HttpServletResponse response) {

        try {
            checkUser(request);
            // 1.判断是否展示插件活动，是：返回插件活动皮肤；否返回null
            setReq(req, request);

            // 获取tenter
            if (StringUtils.isBlank(req.getTenter())) {
                Map<String,String> params = UrlUtils.explainURLParams(req.getReferer());
                if (params != null) {
                    req.setTenter(params.get(Constants.VALUENAME.TENTER));
                }

            }

            // 2 获取cookie 信息:用户已参与过的插件工具
            Cookie cookie = CookieUtil.getCookieByName(request, Constants.FINISHED_PLUGIN_ID_KEY + RequestLocal.get().getUserAccount().getUserId());
            req.setHavePluginIds(cookie == null ? null : cookie.getValue());
            return successResult(pluginToolsService.pluginToolsIndex(req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 嵌入式插件 index
     *
     * @param req
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/embeddedIndex", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<PluginToolsRsp> embeddedToolsIndex(PluginToolsReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            checkUser(request);
            setReq(req, request);
            return successResult(pluginToolsService.embeddedIndex(req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 响应式插件 index
     *
     * @param req
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/responsiveIndex", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<PluginToolsRsp> responsiveIndex(PluginToolsReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (null == req) {
                throw new ActivityException(ErrorCode.E0000001);
            }
            checkUser(request);
            setReq(req, request);
            return successResult(pluginToolsService.responsiveIndex(req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/timingIndex", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<PluginToolsRsp> timingIndex(PluginToolsReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (null == req) {
                throw new BusinessException(ErrorCode.E0000001);
            }
            checkUser(request);
            setReq(req, request);
            return successResult(pluginToolsService.timingIndex(req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    private void setReq(PluginToolsReq req, HttpServletRequest request) {
        req.setIp(getIp(request));
        req.setHost(request.getHeader("host"));
        req.setYunDomain(DomainUtil.getCurrentYunDomain(request));
        req.setReferer(request.getHeader(Constants.HTTPHEADER.REFERER));
    }

    /**
     * @param : a
     * @return :  a
     * @Description :
     * @author :  chengdeman
     * @Date :  17/5/
     */
    @ResponseBody
    @RequestMapping(value = "/dojoin", method = {RequestMethod.GET, RequestMethod.POST})
    public Result<JSONObject> pluginToolsDojoin(@Valid DoJoinActivityReq req, HttpServletRequest request, HttpServletResponse response) {

        try {
            // 1.记录参与的插件工具ID
            AccessLogFilter.putExPair("pluginId", String.valueOf(req.getActivityId()));
            AccessLogFilter.putExPair("pluginType", String.valueOf(req.getActivityType()));

            // 2.用户信息及参数处理
            RequestLocal.get().setRequest(request);
            req.setIp(RequestTool.getIpAddr(request));
            req.setUserAgent(RequestTool.getUserAgent(request));
            req.setOs(RequestTool.getOSNew(request));
            req.setAppId(RequestLocal.get().getAppId());
            req.setConsumerId(RequestLocal.get().getCid());
            req.setUserId(RequestLocal.get().getUserId());
            req.setReferer(request.getHeader(Constants.HTTPHEADER.REFERER));

            // 设置插件工具类型，插件工具与活动公用订单表，设置特殊类型2000区分
            //req.setActivityType(Constants.PLUGIN_TOOLS_TYPE)

            if (StringUtils.isNotBlank(RequestLocal.get().getSlotId()) && !"null".equals(RequestLocal.get().getSlotId())) {
                req.setSlotId(Long.valueOf(RequestLocal.get().getSlotId()));
            }
            req.setDeviceId(RequestLocal.get().getDeviceId());
            // 福袋取coll参数
            req.setParamMap(RequestLocal.get().getCollParams());

            //将网络类型放入logMap中
            if (StringUtils.isNotBlank(req.getConnection_type())) {
                req.getParamMap().put("connection_type", req.getConnection_type());
            }

            // 将流量来源放入logMap中
            if (StringUtils.isNotBlank(req.getAppFlowType())) {
                req.getParamMap().put("appFlowType", req.getAppFlowType());
            }

            // 保存cookie中的活动页来源
            EmbedUtil.getDcmAndDpmMap(request, req.getParamMap(), String.valueOf(req.getActivityId()));


            // 2.参与插件活动结果
            return successResult(pluginToolsService.doJoin(req, request));
        } catch (Exception e) {
            logger.info("插件工具参与异常，插件工具ID ＝ " + req.getActivityId(), e);
            return failResult(e);
        }
    }

    /**
     * get result by ConsumerId and orderId.
     *
     * @param orderId the activity Order Id
     * @return the result< json object>
     */
    @ResponseBody
    @RequestMapping(value = "/result", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "result", httpMethod = "POST", notes = "参与活动接口")
    public Result<JSONObject> pluginToolsResult(@Valid String orderId, Boolean showVersion, HttpServletRequest request, HttpServletResponse response) {
        try {
            return successResult(joinActivityBO.result(request, orderId, showVersion));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * get result by ConsumerId and orderId.
     *
     * @return the result< json object>
     */
    @ResponseBody
    @RequestMapping(value = "/preview", method = {RequestMethod.POST, RequestMethod.GET})
    @ApiOperation(value = "preview", httpMethod = "POST", notes = "插件预览接口")
    public ModelAndView pluginToolsPreview(@Valid Long pluginToolsId, HttpServletRequest request, HttpServletResponse response) {

        // 1.获取用户信息
        UserAccount consumer = RequestLocal.get().getUserAccount();
        if (null == consumer) {
            return new ModelAndView(Constants.MODEL_ERROR);
        }

        try {
            return new ModelAndView("preview/plugin")
                    .addObject("host", DomainUtil.getHost(request))
                    .addObject("pageHost", "//" + request.getHeader("host"));
        } catch (Exception e) {
            logger.warn("初始化活动页面失败，请检查活动ID :" + pluginToolsId, e);
            return new ModelAndView(Constants.MODEL_ERROR);
        }
    }


}
