package com.ruoyi.web.controller.system;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.cc.domain.CcExtNum;
import com.ruoyi.cc.domain.CcGateways;
import com.ruoyi.cc.service.ICcExtNumService;
import com.ruoyi.cc.service.ICcGatewaysService;
import com.ruoyi.common.utils.CacheUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.web.filter.embed.EmbedRequestUtils;
import com.ruoyi.framework.web.service.ConfigService;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Controller
public class SysLoginController extends BaseController
{
    /**
     * 是否开启记住我功能
     */
    @Value("${shiro.rememberMe.enabled: false}")
    private boolean rememberMe;

    /**
     * 系统包版本
     */
    @Value("${sysconfig.sysVersion}")
    private String sysVersion;

    /**
     * 是否开启登陆时选择业务组
     */
    @Value("${sysconfig.show-dynamic-groupid: false}")
    private boolean showDynamicGroupid;

    @Autowired
    private ConfigService configService;
    @Autowired
    private ICcExtNumService ccExtNumService;
    @Autowired
    private ICcGatewaysService ccGatewaysService;

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, ModelMap mmap)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        // 是否开启记住我
        mmap.put("isRemembered", rememberMe);
        // 是否开启用户注册
        mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
        // 版本号
        mmap.put("sysVersion", sysVersion);
        // 是否开启登陆时选择业务组
        mmap.put("showDynamicGroupid", showDynamicGroupid);
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, String extNum, String groupId, String myGateway, Boolean rememberMe)
    {
        boolean embed = EmbedRequestUtils.isEmbed(ServletUtils.getRequest());
        // 校验分机号（HIS iframe 嵌入必须绑定分机；禁止登录成功后再被 main 踢回登录）
        CcExtNum ccExtNum = ccExtNumService.selectCcExtNumByUserCodeTwo(username);
        if (null == ccExtNum) {
            if (!embed && StringUtils.isNotEmpty(username) && username.startsWith("Runtian_")) {
                // 非嵌入：保留润天账号兼容
            } else {
                return AjaxResult.error("未绑定分机号，请联系系统管理员！");
            }
        } else {
            if (!ccExtNum.getExtNum().toString().equals(extNum)) {
                return AjaxResult.error("username="+username+"的分机号不正确！线上:"+ccExtNum.getExtNum()+",传入的分机号:" + extNum);
            }
        }
        CacheUtils.put("groupId-" + username, groupId);
        // cache myGateway for workbench dialing; only purposes 1/3 allowed
        if (StringUtils.isNotEmpty(myGateway)) {
            List<Long> gatewayIds = Arrays.stream(myGateway.split(","))
                    .filter(StringUtils::isNotBlank)
                    .map(String::trim)
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            CcGateways query = new CcGateways();
            query.setGatewayIds(gatewayIds);
            Map<String, Object> params = new HashMap<>();
            params.put("purposes", Arrays.asList(1, 3));
            query.setParams(params);
            List<CcGateways> allowed = ccGatewaysService.selectCcGatewaysList(query);
            if (allowed == null || allowed.isEmpty() || allowed.size() != gatewayIds.size()) {
                return AjaxResult.error("指定网关无效，仅可选择电话条/不限制用途的网关");
            }
            CacheUtils.put("myGateway-" + username, myGateway);
        } else {
            CacheUtils.remove("myGateway-" + username);
        }
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "error/unauth";
    }
}
