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

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.modules.industryservice.domain.BizFarmerHousehold;
import com.ruoyi.web.modules.industryservice.domain.BizGrassLivestockImbalanceWarning;
import com.ruoyi.web.modules.industryservice.domain.vo.FarmerHouseholdImportResultVo;
import com.ruoyi.web.modules.industryservice.mapper.BizFarmerHouseholdMapper;
import com.ruoyi.web.modules.industryservice.service.IBizFarmerHouseholdService;
import com.ruoyi.web.modules.industryservice.support.FarmerHouseholdDerivedSupport;
import com.ruoyi.web.modules.industryservice.support.FarmerHouseholdExcelExporter;
import com.ruoyi.web.modules.industryservice.support.FarmerHouseholdExcelParser;
import com.ruoyi.web.modules.industryservice.support.FarmerHouseholdExcelParser.ParsedRow;
import com.ruoyi.web.modules.industryservice.support.FarmerHouseholdValidation;
import com.ruoyi.web.modules.industryservice.support.GrassLivestockImbalanceWarningRules;
import com.ruoyi.web.modules.industryservice.support.GrassLivestockImbalanceWarningSyncSupport;
import com.ruoyi.web.modules.industryservice.support.ReportDeptDataScopeSupport;
import com.ruoyi.web.modules.industryservice.support.TownDeptSupport;
import com.ruoyi.web.modules.industryservice.support.YakHerdInventoryMonthSupport;
import com.ruoyi.web.modules.industryservice.support.YakHerdInventoryYearSupport;

/**
 * 农牧户数据填报服务实现
 */
@Service
public class BizFarmerHouseholdServiceImpl implements IBizFarmerHouseholdService
{
    @Autowired
    private BizFarmerHouseholdMapper bizFarmerHouseholdMapper;

    @Autowired
    private GrassLivestockImbalanceWarningSyncSupport grassLivestockImbalanceWarningSyncSupport;

    @Autowired
    private TownDeptSupport townDeptSupport;

    @Autowired
    private FarmerHouseholdExcelExporter farmerHouseholdExcelExporter;

    @Override
    public BizFarmerHousehold selectBizFarmerHouseholdById(Long id)
    {
        return bizFarmerHouseholdMapper.selectBizFarmerHouseholdById(id);
    }

    @Override
    public List<BizFarmerHousehold> selectBizFarmerHouseholdList(BizFarmerHousehold query)
    {
        ReportDeptDataScopeSupport.apply(query, "r");
        return bizFarmerHouseholdMapper.selectBizFarmerHouseholdList(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertBizFarmerHousehold(BizFarmerHousehold row)
    {
        FarmerHouseholdValidation.validateRowForSave(row, townDeptSupport);
        assertUniqueYearMonthVillage(row.getStatYear(), row.getStatMonth(), row.getVillageDeptId(), null);
        int rows = bizFarmerHouseholdMapper.insertBizFarmerHousehold(row);
        syncGrassImbalanceWarning(row);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateBizFarmerHousehold(BizFarmerHousehold row)
    {
        if (row.getId() == null)
        {
            throw new ServiceException("主键不能为空");
        }
        FarmerHouseholdValidation.validateRowForSave(row, townDeptSupport);
        requireExistingRow(row.getId());
        assertUniqueYearMonthVillage(row.getStatYear(), row.getStatMonth(), row.getVillageDeptId(), row.getId());
        int rows = bizFarmerHouseholdMapper.updateBizFarmerHousehold(row);
        syncGrassImbalanceWarning(row);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteBizFarmerHouseholdByIds(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;
        }
        Long[] householdIds = cleaned.toArray(new Long[0]);
        List<String> sourceKeys = new ArrayList<>();
        for (Long householdId : householdIds)
        {
            sourceKeys.add(GrassLivestockImbalanceWarningRules.farmerHouseholdSourceKey(householdId));
        }
        grassLivestockImbalanceWarningSyncSupport.deleteBySourceKeys(sourceKeys);
        return bizFarmerHouseholdMapper.deleteBizFarmerHouseholdByIds(householdIds);
    }

    /**
     * 导入：按 (年, 月, 村) 存在则更新、不存在则插入；任一行失败则整批不写。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public FarmerHouseholdImportResultVo importData(MultipartFile file, Integer statYear, Integer statMonth,
            String username)
    {
        if (file == null || file.isEmpty())
        {
            throw new ServiceException("请上传 Excel 文件");
        }
        String filename = file.getOriginalFilename();
        if (filename == null || !filename.toLowerCase().endsWith(".xlsx"))
        {
            throw new ServiceException("仅支持 .xlsx 格式");
        }
        YakHerdInventoryMonthSupport.validateStatPeriod(statYear, statMonth);
        FarmerHouseholdImportResultVo result = new FarmerHouseholdImportResultVo();
        List<ParsedRow> parsedRows;
        try
        {
            parsedRows = FarmerHouseholdExcelParser.parse(file.getInputStream());
        }
        catch (ServiceException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw new ServiceException("读取 Excel 失败：" + ex.getMessage());
        }

        List<BizFarmerHousehold> toSave = new ArrayList<>();
        java.util.Set<String> batchKeys = new java.util.HashSet<>();
        for (ParsedRow parsed : parsedRows)
        {
            try
            {
                SysDept town = townDeptSupport.resolveTownByName(parsed.getTownName());
                if (town == null)
                {
                    result.addFail("第" + parsed.getExcelRowNum() + "行[" + parsed.getTownName() + "]: 乡镇未识别");
                    continue;
                }
                if (StringUtils.isEmpty(parsed.getVillageName()))
                {
                    result.addFail("第" + parsed.getExcelRowNum() + "行[" + parsed.getTownName() + "]: 所属村不能为空");
                    continue;
                }
                SysDept village = townDeptSupport.resolveVillageByTownAndName(town.getDeptId(), parsed.getVillageName());
                if (village == null)
                {
                    result.addFail("第" + parsed.getExcelRowNum() + "行[" + parsed.getTownName() + "/"
                            + parsed.getVillageName() + "]: 村未识别");
                    continue;
                }
                BizFarmerHousehold row = FarmerHouseholdExcelParser.toEntity(parsed, statYear, statMonth,
                        town.getDeptId(), town.getDeptName(), village.getDeptId(), village.getDeptName());
                FarmerHouseholdValidation.validateRowForSave(row, townDeptSupport);
                String batchKey = row.getStatYear() + "|" + row.getStatMonth() + "|" + row.getVillageDeptId();
                if (!batchKeys.add(batchKey))
                {
                    result.addFail("第" + parsed.getExcelRowNum() + "行[" + row.getTownName() + "/"
                            + row.getVillageName() + "]: 文件内存在重复唯一键");
                    continue;
                }
                toSave.add(row);
            }
            catch (ServiceException ex)
            {
                result.addFail("第" + parsed.getExcelRowNum() + "行[" + parsed.getTownName() + "]: " + ex.getMessage());
            }
        }

        if (result.getFailCount() > 0)
        {
            throw new ServiceException("导入失败，未写入数据：" + String.join("；", result.getFailMessages()));
        }
        if (toSave.isEmpty())
        {
            throw new ServiceException("未解析到有效数据行");
        }

        for (BizFarmerHousehold row : toSave)
        {
            BizFarmerHousehold existing = bizFarmerHouseholdMapper.selectByYearMonthAndVillage(row.getStatYear(),
                    row.getStatMonth(), row.getVillageDeptId());
            if (existing != null)
            {
                row.setId(existing.getId());
                row.setUpdateBy(username);
                bizFarmerHouseholdMapper.updateBizFarmerHousehold(row);
                result.setUpdateCount(result.getUpdateCount() + 1);
            }
            else
            {
                row.setCreateBy(username);
                bizFarmerHouseholdMapper.insertBizFarmerHousehold(row);
                result.setInsertCount(result.getInsertCount() + 1);
            }
            syncGrassImbalanceWarning(row);
        }
        return result;
    }

    @Override
    public List<Integer> listYearOptions()
    {
        return YakHerdInventoryYearSupport.resolveYearOptions();
    }

    @Override
    public List<Integer> listMonthOptions()
    {
        return YakHerdInventoryMonthSupport.resolveMonthOptions();
    }

    @Override
    public List<java.util.Map<String, Object>> listTownOptions()
    {
        return townDeptSupport.toOptionList();
    }

    @Override
    public List<com.ruoyi.common.core.domain.TreeSelect> listVillageTree()
    {
        return townDeptSupport.buildVillageTree();
    }

    @Override
    public byte[] exportByYearMonth(Integer statYear, Integer statMonth, Long townDeptId)
    {
        return exportByYearMonth(statYear, statMonth, townDeptId, null);
    }

    @Override
    public byte[] exportByYearMonth(Integer statYear, Integer statMonth, Long townDeptId, String fillerName)
    {
        YakHerdInventoryMonthSupport.validateStatPeriod(statYear, statMonth);
        if (townDeptId != null && townDeptSupport.requireReportTown(townDeptId) == null)
        {
            throw new ServiceException("导出乡镇不合法");
        }
        BizFarmerHousehold query = new BizFarmerHousehold();
        query.setStatYear(statYear);
        query.setStatMonth(statMonth);
        query.setTownDeptId(townDeptId);
        ReportDeptDataScopeSupport.apply(query, "r");
        List<BizFarmerHousehold> list = bizFarmerHouseholdMapper.selectBizFarmerHouseholdList(query);
        return farmerHouseholdExcelExporter.export(statYear, statMonth, list, fillerName);
    }

    /**
     * 草畜失衡预警同步（交接表注 7；不走「草畜平衡计算」模块）。
     * <ul>
     *   <li>新增 / 导入 / 修改后：核定年末草畜平衡载畜量 &lt; 年底牲畜存栏 → 写入/更新预警</li>
     *   <li>修改后核定载畜量 &gt;= 年底存栏（或字段不全）→ 删除对应预警</li>
     *   <li>定位键：source_key=FH-{id}，粒度=年+月+村</li>
     * </ul>
     */
    private void syncGrassImbalanceWarning(BizFarmerHousehold row)
    {
        if (row == null || row.getId() == null)
        {
            return;
        }
        BizGrassLivestockImbalanceWarning warning = new BizGrassLivestockImbalanceWarning();
        warning.setSourceKey(GrassLivestockImbalanceWarningRules.farmerHouseholdSourceKey(row.getId()));
        warning.setDataSource(GrassLivestockImbalanceWarningRules.DATA_SOURCE_FARMER_HOUSEHOLD);
        warning.setSourceRecordId(row.getId());
        warning.setStatYear(row.getStatYear());
        warning.setStatMonth(row.getStatMonth());
        warning.setTownDeptId(row.getTownDeptId());
        warning.setTownName(row.getTownName());
        warning.setVillageDeptId(row.getVillageDeptId());
        warning.setVillageName(row.getVillageName());
        warning.setSubjectName(row.getVillageName());
        warning.setApprovedCarryingCapacity(row.getApprovedCarryingCapacity());
        warning.setYearEndStockSheepUnit(row.getYearEndStockSheepUnit());
        warning.setAlertMessage(GrassLivestockImbalanceWarningSyncSupport.buildMessage(row.getStatYear(),
                row.getStatMonth(), row.getTownName(), row.getVillageName(), null,
                row.getApprovedCarryingCapacity(), row.getYearEndStockSheepUnit()));
        grassLivestockImbalanceWarningSyncSupport.sync(FarmerHouseholdDerivedSupport.isImbalanced(row), warning);
    }

    private void assertUniqueYearMonthVillage(Integer statYear, Integer statMonth, Long villageDeptId, Long excludeId)
    {
        if (bizFarmerHouseholdMapper.countByYearMonthAndVillageExcludeId(statYear, statMonth, villageDeptId,
                excludeId) > 0)
        {
            throw new ServiceException("该年该月该村已填报");
        }
    }

    private BizFarmerHousehold requireExistingRow(Long id)
    {
        BizFarmerHousehold row = bizFarmerHouseholdMapper.selectBizFarmerHouseholdById(id);
        if (row == null)
        {
            throw new ServiceException("记录不存在");
        }
        return row;
    }
}
