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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.account.constant.MerchantEmployeeConstants;
import com.ruoyi.web.modules.account.domain.MerchantEmployeeRow;
import com.ruoyi.web.modules.account.dto.MerchantEmployeeCreateDTO;
import com.ruoyi.web.modules.account.dto.MerchantEmployeePasswordDTO;
import com.ruoyi.web.modules.account.dto.MerchantEmployeeProfileDTO;
import com.ruoyi.web.modules.account.dto.MerchantEmployeeUpdateDTO;
import com.ruoyi.web.modules.account.mapper.MerchantEmployeeMapper;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.store.domain.BizMerchantAccount;
import com.ruoyi.web.modules.store.domain.BizShop;
import com.ruoyi.web.modules.store.facade.IShopGlobalConfigFacade;
import com.ruoyi.web.modules.store.mapper.BizMerchantAccountMapper;
import com.ruoyi.web.modules.store.mapper.BizShopMapper;

/**
 * 员工管理校验与上下文
 */
@Component
public class MerchantEmployeeSupport
{
    @Autowired
    private BizMerchantAccountMapper merchantAccountMapper;

    @Autowired
    private MerchantEmployeeMapper merchantEmployeeMapper;

    @Autowired
    private BizShopMapper shopMapper;

    @Autowired
    private IShopGlobalConfigFacade shopGlobalConfigFacade;

    public Long requireMerchantId(Long operatorUserId)
    {
        BizMerchantAccount admin = merchantAccountMapper.selectMerchantAdminByUserId(operatorUserId);
        if (admin == null)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_MERCHANT_ADMIN_ONLY);
        }
        return admin.getMerchantId();
    }

    public Long requireCurrentShopId(Long merchantId)
    {
        Long shopId = SellerShopContext.getShopId();
        if (shopId == null || shopId <= 0)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_SHOP_CONTEXT_REQUIRED);
        }
        assertShopBelongsToMerchant(merchantId, shopId);
        return shopId;
    }

    public void assertQuotaAvailable(Long merchantId)
    {
        int used = merchantAccountMapper.countEmployeesByMerchantId(merchantId);
        Integer max = shopGlobalConfigFacade.getMaxSubAdmin();
        if (max == null)
        {
            max = 5;
        }
        if (used >= max)
        {
            throw new ServiceException(String.format(MerchantEmployeeConstants.MSG_QUOTA_EXCEEDED, max));
        }
    }

    public MerchantEmployeeRow requireEmployeeRow(Long merchantId, Long shopId, Long userId)
    {
        MerchantEmployeeRow row = merchantEmployeeMapper.selectByUserId(merchantId, shopId, userId);
        if (row == null)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_NOT_FOUND);
        }
        if (!row.isEmployee())
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_CANNOT_OPERATE_ADMIN);
        }
        return row;
    }

    public void assertShopBelongsToMerchant(Long merchantId, Long shopId)
    {
        if (shopId == null)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_SHOP_INVALID);
        }
        BizShop shop = shopMapper.selectById(shopId);
        if (shop == null || !"0".equals(shop.getDelFlag()) || !merchantId.equals(shop.getMerchantId()))
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_SHOP_INVALID);
        }
    }

    public void assertRolesBelongToShop(Long shopId, Long[] roleIds)
    {
        if (roleIds == null || roleIds.length == 0)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_ROLE_REQUIRED);
        }
        int valid = merchantEmployeeMapper.countValidShopRoles(shopId, roleIds);
        if (valid != roleIds.length)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_ROLE_INVALID);
        }
    }

    public void validateCreate(MerchantEmployeeCreateDTO dto, Long shopId)
    {
        if (dto == null)
        {
            throw new ServiceException("参数不能为空");
        }
        validateEmployeeName(dto.getEmployeeName());
        validateMobile(dto.getMobile());
        validateEmail(dto.getEmail());
        validateStatus(dto.getStatus());
        assertRolesBelongToShop(shopId, dto.getRoleIds());
    }

    public void validateUpdate(MerchantEmployeeUpdateDTO dto, Long shopId)
    {
        if (dto == null || dto.getUserId() == null)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_NOT_FOUND);
        }
        validateEmployeeName(dto.getEmployeeName());
        validateMobile(dto.getMobile());
        validateEmail(dto.getEmail());
        validateStatus(dto.getStatus());
        assertRolesBelongToShop(shopId, dto.getRoleIds());
    }

    public void validateProfile(MerchantEmployeeProfileDTO dto)
    {
        if (dto == null || dto.getUserId() == null)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_NOT_FOUND);
        }
        validateEmployeeName(dto.getEmployeeName());
        validateMobile(dto.getMobile());
        validateEmail(dto.getEmail());
    }

    public void validatePasswordUpdate(MerchantEmployeePasswordDTO dto)
    {
        if (dto == null || dto.getUserId() == null)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_NOT_FOUND);
        }
        if (StringUtils.isEmpty(dto.getPassword()))
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_PASSWORD_REQUIRED);
        }
        if (StringUtils.isEmpty(dto.getConfirmPassword())
                || !dto.getPassword().equals(dto.getConfirmPassword()))
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_PASSWORD_MISMATCH);
        }
        if (dto.getPassword().length() < MerchantEmployeeConstants.MIN_PASSWORD_LENGTH)
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_PASSWORD_SHORT);
        }
    }

    public void validateEmployeeName(String employeeName)
    {
        if (StringUtils.isEmpty(employeeName))
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_EMPLOYEE_NAME_REQUIRED);
        }
    }

    public void validateMobile(String mobile)
    {
        if (StringUtils.isEmpty(mobile) || !mobile.matches("^1\\d{10}$"))
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_MOBILE_INVALID);
        }
    }

    public void validateEmail(String email)
    {
        if (StringUtils.isEmpty(email))
        {
            return;
        }
        if (!email.matches("^[\\w.-]+@[\\w.-]+\\.\\w+$"))
        {
            throw new ServiceException(MerchantEmployeeConstants.MSG_EMAIL_INVALID);
        }
    }

    public void validateStatus(String status)
    {
        if (StringUtils.isEmpty(status))
        {
            throw new ServiceException("请选择状态");
        }
        if (!MerchantEmployeeConstants.STATUS_NORMAL.equals(status)
                && !MerchantEmployeeConstants.STATUS_DISABLED.equals(status))
        {
            throw new ServiceException("状态参数无效");
        }
    }

    public String resolveMobile(MerchantEmployeeRow row)
    {
        if (StringUtils.isNotEmpty(row.getPhonenumber()))
        {
            return row.getPhonenumber();
        }
        return row.getUserName();
    }
}
