package com.imdroid.beidou.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imdroid.beidou.common.HttpResult;
import com.imdroid.beidou.entity.Tenant;
import com.imdroid.beidou.entity.TenantMapper;
import com.imdroid.beidou.entity.User;
import com.imdroid.beidou.entity.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController extends BasicController {
    @Value("${default_pwd}")
    private String default_pwd;
    @Autowired
    UserMapper userMapper;
    @Autowired
    TenantMapper tenantMapper;
    /**** 推送页面  *****/
    @RequestMapping("/sys/user/pwd")
    public String userPwd() {
        return "/page/user_pwd";
    }

    @RequestMapping("/sys/user")
    public String listUser(Model m, HttpSession session) {
        initModel(m, session);
        return "/page/user_cfg";
    }

    @RequestMapping("/sys/user/add")
    public String addUser(Model m, HttpSession session){
        initModel(m, session);

        List<Tenant> tenants = tenantMapper.selectList(null);
        m.addAttribute("tenant_list", tenants);

        return "/page/table/user_add";
    }

    @RequestMapping("/sys/user/edit")
    public String editUser(Model m, HttpSession session){
        initModel(m, session);
        List<Tenant> tenants = tenantMapper.selectList(null);
        m.addAttribute("tenant_list", tenants);
        return "/page/table/user_add";
    }

    /**** 推送数据  *****/
    @RequestMapping("/sys/user/list")
    @ResponseBody
    public JSONObject list(HttpSession session, int page, int limit, String searchParams) {
        Page<User> pageable = new Page<>(page, limit);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        IPage<User> cs = userMapper.selectPage(pageable, queryWrapper);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", cs.getTotal());
        jsonObject.put("data", cs.getRecords());
        return jsonObject;
    }

    @PostMapping("/sys/user/update")
    @ResponseBody
    public String update(HttpSession session, @RequestBody JSONObject object) throws Exception {
        // 从请求参数中创建对象
        User userNew = JSONObject.toJavaObject(object,User.class);
        QueryWrapper<Tenant> tenantQueryWrapper = new QueryWrapper<>();
        tenantQueryWrapper.eq("name", userNew.getTenantname());
        Tenant tenant = tenantMapper.selectOne(tenantQueryWrapper);
        if(tenant==null) return HttpResult.result(2, "invalid tenant");
        userNew.setTenantid(tenant.getId());

        // 检测该对象是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", userNew.getName());
        queryWrapper.eq("tenantname",userNew.getTenantname());
        queryWrapper.last("limit 1");
        User userOld = userMapper.selectOne(queryWrapper);
        //新增或更新
        int num = 0;
        if(null != userOld) {
            userNew.setId(userOld.getId());
            num = userMapper.updateById(userNew);
        }
        else{
            userNew.setPwd(new BCryptPasswordEncoder().encode(default_pwd));
            num = userMapper.insert(userNew); //id自增
        }
        if (num == 0) {
            return HttpResult.failed();
        } else {
            return HttpResult.ok();
        }
    }

    @PostMapping("/sys/user/delete")
    @ResponseBody
    public String delete(@RequestParam String name) throws Exception {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        int num = userMapper.delete(wrapper);
        if (num == 0) {
            return HttpResult.failed();
        } else return HttpResult.ok();
    }

    /**** 推送数据  *****/
    @PostMapping("/personal/update_pwd")
    @ResponseBody
    public String updatePwd(HttpSession session, @RequestBody JSONObject object) throws Exception {
        String result = "修改成功";
        boolean flag = false;
        String name = (String) session.getAttribute("login_user");
        User user = userMapper.queryByName(name);
        if (user != null) {
            String old_pwd = object.getString("old_pwd");
            String new_pwd = object.getString("new_pwd");
            String re_pwd = object.getString("re_pwd");
            BCryptPasswordEncoder pwdEncoder = new BCryptPasswordEncoder();
            if (!pwdEncoder.matches(old_pwd, user.getPwd())) {
                result = "原密码错误";
            } else if (!new_pwd.equals(re_pwd)) {
                result = "新密码输入不一致";
            }
            else if(IsSimplePassword(new_pwd)){
                result = "密码过于简单，必须是数字和字母的组合";
            }
            else{
                flag = true;
                user.setPwd(pwdEncoder.encode(new_pwd));
                user.setInit_pwd(false);
                userMapper.updateById(user);

            }
        }
        return HttpResult.result(flag?HttpResult.HTTP_RSP_OK:HttpResult.HTTP_RSP_FAILED,result);
    }

    boolean IsSimplePassword(String pwd){
        if(pwd.length()<8) return true;

        boolean hasNum = false;
        boolean hasNotNum = false;
        for(int i=0; i<pwd.length(); i++){
            char ch = pwd.charAt(i);
            if(ch >='0' && ch <='9') hasNum = true;
            else hasNotNum = true;
        }
        return !(hasNum && hasNotNum);
    }
}
