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

import java.math.BigDecimal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
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.service.ISysUserService;
import com.ruoyi.web.modules.account.constant.MemberConstants;
import com.ruoyi.web.modules.account.domain.BizMember;
import com.ruoyi.web.modules.account.dto.MemberCreateDTO;
import com.ruoyi.web.modules.account.mapper.BizMemberMapper;
import com.ruoyi.web.modules.account.util.UserNameGenerator;

/**
 * 会员注册/创建（C 端与平台端共用：先 sys_user + 角色 member，再 biz_member）
 */
@Component
public class MemberRegistrationSupport
{
    @Autowired
    private BizMemberMapper memberMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private MemberSysUserSupport memberSysUserSupport;

    @Transactional(rollbackFor = Exception.class)
    public Long createMember(MemberCreateDTO dto, String operator)
    {
        validateCreate(dto);
        if (memberMapper.countByMobile(dto.getMobile(), null) > 0)
        {
            throw new ServiceException("手机号已注册");
        }

        String memberName = StringUtils.isNotEmpty(dto.getMemberCode()) ? dto.getMemberCode() : generateUniqueMemberName();
        String nickName = StringUtils.isEmpty(dto.getNickName()) ? memberName : dto.getNickName();
        String status = StringUtils.isEmpty(dto.getStatus()) ? MemberConstants.STATUS_ENABLED : dto.getStatus();
        if (!MemberConstants.STATUS_ENABLED.equals(status) && !MemberConstants.STATUS_DISABLED.equals(status))
        {
            throw new ServiceException("状态参数无效");
        }

        SysUser sysUser = new SysUser();
        sysUser.setDeptId(MemberSysUserSupport.DEFAULT_DEPT_ID);
        sysUser.setUserName(memberName);
        sysUser.setNickName(nickName);
        sysUser.setPhonenumber(dto.getMobile());
        sysUser.setPassword(SecurityUtils.encryptPassword(dto.getPassword()));
        sysUser.setAvatar(StringUtils.isNotEmpty(dto.getAvatar()) ? dto.getAvatar() : null);
        sysUser.setStatus(status);
        sysUser.setCreateBy(operator);
        Long memberRoleId = memberSysUserSupport.resolveMemberRoleId();
        sysUser.setRoleIds(new Long[] { memberRoleId });
        if (!sysUserService.checkUserNameUnique(sysUser))
        {
            throw new ServiceException("会员名称已存在");
        }
        if (!sysUserService.checkPhoneUnique(sysUser))
        {
            throw new ServiceException("手机号已注册");
        }
        sysUserService.insertUser(sysUser);

        BizMember member = new BizMember();
        member.setMemberId(sysUser.getUserId());
        member.setMemberLevel(dto.getMemberLevel());
        member.setOrderCount(0);
        member.setTotalAmount(BigDecimal.ZERO);
        member.setRegisterTime(new Date());
        member.setRemark(dto.getRemark());
        member.setCreateBy(operator);
        memberMapper.insert(member);
        return member.getMemberId();
    }

    public String generateUniqueMemberName()
    {
        String memberName;
        do
        {
            memberName = UserNameGenerator.generateUniqueName();
        } while (memberMapper.countByByMemberName(memberName) > 0
                || sysUserService.selectUserByUserName(memberName) != null);
        return memberName;
    }

    private void validateCreate(MemberCreateDTO dto)
    {
        if (dto == null || StringUtils.isEmpty(dto.getMobile()))
        {
            throw new ServiceException("请输入手机号");
        }
        if (StringUtils.isEmpty(dto.getPassword()))
        {
            throw new ServiceException("请输入密码");
        }
        if (!dto.getMobile().matches("^1\\d{10}$"))
        {
            throw new ServiceException("手机号格式不正确");
        }
        if (StringUtils.isNotEmpty(dto.getMemberCode()) && dto.getMemberCode().length() > 64)
        {
            throw new ServiceException("会员名称过长");
        }
        if (StringUtils.isNotEmpty(dto.getNickName()) && dto.getNickName().length() > 64)
        {
            throw new ServiceException("昵称过长");
        }
    }
}
