package com.huimv.eartag2.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huimv.eartag2.admin.entity.BasePigpen;
import com.huimv.eartag2.admin.mapper.BasePigpenMapper;
import com.huimv.eartag2.admin.service.BasePigpenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.eartag2.admin.utils.IDUtil;
import com.huimv.eartag2.admin.utils.ResultUtil;
import com.huimv.eartag2.admin.vo.TreeBasePigpen;
import com.huimv.eartag2.common.utils.Result;
import com.huimv.eartag2.common.utils.ResultCode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zn
 * @since 2022-11-09
 */
@Service
public class BasePigpenServiceImpl extends ServiceImpl<BasePigpenMapper, BasePigpen> implements BasePigpenService {
    @Autowired
    private BasePigpenMapper basePigpenMapper;
    @Autowired
    private ResultUtil resultUtil;
    @Autowired
    private IDUtil idUtil;

    /**
     * @Method      : addBuilding
     * @Description :
     * @Params      : [farmCode, buildingName, buildingCode, stageCode, sort, type]
     * @Return      : com.huimv.eartag2.common.utils.Result
     *
     * @Author      : ZhuoNing
     * @Date        : 2022/7/23
     * @Time        : 15:16
     */
    @Override
    public Result addBuilding(String farmCode, String buildingName, String buildingCode, String stageCode, Integer sort, Integer type) {
        BasePigpen newBasePigpen = new BasePigpen();
        newBasePigpen.setFarmCode(farmCode);
        newBasePigpen.setPigpenCode(buildingCode);
        newBasePigpen.setPigpenName(buildingName);
        newBasePigpen.setStageCode(stageCode);
        newBasePigpen.setSort(sort);
        newBasePigpen.setFType(type);
        long pigpen_code = this.count(new QueryWrapper<BasePigpen>().eq("pigpen_code", buildingCode));
        if (pigpen_code>1){
            return  new Result(10001,"栋舍编码重复",false);
        }
        return resultUtil.result(basePigpenMapper.insert(newBasePigpen));
    }

    @Override
    public Result editBuilding(String id, String buildingName, String stageCode, Integer sort, Integer type) {
        BasePigpen basePigpen = basePigpenMapper.selectById(id);
        if(basePigpen == null){
            return new Result(ResultCode.FAIL,"该记录不存在.");
        }else{
            basePigpen.setPigpenName(buildingName);
            basePigpen.setStageCode(stageCode);
            basePigpen.setSort(sort);
            return resultUtil.result(basePigpenMapper.updateById(basePigpen));
        }
    }

    @Override
    public Result remove(String ids) {
        //如果删除的节点是父节点，需要将其字节点全部删除掉
//       QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("parent_id",ids);
//        //查寻到所有的子数据
//        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);
//        List<Integer> childIdList = basePigpens.stream().map(BasePigpen::getId).collect(Collectors.toList());
//        //删除子数据
//        basePigpenMapper.deleteBatchIds(childIdList);

        List<Integer> idList = idUtil.convert(ids);
        List<BasePigpen> basePigpens1 = new ArrayList<>();
        for (Integer integer : idList) {
            QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parent_id",integer);
            List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);
            basePigpens1.addAll(basePigpens);
        }
        List<Integer> childIdList = basePigpens1.stream().map(BasePigpen::getId).collect(Collectors.toList());
        System.out.println("___________________"+childIdList);

        //childIdList如果是空的、就说明直接删除单元吧
        if (null == childIdList || childIdList.size() == 0){
            basePigpenMapper.deleteBatchIds(idList);
        }else {
            //删除子数据
            basePigpenMapper.deleteBatchIds(childIdList);
            basePigpenMapper.deleteBatchIds(idList);
        }
        //删除当前id的数据
        return resultUtil.result(1);
    }

    @Override
    public Result addUnit(String farmCode, String parentId, String unitName, String unitCode, String stageCode, Integer sort, Integer type) {
        BasePigpen newBasePigpen = new BasePigpen();
        newBasePigpen.setFarmCode(farmCode);
        newBasePigpen.setPigpenCode(unitCode);
        newBasePigpen.setPigpenName(unitName);
        newBasePigpen.setParentId(Integer.parseInt(parentId));
        newBasePigpen.setSort(sort);
        newBasePigpen.setFType(type);
        newBasePigpen.setStageCode(stageCode);
        return resultUtil.result(basePigpenMapper.insert(newBasePigpen));
    }

    @Override
    public Result editUnit(String id, String parentId, String unitName,  String stageCode, Integer sort, Integer type) {
        BasePigpen basePigpen = basePigpenMapper.selectById(id);
        if(basePigpen == null){
            return new Result(ResultCode.FAIL,"该记录不存在.");
        }else{
            basePigpen.setPigpenName(unitName);
            basePigpen.setParentId(Integer.parseInt(parentId));
            basePigpen.setSort(sort);
            basePigpen.setFType(type);
            basePigpen.setStageCode(stageCode);
            return resultUtil.result(basePigpenMapper.updateById(basePigpen));
        }
    }

    @Override
    public Result list(String farmCode, String pigpenName, String stageCode) {
        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like(StringUtils.isNotBlank(pigpenName),"pigpen_name", pigpenName);
//        queryWrapper.like(StringUtils.isNotBlank(stageCode),"stage_code", stageCode);
        queryWrapper.eq(StringUtils.isNotBlank(farmCode),"farm_code", farmCode);
        //创建排序
//        queryWrapper.orderByAsc("sort");
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);
        //Page<BasePigpen> pageBasePigpen = basePigpenMapper.selectPage(page, queryWrapper);

        //将结果List改为树
        List<TreeBasePigpen> treeBasePigpens = parseBizBaseArea(basePigpens);

        //树型结构模糊查询父名称
        for (int i = 0; i < treeBasePigpens.size(); i++){
            TreeBasePigpen treeBasePigpen = treeBasePigpens.get(i);
            String name = treeBasePigpen.getPigpenName();
            Boolean flag = false;
            for (int j = 0; j < name.length()-pigpenName.length()+1; j++){
                String substring = name.substring(j, j + pigpenName.length());
                if ((pigpenName.equals(substring))){
                    flag = true;
                    break;
                }
            }
            System.out.println(flag);
            if (!flag){
                treeBasePigpens.remove(i);
                i--;
            }
        }

        return new Result(ResultCode.SUCCESS,treeBasePigpens);
    }

    @Override
    public Result listBuildings(Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        return new Result(ResultCode.SUCCESS,basePigpenMapper.listBuildings(farmId));
    }

    @Override
    public Result listUnitByBuilding( Map<String, String> paramsMap) {
        String farmId = paramsMap.get("farmId");
        String buildingId = paramsMap.get("buildingId");
        return new Result(ResultCode.SUCCESS,basePigpenMapper.listUnitByBuilding(farmId,buildingId));
    }


    /**
     * 查询结果 转换成树形结构
     * @param bizBaseAreas 原始数据
     * @return 树
     */
    private List<TreeBasePigpen> parseBizBaseArea(List<BasePigpen> bizBaseAreas){
        //构建需要展示的树形节点结构
        Map<String, TreeBasePigpen> nodeMap = bizBaseAreas.stream().map(basePigpen -> {
            TreeBasePigpen  baseVo = new TreeBasePigpen();
            baseVo.setId(basePigpen.getId()+"");
            baseVo.setFarmCode(basePigpen.getFarmCode());
            baseVo.setPigpenCode(basePigpen.getPigpenCode());
            baseVo.setParentId(basePigpen.getParentId());
            baseVo.setSort(basePigpen.getSort());
            baseVo.setPigpenName(basePigpen.getPigpenName());
            baseVo.setStageCode(basePigpen.getStageCode());
            baseVo.setType(basePigpen.getFType());
            baseVo.setChildNode(new ArrayList<>());
            return baseVo;
        }).collect(Collectors.toMap(TreeBasePigpen::getId, b -> b,(k1, k2)->k1));
        //创建数组存父亲节点
        ArrayList<TreeBasePigpen> roots = new ArrayList<>();
        //构建树形
        nodeMap.values().forEach(item->{
            String parentCode = item.getParentId()+"";
            if (nodeMap.get(parentCode) == null){
                //父节点为空，说明当前节点就已经是父节点了 将该节点存起来
                roots.add(item);
            }else {
                //父节点 不为空，说明有父节点，拿到该节点的父节点的孩子节点（就是我自己),将该节点存起来
                nodeMap.get(parentCode).getChildNode().add(item);
            }
        });
        return roots;
    }
}
