package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.constant.CacheNames;
import org.dromara.common.core.constant.Constants;
import org.dromara.common.core.constant.SmsConstants;
import org.dromara.common.core.constant.UserConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.redis.utils.CacheUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.dromara.system.domain.CaseMessage;
import org.dromara.system.domain.SysSmsConfig;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.bo.SysDeptBo;
import org.dromara.system.domain.bo.SysPostBo;
import org.dromara.system.domain.bo.SysRoleBo;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.vo.*;
import org.dromara.system.listener.SysUserImportListener;
import org.dromara.system.service.*;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author Lion Li
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {

    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysPostService postService;
    private final ISysDeptService deptService;
    private final ISysTenantService tenantService;
    private final ISysDictTypeService dictTypeService;
    private final ISysDoctorVolunteerService sysDoctorVolunteerService;
    private final ICaseMessageService caseMessageService;

    /**
     * 获取用户列表
     */
    //@SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public TableDataInfo<SysUserVo> list(SysUserBo user, PageQuery pageQuery) {
        return userService.selectPageUserList(user, pageQuery);
    }

    /**
     * 导出用户列表
     */
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    //@SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public void export(SysUserBo user, HttpServletResponse response) {
        List<SysUserVo> list = userService.selectUserList(user);
        List<SysUserExportVo> listVo = MapstructUtils.convert(list, SysUserExportVo.class);
        ExcelUtil.exportExcel(listVo, "用户数据", SysUserExportVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    //@SaCheckPermission("system:user:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<SysUserImportVo> result = ExcelUtil.importExcel(file.getInputStream(), SysUserImportVo.class, new SysUserImportListener(updateSupport));
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "用户数据", SysUserImportVo.class, response);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public R<UserInfoVo> getInfo() {
        UserInfoVo userInfoVo = new UserInfoVo();
        LoginUser loginUser = LoginHelper.getLoginUser();
        if (TenantHelper.isEnable() && LoginHelper.isSuperAdmin()) {
            // 超级管理员 如果重新加载用户信息需清除动态租户
            TenantHelper.clearDynamic();
        }
        SysUserVo user = userService.selectUserById(loginUser.getUserId());
        if (ObjectUtil.isNull(user)) {
            return R.fail("没有权限访问用户数据!");
        }
        userInfoVo.setUser(user);
        userInfoVo.setPermissions(loginUser.getMenuPermission());
        userInfoVo.setRoles(loginUser.getRolePermission());
        return R.ok(userInfoVo);
    }

    /**
     * 根据用户编号获取详细信息
     *
     * @param userId 用户ID
     */
    //@SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public R<SysUserInfoVo> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        SysUserInfoVo userInfoVo = new SysUserInfoVo();
        SysRoleBo roleBo = new SysRoleBo();
        roleBo.setStatus(UserConstants.ROLE_NORMAL);
        SysPostBo postBo = new SysPostBo();
        postBo.setStatus(UserConstants.POST_NORMAL);
        List<SysRoleVo> roles = roleService.selectRoleList(roleBo);
        userInfoVo.setRoles(LoginHelper.isSuperAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));
        userInfoVo.setPosts(postService.selectPostList(postBo));
        if (ObjectUtil.isNotNull(userId)) {
            SysUserVo sysUser = userService.selectUserById(userId);

            // 医生
            if (sysUser.getLoginIdentity().equals(UserConstants.LOGIN_IDENTITY_DOCTOR)) {
                // 已绑定志愿者列表
                List<SysDoctorVolunteerVo> voList = sysDoctorVolunteerService.volunteerList(userId);
                if (voList != null && voList.size() > 0) {
                    List<Long> volunteerList = voList.stream().map(SysDoctorVolunteerVo::getVolunteerUserId).collect(Collectors.toList());
                    sysUser.setBindVolunteerList(volunteerList);
                }

            }

            // 志愿者
            if (sysUser.getLoginIdentity().equals(UserConstants.LOGIN_IDENTITY_VOLUNTEER)) {
                // 已绑定医生列表
                List<SysDoctorVolunteerVo> voList = sysDoctorVolunteerService.doctorList(userId);
                if (voList != null && voList.size() > 0) {
                    List<Long> doctorList = voList.stream().map(SysDoctorVolunteerVo::getDoctorUserId).collect(Collectors.toList());
                    sysUser.setBindDoctorList(doctorList);
                }

            }

            userInfoVo.setUser(sysUser);
            userInfoVo.setRoleIds(StreamUtils.toList(sysUser.getRoles(), SysRoleVo::getRoleId));
            userInfoVo.setPostIds(postService.selectPostListByUserId(userId));
        }

        return R.ok(userInfoVo);
    }

    /**
     * 新增用户
     */
    //@SaCheckPermission("system:user:add")
    @Transactional
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R<Void> add(@Validated @RequestBody SysUserBo user) {
        deptService.checkDeptDataScope(user.getDeptId());
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("新增用户失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("新增用户失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("新增用户失败，邮箱账号已存在");
        }
        // 默认密码
        user.setPassword(BCrypt.hashpw(Constants.password));
        int result = userService.insertUser(user);

        if (result > 0) {
            // 绑定医生列表不为空
            if (user.getBindDoctorList() != null && user.getBindDoctorList().size() > 0) {
                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.VOLUNTEERS_BIND_DOCTORS);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                if (sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                    // 医生列表
                    List<SysUser> doctorUserList = userService.selectUserListByIds(user.getBindDoctorList());
                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 志愿者姓名
                    map.put("name", user.getNickName());

                    SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
                    // 循环发送医生通知短信
                    for (SysUser doctorUser : doctorUserList
                    ) {
                        smsBlend.sendMessage(doctorUser.getPhonenumber(), SmsConstants.VOLUNTEERS_BIND_DOCTORS, map);
                    }
                }

                List<CaseMessage> messageList = new ArrayList<>();
                // 循环生成系统内部消息
                for (Long doctorUserId : user.getBindDoctorList()
                ) {

                    CaseMessage userMessage = new CaseMessage();
                    userMessage.setMessageContent("志愿者" + user.getNickName() + "已和您");
                    userMessage.setMessageType("1");
                    userMessage.setUserId(doctorUserId);
                    userMessage.setBusinessStatus("3");
                    messageList.add(userMessage);
                }
                caseMessageService.insertBatch(messageList);

            }

            // 绑定志愿者列表不为空
            if (user.getBindVolunteerList() != null && user.getBindVolunteerList().size() > 0) {
                // 获取缓存SMS短信配置
                String json = CacheUtils.get(CacheNames.SYS_SMS_CONFIG, SmsConstants.DOCTORS_BIND_VOLUNTEERS);
                SysSmsConfig sysSmsConfig = JsonUtils.parseObject(json, SysSmsConfig.class);
                if (sysSmsConfig.getStatus().equals(SmsConstants.SMS_ENABLE)) {
                    // 医生列表
                    List<SysUser> volunteerUserList = userService.selectUserListByIds(user.getBindVolunteerList());

                    LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
                    // 医生姓名
                    map.put("name", user.getNickName());

                    SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.ALIBABA);
                    // 志愿者短信通知
                    for (SysUser volunteerUser : volunteerUserList
                    ) {
                        smsBlend.sendMessage(volunteerUser.getPhonenumber(), SmsConstants.DOCTORS_BIND_VOLUNTEERS, map);

                    }

                }

                List<CaseMessage> messageList = new ArrayList<>();
                // 循环生成系统内部消息
                for (Long volunteerUserId : user.getBindVolunteerList()
                ) {
                    CaseMessage userMessage = new CaseMessage();
                    userMessage.setMessageContent("医生" + user.getNickName() + "已和您");
                    userMessage.setMessageType("1");
                    userMessage.setUserId(volunteerUserId);
                    userMessage.setBusinessStatus("3");
                    messageList.add(userMessage);
                }
                caseMessageService.insertBatch(messageList);
            }

        }
        return toAjax(result);
    }

    /**
     * 修改用户
     */
    //@SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        // 修改手机号，同步修改userName
        if (StringUtils.isNotEmpty(user.getPhonenumber())) {
            user.setUserName(user.getPhonenumber());
        }
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     *
     * @param userIds 角色ID串
     */
    //@SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public R<Void> remove(@PathVariable Long[] userIds) {
        if (ArrayUtil.contains(userIds, LoginHelper.getUserId())) {
            return R.fail("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        return toAjax(userService.resetUserPwd(user.getUserId(), user.getPassword()));
    }

    /**
     * 状态修改
     */
    //@SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.updateUserStatus(user.getUserId(), user.getStatus()));
    }

    /**
     * 协议确认状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeConfirmStatus")
    public R<Void> changeConfirmStatus(@RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        return toAjax(userService.changeConfirmStatus(user.getUserId(), user.getConfirmAgreement()));
    }

    /**
     * 根据用户编号获取授权角色
     *
     * @param userId 用户ID
     */
    //@SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public R<SysUserInfoVo> authRole(@PathVariable Long userId) {
        SysUserVo user = userService.selectUserById(userId);
        List<SysRoleVo> roles = roleService.selectRolesByUserId(userId);
        SysUserInfoVo userInfoVo = new SysUserInfoVo();
        userInfoVo.setUser(user);
        userInfoVo.setRoles(LoginHelper.isSuperAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));
        return R.ok(userInfoVo);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户Id
     * @param roleIds 角色ID串
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public R<Void> insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return R.ok();
    }

    /**
     * 获取部门树列表
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/deptTree")
    public R<List<Tree<Long>>> deptTree(SysDeptBo dept) {
        return R.ok(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门下的所有用户信息
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/list/dept/{deptId}")
    public R<List<SysUserVo>> listByDept(@PathVariable @NotNull Long deptId) {
        return R.ok(userService.selectUserListByDept(deptId));
    }

    /**
     * 查询列表数据中的用户职称字典项
     */
    @GetMapping(value = "/type/title")
    public R<List<SysDictDataVo>> sysUserTitle() {
        // 全部字段数据
        List<SysDictDataVo> data = dictTypeService.selectDictDataByType("sys_user_title");
        // 租户用户列表
        List<SysUserVo> sysUserVoList = userService.selectUserList();
        // 获取身份列表
        List<String> titleList = sysUserVoList.stream().map(SysUserVo::getTitle).distinct().collect(Collectors.toList());

        // 返回列表
        List<SysDictDataVo> result = new ArrayList<>();
        // 用户职称列表不为空
        if (titleList != null && titleList.size() > 0) {

            for (String identity : titleList
            ) {
                for (SysDictDataVo vo : data
                ) {
                    if (vo.getDictValue().equals(identity)) {
                        result.add(vo);
                    }
                }
            }
        }
        return R.ok(result);
    }

    /**
     * 查询列表数据中的用户身份字典项
     */
    @GetMapping(value = "/type/identity")
    public R<List<SysDictDataVo>> sysUserIdentity() {
        // 全部字段数据
        List<SysDictDataVo> data = dictTypeService.selectDictDataByType("sys_register_type");
        // 租户用户列表
        List<SysUserVo> sysUserVoList = userService.selectUserList();
        // 获取身份列表
        List<String> identityList = sysUserVoList.stream().map(SysUserVo::getLoginIdentity).distinct().collect(Collectors.toList());
        // 返回列表
        List<SysDictDataVo> result = new ArrayList<>();
        // 用户列表身份不为空
        if (identityList != null && identityList.size() > 0) {

            for (String identity : identityList
            ) {
                for (SysDictDataVo vo : data
                ) {
                    if (vo.getDictValue().equals(identity)) {
                        result.add(vo);
                    }
                }
            }
        }
        return R.ok(result);
    }
}
