/**
 * Description: CmUser控制器
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-08-10 下午 17:06:21
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-10   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.house365.beans.entity.CmDictionaryEntity;
import com.house365.beans.entity.CmSmsCodeEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.SpringContextUtil;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CmDictionaryListRequest;
import com.house365.ws.beans.request.CmSmsCodeRequest;
import com.house365.ws.beans.request.CmUserListRequest;
import com.house365.ws.beans.request.CmUserRequest;
import com.house365.ws.beans.response.CmDictionaryListResponse;
import com.house365.ws.beans.response.CmSmsCodeResponse;
import com.house365.ws.beans.response.CmUserListResponse;
import com.house365.ws.beans.response.CmUserResponse;
import com.house365.ws.interfaces.server.ICmDictionary;
import com.house365.ws.interfaces.server.ICmSmsCode;
import com.house365.ws.interfaces.server.ICmUser;
import com.house365.ws.system.ReturnResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * CmUser控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-10
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/ranks")
public class RanksController extends BaseController {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RanksController.class);
    @Autowired
    RedisUtilsInterface redisUtils;
    /**
     * 自动注入CmUserWS实现
     */
    @Autowired
    private ICmUser cmUser;

    @Autowired
    private ICmSmsCode smsCode;

    @Autowired
    private ICmDictionary dictionary;

    /**
     * 排行榜主页
     *
     * @return 结果视图
     */
    @RequestMapping(value = "index")
    public String index(Model model) {
        return getAutoUrl("index");
    }

    /**
     * 排行榜主页
     *
     * @return 结果视图
     */
    @RequestMapping(value = "getRanksByType", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public String index(String type) {
        JSONArray ranks = new JSONArray();
        final String serviceCacheKey = "getRanksByType:" + type;
        String resultString = "";
        long timeToSeconds = 0;
        //获取缓存数据
//        try {
//            resultString = redisUtils.getValByKey(serviceCacheKey);
//            if (StringUtils.isNotBlank(resultString)) {
//                LOGGER.info("getRanksByType:{},result:{}", type, resultString);
//                return resultString;
//            }
//        } catch (Exception e) {
//            LOGGER.error("查询事业部榜单缓存失败!", e);
//        }
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        CmUserListRequest listRequest = new CmUserListRequest();
        listRequest.setSearchParams(params);
        CmUserListResponse response = new CmUserListResponse();
        if (type.equals("1") || type.equals("2")) {
            response = cmUser.selectRanksByDivision(listRequest);
        } else if (type.equals("3") || type.equals("4")) {
            response = cmUser.selectRanksByInvite(listRequest);
        }

        for (CmUserEntity user : response.getObjectList()) {
            JSONObject rank = new JSONObject();
            switch (type) {
                case "1":
                case "2":
                    rank.put("id", user.getDivisionId());
                    rank.put("name", user.getDivisionName());
                    rank.put("inviteCount", user.getInviteCount());
                    break;
                case "3":
                case "4":
                    rank.put("id", user.getId());
                    rank.put("name", user.getRealName());
                    rank.put("divisionName", user.getDivisionName());
                    rank.put("inviteCount", user.getInviteCount());
                    break;
                default:
                    break;
            }
            ranks.add(rank);
        }
        if (type.equals("1") || type.equals("2")) {
            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("EQ_dicKey", "business_division");
            CmDictionaryListRequest dictionaryListRequest = new CmDictionaryListRequest();
            dictionaryListRequest.setSearchParams(searchParams);
            dictionaryListRequest.setOrderColumn("id");
            dictionaryListRequest.setOrderMode("asc");
            CmDictionaryListResponse dictionaryListResponse = dictionary.getCmDictionaryList(dictionaryListRequest);
            List<CmDictionaryEntity> dictionaryEntityList = dictionaryListResponse.getObjectList();

            Set<String> notShowDivisionIds = new HashSet<>();
            for (CmDictionaryEntity dictionary : dictionaryEntityList) {
                notShowDivisionIds.add(dictionary.getId().toString());
            }

            Set<String> showDivisionIds = new HashSet<>();
            for (int i = 0; i < ranks.size(); i++) {
                showDivisionIds.add(ranks.getJSONObject(i).getString("id"));
            }

            Iterator<String> it = notShowDivisionIds.iterator();
            while (it.hasNext()) {
                String divisionId = it.next();
                if (showDivisionIds.contains(divisionId)) {
                    it.remove();
                }
            }


            for (CmDictionaryEntity dictionary : dictionaryEntityList) {
                if (notShowDivisionIds.contains(dictionary.getId().toString())) {
                    JSONObject rank = new JSONObject();
                    rank.put("id", dictionary.getId());
                    rank.put("name", dictionary.getDicValue());
                    rank.put("inviteCount", "-");
                    ranks.add(rank);
                }
            }
        }

        resultString = ranks.toString();
        if (type.equals("1") || type.equals("2")) {
            //计算当天剩余缓存时间
            timeToSeconds = 86400 - DateUtils.getFragmentInSeconds(Calendar.getInstance(), Calendar.DATE);
            //置入缓存
            redisUtils.setValueExpireNew(serviceCacheKey, resultString, timeToSeconds);
        }
        LOGGER.info("getRanksByType.setToCache:{},result:{}", type, resultString);
        return resultString;
    }

    /**
     * 去修改CmUser
     *
     * @return 结果视图
     */
    @RequestMapping(value = "inquiry", method = RequestMethod.GET)
    public String updateForm(HttpServletRequest request, Model model) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals("user") && StringUtils.isNotBlank(cookie.getValue())) {
                    return "redirect:/ranks/expand";
                }
            }
        }

        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("EQ_dicKey", "business_division");
        CmDictionaryListRequest dictionaryListRequest = new CmDictionaryListRequest();
        dictionaryListRequest.setSearchParams(searchParams);
        dictionaryListRequest.setOrderColumn("id");
        dictionaryListRequest.setOrderMode("asc");
        CmDictionaryListResponse dictionaryListResponse = dictionary.getCmDictionaryList(dictionaryListRequest);
        List<CmDictionaryEntity> dictionaryEntityList = dictionaryListResponse.getObjectList();
        model.addAttribute("dictionaries", dictionaryEntityList);

        return getAutoUrl("inquiry");
    }

    /**
     * 修改CmUser
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/bindUserToDivision", method = {RequestMethod.POST}, produces = "application/json;charset=utf-8")
    @ResponseBody
    public CmUserResponse bindUserToDivision(HttpServletResponse response, String phone, String captcha,
                                             Integer divisionId, String divisionName, String userName) {
        CmUserResponse updateResponse = new CmUserResponse();

        if(StringUtils.isBlank(userName)){
            updateResponse.setResultCode("-10004");
            updateResponse.setResultMessage("姓名不能为空");
            return updateResponse;
        }

        String key = "sendCaptcha.invite:" + phone;
        // 根据手机获取用户
        String captchaInCache = redisUtils.getValByKeyNew(key);
        if (!captchaInCache.equals(captcha)) {
            updateResponse.setResultCode("-10004");
            updateResponse.setResultMessage("验证码错误，请重新输入");
            return updateResponse;
        }
        //清除手机验证码缓存
        redisUtils.deleteKey(key);

        CmUserResponse userResponse = cmUser.getUserByPhone(phone);
        CmUserEntity user = userResponse.getEntity();
        if (user == null) {
            updateResponse.setResultCode("-10003");
            updateResponse.setResultMessage("该手机号的用户不存在");
            return updateResponse;
        }

        //绑定用户至事业部
        user.setDivisionId(divisionId);
        user.setDivisionName(divisionName);
        user.setRealName(userName);

        CmUserRequest userRequest = new CmUserRequest();
        userRequest.setEntity(user);
        updateResponse = cmUser.updateCmUser(userRequest);

        if (updateResponse.getResultCode().equals(ReturnResult.SUCCESS.getResultCode())) {
            Cookie phoneCookie = new Cookie("user", JSONObject.fromObject(user).toString());
            phoneCookie.setPath("/");
            phoneCookie.setMaxAge(DateTimeUtils.TEN_YEAR_SECONDS);
            response.addCookie(phoneCookie);
        }
        return updateResponse;
    }

    /**
     * 去查看CmUser
     *
     * @param id CmUser页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "expand", method = {RequestMethod.GET})
    public String expand(HttpServletRequest request, HttpServletResponse response, Model model) {
        CmUserEntity user = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user") && StringUtils.isNotBlank(cookie.getValue())) {
                    user = (CmUserEntity) JSONObject.toBean(JSONObject.fromObject(cookie.getValue()), CmUserEntity.class);
                }
            }
        }

        if (user == null) {
            return "redirect:/ranks/inquiry";
        }
        CmUserResponse userInfo = cmUser.getCmUserById(user.getId());

        CmUserResponse userInviteNow = getExpandInfo("5", user.getId());
        CmUserResponse userInviteHistory = getExpandInfo("6", user.getId());

        model.addAttribute("user", userInfo.getEntity());
        model.addAttribute("userInviteNow", userInviteNow.getEntity().getInviteCount());
        model.addAttribute("userInviteHistory", userInviteHistory.getEntity().getInviteCount());

//        Cookie phoneCookie = new Cookie("user", JSONObject.fromObject(user).toString());
//        phoneCookie.setPath("/");
//        phoneCookie.setMaxAge(DateTimeUtils.TEN_YEAR_SECONDS);
//        response.addCookie(phoneCookie);

        return getAutoUrl("expand");
    }

    @RequestMapping(value = "sendCaptcha", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ResponseBody
    public CmUserResponse sendCaptcha(String phone) {
        //短信验证码置入缓存
        RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");

        CmUserResponse updateResponse = new CmUserResponse();
        if (StringUtils.isBlank(phone)) {
            updateResponse.setResultCode("-10003");
            updateResponse.setResultMessage("手机号为空！");
            return updateResponse;
        }
        CmUserResponse userResponse = cmUser.getUserByPhone(phone);
        CmUserEntity user = userResponse.getEntity();
        if (user == null) {
            updateResponse.setResultCode("-10003");
            updateResponse.setResultMessage("该手机号的用户不存在");
            return updateResponse;
        }

        //短信验证码缓存key
        String key = "sendCaptcha.invite:" + phone;
        String keyWaitTime = "sendCaptcha.invite.wait:" + phone;
        if (StringUtils.isNotBlank(redisUtils.getValByKeyNew(keyWaitTime)) && !redisUtils.getValByKeyNew(keyWaitTime).equals("null")) {
            updateResponse.setResultCode("-10003");
            updateResponse.setResultMessage("您的操作太快了，请稍候！");
            return updateResponse;
        }

        CmSmsCodeEntity smsCodeEntity = new CmSmsCodeEntity();
        smsCodeEntity.setCity("nj");
        smsCodeEntity.setPhone(phone);
        CmSmsCodeRequest smsCodeRequest = new CmSmsCodeRequest();
        smsCodeRequest.setEntity(smsCodeEntity);
        //请求短信验证码
        CmSmsCodeResponse smsCodeResponse = smsCode.sendSms(smsCodeRequest);
        String authCode = smsCodeResponse.getEntity().getAuthCode();

        updateResponse.setResultCode(smsCodeResponse.getResultCode());

        redisUtils.setValueExpireNew(key, authCode, 60 * 5);
        //验证码获取等待60秒
        redisUtils.setValueExpireNew(keyWaitTime, authCode, 60);
        return updateResponse;
    }

    /**
     * 登出接口 清除登录cookie
     *
     * @param response
     * @return
     */
    @RequestMapping(value = "logout", method = {RequestMethod.GET})
    public String logout(HttpServletResponse response) {
        Cookie phoneCookie = new Cookie("user", null);
        phoneCookie.setPath("/");
        phoneCookie.setMaxAge(0);
        response.addCookie(phoneCookie);
        return "redirect:/ranks/inquiry";
    }

    private CmUserResponse getExpandInfo(String type, Integer userId) {
        Map<String, Object> params = new HashMap<>();
        params.put("type", type);
        params.put("userId", userId);
        CmUserListRequest listRequest = new CmUserListRequest();
        listRequest.setSearchParams(params);
        return cmUser.getRankByInvite(listRequest);
    }
}
