package com.aucma.production.service.impl;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import com.aucma.common.exception.ServiceException;
import com.aucma.common.utils.DateUtils;
import com.aucma.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.aucma.production.domain.ProdRoute;
import com.aucma.production.domain.ProdRouteDetail;
import com.aucma.production.mapper.ProdRouteMapper;
import com.aucma.production.service.IProdRouteService;

@Service
public class ProdRouteServiceImpl implements IProdRouteService {
    @Autowired
    private ProdRouteMapper prodRouteMapper;

    @Override
    public ProdRoute selectProdRouteByObjId(Long objId) {
        ProdRoute route = prodRouteMapper.selectProdRouteByObjId(objId);
        if (route != null) {
            route.setDetailList(prodRouteMapper.selectProdRouteDetailListByRouteCode(route.getRouteCode()));
        }
        return route;
    }

    @Override
    public List<ProdRoute> selectProdRouteList(ProdRoute prodRoute) {
        return prodRouteMapper.selectProdRouteList(prodRoute);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertProdRoute(ProdRoute prodRoute) {
        validateRoute(prodRoute);
        ensureRouteCodeUnique(prodRoute);
        prodRoute.setCreatedTime(DateUtils.getNowDate());
        int rows = prodRouteMapper.insertProdRoute(prodRoute);
        saveRouteDetails(prodRoute, true);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateProdRoute(ProdRoute prodRoute) {
        validateRoute(prodRoute);
        ensureRouteCodeUnique(prodRoute);
        prodRoute.setUpdatedTime(DateUtils.getNowDate());
        int rows = prodRouteMapper.updateProdRoute(prodRoute);
        // 为什么更新时整单重建明细：首版路线维护优先保证“前端表格提交即数据库最终态”，避免逐行 diff 漏删旧工序。
        prodRouteMapper.deleteProdRouteDetailByRouteCode(prodRoute.getRouteCode());
        saveRouteDetails(prodRoute, false);
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteProdRouteByObjIds(Long[] objIds) {
        for (Long objId : objIds) {
            ProdRoute route = prodRouteMapper.selectProdRouteByObjId(objId);
            if (route != null) {
                prodRouteMapper.deleteProdRouteDetailByRouteCode(route.getRouteCode());
            }
        }
        return prodRouteMapper.deleteProdRouteByObjIds(objIds);
    }

    private void validateRoute(ProdRoute prodRoute) {
        if (prodRoute == null) {
            throw new ServiceException("工艺路线数据不能为空");
        }
        if (StringUtils.isBlank(prodRoute.getRouteCode())) {
            throw new ServiceException("路线编码不能为空");
        }
        if (StringUtils.isBlank(prodRoute.getRouteName())) {
            throw new ServiceException("路线名称不能为空");
        }
        if (StringUtils.isBlank(prodRoute.getMaterialCode())) {
            throw new ServiceException("物料不能为空");
        }
        if (StringUtils.isBlank(prodRoute.getVersionNo())) {
            prodRoute.setVersionNo("V1");
        }
        if (StringUtils.isBlank(prodRoute.getStatus())) {
            prodRoute.setStatus("0");
        }
        if (prodRoute.getDetailList() == null || prodRoute.getDetailList().isEmpty()) {
            throw new ServiceException("工艺路线至少需要一条工序明细");
        }
    }

    private void ensureRouteCodeUnique(ProdRoute prodRoute) {
        ProdRoute existed = prodRouteMapper.selectProdRouteByRouteCode(prodRoute.getRouteCode());
        if (existed != null && !existed.getObjId().equals(prodRoute.getObjId())) {
            throw new ServiceException("路线编码已存在");
        }
    }

    private void saveRouteDetails(ProdRoute prodRoute, boolean insertMode) {
        Set<String> processCodeSet = new LinkedHashSet<String>();
        long sortNo = 1L;
        for (ProdRouteDetail detail : prodRoute.getDetailList()) {
            if (detail == null || StringUtils.isBlank(detail.getProcessCode())) {
                throw new ServiceException("工序明细不能为空");
            }
            if (!processCodeSet.add(detail.getProcessCode())) {
                throw new ServiceException("工艺路线中存在重复工序：" + detail.getProcessCode());
            }
            detail.setRouteCode(prodRoute.getRouteCode());
            if (detail.getSortNo() == null) {
                detail.setSortNo(sortNo);
            }
            if (StringUtils.isBlank(detail.getRequiredFlag())) {
                detail.setRequiredFlag("1");
            }
            if (insertMode) {
                detail.setCreatedBy(prodRoute.getCreatedBy());
                detail.setCreatedTime(DateUtils.getNowDate());
            } else {
                detail.setUpdatedBy(prodRoute.getUpdatedBy());
                detail.setUpdatedTime(DateUtils.getNowDate());
            }
            prodRouteMapper.insertProdRouteDetail(detail);
            sortNo++;
        }
    }
}
