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;

/**
 * 解析并校验所属主体（养殖主体 / 交易市场）。
 */
@Component
public class LivestockMonitorOwnerResolver
{
    @Autowired
    private BizPastureMapper bizPastureMapper;

    @Autowired
    private BizTradeMarketMapper bizTradeMarketMapper;

    /**
     * 校验主体有效并返回展示名称。
     */
    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("所属主体类型无效");
    }

    public void applyOwnerToRow(BizLivestockMonitor row)
    {
        String name = resolveOwnerName(row.getOwnerType(), row.getOwnerId());
        row.setOwnerName(StringUtils.isNotEmpty(name) ? name : "");
    }
}
