package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.hotwj.platform.driverManagement.driver.domain.vo.HotDriverVo;
import com.hotwj.platform.driverManagement.driver.service.IHotDriverService;
import com.hotwj.platform.integration.face.FaceRecognitionService;
import com.hotwj.platform.resourceManagement.company.domain.SysUserLoginPort;
import com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService;
import com.hotwj.platform.resourceManagement.companySafetyManager.domain.vo.HotCompanySafetyManagerVo;
import com.hotwj.platform.resourceManagement.companySafetyManager.service.IHotCompanySafetyManagerService;
import com.hotwj.platform.resourceManagement.govEnterpriseUnit.domain.vo.HotGovEnterpriseUnitVo;
import com.hotwj.platform.resourceManagement.govEnterpriseUnit.service.IHotGovEnterpriseUnitService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.encrypt.annotation.ApiEncrypt;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
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.mybatis.helper.DataPermissionHelper;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.common.web.core.BaseController;
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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

import static com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService.DRIVER_PORT;
import static com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService.ENTERPRISE_PORT;

/**
 * 用户信息
 *
 * @author shihongwei
 */
@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 ISysUserLoginPortService userLoginPortService;
    private final IHotGovEnterpriseUnitService hotGovEnterpriseUnitService;
    private final IHotDriverService hotDriverService;
    private final FaceRecognitionService faceRecognitionService;
    private final ISysOssService ossService;
    private final IHotCompanySafetyManagerService safetyManagerService;

    /**
     * 获取用户列表
     */
    @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<SysUserExportVo> list = userService.selectUserExportList(user);
        ExcelUtil.exportExcel(list, "用户数据", 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());
    }

    /**
     * 上传人脸初始照片
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/profile/face", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> uploadFacePhoto(@RequestPart("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return R.fail("上传文件不能为空");
        }
        byte[] compressed = compressImage(file);
        String base64 = Base64.encode(compressed);
        if (!faceRecognitionService.detect(base64)) {
            return R.fail("人脸检测失败，请上传清晰的人脸照片");
        }
        Path tmp = Files.createTempFile("face_", ".jpg");
        try {
            Files.write(tmp, compressed);
            LoginUser loginUser = LoginHelper.getLoginUser();
            SysOssVo oss = ossService.upload(new java.io.File(tmp.toString()));
            // 判断是安全管理人员还是驾驶员
            if (ENTERPRISE_PORT.equals(loginUser.getLoginPort())) {
                if (safetyManagerService.updateUserFaceInitialOssId(loginUser.getBusinessUserId(), oss.getOssId())) {
                    return R.ok();
                }
            } else if (DRIVER_PORT.equals(loginUser.getLoginPort())) {
                if (hotDriverService.updateUserFaceInitialOssId(loginUser.getBusinessUserId(), oss.getOssId())) {
                    return R.ok();
                }
            }

        } finally {
            try {
                Files.deleteIfExists(tmp);
            } catch (Exception ignored) {
            }
        }
        return R.fail("上传人脸照片失败");
    }

    /**
     * 获取导入模板
     */
    @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 = DataPermissionHelper.ignore(() -> userService.selectUserById(loginUser.getUserId()));
        if (ObjectUtil.isNull(user)) {
            return R.fail("没有权限访问用户数据!");
        }
        // 重新更新用户名称
        if (ObjectUtil.isNotNull(loginUser)) {
            user.setNickName(loginUser.getUsername());
            user.setUserName(loginUser.getUsername());
            user.setCompanyId(loginUser.getCompanyId());
            user.setCompanyName(loginUser.getCompanyName());
            user.setBusinessUserId(loginUser.getBusinessUserId());

            // 获取当前登录端口的头像
            if (loginUser.getCompanyRoleId() != null) {
                SysUserLoginPort port = userLoginPortService.getById(loginUser.getCompanyRoleId());
                if (port != null && port.getAvatar() != null) {
                    user.setAvatar(port.getAvatar());
                }
            }

            // 如果是政府端登录，填充区县编码
            if (ISysUserLoginPortService.GOVERNMENT_PORT.equals(loginUser.getLoginPort())) {
                HotGovEnterpriseUnitVo unitVo = hotGovEnterpriseUnitService.queryById(loginUser.getCompanyId());
                if (unitVo != null) {
                    user.setDistrictCode(unitVo.getDistrictCode());
                }
            } else if (DRIVER_PORT.equals(loginUser.getLoginPort())) {
                // 驾驶员端：返回车辆ID
                if (StringUtils.isNotBlank(user.getBusinessUserId())) {
                    HotDriverVo driver = hotDriverService.queryById(user.getBusinessUserId());
                    if (driver != null) {
                        user.setVehicleId(driver.getVehicleId());
                        user.setDriverAuditStatus(String.valueOf(driver.getAuditStatus()));
                        user.setHasFaceInitialPhoto(StringUtils.isNotBlank(driver.getPortraitUrl()));
                        user.setUserName(driver.getName());
                    } else {
                        user.setDriverAuditStatus("0");
                    }
                }
            } else if (ENTERPRISE_PORT.equals(loginUser.getLoginPort())) {
                if (StringUtils.isNotBlank(user.getBusinessUserId())) {
                    HotCompanySafetyManagerVo safetyManagerVo = safetyManagerService.queryById(Long.valueOf(user.getBusinessUserId()));
                    if (safetyManagerVo != null) {
                        user.setHasFaceInitialPhoto(StringUtils.isNotBlank(safetyManagerVo.getAvatarUrl()));
                        user.setUserName(safetyManagerVo.getName());
                    }
                }
            }
        }
        userInfoVo.setUser(user);
        java.util.Set<String> permissions = new java.util.HashSet<>();
        if (CollUtil.isNotEmpty(loginUser.getMenuPermission())) {
            permissions.addAll(loginUser.getMenuPermission());
        }
        if (CollUtil.isNotEmpty(loginUser.getPermissionCodes())) {
            permissions.addAll(loginUser.getPermissionCodes());
        }
        userInfoVo.setPermissions(permissions);
        userInfoVo.setRoles(loginUser.getRolePermission());
        return R.ok(userInfoVo);
    }

    private byte[] compressImage(MultipartFile file) throws Exception {
        java.awt.image.BufferedImage src = javax.imageio.ImageIO.read(file.getInputStream());
        if (src == null) {
            throw new IllegalArgumentException("无效的图片文件");
        }
        int max = 1280;
        int w = src.getWidth();
        int h = src.getHeight();
        double scale = 1.0;
        if (w > max || h > max) {
            scale = Math.min((double) max / w, (double) max / h);
        }
        int nw = (int) Math.round(w * scale);
        int nh = (int) Math.round(h * scale);
        java.awt.image.BufferedImage resized = new java.awt.image.BufferedImage(nw, nh, java.awt.image.BufferedImage.TYPE_INT_RGB);
        java.awt.Graphics2D g2d = resized.createGraphics();
        g2d.setRenderingHint(java.awt.RenderingHints.KEY_INTERPOLATION, java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2d.drawImage(src, 0, 0, nw, nh, null);
        g2d.dispose();

        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        javax.imageio.ImageWriter writer = javax.imageio.ImageIO.getImageWritersByFormatName("jpg").next();
        javax.imageio.stream.ImageOutputStream ios = javax.imageio.ImageIO.createImageOutputStream(baos);
        writer.setOutput(ios);
        javax.imageio.plugins.jpeg.JPEGImageWriteParam jpegParams = new javax.imageio.plugins.jpeg.JPEGImageWriteParam(null);
        jpegParams.setCompressionMode(javax.imageio.ImageWriteParam.MODE_EXPLICIT);
        jpegParams.setCompressionQuality(0.8f);
        writer.write(null, new javax.imageio.IIOImage(resized, null, null), jpegParams);
        ios.close();
        writer.dispose();
        return baos.toByteArray();
    }

    /**
     * 根据用户编号获取详细信息
     *
     * @param userId 用户ID
     */
    @SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public R<SysUserInfoVo> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        SysUserInfoVo userInfoVo = new SysUserInfoVo();
        if (ObjectUtil.isNotNull(userId)) {
            userService.checkUserDataScope(userId);
            SysUserVo sysUser = userService.selectUserById(userId);
            userInfoVo.setUser(sysUser);
            userInfoVo.setRoleIds(roleService.selectRoleListByUserId(userId));
            Long deptId = sysUser.getDeptId();
            if (ObjectUtil.isNotNull(deptId)) {
                SysPostBo postBo = new SysPostBo();
                postBo.setDeptId(deptId);
                userInfoVo.setPosts(postService.selectPostList(postBo));
                userInfoVo.setPostIds(postService.selectPostListByUserId(userId));
            }
        }
        SysRoleBo roleBo = new SysRoleBo();
        roleBo.setStatus(SystemConstants.NORMAL);
        List<SysRoleVo> roles = roleService.selectRoleList(roleBo);
        // 回显用户端口
        userInfoVo.setLoginPorts(userLoginPortService.selectUserLoginPorts(userId));
        userInfoVo.setRoles(LoginHelper.isSuperAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));
        return R.ok(userInfoVo);
    }

    /**
     * 新增用户
     */
    @SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping
    public R<Void> add(@Validated @RequestBody SysUserBo user) {
        deptService.checkDeptDataScope(user.getDeptId());
        checkLoginPort(user);
        if (!userService.checkUserNameUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (TenantHelper.isEnable()) {
            if (!tenantService.checkAccountBalance(TenantHelper.getTenantId())) {
                return R.fail("当前租户下用户名额不足，请联系管理员");
            }
        }
        user.setPassword(BCrypt.hashpw(user.getPassword()));
        return toAjax(userService.insertUser(user, true));
    }

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

    private void checkLoginPort(SysUserBo user) {
        if (CollUtil.isEmpty(user.getLoginPort())) {
            throw new IllegalArgumentException("登录端口不能为空");
        }
    }

    /**
     * 删除用户
     *
     * @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));
    }

    /**
     * 根据用户ID串批量获取用户基础信息
     *
     * @param userIds 用户ID串
     * @param deptId  部门ID
     */
    @SaCheckPermission("system:user:query")
    @GetMapping("/optionselect")
    public R<List<SysUserVo>> optionselect(@RequestParam(required = false) Long[] userIds,
                                           @RequestParam(required = false) Long deptId) {
        return R.ok(userService.selectUserByIds(ArrayUtil.isEmpty(userIds) ? null : List.of(userIds), deptId));
    }

    /**
     * 重置密码
     */
    @ApiEncrypt
    @SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping("/resetPwd")
    public R<Void> resetPwd(@RequestBody SysUserBo user) {
        userService.checkUserAllowed(user.getUserId());
        userService.checkUserDataScope(user.getUserId());
        // 如果未传companyId，尝试从当前登录用户获取（如果是管理员操作自己？）
        // 但通常这是管理员操作别人。如果userBo中没有companyId，则默认全部重置。
        // 但根据用户要求“重置密码也是需要通过公司id来修改子密码”，前端应该传companyId。
        // 如果没传，可能是旧接口调用，或者意图重置所有。
        // 这里直接传递 user.getCompanyId()，让Service层判断。

        user.setPassword(BCrypt.hashpw(user.getPassword()));
        return toAjax(userService.resetUserPwd(user.getUserId(), user.getPassword(), user.getCompanyId()));
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @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()));
    }

    /**
     * 根据用户编号获取授权角色
     *
     * @param userId 用户ID
     */
    @SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public R<SysUserInfoVo> authRole(@PathVariable Long userId,
                                     @RequestParam(required = false) Long companyId,
                                     @RequestParam(required = false) String loginPort) {
        userService.checkUserDataScope(userId);
        SysUserVo user = userService.selectUserById(userId);
        List<SysRoleVo> roles;
        if (companyId == null || StringUtils.isBlank(loginPort)) {
            roles = roleService.selectRolesAuthByUserId(userId);
        } else {
            SysRoleBo roleBo = new SysRoleBo();
            roleBo.setStatus(SystemConstants.NORMAL);
            roleBo.setLoginPort(loginPort);
            roles = roleService.selectRoleList(roleBo);
        }
        SysUserInfoVo userInfoVo = new SysUserInfoVo();
        userInfoVo.setUser(user);
        userInfoVo.setRoles(LoginHelper.isSuperAdmin(userId) ? roles : StreamUtils.filter(roles, r -> !r.isSuperAdmin()));
        userInfoVo.setRoleIds(roleService.selectRoleListByUserId(userId));
        return R.ok(userInfoVo);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户Id
     * @param roleIds 角色ID串
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @RepeatSubmit()
    @PutMapping("/authRole")
    public R<Void> insertAuthRole(Long userId, Long[] roleIds,
                                  @RequestParam(required = false) Long companyId,
                                  @RequestParam(required = false) String loginPort) {
        userService.checkUserDataScope(userId);
        if (companyId == null) {
            companyId = 1L;
        }
        if (StringUtils.isBlank(loginPort)) {
            loginPort = ISysUserLoginPortService.HEADQUARTERS_PORT;
        }
        userService.insertUserAuth(userId, roleIds, companyId, loginPort);
        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));
    }

    /**
     * 校验用户上传的人脸照片是否与初始照片匹配
     *
     * @param file 上传的照片文件
     * @return 匹配结果
     */
    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    @PostMapping("/face/verify")
    public R<Boolean> verifyUserFace(@RequestPart("file") MultipartFile file) {
        String activeProfile = SpringUtils.getProperty("spring.profiles.active");
        if (StringUtils.containsIgnoreCase(activeProfile, "dev")) {
            return R.ok(Boolean.TRUE);
        }
        return R.ok(userService.verifyUserFace(LoginHelper.getUserId(), file));
    }

    /**
     * 检测图片是否包含人脸
     *
     * @param file 上传的图片文件
     * @return 检测结果
     */
    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    @PostMapping(value = "/face/detect", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Boolean> detectFace(@RequestPart("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return R.fail("上传文件不能为空");
        }
        byte[] compressed = compressImage(file);
        String base64 = Base64.encode(compressed);
        if (faceRecognitionService.detect(base64)) {
            return R.ok(true);
        } else {
            return R.fail("未检测到清晰人脸");
        }
    }
}
