package com.controller;

import com.config.BaseController;
import com.config.ControllerInterface;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.model.User;
import com.service.UserService;
import com.tools.JwtUtils;
import com.utils.CommonUtils;
import com.validator.UserValidator;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;

@ControllerInterface(path="/user")
public class UserController extends BaseController {
    UserService service = UserService.me;

    public void index() {
        render("/view/userrole/user.html");
    }

    public void password(){
        render("/view/userrole/password.html");
    }


    public void list(){
        User bean = getBean(User.class,"bean");
        int pageNumber=  this.getParaToInt("pageNumber");


        User user= getSessionAttr("userInfo");
        int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        bean.setOrgid(user.getOrgid());

        success(service.paginate(pageNumber,this.getParaToInt("pageSize"),bean));
    }


    public void getById(){
        int id =this.getParaToInt("bean.id", 0);
        if(id == 0){
            fail();
        }
        success(service.findById(id));
    }


    //增加或修改
    @Before(UserValidator.class)
    public void addOrUpdate(){
        try {
            User user= getSessionAttr("userInfo");
            int operatorid = JwtUtils.validateJWTForUserId(user.get("token").toString());
            if(operatorid == 0){
                fail(3,"token错误");
                return;
            }

            User bean = getBean(User.class,"bean");
            if(bean.getId() ==null) {
//                if (null !=service.verifyLoginCode(bean.getCode(),user.getOrgid())){
//                    throw new Exception("已经存在当前工号的用户");
//                }
                if (null !=service.verifyLoginName(bean.getLoginname(),user.getOrgid())){
                    throw new Exception("已经存在当前登录名的用户");
                }
                if(CommonUtils.isNullOrEmpty(bean.getPassword())) {
                    bean.setPassword(PropKit.get("initPassword"));
                }
            } else {
                bean.remove("password");
            }
            bean.setOrgid(user.getOrgid());
            service.addOrUpdate(bean,operatorid);
            success();
        }catch(Exception e){
            e.printStackTrace();
            fail(0,e.getMessage());
        }
    }
    //删除
    public void delete(){
        try{
            int id =this.getParaToInt("id");
            User user =service.findById(id);
            if (user.getIsadmin().equals(1)){
                throw new Exception("超级管理员不能删除！");
            }
            service.deleteById(user.getId());
            success();
        }catch (Exception e){
            fail(0,e.getMessage());
        }

    }
    //下拉选
    public void selectType(){
        Map map = service.selectType();
        success(map);
    }

    /**
     * 用户自己修改密码
     */
    public void repasswd(){
        String password = this.getPara("password");
        String oldPassword = this.getPara("oldPassword");
        String token = this.getCookie("token");
        int userid = 0;
        if(StringUtils.isEmpty(token)){
            token = this.getPara("token");
            userid = JwtUtils.validateJWTForUserId(token);
        }
        if(userid == 0){
            fail_token();
            return;
        }
        oldPassword = CommonUtils.getMD5String(CommonUtils.getMD5String(oldPassword));
        User bean = service.findById(userid);
        if(!oldPassword.equals(bean.get("password"))){
            fail(1, "当前密码错误");return;
        }
        if(StringUtils.isEmpty(password)){
            fail(2,"新密码不能为空");return;
        }
        String reg= "(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z].{7,15}";
        if(!password.matches(reg)){
            fail(2,"您的密码复杂度太低（必须包含字母、数字且长度为8-15位）");return;
        }
        bean.setPassword(CommonUtils.getMD5String(CommonUtils.getMD5String(password)));
        bean.update();
        success();
    }

    public void resetpassword(){
        String token = this.getPara("token");
        int operatorid = JwtUtils.validateJWTForUserId(token);
        if(operatorid == 0){
            fail(3,"token错误");
            return;
        }
        //select ifnull(LOCATE((select orgid from t_user where id =3093 ),parentcodes),0) checkFlag from t_org o inner join t_user u on u.orgid = o.id where u.id = 318
        User bean=service.findById(getParaToInt("userid"));

        User currentUser=service.findById(operatorid);
        if(currentUser.getOrgid().intValue() != bean.getOrgid().intValue()) { // 如果被重置密码的部门跟当前登录人的部门不一样 则不允许重置密码
            fail(5,"没有权限重置密码");
            return;
        } else {
            bean.setPassword(CommonUtils.getMD5String(CommonUtils.getMD5String(PropKit.get("initPassword"))));
            bean.update();
            success(PropKit.get("initPassword"));
        }
    }

}
