package com.controller;

import com.config.AuthInterceptor;
import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Clear;
import com.jfinal.captcha.CaptchaRender;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.model.Org;
import com.model.User;
import com.service.OrgService;
import com.service.UserService;
import com.tools.JwtUtils;
import com.utils.CommonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Clear(AuthInterceptor.class)
@ControllerInterface(path="/auth")
public class LoginController extends BaseController {
    static Logger logger = Logger.getLogger(LoginController.class);

    public static final Map<String, Object> userLoginErrorInfoMap = new HashMap<>();
    UserService service = UserService.me;
    OrgService orgService = OrgService.me;
    Org orgDao = new Org().dao();
    public void index() {
        render("/view/index/index.html");
    }



    public void login(){

        String username = this.getPara("loginname");
        String password = this.getPara("password");
        String imgcode = this.getPara("imgcode");
        String type = this.getPara("type");
        if(CommonUtils.isNullOrEmpty(type)){
            success(1,"请求错误！");
            return;
        }
        if(!CaptchaRender.validate(this,imgcode)) {
            success(1,"图形验证码错误！");
            return;
        }
        if(CommonUtils.isNotNullOrNotEmpty(userLoginErrorInfoMap.get(username))){
            Record record = (Record)userLoginErrorInfoMap.get(username);
            int num = record.getInt("number");
            long time = System.currentTimeMillis() - record.getLong("datetime");
            if(time >= 5* 60 * 1000){
                userLoginErrorInfoMap.remove(username);
            }
            /*if(num >= 5 && time < 5* 60 * 1000){
                success(1,"账号已被锁定，请五分钟后再试！");
                return;
            }*/
        }
        password = CommonUtils.getMD5String(CommonUtils.getMD5String(password));
        User user = service.findByNamePassword(username,password,type);
        //用于黔南州单点登录时绑定用户的ssocode
        if(null == user && CommonUtils.isNotNullOrNotEmpty(getPara("personId"))){
            if(type.equals("school")) {
                type = "teach";
            } else {
                type = "school";
            }
            user = service.findByNamePassword(username,password,type);
        }
        if(user == null) {
            int num = 1;
            if(CommonUtils.isNullOrEmpty(userLoginErrorInfoMap.get(username))){
                Record record = new Record();
                record.set("datetime",System.currentTimeMillis());
                record.set("number",num);
                userLoginErrorInfoMap.put(username,record);
            } else {
                Record record = (Record)userLoginErrorInfoMap.get(username);
                num = record.getInt("number");
                num ++;
                record.set("datetime",System.currentTimeMillis());
                record.set("number",num);
                userLoginErrorInfoMap.put(username,record);
            }
            if(num == 1){
                success(1,"用户名密码错误！");
            } else if(num == 5) {
                success(1,"账号已被锁定五分钟！");
            } else {
                success(1,"用户名密码连续错误"+num+"次！连续错误五次账号将锁定五分钟！");
            }
            return;
        } else if(user.getStatus() == 0){
            success(1,"该用户已注销！");
            return;
        } else if(user.getStatus() == 2){
            success(1,"该用户已停用！");
            return;
        } else if (user.getInt("orgstatus") == 2){
            success(1,"该用户审核不通过！");
            return;
        } else if (user.getInt("orgstatus") == 0){
            success(1,"该用户未审核！");
            return;
        } else if (user.getInt("isclose") == 1){
            success(1,"该机构！");
            return;
        }
        userLoginErrorInfoMap.remove(username);
        if(user.get("rffectivetime") != null) {
            Calendar today = Calendar.getInstance();
            Calendar last = Calendar.getInstance();

            last.setTime(user.getDate("rffectivetime"));
            if (today.after(last)) {

                fail(100,"您的服务已过期，请联系客服:073185157311");
                return;
            }
        }

        //用于黔南州单点登录时绑定用户的ssocode
        if(CommonUtils.isNotNullOrNotEmpty(getPara("personId"))){
            Db.update("update t_user set ssocode = ? where id = ?",getPara("personId"),user.getId());
        }
        user.setPassword(null);
        //登录成功，生成jwt的token
        Map info = new HashMap();
        info.put("orgid",user.getOrgid());
        info.put("orgname",user.get("orgname"));
        info.put("userid",user.get("id"));
        info.put("facedevicetype", user.get("facedevicetype"));

        String token = JwtUtils.createJWT(user.getId()+"",info,1000*60*500);
        user.remove("password").put("token",token);
        user.put("view_path",VIEW_PATH);
        String schoolids = orgService.getSchoolForSql(user.getId());
        this.setSessionAttr("schoolids", schoolids);
        this.setSessionAttr("userInfo",user);
        user.setAddress(PropKit.get("channelType"));
         //加载当前机构下面的学校

        //判断是否要到期提醒
        Org org = orgDao.findById(user.getOrgid());

        String msg = "";
        Date lastdate = user.get("rffectivetime") != null ? user.getDate("rffectivetime"): null;
        if(lastdate != null){
            Calendar today = Calendar.getInstance();
            Calendar last = Calendar.getInstance();
            last.setTime(lastdate);
            last.add(Calendar.DATE, -30);
            if(today.after(last)){
                msg+="您的系统服务将于"+format1.format(lastdate)+"到期，请及时联系客服续费！";
            }
        }
        user.put("warn", msg);
        user.put("banben", PropKit.get("banben"));

        success(user);
        User userbak = user;

    }

    public void orgLogo(){

        try {
            Integer orgid = this.getParaToInt("orgid");
            success(orgService.orgLogo(orgid));
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    public void logout(){
        removeSessionAttr("schoolids");
        removeSessionAttr("userInfo");
        //System.out.println(this.getRequest().getRequestURL()+"/"+ PropKit.get("login_page_url"));
        //redirect(this.getRequest().getRequestURL()+"/"+ PropKit.get("login_page_url"));
        URL url = null;
        try {
            url = new URL(getRequest().getRequestURL().toString());
            String path =url.getProtocol()+"://"+url.getHost()+":"+url.getPort()+PropKit.get("login_page_url");
            redirect(path);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }

    /**
     * 图形验证码生成
     */
    public void validateImg(){
        CaptchaRender captcha = new CaptchaRender();
        render(captcha);
    }

    public void welangduSignIn(){
        String custCode = getPara("custCode");
        String readerCode = getPara("readerCode");
        if(CommonUtils.isNullOrEmpty(custCode)) {
            fail(1,"字段custCode不能为空");
            return;
        }
        if(CommonUtils.isNullOrEmpty(readerCode)) {
            fail(1,"字段readerCode不能为空");
            return;
        }
        Record record = Db.findFirst("select r.realname,sex,d.deptname from t_reader r left join t_reading_info ri on r.orgid = ri.orgid left join t_org_dept d on r.orgdeptid = d.id where ri.custCode = ? and r.cardnumber = ?",custCode,readerCode);
        if(CommonUtils.isNullOrEmpty(record)) {
            success(0,"未获取到读者信息");
        } else {
            success(record);
        }
    }

    public void getMessageVersion(){
        if(CommonUtils.isNullOrEmpty(PropKit.get("messageversion"))){
            success(0);
        } else {
            success(PropKit.get("messageversion"));
        }
    }
}
