package com.ruoyi.web.controller.system;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.*;
import com.ruoyi.oa.domain.CmcUserHistory;
import com.ruoyi.oa.service.ICmcUserHistoryService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
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.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

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

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ICmcUserHistoryService cmcUserHistoryService;

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        // 如果指定了部门ID，根据备注中的部门信息添加用户
        if (user.getDeptId() != null) {
            if (user.getDeptId() == 101L) {
                list.addAll(postService.selectDsSecretary(user));
            }
            if (user.getDeptId() == 102L) {
                list.addAll(postService.selectJyLeader(user));
            }
            if (user.getDeptId() == 103L) {
                list = postService.selectGmAssistant(user);
            }
            SysDept dept = deptService.selectDeptById(user.getDeptId());
            if (dept != null) {
                // 查询所有用户
                user.setDeptId(null);
                List<SysUser> allUsers = userService.selectUserList(user);
                for (SysUser sysUser : allUsers) {
                    // 检查用户备注中的部门信息
                    if (sysUser.getRemark() != null) {
                        String remark = sysUser.getRemark();
                        // 提取备注中的部门信息
                        if (remark.contains("隶属部门：" + dept.getDeptName()) || 
                            remark.contains("合同部门：" + dept.getDeptName()) || 
                            remark.contains("工作部门：" + dept.getDeptName())) {
                            // 确保用户不重复添加
                            if (!containsUser(list, sysUser)) {
                                list.add(sysUser);
                            }
                        }
                    }
                }
            }
        }
        for (SysUser sysUser : list) {
            StringBuilder postName = new StringBuilder();
            List<Long> userPostList = postService.selectPostListByUserId(sysUser.getUserId());
            if (userPostList.size() > 0) {
                for (Long post : userPostList)
                    postName.append(postService.selectPostById(post).getPostName()).append("/");
                sysUser.setPostNames(postName.substring(0, postName.length() - 1));
            }
        }
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        for (SysUser sysUser : list) {
            sysUser.setAge(IDCard.getBirAgeSex(sysUser.getIdCard()).getInteger("age"));
            sysUser.setBirthday(IDCard.getBirAgeSex(sysUser.getIdCard()).getDate("birthday"));
            StringBuilder postName = new StringBuilder();
            List<Long> userPostList = postService.selectPostListByUserId(sysUser.getUserId());
            for (Long post : userPostList)
                postName.append(postService.selectPostById(post).getPostName()).append("/");
            if (!postName.toString().equals(""))
                sysUser.setPostNames(postName.substring(0, postName.length() - 1));
            sysUser.setUserId(sysUser.getUserId() - 1);
        }
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
//    @PreAuthorize("@ss.hasPermi('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 = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

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

    /**
     * 根据用户编号获取详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(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()));
        }
        return ajax;
    }

    /**
     * 根据用户编号获取变更记录
     */
    @GetMapping("/change")
    public TableDataInfo getChangeInfo(SysUser user) {
        Long userId = user.getUserId();
        SysUser sysUser = userService.selectUserById(userId);
        List<Long> userPostList = postService.selectPostListByUserId(userId);
        List<Long> userRoleList = roleService.selectRoleListByUserId(userId);
        sysUser.setRoleIds(userRoleList.toArray(new Long[userRoleList.size()]));
        sysUser.setPostIds(userPostList.toArray(new Long[userPostList.size()]));
        JSONObject jsonObj = (JSONObject) JSON.toJSON(sysUser);
        CmcUserHistory userHistory = new CmcUserHistory();
        userHistory.setUserId(userId);
        List<CmcUserHistory> cmcUserHistoryList = cmcUserHistoryService.selectCmcUserHistoryList(userHistory);
        Field[] fields = userHistory.getClass().getDeclaredFields();
        JSONArray jsonArray = new JSONArray();
        int changeNumber = 1;
        for (int i = 0; i < cmcUserHistoryList.size(); i++) {
            JSONObject beforeChangeHistoryJsonObj = (JSONObject) JSON.toJSON(cmcUserHistoryList.get(i));
            JSONObject afterChangeHistoryJsonObj = new JSONObject();
            if (i == 0)
                afterChangeHistoryJsonObj = (JSONObject) JSON.toJSON(jsonObj);
            else
                afterChangeHistoryJsonObj = (JSONObject) JSON.toJSON(cmcUserHistoryList.get(i - 1));
            for (Field field : fields) {
                JSONObject jsonObject = new JSONObject();
                String fieldName = field.getName().split("\\.")[field.getName().split("\\.").length - 1];
                if (!fieldName.equals("historyId") && !fieldName.equals("serialVersionUID")  && !fieldName.equals("updateReason")  && !fieldName.equals("updateTime")) {
                    if (!fieldName.equals("roleIds") && !fieldName.equals("postIds")) {
                        if ((beforeChangeHistoryJsonObj.getString(fieldName) != null && afterChangeHistoryJsonObj.getString(fieldName) != null
                                && !beforeChangeHistoryJsonObj.getString(fieldName).equals(afterChangeHistoryJsonObj.getString(fieldName)))
                                || (beforeChangeHistoryJsonObj.getString(fieldName) == null && afterChangeHistoryJsonObj.getString(fieldName) != null)
                                || (beforeChangeHistoryJsonObj.getString(fieldName) != null && afterChangeHistoryJsonObj.getString(fieldName) == null)) {
                            if (fieldName.equals("deptId")) {
                                jsonObject.put("before", deptService.selectDeptById(beforeChangeHistoryJsonObj.getLong(fieldName)).getDeptName());
                                jsonObject.put("after", deptService.selectDeptById(afterChangeHistoryJsonObj.getLong(fieldName)).getDeptName());
                            }
                            else {
                                jsonObject.put("before", beforeChangeHistoryJsonObj.getString(fieldName));
                                jsonObject.put("after", afterChangeHistoryJsonObj.getString(fieldName));
                            }
                            jsonObject.put("id", changeNumber++);
                            jsonObject.put("field", getFieldName(fieldName));
                            jsonObject.put("date", DateFormatUtils.format(beforeChangeHistoryJsonObj.getDate("updateTime"), "yyyy-MM-dd"));
                            jsonArray.add(jsonObject);
                        }
                    } else {
                        if (i == 0) {
                            if (!beforeChangeHistoryJsonObj.getString(fieldName).equals(StringUtils.join(afterChangeHistoryJsonObj.getJSONArray(fieldName), ","))) {
                                if (fieldName.equals("roleIds")) {
                                    getRoleOrPostName(beforeChangeHistoryJsonObj.getString(fieldName), jsonObject, "role", "before");
                                    getRoleOrPostName(StringUtils.join(afterChangeHistoryJsonObj.getJSONArray(fieldName), ","), jsonObject, "role", "after");
                                }
                                else {
                                    getRoleOrPostName(beforeChangeHistoryJsonObj.getString(fieldName), jsonObject, "post", "before");
                                    getRoleOrPostName(StringUtils.join(afterChangeHistoryJsonObj.getJSONArray(fieldName), ","), jsonObject, "post", "after");
                                }
                                jsonObject.put("id", changeNumber++);
                                jsonObject.put("field", getFieldName(fieldName));
                                jsonObject.put("date", DateFormatUtils.format(beforeChangeHistoryJsonObj.getDate("updateTime"), "yyyy-MM-dd"));
                                jsonArray.add(jsonObject);
                            }
                        }
                        else {
                            if (!beforeChangeHistoryJsonObj.getString(fieldName).equals(afterChangeHistoryJsonObj.getString(fieldName))) {
                                if (fieldName.equals("roleIds")) {
                                    getRoleOrPostName(beforeChangeHistoryJsonObj.getString(fieldName), jsonObject, "role", "before");
                                    getRoleOrPostName(afterChangeHistoryJsonObj.getString(fieldName), jsonObject, "role", "after");
                                }
                                else {
                                    getRoleOrPostName(beforeChangeHistoryJsonObj.getString(fieldName), jsonObject, "post", "before");
                                    getRoleOrPostName(afterChangeHistoryJsonObj.getString(fieldName), jsonObject, "post", "after");
                                }
                                jsonObject.put("id", changeNumber++);
                                jsonObject.put("field", getFieldName(fieldName));
                                jsonObject.put("date", DateFormatUtils.format(beforeChangeHistoryJsonObj.getDate("updateTime"), "yyyy-MM-dd"));
                                jsonArray.add(jsonObject);
                            }
                        }
                    }
                }
            }
        }
        return getDataTable(jsonArray);
    }

    private void getRoleOrPostName(String fieldValue, JSONObject jsonObject, String roleOrPost, String beforeOrAfter) {
        if (!fieldValue.equals("") && fieldValue.split(",").length > 0) {
            StringBuilder names = new StringBuilder();
            for (String id : fieldValue.split(",")) {
                if (roleOrPost.equals("role"))
                    names.append(roleService.selectRoleById(Long.parseLong(id)).getRoleName()).append(",");
                else
                    names.append(postService.selectPostById(Long.parseLong(id)).getPostName()).append(",");
            }
            if (beforeOrAfter.equals("before"))
                jsonObject.put("before", names.substring(0, names.length() - 1));
            else
                jsonObject.put("after", names.substring(0, names.length() - 1));
        }
    }

    /**
     * 获取字段名备注
     */
    private String getFieldName(String fieldName) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("deptId", "部门");
        jsonObject.put("pmLevel", "项目经理级别");
        jsonObject.put("titles", "技术职称");
        jsonObject.put("certificates", "执业证书");
        jsonObject.put("engineerLevel", "工程师岗级");
        jsonObject.put("postLevel", "岗级");
        jsonObject.put("salaryLevel", "薪档");
        jsonObject.put("operatorLevel", "技工等级");
        jsonObject.put("politicalAffiliation", "政治面貌");
        jsonObject.put("graduateSchool", "毕业院校");
        jsonObject.put("major", "专业");
        jsonObject.put("degree", "学历");
        jsonObject.put("contractSign", "合同签订");
        jsonObject.put("contractExpire", "合同期满");
        jsonObject.put("roleIds", "角色");
        jsonObject.put("postIds", "岗位");
        jsonObject.put("status", "状态");
        return jsonObject.getString(fieldName);
    }

    /**
     * 新增用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        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(getUsername());
        if (user.getPoliticalAffiliation() == null || user.getPoliticalAffiliation().equals(""))
            user.setPoliticalAffiliation("13");
//        String pinyin = Pinyin4jUtil.getPinyin(user.getNickName());
//        user.setPinyin(pinyin.contains(",") ? pinyin.split(",")[0] : pinyin);
        user.setPinyin(user.getUserName());
        Long[] roleIds = new Long[1];
        roleIds[0] = 2L;
        user.setRoleIds(roleIds);
        user.setPassword(SecurityUtils.encryptPassword(user.getIdCard().substring(12,18)));
        if (user.getBirthday() != null)
            user.setAge(DateUtils.getAgeByBirth(user.getBirthday()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPassword")
    public AjaxResult editPassword()
    {
        for (SysUser user : userService.selectUserList(new SysUser())) {
            if (user.getUserId() > 1) {
                user.setPassword(SecurityUtils.encryptPassword(user.getIdCard().substring(12,18)));
                userService.resetPwd(user);
            }
        }
        return toAjax(1);
    }

    /**
     * 修改用户密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/pinyin")
    public AjaxResult setPinyin()
    {
        for (SysUser user : userService.selectUserList(new SysUser())) {
            if (user.getUserId() > 1) {
                String pinyin = Pinyin4jUtil.getPinyin(user.getNickName());
                user.setPinyin(pinyin.contains(",") ? pinyin.split(",")[0] : pinyin);
                if (user.getContractSign() == null || user.getContractExpire() == null) {
                    if (user.getContractSign() == null)
                        userService.updateUserContractSign(user);
                    if (user.getContractExpire() == null)
                        userService.updateUserContractExpire(user);
                }
                userService.updateUser(user);
            }
        }
        return toAjax(1);
    }

    /**
     * 修改用户
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        CmcUserHistory cmcUserHistory = new CmcUserHistory();
        SysUser sysUser = userService.selectUserById(user.getUserId());
        cmcUserHistory.setUserId(user.getUserId());
        cmcUserHistory.setDeptId(sysUser.getDeptId());
        cmcUserHistory.setTitles(sysUser.getTitles());
        cmcUserHistory.setCertificates(sysUser.getCertificates());
        cmcUserHistory.setEngineerLevel(sysUser.getEngineerLevel());
        cmcUserHistory.setPostLevel(sysUser.getPostLevel());
        cmcUserHistory.setSalaryLevel(sysUser.getSalaryLevel());
        cmcUserHistory.setPmLevel(sysUser.getPmLevel());
        cmcUserHistory.setOperatorLevel(sysUser.getOperatorLevel());
        cmcUserHistory.setPoliticalAffiliation(sysUser.getPoliticalAffiliation());
        cmcUserHistory.setGraduateSchool(sysUser.getGraduateSchool());
        cmcUserHistory.setMajor(sysUser.getMajor());
        cmcUserHistory.setDegree(sysUser.getDegree());
        cmcUserHistory.setContractSign(sysUser.getContractSign());
        cmcUserHistory.setContractExpire(sysUser.getContractExpire());
        cmcUserHistory.setUpdateReason(user.getUpdateReason());
        cmcUserHistory.setUpdateTime(DateUtils.getNowDate());
        cmcUserHistory.setRoleIds(StringUtils.join(roleService.selectRoleListByUserId(user.getUserId()),","));
        cmcUserHistory.setPostIds(StringUtils.join(postService.selectPostListByUserId(user.getUserId()),","));
        cmcUserHistory.setUpdateTime(DateUtils.getNowDate());
        cmcUserHistory.setStatus(sysUser.getStatus());
        cmcUserHistoryService.insertCmcUserHistory(cmcUserHistory);
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        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(getUsername());
        user.setUpdateReason(user.getUpdateReason());
        if (user.getBirthday() != null)
            user.setAge(DateUtils.getAgeByBirth(user.getBirthday()));
        if (user.getContractSign() == null || user.getContractExpire() == null || user.getEntryDate() == null) {
            if (user.getEntryDate() == null)
                userService.updateUserEntryDate(user);
            if (user.getContractSign() == null)
                userService.updateUserContractSign(user);
            if (user.getContractExpire() == null)
                userService.updateUserContractExpire(user);
        }
        return toAjax(userService.updateUser(user));
    }

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

    /**
     * 重置密码
     */
//    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (user.getPassword() == null)
            user.setPassword(SecurityUtils.encryptPassword(user.getIdCard().substring(12,18)));
        else
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
//    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
//    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @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;
    }

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

    /**
     * 获取部门树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门树列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTreeNew")
    public AjaxResult deptTreeNew(SysDept dept)
    {
        return success(deptService.selectDeptTreeListNew(dept));
    }

    /**
     * 检查列表中是否包含指定用户
     */
    private boolean containsUser(List<SysUser> userList, SysUser user) {
        if (userList == null || user == null || user.getUserId() == null) {
            return false;
        }
        for (SysUser existingUser : userList) {
            if (existingUser.getUserId() != null && existingUser.getUserId().equals(user.getUserId())) {
                return true;
            }
        }
        return false;
    }
}
