package com.ruoyi.web.modules.trading.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;

/**
 * 为供应商/承销商创建平台账号并绑定角色。
 */
@Component
public class TradePartnerAccountAssigner
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 登录名：名称汉字拼音首字母 + 主键 id；角色按 {@code roleKey} 解析。
     */
    public SysUser createAccount(String partnerName, String contactPhone, Long partnerId, String roleKey,
            String operator)
    {
        String loginName = TradingPartnerLoginNameGenerator.generate(partnerName, partnerId);
        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(partnerName);
        user.setPhonenumber(contactPhone);
        user.setPassword(SecurityUtils.encryptPassword(initPwd));
        user.setStatus("0");
        user.setCreateBy(operator);
        user.setRoleIds(new Long[] { resolveRoleId(roleKey) });
        int rows = sysUserService.insertUser(user);
        if (rows <= 0 || user.getUserId() == null)
        {
            throw new ServiceException("账号创建失败：用户保存失败");
        }
        return user;
    }

    public void deleteLinkedAccount(Integer accountAssigned, Long sysUserId)
    {
        if (accountAssigned == null
                || accountAssigned != TradePartnerAccountRules.ACCOUNT_ASSIGNED_YES
                || sysUserId == null)
        {
            return;
        }
        sysUserService.deleteUserById(sysUserId);
    }

    private long resolveRoleId(String roleKey)
    {
        if (StringUtils.isEmpty(roleKey))
        {
            throw new ServiceException(String.format(TradePartnerAccountRules.MSG_ROLE_NOT_FOUND, ""));
        }
        SysRole role = sysRoleMapper.checkRoleKeyUnique(roleKey.trim());
        if (role == null || role.getRoleId() == null)
        {
            throw new ServiceException(String.format(TradePartnerAccountRules.MSG_ROLE_NOT_FOUND, roleKey));
        }
        return role.getRoleId();
    }
}
