package cn.pluss.platform.controller.userInfo;

import cn.pluss.platform.annotation.OpLog;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.controller.BaseNoModelController;
import cn.pluss.platform.entity.RoleInfo;
import cn.pluss.platform.entity.RoleUserInfo;
import cn.pluss.platform.entity.UserInfo;
import cn.pluss.platform.roleInfo.RoleInfoService;
import cn.pluss.platform.roleUserInfo.RoleUserInfoService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Controller
@RequiredArgsConstructor
@RequestMapping("userInfo")
public class UserInfoController extends BaseNoModelController {

    private Integer PAGE_SIZE = 12;

    private final RoleInfoService roleInfoService;
    private final RoleUserInfoService roleUserInfoService;

    @Autowired
    private UserInfoService userInfoNewService;

    /**
     * 引导页
     *
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index() {

        return "auth/userInfo/userInfoList";
    }

    /**
     * 分页查询
     */
    @RequestMapping(value = "/queryUserInfoByPage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> queryUserInfoByPage(@RequestParam(defaultValue = "1") Integer currPage, UserInfo userInfo) {
        Map<String, Object> map = new HashMap<String, Object>(16);
        Map<String, Object> result = new HashMap<String, Object>(16);
        map.put("pageSize", PAGE_SIZE);
        map.put("offset", (currPage - 1) * PAGE_SIZE);
        if (StringUtil.isNotEmpty(userInfo.getLoginName())) {
            map.put("loginName", userInfo.getLoginName());
        }
        List<UserInfo> userInfoList = uiService.queryUserInfoPage(map);
        Integer count = uiService.queryUserInfoPageCount(map);
        result.put("userInfoList", userInfoList);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
        return result;
    }

    /**
     * 编辑导航
     *
     * @return
     */

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Long id) {
        System.out.println("========================");
        if (id != null && id != 0) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo = uiService.queryUserInfo(userInfo);
            request.setAttribute("userInfo", userInfo);
        }
        return "auth/user/editUser";
    }

    /**
     * 详情
     *
     * @return
     */

    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Long id) {
        if (id != null && id != 0) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo = uiService.queryUserInfo(userInfo);
            request.setAttribute("userInfo", userInfo);
        }
        return "auth/user/userDetail";
    }

    /**
     * 根据id查询user对象
     *
     * @throws IOException
     */

    @RequestMapping(value = "/findById", method = RequestMethod.POST)
    @ResponseBody
    public UserInfo findById(String id) throws IOException {

        UserInfo user = new UserInfo();
        user.setId(Long.valueOf(id));
        UserInfo userInfo = uiService.queryUserInfo(user);

        return userInfo;
    }

    /**
     * 获取可配置的角色
     *
     * @throws IOException
     */
    @RequestMapping(value = "/permitRoles", method = RequestMethod.POST)
    @ResponseBody
    public List<RoleInfo> permitRoles() throws IOException {
        List<RoleInfo> list = null;
        String userId = request.getHeader("userId");
        UserInfo userInfo = uiService.getById(userId);

        if (userInfo == null) {
            list = new ArrayList<>();
        } else {
            if (verifyUserRole()) {
                list = roleInfoService.queryRoleInfoList(null);
            } else {
                list = roleInfoService.getRolesByUser(userInfo);
            }
        }

        return list;
    }

    /**
     * 保存用户信息
     *
     * @throws IOException
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public UserInfo save(UserInfo user) throws IOException {

        String userId = request.getHeader("userId");
        UserInfo handler = uiService.getById(userId);

        // 设置修改时间
        user.setUpdateTime(new Date());
        user.setUpdator(handler.getId() + "");
        // 并不修改密码
        user.setPassword(null);
        if (user.getId() != null && user.getId() != 0) {
            uiService.updateById(user);
        } else {
            // 设置创建时间
            user.setCreator(handler.getId() + "");
            user.setCreateTime(new Date());
            // 初始密码 123456
            String password = "e10adc3949ba59abbe56e057f20f883e";
            user.setPassword(password);
            uiService.save(user);

            UserInfo userInfo = new UserInfo();
            userInfo.setLoginName(user.getLoginName());
            List<UserInfo> userList = uiService.queryUserInfoList(userInfo);
            user.setId(userList.get(0).getId());
        }
        // 保存用户角色信息
        // 删除之前保存的用户角色绑定关系
        RoleUserInfo roleUserInfo = new RoleUserInfo();
        roleUserInfo.setUserId(user.getId());
        roleUserInfoService.deleteRoleUserInfo(roleUserInfo);
        // 保存现有的角色绑定关系
        if (!StringUtil.isEmpty(user.getRoleIds())) {
            String roleIds = user.getRoleIds();
            roleIds = roleIds.substring(0, roleIds.length() - 1);
            String[] ids = roleIds.split(",");
            List<RoleUserInfo> roleUserInfoList = new ArrayList<>();
            RoleUserInfo ruf;
            for (String id : ids) {
                ruf = new RoleUserInfo();
                ruf.setUserId(user.getId());
                ruf.setRoleId(Long.valueOf(id));
                roleUserInfoList.add(ruf);
            }
            // 批量保存
            for (RoleUserInfo r : roleUserInfoList) {
                roleUserInfoService.saveRoleUserInfo(r);
            }

        }
// 		String json = JSON.toJSONString(user);
// 		this.sendMessages(json);
        return user;
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryUserInfoDetails", method = RequestMethod.GET)
    public String queryUserInfoDetails(HttpServletRequest request, Long id, Integer pageIndex) {

        if (id != null && id != 0) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo = uiService.queryUserInfo(userInfo);
            request.setAttribute("userInfo", userInfo);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "auth/userInfo/userInfoDetails";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryUserInfoBaseInfo", method = RequestMethod.GET)
    public String queryUserInfoBaseInfo(HttpServletRequest request, Long id, Integer pageIndex) {

        if (id != null && id != 0) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo = uiService.queryUserInfo(userInfo);
            request.setAttribute("userInfo", userInfo);
            request.setAttribute("pageIndex", pageIndex);
        }
        return "auth/userInfo/userInfoBaseInfo";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryUserInfoExtendsInfo", method = RequestMethod.GET)
    public String queryUserInfoExtendsInfo() {
        return "auth/userInfo/userInfoExtendsInfo";
    }

    /**
     * 查询详情
     */
    @RequestMapping(value = "/queryUserInfoFunctionsInfo", method = RequestMethod.GET)
    public String queryUserInfoFunctionsInfo() {
        return "auth/userInfo/userInfoFunctionsInfo";
    }

    /**
     * 保存对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/saveUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> saveUserInfo(UserInfo userInfo) {

        if (userInfo.getId() != null && userInfo.getId() != 0) {
            uiService.updateUserInfo(userInfo);
        } else {
            uiService.saveUserInfo(userInfo);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 修改对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> updateUserInfo(Long id) {

        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        uiService.updateUserInfo(userInfo);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    /**
     * 删除对象
     *
     * @throws IOException
     */
    @RequestMapping(value = "/deleteUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteUserInfo(Long id) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        uiService.deleteUserInfo(userInfo);
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "1");
        result.put("resultMessage", "保存成功!");
        return result;
    }

    @RequestMapping(value = "/findRolesByUser", method = RequestMethod.POST)
    @ResponseBody
    public List<RoleUserInfo> findRolesByUser(Long userId) {
        RoleUserInfo roleUserInfo = new RoleUserInfo();
        roleUserInfo.setUserId(userId);
        return roleUserInfoService.queryRoleUserInfoList(roleUserInfo);
    }

    @OpLog(opCode = "APP_FACE_CERT", opDetail = "APP人脸识别通过", opName = "APP人脸识别结果", opUserId = "userId")
    @PostMapping("/verifyFaceCert")
    @ResponseBody
    public Result<Object> verifyFaceCert(Long userId) {
        userInfoNewService.verifyFaceCert(userId);
        return ResultGenerator.genSuccessResult("修改成功", null);
    }

}
