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.QueryWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.dao.DuplicateKeyException;
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.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.system.entity.SysAccount;
import tech.easyflow.system.entity.vo.SysAccountBatchActionResultVo;
import tech.easyflow.system.entity.vo.SysAccountImportResultVo;
import tech.easyflow.system.service.SysAccountService;
import tech.easyflow.system.util.SysPasswordPolicy;

import java.io.Serializable;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 用户表 控制层。
 *
 * @author ArkLight
 * @since 2025-03-14
 */
@RestController("sysAccountController")
@RequestMapping("/api/v1/sysAccount")
public class SysAccountController extends BaseCurdController<SysAccountService, SysAccount> {
    private final AuthCredentialKeyService credentialKeyService;

    public SysAccountController(SysAccountService service, AuthCredentialKeyService credentialKeyService) {
        super(service);
        this.credentialKeyService = credentialKeyService;
    }

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

    @Override
    protected Result onSaveOrUpdateBefore(SysAccount entity, boolean isSave) {
        LoginAccount loginUser = SaTokenUtil.getLoginAccount();
        BigInteger tenantId = loginUser.getTenantId();
        if (isSave) {
            commonFiled(entity, loginUser.getId(), tenantId, loginUser.getDeptId());
            // 查询用户名是否存在
            // 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, "用户名已存在");
            }
            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;
    }

    @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);
    }

    @GetMapping("/myProfile")
    public Result<SysAccount> myProfile() {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        SysAccount sysAccount = service.getById(account.getId());
        return Result.ok(sysAccount);
    }

    @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 加密后的旧密码、新密码与确认密码
     */
    @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();
        SysAccount record = service.getById(loginAccountId);
        if (record == null) {
            return Result.fail("修改失败");
        }
        String pwdDb = record.getPassword();
        if (!BCrypt.checkpw(password, pwdDb)) {
            return Result.fail(1, "密码不正确");
        }
        if (!newPassword.equals(confirmPassword)) {
            return Result.fail(2, "两次密码不一致");
        }
        SysPasswordPolicy.validateStrongPassword(newPassword);
        SysAccount update = new SysAccount();
        update.setId(loginAccountId);
        update.setPassword(BCrypt.hashpw(newPassword));
        update.setPasswordResetRequired(false);
        update.setModified(new Date());
        update.setModifiedBy(loginAccountId);
        service.updateById(update);
        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);
    }

    @PostMapping("/resetPassword")
    @SaCheckPermission("/api/v1/sysAccount/save")
    public Result<Void> resetPassword(@JsonBody(value = "id", required = true) BigInteger id) {
        service.resetPassword(id, SaTokenUtil.getLoginAccount().getId());
        return Result.ok();
    }

    @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());
    }

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