package com.huashe.park.core.service.impl;

import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.huashe.common.exception.ServiceException;
import com.huashe.park.common.i18n.MessageUtils;
import com.huashe.park.core.mapper.ConsUnitInfoMapper;
import com.huashe.park.core.service.IConsPileHoleInfoService;
import com.huashe.park.core.service.IConsUnitInfoService;
import com.huashe.park.core.service.IConsUnitMachineRelService;
import com.huashe.park.domain.dto.cons.ConsUnitMachine;
import com.huashe.park.domain.entity.ConsPileHoleInfo;
import com.huashe.park.domain.entity.ConsUnitInfo;
import com.huashe.park.domain.entity.ConsUnitMachineRel;
import com.huashe.park.infrastructure.excel.ExcelHandle;
import com.ruoyi.common.config.RuoYiConfig;

/**
 * 施工单元Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-02-14
 */
@Service
public class ConsUnitInfoServiceImpl implements IConsUnitInfoService {

    @Autowired
    private ConsUnitInfoMapper consUnitInfoMapper;

    @Autowired
    private IConsUnitMachineRelService consUnitMachineRelService;

    @Autowired
    private IConsPileHoleInfoService pileHoleInfoService;

    @Autowired
    private ExcelHandle excelHandle;

    private final static String PROFILE = "/profile";

    /**
     * 查询施工单元
     * 
     * @param id 施工单元主键
     * @return 施工单元
     */
    @Override
    public ConsUnitMachine selectConsUnitInfoById(Long id) {
        ConsUnitInfo consUnitInfo = consUnitInfoMapper.selectConsUnitInfoById(id);
        List<Long> machineIds = consUnitMachineRelService.qryConsUnitMachineRelByUnitId(id);
        // constUnitInfo 赋值 ConsUnitMachine
        ConsUnitMachine result = new ConsUnitMachine();
        BeanUtils.copyProperties(consUnitInfo, result);
        result.setMachineId(machineIds);
        return result;
    }

    /**
     * 查询施工单元列表
     * 
     * @param consUnitInfo 施工单元
     * @return 施工单元
     */
    @Override
    public List<ConsUnitInfo> selectConsUnitInfoList(ConsUnitInfo consUnitInfo) {
        return consUnitInfoMapper.selectConsUnitInfoList(consUnitInfo);
    }

    /**
     * 新增施工单元
     * 
     * @param consUnitInfo 施工单元
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertConsUnitInfo(ConsUnitMachine consUnitInfo) {
        // 处理施工单元信息
        ConsUnitInfo parentConsUnit = consUnitInfoMapper.selectConsUnitInfoById(consUnitInfo.getParentId());
        consUnitInfo.setAncestors(parentConsUnit.getAncestors() + "," + parentConsUnit.getId());
        int cnt = consUnitInfoMapper.insertConsUnitInfo(consUnitInfo);
        // 处理施工单元关联信息
        handleMachine(consUnitInfo);
        return cnt;
    }

    /**
     * 修改施工单元
     * 
     * @param consUnitInfo 施工单元
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateConsUnitInfo(ConsUnitMachine consUnitInfo) {
        if (consUnitInfo.getParentId().equals(consUnitInfo.getId())) {
            throw new ServiceException(MessageUtils.message("cons.unit.modify.not.self", consUnitInfo.getName()));
        }
        ConsUnitMachine oldConsUnit = selectConsUnitInfoById(consUnitInfo.getId());
        if (!consUnitInfo.getParentId().equals(oldConsUnit.getParentId())) {
            ConsUnitInfo newParentConsUnit = consUnitInfoMapper.selectConsUnitInfoById(consUnitInfo.getParentId());
            if (ObjectUtils.isNotEmpty(newParentConsUnit) && ObjectUtils.isNotEmpty(oldConsUnit)) {
                String newAncestors = newParentConsUnit.getAncestors() + "," + newParentConsUnit.getId();
                String oldAncestors = oldConsUnit.getAncestors();
                consUnitInfo.setAncestors(newAncestors);
                updateConsUnitChildren(consUnitInfo.getId(), newAncestors, oldAncestors);
            }
        }
        return consUnitInfoMapper.updateConsUnitInfo(consUnitInfo);
    }

    @Override
    public void assignMachine(ConsUnitMachine consUnitInfo) {
        handleMachine(consUnitInfo);
    }

    /**
     * 批量删除施工单元
     * 
     * @param ids 需要删除的施工单元主键
     * @return 结果
     */
    @Override
    public int deleteConsUnitInfoByIds(Long[] ids) {
        return consUnitInfoMapper.deleteConsUnitInfoByIds(ids);
    }

    @Override
    public boolean hasChildById(Long id) {
        return consUnitInfoMapper.hasChildById(id) > 0;
    }

    /**
     * 删除施工单元信息
     * 
     * @param id 施工单元主键
     * @return 结果
     */
    @Override
    public int deleteConsUnitInfoById(Long id) {
        if (hasChildById(id)) {
            throw new ServiceException(MessageUtils.message("cons.unit.delete.no.child"));
        }
        pileHoleInfoService.deleteConsPileHoleInfoByConsUnitId(id);
        consUnitMachineRelService.deleteConsUnitMachineRelByUnitId(id);
        return consUnitInfoMapper.deleteConsUnitInfoById(id);
    }

    @Override
    public void importConsUnitHole(ConsUnitInfo consUnitHole) {
        int lastIndex = RuoYiConfig.getUploadPath().lastIndexOf("/");
        String filePath = consUnitHole.getFileId().replaceFirst(PROFILE,
            RuoYiConfig.getUploadPath().substring(0, lastIndex));
        consUnitInfoMapper.updateConsUnitInfo(consUnitHole);
        pileHoleInfoService.deleteConsPileHoleInfoByConsUnitId(consUnitHole.getId());
        excelHandle.importExcel(filePath, ConsPileHoleInfo.class, (data) -> {
            data.forEach((d) -> {
                d.setConsUnitId(consUnitHole.getId());
            });
            pileHoleInfoService.importConsPileHole(data);
        });
    }

    private void updateConsUnitChildren(Long id, String newAncestors, String oldAncestors) {
        List<ConsUnitInfo> children = consUnitInfoMapper.selectChildrenById(id);
        if (CollectionUtils.isEmpty(children)) {
            return;
        }
        for (ConsUnitInfo child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        consUnitInfoMapper.updateConstUnitChildren(children);
    }

    private void handleMachine(ConsUnitMachine consUnitMachine) {
        consUnitMachineRelService.deleteConsUnitMachineRelByUnitId(consUnitMachine.getId());
        if (!CollectionUtils.isEmpty(consUnitMachine.getMachineId())) {
            List<ConsUnitMachineRel> consUnitMachineRel = new java.util.ArrayList<>();
            for (Long machineId : consUnitMachine.getMachineId()) {
                consUnitMachineRel.add(new ConsUnitMachineRel() {
                    {
                        setConsUnitId(consUnitMachine.getId());
                        setMachineId(machineId);
                        // 存在更新问题，在施工单元换节点的时候存在不一致的场景
                        // setUnitAncestors(consUnitMachine.getAncestors());
                    }
                });
            }
            consUnitMachineRelService.insertConsUnitMachineRelList(consUnitMachineRel);
        }
    }
}
