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

import cn.com.duiba.tuia.activity.center.api.constant.BalanceType;
import cn.com.duiba.tuia.activity.center.api.dto.GameConfigDto;
import cn.com.duiba.tuia.activity.center.api.dto.NickNameDto;
import cn.com.duiba.wolf.utils.UrlUtils;
import com.alibaba.fastjson.JSONObject;
import com.duiba.tuia.youtui.web.bo.ConsumerBO;
import com.duiba.tuia.youtui.web.constant.ErrorCode;
import com.duiba.tuia.youtui.web.exception.BusinessException;
import com.duiba.tuia.youtui.web.model.AutoLoginReq;
import com.duiba.tuia.youtui.web.model.CommonLoginReq;
import com.duiba.tuia.youtui.web.model.Result;
import com.duiba.tuia.youtui.web.model.req.ConsumerReq;
import com.duiba.tuia.youtui.web.model.rsp.LoginMidPageRsp;
import com.duiba.tuia.youtui.web.service.ConsumerService;
import com.duiba.tuia.youtui.web.service.GameCacheService;
import com.duiba.tuia.youtui.web.tongdun.FraudApiRequest;
import com.duiba.tuia.youtui.web.tongdun.FraudApiResponse;
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 com.duiba.tuia.youtui.web.tool.http.JsoupUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/12/12.
 */
@Controller
@RequestMapping("/consumer")
@Api("用户API")
public class ConsumerController extends BaseController {

    @Autowired
    private ConsumerBO consumerBO;

    @Autowired
    private ConsumerService consumerService;

    @Autowired
    private GameCacheService gameCacheService;

    @ResponseBody
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    @ApiOperation(value = "login", httpMethod = "POST", notes = "登录接口")
    public Result<Boolean> login( ConsumerReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            if(req.getPassword() == null && req.getInitialPassword() == null){
                throw new BusinessException(ErrorCode.E0000001);
            }
            return successResult(consumerBO.login(req, request));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = {RequestMethod.POST})
    @ApiOperation(value = "register", httpMethod = "POST", notes = "注册接口")
    public Result<Boolean> register(ConsumerReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            return successResult(consumerBO.register(req, request));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/resetPassword", method = {RequestMethod.POST})
    @ApiOperation(value = "resetPassword", httpMethod = "POST", notes = "密码重置接口")
    public Result<Boolean> resetPassword(ConsumerReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            checkLogin();
            if(req.getPassword() == null){
                throw new BusinessException(ErrorCode.E0000001);
            }
            return successResult(consumerBO.resetPassword(req));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/sendSms", method = {RequestMethod.POST})
    @ApiOperation(value = "sendSms", httpMethod = "POST", notes = "下发短信接口")
    public Result<Boolean> sendSms(ConsumerReq req, @Valid String validate, @Valid Integer type, HttpServletRequest request, HttpServletResponse response) {
        try {
            return successResult(consumerBO.sendSms(req, validate, type));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/imgCheck", method = {RequestMethod.POST})
    @ApiOperation(value = "imgCheck", httpMethod = "POST", notes = "校验触发图形验证接口")
    public Result<Boolean> imgCheck(@Valid String phone,HttpServletRequest request, HttpServletResponse response) {
        try {
            return successResult(consumerBO.imgCheck(phone));
        } catch (Exception e) {
            return failResult(e);
        }
    }

    /**
     * 微信授权统一访问日志
     */
    @ResponseBody
    @RequestMapping(value = "/weChatAuthorized", method = {RequestMethod.GET,RequestMethod.POST})
    public void weChatAuthorized(){ return;}

    @RequestMapping(value = "/autoLogin", method = {RequestMethod.GET})
    @ApiOperation(value = "autoLogin", httpMethod = "GET", notes = "自动登录接口")
    public void autoLogin(AutoLoginReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            req.checkParam();
            consumerBO.autoLogin(req, BalanceType.GAME);
            //.重定向链接
            String url = StringEscapeUtils.unescapeHtml3(req.getRedirectUrl());
            response.sendRedirect(url);
        } catch (Exception e) {
            logger.error("自动登录失败，请检查", e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/commonLogin", method = {RequestMethod.POST})
    @ApiOperation(value = "commonLogin", httpMethod = "POST", notes = "游客普通登录接口")
    public LoginMidPageRsp commonLogin(CommonLoginReq req, HttpServletRequest request, HttpServletResponse response) {
        try {
            //用户识别过程
            req.checkParam();
            String host = request.getHeader("host");
            return consumerBO.commonlogin(req,host);
        } catch (Exception e) {
            logger.error("游客登录失败，请检查", e);
            return null;
        }
    }

    @RequestMapping(value = "/loginIndex", method = {RequestMethod.GET})
    @ApiOperation(value = "loginIndex", httpMethod = "GET", notes = "游客普通登录中间页接口")
    public ModelAndView loginIndex(CommonLoginReq req, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView loginIndex = new ModelAndView("login/index");
        loginIndex.addObject("host", DomainUtil.getHost(request));
        loginIndex.addObject("deviceId", consumerBO.getTongDunDeviceId(req.getTokenId(), request));
        try {
            String redirectUrl = StringEscapeUtils.unescapeHtml4(req.getRedirectUrl());
            if (StringUtils.contains(redirectUrl, "direct/index")) {
                String str = gameCacheService.getGameLoginBgUrl();
                if (str != null) {
                    String bgUrl = JSONObject.parseObject(str).getString("0");
                    loginIndex.addObject("bgUrl", bgUrl);
                }
            } else if (StringUtils.contains(redirectUrl, "game/index")) {
                Map<String, String> stringMap = UrlUtils.uRLRequest(redirectUrl);
                String gameId = stringMap.get("id");
                GameConfigDto gameConfigDto = gameCacheService.getGameConfigDto(Long.parseLong(gameId));
                Integer gameType = gameConfigDto.getGameType();
                String str = gameCacheService.getGameLoginBgUrl();
                if (str != null) {
                    String bgUrl = JSONObject.parseObject(str).getString(gameType.toString());
                    loginIndex.addObject("bgUrl", bgUrl);
                }
            }
        } catch (Exception e) {
            logger.warn("设置背景图片出错", e);
        }
        return loginIndex;
    }

    @RequestMapping(value = "/getNickName", method = {RequestMethod.GET})
    @ApiOperation(value = "getNickName", httpMethod = "GET", notes = "获取昵称接口")
    @ResponseBody
    public NickNameDto getNickName(Long id) {
        return consumerService.getNextNickName(id);
    }

    @RequestMapping(value = "/updateConsumerInfo", method = {RequestMethod.GET})
    @ApiOperation(value = "updateConsumerInfo", httpMethod = "GET", notes = "更新用户信息接口")
    public void updateConsumerInfo(CommonLoginReq req, HttpServletResponse response) {
        try {
            //用户信息更新
            if (StringUtils.isNotBlank(req.getNickName())) {
                consumerBO.updateConsumerInfo(req);
            }
            //.重定向链接
            String url = StringEscapeUtils.unescapeHtml3(req.getRedirectUrl());
            StringBuilder sb = new StringBuilder(url);
            sb.append("&deviceId=").append(RequestLocal.get().getDeviceId());
            response.sendRedirect(sb.toString());
        } catch (Exception e) {
            logger.error("游客登录失败，请检查", e);
        }
    }

}
