package com.zhyc.module.produce.manage_sheep.service.impl;

import java.util.*;

import com.zhyc.common.annotation.DataScope;
import com.zhyc.common.utils.DateUtils;
import com.zhyc.common.utils.SecurityUtils;
import com.zhyc.common.utils.StringUtils;
import com.zhyc.module.base.domain.BasSheep;
import com.zhyc.module.base.domain.DaRanch;
import com.zhyc.module.base.mapper.BasSheepMapper;
import com.zhyc.module.base.service.IBasSheepService;
import com.zhyc.module.base.service.IDaRanchService;
import com.zhyc.module.produce.manage_sheep.mapper.ScTransitionInfoMapper;
import com.zhyc.module.produce.manage_sheep.domain.ScTransitionInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhyc.module.produce.manage_sheep.service.IScTransitionInfoService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 转场Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-10
 */
@Service
public class ScTransitionInfoServiceImpl implements IScTransitionInfoService 
{
    @Autowired
    private ScTransitionInfoMapper scTransitionInfoMapper;
    @Autowired
    private BasSheepMapper basSheepMapper;
    @Autowired
    private IDaRanchService daRanchService;
    @Autowired
    private IBasSheepService basSheepService;
    /**
     * 查询转场
     * 
     * @param id 转场主键
     * @return 转场
     */
    @Override
    public ScTransitionInfo selectScTransitionInfoById(Integer id)
    {
        return scTransitionInfoMapper.selectScTransitionInfoById(id);
    }

    /**
     * 查询转场列表
     * 
     * @param scTransitionInfo 转场
     * @return 转场
     */
    @Override
    @DataScope(deptAlias = "t", userAlias = "t")
    public List<ScTransitionInfo> selectScTransitionInfoList(ScTransitionInfo scTransitionInfo)
    {
        return scTransitionInfoMapper.selectScTransitionInfoList(scTransitionInfo,
                scTransitionInfo.getManageTagsList());
    }

    /**
     * 新增转场
     * 
     * @param scTransitionInfo 转场
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertScTransitionInfo(ScTransitionInfo scTransitionInfo) {
        // 根据耳号查询羊只信息
        String manageTags = scTransitionInfo.getManageTags();
        if (StringUtils.isNotBlank(manageTags)) {
            BasSheep sheep = basSheepService.selectBasSheepByManageTags(manageTags.trim());
            if (sheep == null) {
                throw new RuntimeException("耳号不存在，请检查输入");
            }
            scTransitionInfo.setSheepId(sheep.getId().intValue());
            scTransitionInfo.setVarietyId(sheep.getVarietyId());
        } else {
            throw new RuntimeException("耳号不能为空");
        }

        scTransitionInfo.setStatus(0);
        scTransitionInfo.setCreateTime(DateUtils.getNowDate());
        return scTransitionInfoMapper.insertScTransitionInfo(scTransitionInfo);
    }


    /**
     * 修改转场
     * 
     * @param scTransitionInfo 转场
     * @return 结果
     */
    @Override
    public int updateScTransitionInfo(ScTransitionInfo scTransitionInfo)
    {
        return scTransitionInfoMapper.updateScTransitionInfo(scTransitionInfo);
    }

    /**
     * 批量删除转场
     * 
     * @param ids 需要删除的转场主键
     * @return 结果
     */
    @Override
    public int deleteScTransitionInfoByIds(Integer[] ids)
    {
        return scTransitionInfoMapper.deleteScTransitionInfoByIds(ids);
    }

    /**
     * 删除转场信息
     * 
     * @param id 转场主键
     * @return 结果
     */
    @Override
    public int deleteScTransitionInfoById(Integer id)
    {
        return scTransitionInfoMapper.deleteScTransitionInfoById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertScTransitionInfoBatch(List<ScTransitionInfo> transitionInfoList) {
        String username = SecurityUtils.getUsername();
        Date now = DateUtils.getNowDate();

        for (ScTransitionInfo info : transitionInfoList) {
            // 每条记录根据耳号查询羊只信息
            String manageTags = info.getManageTags();
            if (StringUtils.isNotBlank(manageTags)) {
                BasSheep sheep = basSheepService.selectBasSheepByManageTags(manageTags.trim());
                if (sheep == null) {
                    throw new RuntimeException("耳号 " + manageTags + " 不存在，请检查输入");
                }
                info.setSheepId(sheep.getId().intValue());
                info.setVarietyId(sheep.getVarietyId());
            } else {
                throw new RuntimeException("耳号不能为空");
            }

            info.setCreateBy(username);
            info.setCreateTime(now);
            info.setStatus(0);
        }
        return scTransitionInfoMapper.insertScTransitionInfoBatch(transitionInfoList);
    }

    /**
     * 审批转场记录（通过时更新羊只所在牧场）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int approveScTransitionInfo(ScTransitionInfo scTransitionInfo) {
        ScTransitionInfo existing = scTransitionInfoMapper.selectScTransitionInfoById(scTransitionInfo.getId());
        if (existing == null) {
            throw new RuntimeException("转场记录不存在");
        }
        if (existing.getStatus() != 0) {
            throw new RuntimeException("该记录已完成审批，无法重复操作");
        }
        if (scTransitionInfo.getStatus() == 1) { // 同意
            if ("转场转入".equals(scTransitionInfo.getEventType()) && scTransitionInfo.getSheepfoldId() == null) {
                throw new RuntimeException("转场转入时，接收羊舍ID不能为空");
            }
        }
        int rows = scTransitionInfoMapper.updateScTransitionInfo(scTransitionInfo);
        if (rows > 0 && scTransitionInfo.getStatus() == 1) {
            updateSheepRanch(scTransitionInfo);
        }
        return rows;
    }

    /**
     * 更新羊只的所在牧场及羊舍
     */
    private void updateSheepRanch(ScTransitionInfo transitionInfo) {
        /* 1. 目标牧场 */
        String transTo = transitionInfo.getTransTo();
        if (StringUtils.isBlank(transTo)) {
            throw new RuntimeException("转入牧场不能为空");
        }
        DaRanch query = new DaRanch();
        query.setRanch(transTo);
        List<DaRanch> ranchList = daRanchService.selectDaRanchList(query);
        Optional<DaRanch> matchedRanch = ranchList.stream()
                .filter(ranch -> transTo.equals(ranch.getRanch()))
                .findFirst();
        if (!matchedRanch.isPresent()) {
            throw new RuntimeException("转入牧场 [" + transTo + "] 不存在");
        }
        Long targetRanchId = matchedRanch.get().getId();

        /* 2. 接收羊舍（审批通过时必传） */
        Long targetSheepfoldId = transitionInfo.getSheepfoldId();
        if (targetSheepfoldId == null) {
            throw new RuntimeException("接收羊舍不能为空");
        }

        /* 3. 逐只迁移 */
        String manageTags = transitionInfo.getManageTags();
        if (StringUtils.isBlank(manageTags)) {
            throw new RuntimeException("耳号不能为空");
        }
        List<String> tagList = Arrays.asList(manageTags.split(","));
        for (String tag : tagList) {
            BasSheep sheep = basSheepService.selectBasSheepByManageTags(tag.trim());
            if (sheep == null) {
                throw new RuntimeException("耳号 [" + tag + "] 不存在");
            }
            BasSheep upd = new BasSheep();
            upd.setId(sheep.getId());
            upd.setRanchId(targetRanchId);
            upd.setSheepfoldId(targetSheepfoldId);   // 真正换舍
            basSheepMapper.updateBasSheep(upd);
        }
    }

    /**
     * 状态
     */
    public String convertStatus(Integer statusCode) {
        Map<Integer, String> statusMap = new HashMap<>();
        statusMap.put(0, "待批准");
        statusMap.put(1, "通过");
        statusMap.put(2, "驳回");
        return statusMap.getOrDefault(statusCode, "未知状态");
    }

    /**
     * 转场类型
     */
    public String convertTransType(Integer transTypeCode) {
        Map<Integer, String> transTypeMap = new HashMap<>();
        transTypeMap.put(0, "内部调拨");
        transTypeMap.put(1, "内部销售");
        transTypeMap.put(2, "育肥调拨");
        return transTypeMap.getOrDefault(transTypeCode, "未知类型");
    }

    @Override
    public List<String> searchEarNumbers(String query) {
        return scTransitionInfoMapper.searchEarNumbers(query.trim());
    }
}
