package com.ruoyi.web.modules.diagnosis.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.diagnosis.domain.BizMedicalResource;

/**
 * 为兽医/机构资源创建平台账号并绑定角色。
 */
@Component
public class MedicalResourceAccountAssigner
{
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    public SysUser createAccount(BizMedicalResource resource, String operator)
    {
        String loginName = MedicalResourceLoginNameGenerator.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());
        if (resource.getTownDeptId() != null)
        {
            user.setDeptId(resource.getTownDeptId());
        }
        user.setPassword(SecurityUtils.encryptPassword(initPwd));
        user.setStatus("0");
        user.setCreateBy(operator);
        user.setRoleIds(new Long[] { resolveRoleId(resource.getResourceType()) });
        int rows = sysUserService.insertUser(user);
        if (rows <= 0 || user.getUserId() == null)
        {
            throw new ServiceException("账号创建失败：用户保存失败");
        }
        return user;
    }

    /**
     * 已分配账号时，将所属乡镇同步到 sys_user.dept_id（可为空以清空）。
     */
    public void syncLinkedUserDept(BizMedicalResource resource)
    {
        if (resource == null
                || resource.getAccountAssigned() == null
                || resource.getAccountAssigned() != MedicalResourceRules.ACCOUNT_ASSIGNED_YES
                || resource.getSysUserId() == null)
        {
            return;
        }
        SysUser user = new SysUser();
        user.setUserId(resource.getSysUserId());
        user.setDeptId(resource.getTownDeptId());
        sysUserService.updateUserProfile(user);
    }

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

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