package com.kiisoo.ic.login.controller;

import com.kiisoo.ic.common.BaseController;
import com.kiisoo.ic.login.bean.LoginBean;
import com.kiisoo.ic.login.enums.LoginEnum;
import com.kiisoo.ic.login.service.LoginService;
import com.kiisoo.ic.utils.PasswordEncry;
import com.kiisoo.ic.wx.service.QWMailListManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

import static com.kiisoo.ic.constants.Constants.ERROR_ACCOUNT_NOT_BIND;
import static com.kiisoo.ic.constants.Constants.ERROR_SYSTEM;

/**
 * @Description: 用户登入
 * @Author: wangyinjia
 * @Date: 2020/2/18
 * @Company: kiisoo
 * @Version: 1.0
 */
@Controller
@Slf4j
public class LoginController extends BaseController {

    /**
     * 登录 service
     */
    private final LoginService loginService;

    @Autowired
    public LoginController(LoginService loginService) {
        this.loginService = loginService;
    }

    /**
     * 登录账号
     * @param login 用户名
     * @param password 密码
     * @return 成功/失败
     */
    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> loginAccount(@RequestParam(value = "login")String login,
                                            @RequestParam(value = "password")String password,
                                            @RequestParam(value = "isMD5",required = false,defaultValue = "false")Boolean isMD5){
        try{
            Map<String, Object> resultMap = new HashMap<>();
            LoginBean loginBean = loginService.login(login, password,isMD5);
            resultMap.put("code", loginBean.getLoginInfo().get("code"));
            resultMap.put("results", loginBean);
            resultMap.put("success", Boolean.TRUE);
            return resultMap;
        }catch (Exception e){
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 小程序登录账号
     * @param loginParams 登录参数
     * @return 成功/失败
     */
    @RequestMapping(value = "/mini/login",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> miniLoginAccount(@RequestBody LoginBean loginParams){
        try{
            Map<String, Object> resultMap = new HashMap<>();
            LoginBean loginBean = loginService.miniLogin(loginParams.getLogin(), loginParams.getPassword(),false);
            resultMap.put("code", loginBean.getLoginInfo().get("code"));
            resultMap.put("results", loginBean);
            resultMap.put("success", Boolean.TRUE);
            return resultMap;
        }catch (Exception e){
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 解码获得手机号码后，根据手机号码关联账号
     * @param encrypdata
     * @param ivdata
     * @param sessionkey
     * @return 返回成功用户信息
     */
    @RequestMapping(value = "/mobile/login",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> mobileLoginAccount(@RequestParam("encrypdata") String encrypdata, @RequestParam("ivdata") String ivdata, @RequestParam("sessionkey")String sessionkey){
        try{
            Map<String, Object> resultMap = new HashMap<>();

            String mobile = PasswordEncry.encode(encrypdata, ivdata, sessionkey);
            if(StringUtils.isNotBlank(mobile)){
                LoginBean loginBean = loginService.mobileLogin(mobile);
                resultMap.put("code", loginBean.getLoginInfo().get("code"));
                resultMap.put("results", loginBean);
                resultMap.put("success", Boolean.TRUE);
            }else{
                // 手机号码解析失败，请重新授权
                resultMap.put("code", "0010");
                resultMap.put("success", Boolean.FALSE);
            }

            return resultMap;
        }catch (Exception e){
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 根据cpUserId关联账号
     * @param cpUserId
     * @return 返回成功用户信息
     */
    @RequestMapping(value = "/cpuser/login",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> cpuserLoginAccount(@RequestParam("cpUserId") String cpUserId){
        try{
            Map<String, Object> resultMap = new HashMap<>();

            if(StringUtils.isNotBlank(cpUserId)){
                LoginBean loginBean = loginService.cpUserIdLogin(cpUserId);
                resultMap.put("code", loginBean.getLoginInfo().get("code"));
                resultMap.put("results", loginBean);
                resultMap.put("success", Boolean.TRUE);
            }else{
                //企业微信账号为空
                resultMap.put("code", "0010");
                resultMap.put("success", Boolean.FALSE);
            }

            return resultMap;
        }catch (Exception e){
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 登录账号
     * @param code
     * @return 成功/失败
     */
    @RequestMapping(value = "/qy/mini/login",method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> qyMiniAutoLogin(@RequestParam(value = "code")String code){
        try{
            Map<String, String> accountInfo = loginService.qyMiniAutoLogin(code);
            LoginBean loginBean = null;
            if (accountInfo!=null){
                if (StringUtils.isNotBlank(accountInfo.get("login")) && StringUtils.isNotBlank(accountInfo.get("password"))){
                    loginBean = loginService.miniLogin(accountInfo.get("login"), accountInfo.get("password"), true);
                    if (accountInfo.get("cpUserId").equals(loginBean.getCpUserId())){
                        loginBean.getLoginInfo().put("code",LoginEnum.LOGIN_SUCCEED.getCode());
                    }
                    loginBean.setSessionKey(accountInfo.get("sessionKey"));
                }else{
                    if (StringUtils.isNotBlank(accountInfo.get("cpUserId"))){
                        String cpUserId = accountInfo.get("cpUserId");
                        loginBean = new LoginBean(ERROR_ACCOUNT_NOT_BIND);
                        loginBean.setLogin(cpUserId);
                        loginBean.setSessionKey(accountInfo.get("sessionKey"));
                    }
                }
            }else{
                loginBean = new LoginBean(ERROR_SYSTEM);
            }
            return data(loginBean);
        }catch (Exception e){
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 登录账号
     * @param loginParams 登录参数
     * @return 成功/失败
     */
    @RequestMapping(value = "/login/bind",method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> loginAccountBind(@RequestBody LoginBean loginParams){
        try{
            Map<String, Object> resultMap = new HashMap<>();
            LoginBean loginBean = loginService.miniLogin(loginParams.getLogin(), loginParams.getPassword(),false);
            resultMap.put("code", loginBean.getLoginInfo().get("code"));
            if (LoginEnum.LOGIN_SUCCEED.getCode().equals(loginBean.getLoginInfo().get("code"))){
                loginService.bindQywxUserIdByUserId(loginBean.getUserId(),loginParams.getCpUserId());
            }
            resultMap.put("results", loginBean);
            resultMap.put("success", Boolean.TRUE);
            return resultMap;
        }catch (Exception e){
            log.error("登录失败", e);
            return fail();
        }
    }

    /**
     * 登出
     * @param session 用户会话
     * @return string
     */
    @RequestMapping("/logout")
    public String logOut(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
}
