package tech.easyflow.admin.controller.system;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.alibaba.fastjson2.JSONObject;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import tech.easyflow.auth.entity.EncryptedCredentialDTO;
import tech.easyflow.auth.service.AuthCredentialKeyService;
import tech.easyflow.auth.service.AuthService;
import tech.easyflow.common.constant.Constants;
import tech.easyflow.common.constant.enums.EnumAccountType;
import tech.easyflow.common.constant.enums.EnumDataStatus;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.util.StringUtil;
import tech.easyflow.common.web.controller.BaseCurdController;
import tech.easyflow.common.web.jsonbody.JsonBody;
import tech.easyflow.log.annotation.LogRecord;
import tech.easyflow.admin.controller.system.vo.SysAccountProfileVo;
import tech.easyflow.admin.model.SystemFormOptionsView;
import tech.easyflow.admin.service.system.SystemFormOptionService;
import tech.easyflow.system.entity.SysAccount;
import tech.easyflow.system.entity.SysRole;
import tech.easyflow.system.entity.vo.SysAccountBatchActionResultVo;
import tech.easyflow.system.entity.vo.SysAccountImportResultVo;
import tech.easyflow.system.service.SysAccountService;
import tech.easyflow.system.service.SysRoleService;
import tech.easyflow.system.util.SysPasswordPolicy;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import static tech.easyflow.system.entity.table.SysAccountRoleTableDef.SYS_ACCOUNT_ROLE;
import static tech.easyflow.system.entity.table.SysAccountTableDef.SYS_ACCOUNT;
import static tech.easyflow.system.entity.table.SysRoleTableDef.SYS_ROLE;

/**
 * 用户表 控制层。
 *
 * @author ArkLight
 * @since 2025-03-14
 */
@RestController("sysAccountController")
@RequestMapping("/api/v1/sysAccount")
public class SysAccountController extends BaseCurdController<SysAccountService, SysAccount> {
    private static final String ACCOUNT_SEARCH_KEYWORD_PARAM = "keyword";
    private static final String SUPER_ADMIN_HOME_PATH = "/dashboard/workspace";
    private static final String USER_HOME_PATH = "/ai/agent-chat";

    private final AuthCredentialKeyService credentialKeyService;
    private final SysRoleService sysRoleService;
    private final SystemFormOptionService systemFormOptionService;
    @Resource
    private AuthService authService;

    /**
     * 创建用户管理控制器。
     *
     * @param service 用户服务
     * @param credentialKeyService 凭证密钥服务
     * @param sysRoleService 角色服务
     * @param systemFormOptionService 用户表单安全选项服务
     */
    public SysAccountController(SysAccountService service,
                                AuthCredentialKeyService credentialKeyService,
                                SysRoleService sysRoleService,
                                SystemFormOptionService systemFormOptionService) {
        super(service);
        this.credentialKeyService = credentialKeyService;
        this.sysRoleService = sysRoleService;
        this.systemFormOptionService = systemFormOptionService;
    }

    /**
     * 构造账号列表查询条件。
     *
     * <p>统一关键字同时匹配账号、昵称、电话、邮件和已关联角色名称。角色条件使用相关
     * {@code EXISTS} 子查询，避免多角色关联导致分页记录重复。</p>
     *
     * @param request 当前 HTTP 请求
     * @return 账号列表查询条件
     */
    @Override
    protected QueryWrapper buildQueryWrapper(HttpServletRequest request) {
        String keyword = request.getParameter(ACCOUNT_SEARCH_KEYWORD_PARAM);
        if (!StringUtil.hasText(keyword)) {
            return super.buildQueryWrapper(request);
        }

        String likePattern = buildLiteralContainsPattern(normalizeSearchKeyword(keyword));
        QueryWrapper roleExistsQuery = QueryMethods.selectOne()
                .from(SYS_ACCOUNT_ROLE)
                .innerJoin(SYS_ROLE)
                .on(SYS_ACCOUNT_ROLE.ROLE_ID.eq(SYS_ROLE.ID))
                .where(SYS_ACCOUNT_ROLE.ACCOUNT_ID.eq(SYS_ACCOUNT.ID))
                // 关联角色必须与账号属于同一租户，避免异常关系数据跨租户命中。
                .and(SYS_ROLE.TENANT_ID.eq(SYS_ACCOUNT.TENANT_ID))
                .and(SYS_ROLE.ROLE_NAME.likeRaw(likePattern));
        QueryCondition keywordCondition = SYS_ACCOUNT.LOGIN_NAME.likeRaw(likePattern)
                .or(SYS_ACCOUNT.NICKNAME.likeRaw(likePattern))
                .or(SYS_ACCOUNT.MOBILE.likeRaw(likePattern))
                .or(SYS_ACCOUNT.EMAIL.likeRaw(likePattern))
                .or(QueryMethods.exists(roleExistsQuery));

        return super.buildQueryWrapper(request).and(keywordCondition);
    }

    @Override
    @LogRecord("分页查询")
    protected Page<SysAccount> queryPage(Page<SysAccount> page, QueryWrapper queryWrapper) {
        Page<SysAccount> result = service.getMapper().paginateWithRelations(page, queryWrapper);
        fillRoleNames(result.getRecords());
        return result;
    }

    /**
     * 按当前分页内的角色 ID 批量补全角色名称。
     *
     * @param accounts 当前页账号
     */
    private void fillRoleNames(List<SysAccount> accounts) {
        if (accounts == null || accounts.isEmpty()) {
            return;
        }
        Set<BigInteger> roleIds = accounts.stream()
                .map(SysAccount::getRoleIds)
                .filter(java.util.Objects::nonNull)
                .flatMap(Collection::stream)
                .filter(java.util.Objects::nonNull)
                .collect(Collectors.toCollection(LinkedHashSet::new));
        if (roleIds.isEmpty()) {
            accounts.forEach(account -> account.setRoleNames(List.of()));
            return;
        }

        Map<BigInteger, String> roleNameMap = sysRoleService.listByIds(roleIds).stream()
                .filter(role -> role.getId() != null && StringUtil.hasText(role.getRoleName()))
                .collect(Collectors.toMap(
                        SysRole::getId,
                        SysRole::getRoleName,
                        (first, ignored) -> first
                ));
        accounts.forEach(account -> {
            List<BigInteger> accountRoleIds = account.getRoleIds();
            if (accountRoleIds == null || accountRoleIds.isEmpty()) {
                account.setRoleNames(List.of());
                return;
            }
            List<String> roleNames = accountRoleIds.stream()
                    .map(roleNameMap::get)
                    .filter(StringUtil::hasText)
                    .distinct()
                    .collect(Collectors.toList());
            account.setRoleNames(roleNames);
        });
    }

    @Override
    protected Result onSaveOrUpdateBefore(SysAccount entity, boolean isSave) {
        systemFormOptionService.validateAccountReferences(entity);
        LoginAccount loginUser = SaTokenUtil.getLoginAccount();
        if (isSave) {
            // 查询用户名是否存在
            // long count = Db.selectCount(SqlPrepare.COUNT_ACCOUNT_BY_UNI_KEY, entity.getLoginName(), tenantId);
            QueryWrapper w = QueryWrapper.create();
            w.eq(SysAccount::getLoginName, entity.getLoginName());
            long count = service.count(w);
            if (count > 0) {
                return Result.fail(1, "用户名已存在");
            }
            Result<?> roleValidation = validateCreateRoles(entity);
            if (roleValidation != null) {
                return roleValidation;
            }
            String password = decryptInitialPassword(entity.getPasswordCredential());
            if (!StringUtil.hasText(password)) {
                return Result.fail(1, "密码不能为空");
            }
            SysPasswordPolicy.validateStrongPassword(password);
            entity.setPassword(BCrypt.hashpw(password));
            Integer status = entity.getStatus();
            if (status == null) {
                entity.setStatus(EnumDataStatus.AVAILABLE.getCode());
            }
            if (entity.getAccountType() == null) {
                entity.setAccountType(EnumAccountType.NORMAL.getCode());
            }
            if (entity.getPasswordResetRequired() == null) {
                entity.setPasswordResetRequired(false);
            }
        } else {
            SysAccount record = service.getById(entity.getId());
            // 如果修改了部门，就将用户踢下线，避免用户操作数据造成数据错误
            if (record.getDeptId() != null && !record.getDeptId().equals(entity.getDeptId())) {
                StpUtil.kickout(record.getId());
            }
            // 不让修改用户名/密码，浏览器记住密码有可能会带上来
            entity.setLoginName(null);
            entity.setPassword(null);
            entity.setModified(new Date());
            entity.setModifiedBy(loginUser.getId());
        }
        return null;
    }

    /**
     * 查询账号表单所需的部门、角色和岗位选项。
     *
     * @return 账号表单安全选项
     */
    @GetMapping("/formOptions")
    @SaCheckPermission("/api/v1/sysAccount/save")
    public Result<SystemFormOptionsView.AccountFormOptions> formOptions() {
        return Result.ok(systemFormOptionService.accountFormOptions());
    }

    /**
     * 填充账号创建的公共字段。
     *
     * <p>账号部门由管理端表单指定；只有未提交部门时才沿用通用创建流程的默认部门。</p>
     *
     * @param entity 待创建的账号
     * @param loginAccount 当前登录账号
     */
    @Override
    protected void fillCreateCommonFields(SysAccount entity, LoginAccount loginAccount) {
        BigInteger selectedDeptId = entity.getDeptId();
        super.fillCreateCommonFields(entity, loginAccount);
        if (selectedDeptId != null) {
            entity.setDeptId(selectedDeptId);
        }
    }

    @Override
    protected void onSaveOrUpdateAfter(SysAccount entity, boolean isSave) {
        service.syncRelations(entity);
    }

    @Override
    protected Result onRemoveBefore(Collection<Serializable> ids) {
        List<SysAccount> sysAccounts = service.listByIds(ids);
        for (SysAccount account : sysAccounts) {
            Integer accountType = account.getAccountType();
            if (EnumAccountType.SUPER_ADMIN.getCode().equals(accountType)) {
                return Result.fail(1, "不能删除超级管理员");
            }
            if (EnumAccountType.TENANT_ADMIN.getCode().equals(accountType)) {
                return Result.fail(1, "不能删除租户管理员");
            }
        }
        return super.onRemoveBefore(ids);
    }

    /**
     * 获取当前账号资料、角色标识与默认首页。
     *
     * @return 当前账号资料视图
     */
    @GetMapping("/myProfile")
    public Result<SysAccountProfileVo> myProfile() {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        SysAccount sysAccount = service.getById(account.getId());
        List<String> roles = sysRoleService.getRolesByAccountId(account.getId()).stream()
                .map(SysRole::getRoleKey)
                .filter(StringUtil::hasText)
                .distinct()
                .collect(Collectors.toList());
        String homePath = roles.contains(Constants.SUPER_ADMIN_ROLE_CODE)
                ? SUPER_ADMIN_HOME_PATH
                : USER_HOME_PATH;
        return Result.ok(SysAccountProfileVo.from(sysAccount, roles, homePath));
    }

    @PostMapping("/updateProfile")
    public Result<Void> updateProfile(@JsonBody SysAccount account) {
        BigInteger loginAccountId = SaTokenUtil.getLoginAccount().getId();
        SysAccount update = new SysAccount();
        update.setId(loginAccountId);
        update.setNickname(account.getNickname());
        update.setMobile(account.getMobile());
        update.setEmail(account.getEmail());
        update.setAvatar(account.getAvatar());
        update.setModified(new Date());
        update.setModifiedBy(loginAccountId);
        service.updateById(update);
        return Result.ok();
    }

    /**
     * 修改密码，用于修改用户自己的密码
     *
     * @param encryptedCredential 加密后的当前密码、新密码与确认密码
     * @return 密码修改结果
     */
    @PostMapping("/updatePassword")
    public Result<Void> updatePassword(@JsonBody EncryptedCredentialDTO encryptedCredential) {
        JSONObject payload = credentialKeyService.decryptPayload(encryptedCredential);
        String password = payload.getString("password");
        String newPassword = payload.getString("newPassword");
        String confirmPassword = payload.getString("confirmPassword");
        BigInteger loginAccountId = SaTokenUtil.getLoginAccount().getId();
        authService.updateOwnPassword(
                loginAccountId,
                password,
                newPassword,
                confirmPassword,
                StpUtil.getLoginDevice()
        );
        return Result.ok();
    }

    private String decryptInitialPassword(Map<String, Object> passwordCredential) {
        if (passwordCredential == null || passwordCredential.isEmpty()) {
            return null;
        }
        JSONObject payload = credentialKeyService.decryptPayload(toEncryptedCredential(passwordCredential));
        return payload.getString("password");
    }

    private EncryptedCredentialDTO toEncryptedCredential(Map<String, Object> passwordCredential) {
        EncryptedCredentialDTO encryptedCredential = new EncryptedCredentialDTO();
        encryptedCredential.setKeyId(asString(passwordCredential.get("keyId")));
        encryptedCredential.setEncryptedKey(asString(passwordCredential.get("encryptedKey")));
        encryptedCredential.setIv(asString(passwordCredential.get("iv")));
        encryptedCredential.setCiphertext(asString(passwordCredential.get("ciphertext")));
        encryptedCredential.setNonce(asString(passwordCredential.get("nonce")));
        return encryptedCredential;
    }

    private String asString(Object value) {
        return value == null ? null : String.valueOf(value);
    }

    /**
     * 将指定账号密码重置为系统默认强密码。
     *
     * @param id 账号 ID
     * @return 本次重置后使用的明文密码
     */
    @PostMapping("/resetPassword")
    @SaCheckPermission("/api/v1/sysAccount/save")
    public Result<String> resetPassword(@JsonBody(value = "id", required = true) BigInteger id) {
        String password = service.resetPassword(id, SaTokenUtil.getLoginAccount().getId());
        return Result.ok(password);
    }

    @PostMapping("/removeBatchWithResult")
    @SaCheckPermission("/api/v1/sysAccount/remove")
    @LogRecord("批量删除用户")
    public Result<SysAccountBatchActionResultVo> removeBatchWithResult(
            @JsonBody(value = "ids", required = true) List<BigInteger> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.fail("ids不能为空", null);
        }
        return Result.ok(service.removeBatchWithResult(ids));
    }

    @PostMapping("/resetPasswordBatch")
    @SaCheckPermission("/api/v1/sysAccount/save")
    @LogRecord("批量重置用户密码")
    public Result<SysAccountBatchActionResultVo> resetPasswordBatch(
            @JsonBody(value = "ids", required = true) List<BigInteger> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.fail("ids不能为空", null);
        }
        return Result.ok(service.resetPasswordBatch(ids, SaTokenUtil.getLoginAccount().getId()));
    }

    @PostMapping("/importExcel")
    @SaCheckPermission("/api/v1/sysAccount/save")
    public Result<SysAccountImportResultVo> importExcel(MultipartFile file) {
        return Result.ok(service.importAccounts(file, SaTokenUtil.getLoginAccount()));
    }

    @GetMapping("/downloadImportTemplate")
    @SaCheckPermission("/api/v1/sysAccount/query")
    public void downloadImportTemplate(HttpServletResponse response) throws Exception {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("user_import_template", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        service.writeImportTemplate(response.getOutputStream());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @PostMapping("save")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> save(@JsonBody SysAccount entity) {
        try {
            return super.save(entity);
        } catch (DuplicateKeyException e) {
            return Result.fail(1, "用户名已存在");
        }
    }

    /**
     * 校验创建账号时提交的角色，并归一化角色 ID。
     *
     * @param entity 待创建账号
     * @return 校验失败结果，校验通过返回 null
     */
    private Result<?> validateCreateRoles(SysAccount entity) {
        List<BigInteger> roleIds = entity == null ? null : entity.getRoleIds();
        Set<BigInteger> uniqueRoleIds = new LinkedHashSet<>();
        if (roleIds != null) {
            roleIds.stream()
                    .filter(java.util.Objects::nonNull)
                    .forEach(uniqueRoleIds::add);
        }
        if (uniqueRoleIds.isEmpty()) {
            return Result.fail(1, "角色不能为空");
        }

        List<SysRole> roles = sysRoleService.listByIds(uniqueRoleIds);
        boolean valid = roles.size() == uniqueRoleIds.size()
                && roles.stream().allMatch(role ->
                EnumDataStatus.AVAILABLE.getCode().equals(role.getStatus()));
        if (!valid) {
            return Result.fail(1, "角色不存在或已禁用");
        }
        entity.setRoleIds(new ArrayList<>(uniqueRoleIds));
        return null;
    }
}
