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

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.mapper.BasSheepMapper;
import com.zhyc.module.base.service.IBasSheepService;
import com.zhyc.module.produce.manage_sheep.mapper.ScTransGroupMapper;
import com.zhyc.module.produce.manage_sheep.service.IScTransGroupService;
import com.zhyc.module.produce.manage_sheep.domain.ScTransGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 转群记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-10
 */
@Service
public class ScTransGroupServiceImpl implements IScTransGroupService {
    @Autowired
    private ScTransGroupMapper scTransGroupMapper;
    @Autowired
    private BasSheepMapper basSheepMapper;
    @Autowired
    private IBasSheepService basSheepService;

    /**
     * 查询转群记录
     *
     * @param id 转群记录主键
     * @return 转群记录
     */
    @Override
    public ScTransGroup selectScTransGroupById(Integer id) {
        ScTransGroup group = scTransGroupMapper.selectScTransGroupById(id);
        group.setReasonText(convertReason(group.getReason()));
        group.setEventTypeText(convertEventType(group.getEventType()));
        return group;
    }


    /**
     * 查询转群记录列表
     *
     * @param scTransGroup 转群记录
     * @return 转群记录
     */
    @Override
    @DataScope(deptAlias = "tg", userAlias = "tg")
    public List<ScTransGroup> selectScTransGroupList(ScTransGroup scTransGroup) {
        List<ScTransGroup> list = scTransGroupMapper.selectScTransGroupList(scTransGroup,
                scTransGroup.getManageTagsList());
        list.forEach(group -> {
            group.setReasonText(convertReason(group.getReason()));
            group.setEventTypeText(convertEventType(group.getEventType()));
        });
        return list;
    }

    /**
     * 新增转群记录
     *
     * @param scTransGroup 转群记录
     * @return 结果
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertScTransGroup(ScTransGroup scTransGroup) {
        // 1. 根据耳号查询羊只信息，填充 sheepId、varietyId 等字段
        String manageTags = scTransGroup.getManageTags();
        if (StringUtils.isNotBlank(manageTags)) {
            BasSheep sheep = basSheepService.selectBasSheepByManageTags(manageTags.trim());
            if (sheep == null) {
                throw new RuntimeException("耳号不存在，请检查输入");
            }
            scTransGroup.setSheepId(sheep.getId().intValue());
            scTransGroup.setVarietyId(sheep.getVarietyId());
            // 转出羊舍取羊只当前所在羊舍
            scTransGroup.setFoldFrom(String.valueOf(sheep.getSheepfoldId()));
        } else {
            throw new RuntimeException("耳号不能为空");
        }

        // 2. 设置创建信息
        scTransGroup.setCreateTime(DateUtils.getNowDate());
        scTransGroup.setCreateBy(SecurityUtils.getUsername());

        // 3. 数据分离字段已在 Controller 设置，这里不需要再设置

        // 4. 插入数据库
        int rows = scTransGroupMapper.insertScTransGroup(scTransGroup);
        if (rows > 0) {
            try {
                updateSheepFold(scTransGroup);
            } catch (Exception e) {
                throw new RuntimeException("新增转群记录后更新羊舍失败：" + e.getMessage(), e);
            }
        }
        return rows;
    }

    /**
     * 修改转群记录
     *
     * @param scTransGroup 转群记录
     * @return 结果
     */
    @Override
    public int updateScTransGroup(ScTransGroup scTransGroup) {
        return scTransGroupMapper.updateScTransGroup(scTransGroup);
    }

    /**
     * 批量删除转群记录
     *
     * @param ids 需要删除的转群记录主键
     * @return 结果
     */
    @Override
    public int deleteScTransGroupByIds(Integer[] ids) {
        return scTransGroupMapper.deleteScTransGroupByIds(ids);
    }

    /**
     * 删除转群记录信息
     *
     * @param id 转群记录主键
     * @return 结果
     */
    @Override
    public int deleteScTransGroupById(Integer id) {
        return scTransGroupMapper.deleteScTransGroupById(id);
    }

    /**
     * 更新羊只所在羊舍
     */
    private void updateSheepFold(ScTransGroup transGroup) {
        Object foldToObj = transGroup.getFoldTo();
        if (foldToObj == null) {
            throw new RuntimeException("转入羊舍ID为空，请检查前端提交的foldTo参数");
        }
        Long foldTo;
        try {
            foldTo = Long.valueOf(foldToObj.toString());
        } catch (NumberFormatException e) {
            throw new RuntimeException("转入羊舍ID格式错误，应为数字，实际值：" + foldToObj);
        }

        String manageTags = transGroup.getManageTags();
        if (manageTags == null || manageTags.isEmpty()) {
            throw new RuntimeException("耳号不能为空");
        }

        List<String> tagList = Arrays.asList(manageTags.split(","));

        for (String tag : tagList) {
            BasSheep sheep = basSheepService.selectBasSheepByManageTags(tag.trim());
            if (sheep != null) {
                BasSheep updateSheep = new BasSheep();
                updateSheep.setId(sheep.getId());
                updateSheep.setSheepfoldId(foldTo);
                basSheepMapper.updateBasSheep(updateSheep);
            } else {
                throw new RuntimeException("耳号 [" + tag + "] 不存在");
            }
        }
    }

    /**
     * 转换转群原因
     */
    private String convertReason(String reasonCode) {
        if (reasonCode == null) return "未知原因";
        Map<String,String> map = new HashMap<>();
        map.put("0","新产羊过抗转群");
        map.put("1","治愈转群");
        map.put("2","病羊过抗转群");
        return map.getOrDefault(reasonCode, reasonCode);
    }

    /**
     * 转换事件类型（1-围产转群，2-普通转群，3-育肥转群，4-预售转群）
     */
    private String convertEventType(String eventType) {
        if (eventType == null) {
            return "未知";
        }
        Map<String, String> eventTypeMap = new HashMap<>();
        eventTypeMap.put("1", "围产转群");
        eventTypeMap.put("2", "普通转群");
        eventTypeMap.put("3", "育肥转群");
        eventTypeMap.put("4", "预售转群");
        return eventTypeMap.getOrDefault(eventType, eventType);
    }

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