package com.ruoyi.web.modules.farming.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.modules.farming.domain.BizTechResource;

/**
 * 为专家资源创建平台账号并绑定角色。
 */
@Component
public class TechResourceAccountAssigner
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    public SysUser createAccount(BizTechResource resource, String operator)
    {
        String loginName = TechResourceLoginNameGenerator.generate(
                resource.getResourceName(), resource.getId());
        SysUser probe = new SysUser();
        probe.setUserName(loginName);
        if (!sysUserService.checkUserNameUnique(probe))
        {
            throw new ServiceException("账号创建失败：登录名已存在");
        }
        String initPwd = configService.selectConfigByKey("sys.user.initPassword");
        if (StringUtils.isEmpty(initPwd))
        {
            initPwd = "123456";
        }
        SysUser user = new SysUser();
        user.setUserName(loginName);
        user.setNickName(resource.getResourceName());
        user.setPhonenumber(resource.getContactPhone());
        user.setPassword(SecurityUtils.encryptPassword(initPwd));
        user.setStatus("0");
        user.setCreateBy(operator);
        user.setRoleIds(new Long[] { resolveRoleId() });
        int rows = sysUserService.insertUser(user);
        if (rows <= 0 || user.getUserId() == null)
        {
            throw new ServiceException("账号创建失败：用户保存失败");
        }
        return user;
    }

    /**
     * 逻辑删除资源时，若专家已分配平台账号则一并删除（草稿 §10）。
     */
    public void deleteLinkedAccount(BizTechResource resource)
    {
        if (resource == null
                || resource.getAccountAssigned() == null
                || resource.getAccountAssigned() != TechResourceRules.ACCOUNT_ASSIGNED_YES
                || resource.getSysUserId() == null)
        {
            return;
        }
        sysUserService.deleteUserById(resource.getSysUserId());
    }

    private long resolveRoleId()
    {
        SysRole role = sysRoleMapper.checkRoleKeyUnique(TechResourceRules.ROLE_KEY_EXPERT);
        if (role == null || role.getRoleId() == null)
        {
            throw new ServiceException(String.format(TechResourceRules.MSG_ROLE_NOT_FOUND,
                    TechResourceRules.ROLE_KEY_EXPERT));
        }
        return role.getRoleId();
    }
}
