package com.hxhq.system.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.hxhq.business.domain.Study;
import com.hxhq.business.dto.select.DeptUserTreeDto;
import com.hxhq.business.enums.dept.DeptTypeEnum;
import com.hxhq.business.enums.study.StudyTypeEnum;
import com.hxhq.business.form.common.SignForm;
import com.hxhq.business.service.IStudyService;
import com.hxhq.common.core.exception.ServiceException;
import com.hxhq.common.core.utils.ServletUtils;
import com.hxhq.system.api.RemoteIntegrationService;
import com.hxhq.system.api.RemoteUserService;
import com.hxhq.system.dto.UserExportDto;
import com.hxhq.system.form.UserSaveForm;
import com.hxhq.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.hxhq.common.core.domain.R;
import com.hxhq.common.core.text.Convert;
import com.hxhq.common.core.utils.DateUtils;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.core.utils.poi.ExcelUtil;
import com.hxhq.common.core.web.controller.BaseController;
import com.hxhq.common.core.web.domain.AjaxResult;
import com.hxhq.common.core.web.page.TableDataInfo;
import com.hxhq.common.log.annotation.Log;
import com.hxhq.common.log.enums.BusinessType;
import com.hxhq.common.security.annotation.InnerAuth;
import com.hxhq.common.security.annotation.RequiresPermissions;
import com.hxhq.common.security.service.TokenService;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.domain.SysDept;
import com.hxhq.system.api.domain.SysRole;
import com.hxhq.system.api.domain.SysUser;
import com.hxhq.system.api.model.LoginUser;

/**
 * 用户信息
 * 
 * @author hxhq
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private IStudyService studyService;
    @Autowired
    private ISysMenuService sysMenuService;

    @Autowired
    private RemoteIntegrationService remoteIntegrationService;

    /**
     * 获取用户列表
     */
    @GetMapping("/checkStatus")
    public AjaxResult checkStatus()
    {
        return AjaxResult.success();
    }

    /**
     * 获取用户列表
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        List<UserExportDto> userList = new ArrayList<>();
        for(SysUser u : list){
            UserExportDto exportDto = new UserExportDto();
            exportDto.setUserName(u.getUserName());
            exportDto.setNickName(u.getNickName());
            exportDto.setEmail(u.getEmail());
            exportDto.setDeptName(u.getDept()==null?"":u.getDept().getDeptName());
            exportDto.setRoleName(getRoleName(u.getRoles()));

            exportDto.setStatus("0".endsWith(u.getStatus())?("zh_CN".equals(ServletUtils.getRequest().getHeader("lang"))?"启用":"Enabled"):("zh_CN".equals(ServletUtils.getRequest().getHeader("lang"))?"禁用":"Disabled"));
            userList.add(exportDto);
        }
        ExcelUtil<UserExportDto> util = new ExcelUtil<UserExportDto>(UserExportDto.class);
        util.exportExcel(response, userList, "用户数据");
    }

    private String getRoleName(List<SysRole> roleList){
        if(roleList==null || roleList.size()==0){
            return "";
        }
        return String.join("，",roleList.stream().map(o->o.getRoleName()).toArray(String[]::new));
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        sysUserVo.setDefaultUrl(sysMenuService.getUserFirstUrl(sysUser.getUserId()));
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser)
    {
        String username = sysUser.getUserName();
        String a1 = "true";
        String a2 = "sys.account.registerUser";
        if (!(a1.equals(configService.selectConfigByKey(a2))))
        {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser))
        {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

    /**
     *记录用户登录IP地址和登录时间
     */
    @InnerAuth
    @PutMapping("/recordlogin")
    public R<Boolean> recordlogin(@RequestBody SysUser sysUser)
    {
        return R.ok(userService.updateLoginInfo(sysUser));
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getSysUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        ajax.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        ajax.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        return ajax;
    }

    /**
     * 检查初始密码是否提醒修改
     * @param pwdUpdateDate
     * @return
     */
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    /**
     * 检查密码是否过期
     * @param pwdUpdateDate
     * @return
     */
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:list")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            userService.checkUserDataScope(userId);
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        List<SysRole> roles = roleService.selectRoleAll();
        roles = roles.stream().filter(o->o.getStatus().equals("0")).collect(Collectors.toList());
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        return ajax;
    }

    @GetMapping("/checkExist")
    public AjaxResult checkExist(@PathVariable("username") String username){
        AjaxResult exists = remoteIntegrationService.checkAccountExists(username);
        return exists;
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody UserSaveForm form)
    {
//        AjaxResult exists = remoteIntegrationService.checkAccountExists(form.getUser().getUserName());
//        AjaxResult exists = remoteIntegrationService.validate(form.getUser().getUserName(),form.getUser().getPassword());
//        return exists;
        SysUser user = form.getUser();
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(form));
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody UserSaveForm form)
    {
        SysUser user = form.getUser();
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(form));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @RequiresPermissions("system:user:enable")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody UserSaveForm form)
    {
        SysUser user = form.getUser();
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(form));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:list")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门树列表
     * @return
     */
    @GetMapping("/deptUserList")
    public AjaxResult deptUserList()
    {
        List<DeptUserTreeDto> depts = userService.selectDeptAndUser();
        for(DeptUserTreeDto dept : depts){
            Boolean isDept = dept.getType().equals(DeptTypeEnum.dept.getValue()) || dept.getType().equals(DeptTypeEnum.subject.getValue()) || dept.getType().equals(DeptTypeEnum.team.getValue());
            if(isDept){
                dept.setId("d_"+dept.getId());
                dept.setParentId(("0".equals(dept.getParentId())?"":"d_")+dept.getParentId());
            }else{
                dept.setId("u_"+dept.getId());
                dept.setParentId("d_"+dept.getParentId());
            }
        }
        return success(depts);
    }

    /**
     * 获取试验人员
     * @param studyId
     * @param studySubjectId
     * @param permit
     * @return
     */
    @GetMapping("/studyUser")
    public AjaxResult studyUser(Long studyId,Long studySubjectId,String permit)
    {
        if(studyId==null || studyId.longValue()<=0){
            return AjaxResult.success(new ArrayList<>());
        }
        Study study = studyService.getById(studyId);
        if(study==null){
            return AjaxResult.error("信息不存在");
        }
        //试验学科内部的人+非试验部门内的人+麻精药不用判断（只需要判断有审核按钮）
        List<DeptUserTreeDto> depts = userService.selectStudyUser(study.getType().equals(StudyTypeEnum.sy.getValue())?studyId:null,study.getType().equals(StudyTypeEnum.sy.getValue())?studySubjectId:null,study.getType().equals(StudyTypeEnum.fsy.getValue())?study.getDeptId():null,permit);
        return success(depts);
    }
}
