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.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("添加失败，耳号已存在");
        }

        // userId 和 deptId 已在 Controller 中设置，直接插入
        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());
        bs.setFatherId(null);
        bs.setMotherId(null);
        bs.setBirthWeight(scAddSheep.getBornWeight().longValue());
        bs.setWeaningWeight(scAddSheep.getWeaningWeight().longValue());
        bs.setSource(String.valueOf(2));
        bs.setBirthday(scAddSheep.getBirthday());
        bs.setGender(scAddSheep.getGender().longValue());
        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")  // sas 是 sc_add_sheep 的别名
    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;
    }

    //导入羊只
    @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.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());
                }

                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;
                }

                // 数据分离：设置用户和部门
                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 + " 条";
    }
}