package com.bonus.material.ma.service.impl;

import cn.hutool.core.convert.Convert;
import com.bonus.common.biz.config.ListPagingUtil;
import com.bonus.common.biz.domain.TreeSelect;
import com.bonus.common.biz.enums.HttpCodeEnum;
import com.bonus.common.core.utils.DateUtils;
import com.bonus.common.core.utils.ServletUtils;
import com.bonus.common.core.utils.StringUtils;
import com.bonus.common.core.web.domain.AjaxResult;
import com.bonus.common.security.utils.SecurityUtils;
import com.bonus.material.common.domain.vo.SelectVo;
import com.bonus.material.ma.domain.StandardConfigBean;
import com.bonus.material.ma.domain.Type;
import com.bonus.material.ma.domain.vo.MaTypeVo;
import com.bonus.material.ma.domain.vo.StandardConfigDetailsVo;
import com.bonus.material.ma.mapper.StandardConfigManageMapper;
import com.bonus.material.ma.mapper.TypeMapper;
import com.bonus.material.ma.service.StandardConfigManageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * 机械设备标准配置管理Service业务层实现
 *
 * @author hay
 */
@Service
public class StandardConfigManageServiceImpl implements StandardConfigManageService {

    @Resource
    private StandardConfigManageMapper mapper;


    @Override
    public AjaxResult getConfigTreeSelect(String configName, String parentId) {
        // 定义最终接口返回集合
        List<TreeSelect> treeSelectResultList = new ArrayList<>();
        try {
            // 1.顶级节点及子节点数据全部查询完毕
            treeSelectResultList = this.getConfigTree(configName, parentId);
            return AjaxResult.success(treeSelectResultList);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success(treeSelectResultList);
        }
    }

    @Override
    public AjaxResult getListByConfigId(StandardConfigDetailsVo bean) {
        List<StandardConfigDetailsVo> list = new ArrayList<>();
        Integer pageIndex = Convert.toInt(ServletUtils.getParameter("pageNum"), 1);
        Integer pageSize = Convert.toInt(ServletUtils.getParameter("pageSize"), 10);
        try {
            if (StringUtils.isNull(bean.getConfigId())){
                //查全部
                list.addAll(mapper.getListByParentId(null, bean));
            }else {
                //根据level层级和配置id 查询父级ID
                List<Integer> parentIds = mapper.selectParentId(bean);
                if (CollectionUtils.isEmpty(parentIds)) {
                    return AjaxResult.success(new ArrayList<>());
                }
                for (Integer parentId : parentIds) {
                    list.addAll(mapper.getListByParentId(parentId.longValue(), bean));
                }
            }
            return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, list));
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success(ListPagingUtil.paging(pageIndex, pageSize, new ArrayList<>()));
        }
    }

    @Override
    public AjaxResult getListsByConfigId(StandardConfigDetailsVo bean) {
        List<StandardConfigDetailsVo> list = new ArrayList<>();
        try {
            list= mapper.getListsByConfigId(bean.getConfigId());
            return AjaxResult.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.success(new ArrayList<>());
        }
    }

    /**
     * 导出标准配置管理列表
     * @param bean
     * @return
     */
    @Override
    public List<StandardConfigDetailsVo> selectStandardList(StandardConfigDetailsVo bean) {
        List<StandardConfigDetailsVo> list = new ArrayList<>();
        try {
            if (StringUtils.isNull(bean.getConfigId())){
                //查全部
                list.addAll(mapper.getListByParentId(null, bean));
            }else {
                //根据level层级和配置id 查询父级ID
                List<Integer> parentIds = mapper.selectParentId(bean);
                if (CollectionUtils.isEmpty(parentIds)) {
                    return new ArrayList<>();
                }
                for (Integer parentId : parentIds) {
                    list.addAll(mapper.getListByParentId(parentId.longValue(), bean));
                }
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public int insertConfig(StandardConfigBean bean) {
        //根据类型名称判断，去重
        StandardConfigBean bean1 = mapper.queryByNameAndParentId(bean.getConfigName(), bean.getParentId());
        if (bean1 != null) {
            throw new RuntimeException("同级下类型配置存在重复！");
        }
        bean.setLevel(String.valueOf(2));
        bean.setCreateTime(DateUtils.getNowDate());
        bean.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
        int count = mapper.insertConfig(bean);
        return count;
    }

    @Override
    public int updateConfig(StandardConfigBean bean) {
        //根据类型名称判断，去重
        StandardConfigBean bean1 = mapper.queryByNameAndParentId(bean.getConfigName(), bean.getParentId());
        if (bean1 != null && !bean1.getConfigId().equals(bean1.getConfigId())) {
            throw new RuntimeException("同级下类型配置存在重复！");
        }
        bean.setUpdateTime(DateUtils.getNowDate());
        bean.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
        int updateResult = mapper.updateConfig(bean);
        return updateResult;
    }

    @Override
    public AjaxResult deleteConfigByConfigId(StandardConfigBean bean) {
        if (StringUtils.isNull(bean.getConfigId())){
            return AjaxResult.error("删除失败,缺少参数");
        }
//        //根据configId查询删除类型下属是否有关联，有关联无法删除
//        List<StandardConfigDetailsVo> list = mapper.selectByConfigId(bean.getConfigId());
//        if (list!=null && list.size()>0) {
//            return AjaxResult.error("该类型下有子类型，无法删除");
//        }
        bean.setUpdateTime(DateUtils.getNowDate());
        bean.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
        int result = mapper.deleteConfigByConfigId(bean);
        int result2 = mapper.deleteConfigDetailByConfigId(bean);
        if (result > 0) {
            return AjaxResult.success(HttpCodeEnum.SUCCESS.getMsg(), result);
        }
        return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addConfigDetails(StandardConfigDetailsVo bean) throws Exception {
        if (bean.getTypeIds() != null && bean.getTypeIds().length > 0){
            for (Long typeId : bean.getTypeIds()) {
                // 根据configId和typeId 查询是否存在数据
                StandardConfigDetailsVo bean1 = new StandardConfigDetailsVo();
                bean1.setConfigId(bean.getConfigId());
                bean1.setTypeId(typeId);
                bean1.setNum(bean.getNum());
                int count = mapper.getCountById(bean1);
                if (count > 0) {
                    throw new Exception("该类型下已存在该配置！");
                }
                bean1.setCreateTime(DateUtils.getNowDate());
                bean1.setCreateBy(SecurityUtils.getLoginUser().getUserid().toString());
                int result = mapper.addConfigDetails(bean1);
                if(result <= 0){
                    throw new Exception("操作失败！");
                }
            }
        }
        return 1;
    }

    @Override
    public int updateConfigDetails(StandardConfigDetailsVo bean) {
        try {
            bean.setUpdateTime(DateUtils.getNowDate());
            bean.setUpdateBy(SecurityUtils.getLoginUser().getUserid().toString());
            int result = mapper.updateConfigDetails(bean);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public AjaxResult delConfigDetails(StandardConfigDetailsVo bean) {
        try {
            if (StringUtils.isNull(bean.getDetailsId())){
                return AjaxResult.error("删除失败,缺少参数");
            }
            int result = mapper.delConfigDetails(bean);
            return AjaxResult.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(HttpCodeEnum.FAIL.getCode(), HttpCodeEnum.FAIL.getMsg());
        }
    }

    @Override
    public AjaxResult getConfigLevelTwoList(StandardConfigBean bean) {
        List<StandardConfigBean> list = new ArrayList<>();
        try {
            list = mapper.getConfigLevelTwoList(bean);
        } catch (Exception e) {
            return AjaxResult.success(new ArrayList());
        }
        return AjaxResult.success(list);
    }

    public List<TreeSelect> getConfigTree(String typeName, String parentId) {
        List<StandardConfigBean> standardConfigs = mapper.selectStandardConfigTree();
        List<StandardConfigBean> builtConfigList = buildConfigTree(standardConfigs);

        // 查询顶级节点的仓库配置信息

        // 如果没有查询到那么返回空
        return builtConfigList.stream()
                .filter(Objects::nonNull)
                .map(this::convertToTreeSelect)
                .collect(Collectors.toList());
    }

    public List<StandardConfigBean> buildConfigTree(List<StandardConfigBean> configList) {
        List<StandardConfigBean> returnList = new ArrayList<StandardConfigBean>();
        List<Long> tempList = configList.stream().map(StandardConfigBean::getId).collect(Collectors.toList());
        for (StandardConfigBean maType : configList) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(maType.getParentId())) {
                recursionFn(configList, maType);
                returnList.add(maType);
            }
        }
        if (returnList.isEmpty()) {
            returnList = configList;
        }
        return returnList;
    }

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

    /**
     * 得到子节点列表
     */
    private List<StandardConfigBean> getChildList(List<StandardConfigBean> list, StandardConfigBean t) {
        List<StandardConfigBean> tlist = new ArrayList<>();
        for (StandardConfigBean n : list) {
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<StandardConfigBean> list, StandardConfigBean t) {
        return !getChildList(list, t).isEmpty();
    }

    /**
     * 通过构造函数将 Type对象 转换为 TreeSelect -- 并递归处理子节点
     *
     * @param type 要进行转换的object对象
     */
    private TreeSelect convertToTreeSelect(StandardConfigBean type) {
        List<TreeSelect> children = type.getChildren().stream()
                .filter(Objects::nonNull)
                .map(this::convertToTreeSelect)
                .collect(Collectors.toList());
        return new TreeSelect(type.getId(), type.getConfigName(), null, Integer.valueOf(type.getLevel()), type.getParentId(), children, null, null, null);
    }
}
