package com.bonus.sgzb.base.service.impl;

import com.bonus.sgzb.base.api.domain.MaType;
import com.bonus.sgzb.base.domain.MaPropSet;
import com.bonus.sgzb.base.domain.MaTypeFile;
import com.bonus.sgzb.base.domain.MaTypeKeeper;
import com.bonus.sgzb.base.domain.MaTypeRepair;
import com.bonus.sgzb.base.domain.vo.TreeSelect;
import com.bonus.sgzb.base.mapper.MaTypeFileMapper;
import com.bonus.sgzb.base.mapper.MaTypeMapper;
import com.bonus.sgzb.base.service.ITypeService;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.common.core.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工机具类型管理实现层
 */
@Service
public class MaTypeServiceImpl implements ITypeService {

    @Resource
    private MaTypeMapper maTypeMapper;

    @Resource
    private MaTypeFileMapper typeFileMapper;

    /**
     * 查询机具类型管理ma_type
     *
     * @param typeId 机具类型管理ma_type主键
     * @return 机具类型管理ma_type
     */
    @Override
    public MaType selectMaTypeByTypeId(Long typeId) {
        return maTypeMapper.selectMaTypeByTypeId(typeId);
    }


    /**
     * 新增机具类型管理ma_type
     *
     * @param maType 机具类型管理ma_type
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMaType(MaType maType) {
        Long parentId = maType.getParentId();
        List<MaType> subMas = maTypeMapper.getListByParentId(parentId, null);
        boolean containsSameBrother = subMas.stream().anyMatch(o -> o.getTypeName().contains(maType.getTypeName()));
        if (containsSameBrother) {
            return 0;
        }
        MaType maType1 = maTypeMapper.selectMaTypeByTypeId(parentId);
        String level = maType1.getLevel();
        maType.setLevel(String.valueOf(Integer.parseInt(level) + 1));
        maType.setCreateTime(DateUtils.getNowDate());
        int i = maTypeMapper.insertType(maType);
        Long typeId = maType.getTypeId();
        // 图片路径保存
        if (StringUtils.isNotEmpty(maType.getPhotoName()) && StringUtils.isNotEmpty(maType.getPhotoUrl())) {
            MaTypeFile typeFile = new MaTypeFile();
            typeFile.setTypeId(typeId);
            typeFile.setFileName(maType.getPhotoName());
            typeFile.setFileUrl(maType.getPhotoUrl());
            typeFile.setFileType("1");
            typeFileMapper.insertMaTypeFile(typeFile);
        }
        // 文档路径保存
        if (StringUtils.isNotEmpty(maType.getDocumentName()) && StringUtils.isNotEmpty(maType.getDocumentUrl())) {
            MaTypeFile typeFile1 = new MaTypeFile();
            typeFile1.setTypeId(typeId);
            typeFile1.setFileName(maType.getDocumentName());
            typeFile1.setFileUrl(maType.getDocumentUrl());
            typeFile1.setFileType("2");
            typeFileMapper.insertMaTypeFile(typeFile1);
        }
        // 库管员配置
        MaTypeKeeper typeKeeper = new MaTypeKeeper();
        typeKeeper.setUserId(maType.getKeeperUserId());
        typeKeeper.setTypeId(typeId);
        maTypeMapper.insertKeeper(typeKeeper);

        // 维修员配置
        MaTypeRepair typeRepair = new MaTypeRepair();
        typeRepair.setUserId(maType.getRepairUserId());
        typeRepair.setTypeId(typeId);
        maTypeMapper.insertRepair(typeRepair);
        // 资产属性配置
        MaPropSet propSet = new MaPropSet();
        propSet.setTypeId(typeId);
        propSet.setPropId(maType.getPropId());
        maTypeMapper.insertMaPropSet(propSet);
        return i;
    }

    /**
     * 修改机具类型管理ma_type
     *
     * @param maType 机具类型管理ma_type
     * @return 结果
     */
    @Override
    public int updateMaType(MaType maType) {
        Long typeId = maType.getTypeId();
        maType.setUpdateTime(DateUtils.getNowDate());
        int i = maTypeMapper.updateType(maType);
        // 图片路径保存
        if (StringUtils.isNotEmpty(maType.getPhotoName()) && StringUtils.isNotEmpty(maType.getPhotoUrl())) {
            typeFileMapper.deleteMaTypeFileByTypeId(typeId, "1");
            MaTypeFile typeFile = new MaTypeFile();
            typeFile.setTypeId(typeId);
            typeFile.setFileName(maType.getPhotoName());
            typeFile.setFileUrl(maType.getPhotoUrl());
            typeFile.setFileType("1");
            typeFileMapper.insertMaTypeFile(typeFile);
        }
        // 文档路径保存
        if (StringUtils.isNotEmpty(maType.getDocumentName()) && StringUtils.isNotEmpty(maType.getDocumentUrl())) {
            typeFileMapper.deleteMaTypeFileByTypeId(typeId, "2");
            MaTypeFile typeFile1 = new MaTypeFile();
            typeFile1.setTypeId(typeId);
            typeFile1.setFileName(maType.getDocumentName());
            typeFile1.setFileUrl(maType.getDocumentUrl());
            typeFile1.setFileType("2");
            typeFileMapper.insertMaTypeFile(typeFile1);
        }
        // 库管员配置
        if (maType.getKeeperUserId() >= 0L) {
            maTypeMapper.deleteKeeperByTypeId(typeId);
            MaTypeKeeper typeKeeper = new MaTypeKeeper();
            typeKeeper.setUserId(maType.getKeeperUserId());
            typeKeeper.setTypeId(typeId);
            maTypeMapper.insertKeeper(typeKeeper);
        }

        // 维修员配置
        if (maType.getRepairUserId() >= 0L) {
            maTypeMapper.deleteTypeByTypeId(typeId);
            MaTypeRepair typeRepair = new MaTypeRepair();
            typeRepair.setUserId(maType.getRepairUserId());
            typeRepair.setTypeId(typeId);
            maTypeMapper.insertRepair(typeRepair);
        }
        // 资产属性配置
        if (maType.getPropId() >= 0L) {
            maTypeMapper.deletePropSetByTypeId(typeId);
            MaPropSet propSet = new MaPropSet();
            propSet.setTypeId(typeId);
            propSet.setPropId(maType.getPropId());
            maTypeMapper.insertMaPropSet(propSet);
        }
        return i;
    }

    /**
     * 删除机具类型管理ma_type信息
     *
     * @param typeId 机具类型管理ma_type主键
     * @return 结果
     */
    @Override
    public int deleteMaTypeByTypeId(Long typeId) throws Exception {
        List<MaType> listByParentId = maTypeMapper.getListByParentId(typeId, "");
        if (listByParentId.size() > 0) {
            throw new Exception("子级类型不为空!!!");
        }
        return maTypeMapper.deleteTypeById(typeId);
    }

    @Override
    public List<TreeSelect> getMaTypeList(String typeName, String parentId) {
        List<MaType> maTypes = maTypeMapper.selectMaTypeTree(parentId);
        List<TreeSelect> treeSelectList = buildDeptTreeSelect(maTypes);
        //如果没有查询到那么返回空
        return treeSelectList;
    }

    @Override
    public List<TreeSelect> getMaTypeSelect(String typeName, String parentId) {
        List<MaType> maTypes = maTypeMapper.getMaTypeSelect(parentId);
        List<TreeSelect> treeSelectList = buildDeptTreeSelect(maTypes);
        //如果没有查询到那么返回空
        return treeSelectList;
    }


    /**
     * 根据左列表类型id查询右表格
     *
     * @param typeId
     * @return
     */
    @Override
    public List<MaType> getListByMaType(Long typeId, String typeName) {
        List<MaType> maTypes = maTypeMapper.selectMaTypeList("");
        MaType maType = new MaType();
        maType.setTypeId(typeId);

        List<MaType> typeListByMaType = getTypeListByMaType(Collections.singletonList(maType), maTypes, new ArrayList<>());

        if (StringUtils.isNotNull(typeName)) {
            //根据类型名称过滤集合
            List<MaType> types = typeListByMaType
                    .stream()
                    .filter(ma -> ma.getTypeName().contains(typeName))
                    .collect(Collectors.toList());
            //如果没有查询到那么返回空
            return types;
        }
        return typeListByMaType;
    }

    /**
     * 根据父级类型递归获取树结构
     *
     * @param
     * @return
     */
    private List<MaType> getTypeListByMaType(List<MaType> parentTypes, List<MaType> oldMaTypes, List<MaType> newMaTypes) {
        //初始化新容器
        if (newMaTypes == null) {
            newMaTypes = new ArrayList<>();
            //添加父级对象 左边需要添加因为需要显示  右边不需要添加因为不需要显示
            newMaTypes.addAll(parentTypes);
        }
        //递归父级容器
        List<MaType> parentList = new ArrayList<>();
        //过滤相同数据,减少循环,性能优化
        oldMaTypes = oldMaTypes.stream().filter(oldMaType -> !parentTypes.contains(oldMaType)).collect(Collectors.toList());
        for (MaType maType : oldMaTypes) {
            for (MaType parentType : parentTypes) {
                if (maType.getParentId().equals(parentType.getTypeId())) {

                    newMaTypes.add(maType);
                    parentList.add(maType);
                }
            }
        }
        //如果还有父级递归查询
        if (parentList.size() > 0) {
            return getTypeListByMaType(parentList, oldMaTypes, newMaTypes);
        } else {
            List<MaType> result = new ArrayList<>();
            for (MaType type : newMaTypes) {
                boolean a = true;
                Long typeId1 = type.getTypeId();
                for (MaType type1 : newMaTypes) {
                    Long pid = type1.getParentId();
                    if (typeId1.equals(pid)) {
                        a = false;
                    }
                }
                if (a) {
                    result.add(type);
                }
            }
            //返回
            return result;
        }
    }


    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<MaType> depts) {
        List<MaType> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建前端所需要树结构
     *
     * @param maTypeList 部门列表
     * @return 树结构列表
     */
    @Override
    public List<MaType> buildDeptTree(List<MaType> maTypeList) {
        List<MaType> returnList = new ArrayList<MaType>();
        List<Long> tempList = maTypeList.stream().map(MaType::getTypeId).collect(Collectors.toList());
        for (MaType maType : maTypeList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(maType.getParentId())) {
                recursionFn(maTypeList, maType);
                returnList.add(maType);
            }
        }
        if (returnList.isEmpty()) {
            returnList = maTypeList;
        }
        return returnList;
    }

    /**
     * 根据组织树parent_id查询结果
     *
     * @param typeId   父级id
     * @param typeName 名称筛选
     * @return
     */
    @Override
    public List<MaType> getListByParentId(Long typeId, String typeName) {
        return maTypeMapper.getListByParentId(typeId, typeName);
    }

    /**
     * 查询工器具类型四级组织树
     *
     * @param typeId
     * @param typeName
     * @return
     */
    @Override
    public List<MaType> getEquipmentType(Long typeId, String typeName) {
        List<MaType> maTypes = maTypeMapper.selectMaTypeList("");
        List<MaType> list = new ArrayList<>();
        for (MaType maType : maTypes) {
            if (maType.getParentId() == 0) {
                list.add(maType);
            }
        }
        List<MaType> tree = new ArrayList<>();
        //根据父节点获取对应的儿子节点
        for (MaType maType : list) {
            List<MaType> child = getChild(maTypes, maType.getTypeId());
            maType.setChildren(child);
            tree.add(maType);
        }

        return list;
    }


    /**
     * @Author dingjie
     * @Date 2023/12/14
     * @Description 递归调用获取儿子
     */
    public List<MaType> getChild(List<MaType> list, Long parentId) {
        List<MaType> childList = new ArrayList<MaType>();
        for (MaType maType : list) {
            Long typeId = maType.getTypeId();
            Long pid = maType.getParentId();
            if (parentId.equals(pid)) {
                List<MaType> childLists = getChild(list, typeId);

                maType.setChildren(childLists);
                childList.add(maType);
            }
        }
        return childList;
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<MaType> list, MaType t) {
        // 得到子节点列表
        List<MaType> childList = getChildList(list, t);
        t.setChildren(childList);
        for (MaType tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 得到子节点列表
     */
    private List<MaType> getChildList(List<MaType> list, MaType t) {
        List<MaType> tlist = new ArrayList<MaType>();
        Iterator<MaType> it = list.iterator();
        while (it.hasNext()) {
            MaType n = (MaType) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getTypeId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }


    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<MaType> list, MaType t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }
}
