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

import com.zhyc.common.annotation.DataScope;
import com.zhyc.common.exception.ServiceException;
import com.zhyc.common.utils.StringUtils;
import com.zhyc.module.base.domain.BasSheepType;
import com.zhyc.module.base.domain.DaRanch;
import com.zhyc.module.base.mapper.BasSheepVarietyMapper;
import com.zhyc.module.base.service.IBasSheepTypeService;
import com.zhyc.module.base.service.IDaRanchService;
import com.zhyc.module.produce.manage_sheep.domain.ScAddSheep;
import com.zhyc.module.produce.manage_sheep.mapper.ScAddSheepMapper;
import com.zhyc.module.produce.manage_sheep.service.IScAddSheepService;
import com.zhyc.module.base.domain.BasSheep;
import com.zhyc.module.base.service.IBasSheepService;
import com.zhyc.module.base.domain.DaSheepfold;
import com.zhyc.module.base.mapper.DaSheepfoldMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class ScAddSheepServiceImpl implements IScAddSheepService {

    @Autowired
    private ScAddSheepMapper scAddSheepMapper;

    @Autowired
    private DaSheepfoldMapper daSheepfoldMapper;

    @Autowired
    private IBasSheepService basSheepService;

    @Autowired
    private BasSheepVarietyMapper basSheepVarietyMapper;

    @Autowired
    private IBasSheepTypeService basSheepTypeService;

    @Autowired
    private IDaRanchService daRanchService;

    //新增
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertScAddSheep(ScAddSheep scAddSheep) {
        BasSheep existSheep = basSheepService.selectBasSheepByManageTags(scAddSheep.getEarNumber().trim());
        if (existSheep != null) {
            throw new ServiceException("添加失败，耳号已存在");
        }

        boolean ok = scAddSheepMapper.insert(scAddSheep) > 0;
        if (!ok) return false;

        BasSheep bs = new BasSheep();
        bs.setManageTags(scAddSheep.getEarNumber());
        bs.setRanchId(scAddSheep.getRanchId().longValue());
        bs.setSheepfoldId(scAddSheep.getSheepfold().longValue());
        if (StringUtils.isNotBlank(scAddSheep.getFather())) {
            BasSheep fatherSheep = basSheepService.selectBasSheepByManageTags(scAddSheep.getFather().trim());
            if (fatherSheep == null) {
                throw new ServiceException("父号【" + scAddSheep.getFather() + "】不存在");
            }
            bs.setFatherId(fatherSheep.getId());
        }
        if (StringUtils.isNotBlank(scAddSheep.getMother())) {
            BasSheep motherSheep = basSheepService.selectBasSheepByManageTags(scAddSheep.getMother().trim());
            if (motherSheep == null) {
                throw new ServiceException("母号【" + scAddSheep.getMother() + "】不存在");
            }
            bs.setMotherId(motherSheep.getId());
        }
        bs.setGrandpa(scAddSheep.getGrandpa());
        bs.setGrandma(scAddSheep.getGrandma());
        bs.setBirthWeight(scAddSheep.getBornWeight().longValue());
        if (scAddSheep.getWeaningWeight() != null) {
            bs.setWeaningWeight(scAddSheep.getWeaningWeight().longValue());
        } else {
            bs.setWeaningWeight(null);
        }
        bs.setSource(String.valueOf(2));
        bs.setBirthday(scAddSheep.getBirthday());
        bs.setGender(scAddSheep.getGender().longValue());
        Integer gender = scAddSheep.getGender();
        if (gender != null) {
            if (gender == 1) {          // 母羊
                bs.setBreedStatusId(1L);    // 后备
            } else if (gender == 2) {   // 公羊
                bs.setBreedStatusId(5L);    // 公羊
            }
        }
        if (scAddSheep.getParity() != null) {
            bs.setParity(scAddSheep.getParity().longValue());
        } else {
            bs.setParity(null);
        }
        bs.setVarietyId(scAddSheep.getVarietyId().longValue());
        bs.setSourceDate(scAddSheep.getJoinDate());
        bs.setComment(scAddSheep.getComment());

        bs.setCreateBy(scAddSheep.getCreateBy());
        bs.setCreateTime(new Date());
        if (scAddSheep.getTypeId() != null) {
            bs.setTypeId(scAddSheep.getTypeId().longValue());
        }
        bs.setStatusId(1L);
        basSheepService.insertBasSheep(bs);
        return true;
    }

    //查询
    @Override
    @DataScope(deptAlias = "sas", userAlias = "sas")
    public List<ScAddSheep> selectScAddSheepList(ScAddSheep scAddSheep) {
        return scAddSheepMapper.selectScAddSheepList(scAddSheep);
    }

    //修改
    @Override
    public boolean updateScAddSheep(ScAddSheep scAddSheep) {
        return scAddSheepMapper.updateScAddSheep(scAddSheep) > 0;
    }

    //删除
    @Override
    public boolean deleteScAddSheepByIds(Integer[] ids) {
        return scAddSheepMapper.deleteScAddSheepByIds(ids) > 0;
    }

    /**
     * 根据出生日期计算月龄
     */
    private int calculateMonthAge(Date birthday) {
        if (birthday == null) return 0;

        Calendar birthCal = Calendar.getInstance();
        birthCal.setTime(birthday);

        Calendar nowCal = Calendar.getInstance();

        int yearDiff = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
        int monthDiff = nowCal.get(Calendar.MONTH) - birthCal.get(Calendar.MONTH);

        return yearDiff * 12 + monthDiff;
    }

    /**
     * 根据月龄、断奶体重、性别自动判断羊只类别ID
     */
    private Long determineSheepType(BigDecimal weaningWeight, int monthAge, Integer gender) {
        // 1. 断奶体重为空 -> 哺乳羊
        if (weaningWeight == null) {
            return 1L; // 哺乳羊
        }

        // 2. 断奶体重不为空 且 月龄 0-4 -> 断奶羊
        if (monthAge >= 0 && monthAge <= 4) {
            return 2L; // 断奶羊
        }

        // 3. 断奶体重不为空 且 月龄 4-7 -> 育成羊
        if (monthAge > 4 && monthAge <= 7) {
            return 3L; // 育成羊
        }

        // 4. 月龄 7-12 且 母羊 -> 青年羊
        if (monthAge > 7 && monthAge < 12 && gender != null && gender == 1) { // 1=母
            return 4L; // 青年羊
        }

        // 5. 月龄 >=12 且 公羊 -> 成年公羊
        if (monthAge >= 12 && gender != null && gender == 2) { // 2=公
            return 8L; // 成年公羊
        }

        // 6. 月龄 >=12 且 母羊 -> 超龄羊
        if (monthAge >= 12 && gender != null && gender == 1) { // 1=母
            return 5L; // 超龄羊
        }

        // 默认返回哺乳羊
        return 1L;
    }

    //导入羊只
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importSheep(List<ScAddSheep> list, boolean updateSupport, String operName, Long userId, Long deptId) {
        if (list == null || list.isEmpty()) {
            throw new ServiceException("导入数据不能为空！");
        }

        int success = 0, failure = 0;
        StringBuilder failureMsg = new StringBuilder();

        for (int i = 0; i < list.size(); i++) {
            ScAddSheep sheep = list.get(i);
            try {
                // 校验牧场名称
                if (StringUtils.isBlank(sheep.getRanchName())) {
                    failure++;
                    failureMsg.append("<br/>第").append(i + 1).append("行：牧场名称不能为空");
                    continue;
                }
                DaRanch ranchParam = new DaRanch();
                ranchParam.setRanch(sheep.getRanchName().trim());
                List<DaRanch> ranchList = daRanchService.selectDaRanchList(ranchParam);

                if (ranchList == null || ranchList.isEmpty()) {
                    failure++;
                    failureMsg.append("<br/>第").append(i + 1)
                            .append("行：牧场名称不存在【").append(sheep.getRanchName()).append("】");
                    continue;
                }
                sheep.setRanchId(ranchList.get(0).getId().intValue());

                // 校验品种名称
                if (StringUtils.isNotBlank(sheep.getVarietyName())) {
                    Long varietyId = basSheepVarietyMapper.selectIdByName(sheep.getVarietyName());
                    if (varietyId == null) {
                        failure++;
                        failureMsg.append("<br/>第")
                                .append(i + 1)
                                .append("行：品种名称不存在【")
                                .append(sheep.getVarietyName())
                                .append("】");
                        continue;
                    }
                    sheep.setVarietyId(varietyId.intValue());
                } else {
                    failure++;
                    failureMsg.append("<br/>第")
                            .append(i + 1)
                            .append("行：品种不能为空");
                    continue;
                }

                // 校验羊舍名称
                if (StringUtils.isNotBlank(sheep.getSheepfoldNameExcel())) {
                    DaSheepfold param = new DaSheepfold();
                    param.setSheepfoldName(sheep.getSheepfoldNameExcel());
                    param.setRanchId(sheep.getRanchId().longValue());
                    List<DaSheepfold> foldList = daSheepfoldMapper.selectDaSheepfoldList(param);
                    if (foldList == null || foldList.isEmpty()) {
                        failure++;
                        failureMsg.append("<br/>第")
                                .append(i + 1)
                                .append("行：羊舍名称不存在【")
                                .append(sheep.getSheepfoldNameExcel())
                                .append("】");
                        continue;
                    }
                    sheep.setSheepfold(foldList.get(0).getId().intValue());
                }

                // 校验耳号
                if (StringUtils.isBlank(sheep.getEarNumber())) {
                    failure++;
                    failureMsg.append("<br/>第")
                            .append(i + 1)
                            .append("行：耳号不能为空");
                    continue;
                }

                BasSheep existSheep = basSheepService.selectBasSheepByManageTags(sheep.getEarNumber().trim());
                if (existSheep != null) {
                    failure++;
                    failureMsg.append("<br/>第")
                            .append(i + 1)
                            .append("行：耳号已存在且未删除【")
                            .append(sheep.getEarNumber())
                            .append("】");
                    continue;
                }

                // 校验父号（如果填写了）
                if (StringUtils.isNotBlank(sheep.getFather())) {
                    BasSheep father = basSheepService.selectBasSheepByManageTags(sheep.getFather().trim());
                    if (father == null) {
                        failure++;
                        failureMsg.append("<br/>第").append(i + 1).append("行：父号不存在【").append(sheep.getFather()).append("】");
                        continue;
                    }
                }

                // 校验母号（如果填写了）
                if (StringUtils.isNotBlank(sheep.getMother())) {
                    BasSheep mother = basSheepService.selectBasSheepByManageTags(sheep.getMother().trim());
                    if (mother == null) {
                        failure++;
                        failureMsg.append("<br/>第").append(i + 1).append("行：母号不存在【").append(sheep.getMother()).append("】");
                        continue;
                    }
                }

                // 校验出生日期必填
                if (sheep.getBirthday() == null) {
                    failure++;
                    failureMsg.append("<br/>第").append(i + 1).append("行：出生日期不能为空");
                    continue;
                }

                // 校验性别必填
                if (sheep.getGender() == null) {
                    failure++;
                    failureMsg.append("<br/>第").append(i + 1).append("行：性别不能为空");
                    continue;
                }

                // 自动判断羊只类别
                int monthAge = calculateMonthAge(sheep.getBirthday());
                Long autoTypeId = determineSheepType(sheep.getWeaningWeight(), monthAge, sheep.getGender());

                // 如果Excel中填写了typeName，以Excel为准
                if (StringUtils.isNotBlank(sheep.getTypeName())) {
                    BasSheepType typeQuery = new BasSheepType();
                    typeQuery.setName(sheep.getTypeName().trim());
                    List<BasSheepType> typeList = basSheepTypeService.selectBasSheepTypeList(typeQuery);

                    if (typeList == null || typeList.isEmpty()) {
                        failure++;
                        failureMsg.append("<br/>第")
                                .append(i + 1)
                                .append("行：羊只类型名称不存在【")
                                .append(sheep.getTypeName())
                                .append("】");
                        continue;
                    }
                    sheep.setTypeId(typeList.get(0).getId().longValue());
                } else {
                    // 使用自动判断的类别
                    sheep.setTypeId(autoTypeId);
                }

                // 数据分离：设置用户和部门
                sheep.setUserId(userId);
                sheep.setDeptId(deptId);

                if (updateSupport && sheep.getId() != null) {
                    sheep.setUpdateBy(operName);
                    updateScAddSheep(sheep);
                } else {
                    sheep.setCreateBy(operName);
                    insertScAddSheep(sheep);
                }
                success++;

            } catch (Exception e) {
                failure++;
                failureMsg.append("<br/>第")
                        .append(i + 1)
                        .append("行：")
                        .append(e.getMessage());
            }
        }

        if (failure > 0) {
            throw new ServiceException("导入失败！共 " + failure + " 条：" + failureMsg);
        }
        return "导入成功！共 " + success + " 条";
    }
}