package com.ruoyi.web.modules.video.service.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.github.pagehelper.PageHelper;
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.industryservice.domain.BizPasture;
import com.ruoyi.web.modules.industryservice.mapper.BizPastureMapper;
import com.ruoyi.web.modules.video.domain.BizLivestockMonitor;
import com.ruoyi.web.modules.video.domain.MonitorOwnerOption;
import com.ruoyi.web.modules.video.mapper.BizLivestockMonitorMapper;
import com.ruoyi.web.modules.video.service.IBizLivestockMonitorService;
import com.ruoyi.web.modules.video.support.LivestockMonitorOwnerResolver;
import com.ruoyi.web.modules.video.support.LivestockMonitorRules;
import com.ruoyi.web.modules.video.support.LivestockMonitorValidation;

/**
 * 畜牧监控服务实现。
 */
@Service
public class BizLivestockMonitorServiceImpl implements IBizLivestockMonitorService
{
    @Autowired
    private BizLivestockMonitorMapper bizLivestockMonitorMapper;

    @Autowired
    private LivestockMonitorOwnerResolver ownerResolver;

    @Autowired
    private BizPastureMapper bizPastureMapper;

    @Autowired
    private BizTradeMarketMapper bizTradeMarketMapper;

    @Override
    public BizLivestockMonitor selectBizLivestockMonitorById(Long id)
    {
        BizLivestockMonitor row = bizLivestockMonitorMapper.selectBizLivestockMonitorById(id);
        enrichOwnerTypeName(row);
        return row;
    }

    @Override
    public List<BizLivestockMonitor> selectBizLivestockMonitorList(BizLivestockMonitor query)
    {
        if (query != null && StringUtils.isNotEmpty(query.getMonitorName()))
        {
            query.setMonitorName(query.getMonitorName().trim());
        }
        List<BizLivestockMonitor> list = bizLivestockMonitorMapper.selectBizLivestockMonitorList(query);
        if (list != null)
        {
            for (BizLivestockMonitor row : list)
            {
                enrichOwnerTypeName(row);
            }
        }
        return list;
    }

    @Override
    public List<MonitorOwnerOption> selectOwnerOptions(String keyword)
    {
        String kw = StringUtils.isNotEmpty(keyword) ? keyword.trim() : null;
        List<MonitorOwnerOption> options = new ArrayList<>();

        BizPasture pastureQuery = new BizPasture();
        pastureQuery.setKeyword(kw);
        PageHelper.startPage(1, LivestockMonitorRules.OWNER_OPTIONS_LIMIT, false);
        List<BizPasture> pastures = bizPastureMapper.selectBizPastureList(pastureQuery);
        PageHelper.clearPage();
        if (pastures != null)
        {
            for (BizPasture p : pastures)
            {
                MonitorOwnerOption opt = new MonitorOwnerOption();
                opt.setOwnerType(LivestockMonitorRules.OWNER_TYPE_PASTURE);
                opt.setOwnerTypeName(LivestockMonitorRules.ownerTypeName(opt.getOwnerType()));
                opt.setOwnerId(p.getId());
                opt.setOwnerName(p.getPastureName());
                options.add(opt);
            }
        }

        BizTradeMarket marketQuery = new BizTradeMarket();
        marketQuery.setOperateStatus(TradeMarketRules.OPERATE_STATUS_NORMAL);
        if (StringUtils.isNotEmpty(kw))
        {
            marketQuery.setMarketName(kw);
        }
        PageHelper.startPage(1, LivestockMonitorRules.OWNER_OPTIONS_LIMIT, false);
        List<BizTradeMarket> markets = bizTradeMarketMapper.selectBizTradeMarketList(marketQuery);
        PageHelper.clearPage();
        if (markets != null)
        {
            for (BizTradeMarket m : markets)
            {
                MonitorOwnerOption opt = new MonitorOwnerOption();
                opt.setOwnerType(LivestockMonitorRules.OWNER_TYPE_TRADE_MARKET);
                opt.setOwnerTypeName(LivestockMonitorRules.ownerTypeName(opt.getOwnerType()));
                opt.setOwnerId(m.getId());
                opt.setOwnerName(m.getMarketName());
                options.add(opt);
            }
        }

        options.sort(Comparator.comparing(MonitorOwnerOption::getOwnerName,
                Comparator.nullsLast(String::compareTo)));
        return options;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizLivestockMonitor(BizLivestockMonitor row)
    {
        LivestockMonitorValidation.validateRowForSave(row);
        ownerResolver.applyOwnerToRow(row);
        row.setDelFlag(LivestockMonitorRules.DEL_FLAG_NORMAL);
        return bizLivestockMonitorMapper.insertBizLivestockMonitor(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizLivestockMonitor(BizLivestockMonitor row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        requireActiveRow(row.getId());
        LivestockMonitorValidation.validateRowForSave(row);
        ownerResolver.applyOwnerToRow(row);
        row.setDelFlag(LivestockMonitorRules.DEL_FLAG_NORMAL);
        return bizLivestockMonitorMapper.updateBizLivestockMonitor(row);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizLivestockMonitorByIds(Long[] ids, String updateBy)
    {
        if (ids == null || ids.length == 0)
        {
            return 0;
        }
        List<Long> cleaned = new ArrayList<>();
        for (Long id : ids)
        {
            if (id != null)
            {
                cleaned.add(id);
            }
        }
        if (cleaned.isEmpty())
        {
            return 0;
        }
        for (Long id : cleaned)
        {
            BizLivestockMonitor row = bizLivestockMonitorMapper.selectBizLivestockMonitorByIdAny(id);
            if (row == null || LivestockMonitorRules.DEL_FLAG_DELETED.equals(row.getDelFlag()))
            {
                continue;
            }
        }
        return bizLivestockMonitorMapper.logicDeleteBizLivestockMonitorByIds(
                cleaned.toArray(new Long[0]), updateBy);
    }

    private BizLivestockMonitor requireActiveRow(Long id)
    {
        BizLivestockMonitor row = bizLivestockMonitorMapper.selectBizLivestockMonitorById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在或已删除");
        }
        return row;
    }

    private static void enrichOwnerTypeName(BizLivestockMonitor row)
    {
        if (row != null)
        {
            row.setOwnerTypeName(LivestockMonitorRules.ownerTypeName(row.getOwnerType()));
        }
    }
}
