package org.dromara.system.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.hotwj.platform.resourceManagement.company.domain.SysUserLoginPort;
import com.hotwj.platform.resourceManagement.company.service.ISysUserLoginPortService;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.MimeTypeUtils;
import org.dromara.common.encrypt.annotation.ApiEncrypt;
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.helper.DataPermissionHelper;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.system.domain.bo.SysUserBo;
import org.dromara.system.domain.bo.SysUserElectronicSignatureBo;
import org.dromara.system.domain.bo.SysUserPasswordBo;
import org.dromara.system.domain.bo.SysUserProfileBo;
import org.dromara.system.domain.vo.ProfileUserVo;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.domain.vo.SysUserElectronicSignatureVo;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserElectronicSignatureService;
import org.dromara.system.service.ISysOssService;
import org.dromara.system.service.ISysUserService;
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.util.Arrays;

/**
 * 个人信息 业务处理
 *
 * @author shihongwei
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {

    private final ISysUserService userService;
    private final ISysOssService ossService;
    private final ISysUserLoginPortService sysUserLoginPortService;
    private final ISysUserElectronicSignatureService userElectronicSignatureService;

    /**
     * 个人信息
     */
    @GetMapping
    public R<ProfileVo> profile() {
        SysUserVo user = userService.selectUserById(LoginHelper.getUserId());
        String roleGroup = userService.selectUserRoleGroup(user.getUserId());
        String postGroup = userService.selectUserPostGroup(user.getUserId());
        // 单独做一个vo专门给个人中心用 避免数据被脱敏
        ProfileUserVo profileUser = BeanUtil.toBean(user, ProfileUserVo.class);

        // 尝试获取当前登录端口的自定义头像
        Long portId = LoginHelper.getLoginUser().getCompanyRoleId();
        if (portId != null) {
            SysUserLoginPort port = sysUserLoginPortService.getById(portId);
            if (port != null && port.getAvatar() != null) {
                profileUser.setPortAvatar(port.getAvatar());
            }
        }

        ProfileVo profileVo = new ProfileVo(profileUser, roleGroup, postGroup);
        return R.ok(profileVo);
    }

    /**
     * 修改用户信息
     */
    @RepeatSubmit
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> updateProfile(@Validated @RequestBody SysUserProfileBo profile) {
        SysUserBo user = BeanUtil.toBean(profile, SysUserBo.class);
        user.setUserId(LoginHelper.getUserId());
        String username = LoginHelper.getUsername();
        if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return R.fail("修改用户'" + username + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return R.fail("修改用户'" + username + "'失败，邮箱账号已存在");
        }
        int rows = DataPermissionHelper.ignore(() -> userService.updateUserProfile(user));
        if (rows > 0) {
            return R.ok();
        }
        return R.fail("修改个人信息异常，请联系管理员");
    }

    /**
     * 当前登录人员电子签名信息
     */
    @GetMapping("/electronic-signature/info")
    public R<SysUserElectronicSignatureVo> electronicSignatureInfo() {
        return R.ok(userElectronicSignatureService.getCurrentUserSignature());
    }

    /**
     * 获取当前登录人员可直接用于业务回填的电子签名
     */
    @GetMapping("/electronic-signature/current")
    public R<SysUserElectronicSignatureVo> currentElectronicSignature() {
        SysUserElectronicSignatureVo vo = userElectronicSignatureService.getCurrentUserSignature();
        if (Boolean.FALSE.equals(vo.getConfigured())) {
            return R.fail("暂未设置电子签名，请在个人资料内设置后重试或使用手动签名");
        }
        return R.ok(vo);
    }

    /**
     * 保存当前登录人员电子签名
     */
    @RepeatSubmit
    @Log(title = "电子签名", businessType = BusinessType.UPDATE)
    @PutMapping("/electronic-signature")
    public R<SysUserElectronicSignatureVo> saveElectronicSignature(@Validated @RequestBody SysUserElectronicSignatureBo bo) {
        return R.ok(userElectronicSignatureService.saveCurrentUserSignature(bo));
    }

    /**
     * 清空当前登录人员电子签名
     */
    @RepeatSubmit
    @Log(title = "电子签名", businessType = BusinessType.UPDATE)
    @DeleteMapping("/electronic-signature")
    public R<Void> clearElectronicSignature() {
        return toAjax(userElectronicSignatureService.clearCurrentUserSignature());
    }

    /**
     * 重置密码
     *
     * @param bo 新旧密码
     */
    @RepeatSubmit
    @ApiEncrypt
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public R<Void> updatePwd(@Validated @RequestBody SysUserPasswordBo bo) {
        Long userId = LoginHelper.getUserId();
        // 如果是超级管理员，走原来的密码修改逻辑
        if (LoginHelper.isSuperAdmin(userId)) {
            SysUserVo user = userService.selectUserById(userId);
            String password = user.getPassword();
            if (!BCrypt.checkpw(bo.getOldPassword(), password)) {
                return R.fail("修改密码失败，旧密码错误");
            }
            if (BCrypt.checkpw(bo.getNewPassword(), password)) {
                return R.fail("新密码不能与旧密码相同");
            }
            int rows = DataPermissionHelper.ignore(() -> userService.resetUserPwd(user.getUserId(), BCrypt.hashpw(bo.getNewPassword()), null));
            if (rows > 0) {
                return R.ok();
            }
            return R.fail("修改密码异常，请联系管理员");
        }

        // 普通用户，修改当前登录端口的子密码
        // 优先使用前端传来的 portId
        Long targetPortId = bo.getPortId();
        if (targetPortId == null) {
            targetPortId = LoginHelper.getLoginUser().getCompanyRoleId();
        }

        if (targetPortId == null) {
            return R.fail("无法确定修改的目标企业，请指定portId");
        }

        return updateSubPwd(bo, targetPortId);
    }

    /**
     * 修改子密码
     *
     * @param bo     新旧密码
     * @param portId 端口ID
     */
    @RepeatSubmit
    @ApiEncrypt
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateSubPwd")
    public R<Void> updateSubPwd(@Validated @RequestBody SysUserPasswordBo bo, @RequestParam(required = false) Long portId) {
        Long userId = LoginHelper.getUserId();
        Long targetPortId = portId;
        if (targetPortId == null) {
            targetPortId = LoginHelper.getLoginUser().getCompanyRoleId();
        }
        if (targetPortId == null) {
            return R.fail("无法确定修改的目标企业，请指定portId");
        }

        // Fetch port
        SysUserLoginPort port = sysUserLoginPortService.getById(targetPortId);
        if (port == null || !port.getUserId().equals(userId)) {
            return R.fail("未找到对应企业端口或无权修改");
        }

        // Check old password
        String currentSubPwd = port.getSubPassword();
        if (StringUtils.isBlank(currentSubPwd)) {
            // 如果没有设置子密码，视为未设置密码或无法修改（需根据业务决定，这里假设必须先有子密码）
            // 或者，如果为空，允许直接设置？
            // 考虑到用户迁移，如果为空，可能允许使用空密码验证？或者要求联系管理员重置。
            // 这里遵循用户指令：完全依赖子密码。如果为空，可能无法通过旧密码验证。
            // 但为了首次设置，如果为空，允许旧密码为空？
            if (StringUtils.isNotBlank(bo.getOldPassword())) {
                return R.fail("修改密码失败，旧密码错误");
            }
        } else {
            if (!BCrypt.checkpw(bo.getOldPassword(), currentSubPwd)) {
                return R.fail("修改密码失败，旧密码错误");
            }
        }

        if (BCrypt.checkpw(bo.getNewPassword(), currentSubPwd)) {
            return R.fail("新密码不能与旧密码相同");
        }

        // Update
        port.setSubPassword(BCrypt.hashpw(bo.getNewPassword()));
        sysUserLoginPortService.updateById(port);

        return R.ok();
    }

    /**
     * 头像上传
     *
     * @param avatarfile 用户头像
     */
    @RepeatSubmit
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<AvatarVo> avatar(@RequestPart("avatarfile") MultipartFile avatarfile) {
        if (!avatarfile.isEmpty()) {
            String extension = FileUtil.extName(avatarfile.getOriginalFilename());
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION)) {
                return R.fail("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            SysOssVo oss = ossService.upload(avatarfile);
            String avatar = oss.getUrl();
            boolean updateSuccess = DataPermissionHelper.ignore(() -> userService.updateUserAvatar(LoginHelper.getUserId(), oss.getOssId()));
            if (updateSuccess) {
                return R.ok(new AvatarVo(avatar));
            }
        }
        return R.fail("上传图片异常，请联系管理员");
    }

    /**
     * 用户头像信息
     *
     * @param imgUrl 头像地址
     */
    public record AvatarVo(String imgUrl) {}

    /**
     * 用户个人信息
     *
     * @param user      用户信息
     * @param roleGroup 用户所属角色组
     * @param postGroup 用户所属岗位组
     */
    public record ProfileVo(ProfileUserVo user, String roleGroup, String postGroup) {}

}
