package com.ruoyi.web.modules.video.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.circulation.domain.BizTradeMarket;
import com.ruoyi.web.modules.circulation.mapper.BizTradeMarketMapper;
import com.ruoyi.web.modules.circulation.support.TradeMarketRules;
import com.ruoyi.web.modules.industrypolicy.support.PastureRules;
import com.ruoyi.web.modules.industryservice.domain.BizPasture;
import com.ruoyi.web.modules.industryservice.mapper.BizPastureMapper;
import com.ruoyi.web.modules.video.domain.BizLivestockMonitor;

/**
 * 畜牧监控所属主体解析器。
 * <p>
 * 手工保存时根据 {@code ownerType} + {@code ownerId} 查库校验主体有效，
 * 并将展示名称写入 {@code owner_name} 冗余字段（列表无需再 join 牧场/市场表）。
 * 第三方同步时按 {@code farmName} 查 {@code biz_pasture} 自动绑定 {@code owner_type=1}、{@code owner_id}。
 * </p>
 */
@Component
public class LivestockMonitorOwnerResolver
{
    @Autowired
    private BizPastureMapper bizPastureMapper;

    @Autowired
    private BizTradeMarketMapper bizTradeMarketMapper;

    /**
     * 校验主体存在且处于可用状态，返回展示名称。
     *
     * @param ownerType {@link LivestockMonitorRules#OWNER_TYPE_PASTURE} 或 {@link LivestockMonitorRules#OWNER_TYPE_TRADE_MARKET}
     * @param ownerId   对应 {@code biz_pasture.id} 或 {@code biz_trade_market.id}
     * @return 牧场名或市场名
     * @throws ServiceException 主体不存在、已删除或市场非营业
     */
    public String resolveOwnerName(Integer ownerType, Long ownerId)
    {
        if (ownerType == LivestockMonitorRules.OWNER_TYPE_PASTURE)
        {
            BizPasture pasture = bizPastureMapper.selectBizPastureById(ownerId);
            if (pasture == null || !PastureRules.DEL_FLAG_NORMAL.equals(pasture.getDelFlag()))
            {
                throw new ServiceException("所属主体不存在或已停用");
            }
            return pasture.getPastureName();
        }
        if (ownerType == LivestockMonitorRules.OWNER_TYPE_TRADE_MARKET)
        {
            BizTradeMarket market = bizTradeMarketMapper.selectBizTradeMarketById(ownerId);
            if (market == null || !TradeMarketRules.DEL_FLAG_NORMAL.equals(market.getDelFlag())
                    || market.getOperateStatus() == null
                    || market.getOperateStatus() != TradeMarketRules.OPERATE_STATUS_NORMAL)
            {
                throw new ServiceException("所属主体不存在或已停用");
            }
            return market.getMarketName();
        }
        throw new ServiceException("所属主体类型无效");
    }

    /**
     * 解析主体名称并写回 row。调用方须已确认 {@code ownerType}、{@code ownerId} 非空。
     */
    public void applyOwnerToRow(BizLivestockMonitor row)
    {
        if (row == null || row.getOwnerType() == null || row.getOwnerId() == null)
        {
            return;
        }
        String name = resolveOwnerName(row.getOwnerType(), row.getOwnerId());
        row.setOwnerName(StringUtils.isNotEmpty(name) ? name : null);
    }
}
