package com.huimv.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.huimv.admin.common.utils.Result;
import com.huimv.admin.common.utils.ResultCode;
import com.huimv.admin.common.utils.ResultUtil;
import com.huimv.admin.entity.BasePigpen;
import com.huimv.admin.entity.EnergyEnvDevice;
import com.huimv.admin.entity.EnvDevice;
import com.huimv.admin.entity.dto.BasePigpenDto;
import com.huimv.admin.entity.vo.TreeBasePigpen;
import com.huimv.admin.mapper.BasePigpenMapper;
import com.huimv.admin.mapper.EnergyEnvDeviceMapper;
import com.huimv.admin.mapper.EnvDeviceMapper;
import com.huimv.admin.service.IBasePigpenService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-02-13
 */
@Service
public class BasePigpenServiceImpl extends ServiceImpl<BasePigpenMapper, BasePigpen> implements IBasePigpenService {
    @Autowired
    private BasePigpenMapper basePigpenMapper;
    @Autowired
    private EnvDeviceMapper envDeviceMapper;
    @Autowired
    private EnergyEnvDeviceMapper energyEnvDeviceMapper;
    @Override
    @Transactional
    public Result addPigpen(BasePigpenDto basePigpenDto) {
        Integer num = basePigpenMapper.selectCount(new QueryWrapper<BasePigpen>().eq("build_name", basePigpenDto.getBuildName())
                .eq("farm_id", basePigpenDto.getFarmId()).ne("other3",1));
        if (num > 0) {
            return new Result(10001, "栋舍名称已存在！", false);
        }
        BasePigpen basePigpen = new BasePigpen();
        BeanUtil.copyProperties(basePigpenDto, basePigpen);
        basePigpen.setParentId(0);
        basePigpen.setFType(1);
        basePigpen.setOther2("0");
        int insert = basePigpenMapper.insert(basePigpen);
        Integer id = basePigpen.getId();
        String buildName = basePigpen.getBuildName();
        Integer floorNum = basePigpenDto.getFloorNum();
        for (Integer integer = 1; integer <= floorNum; integer++) {
            BasePigpen basePigpen1 = new BasePigpen();
            basePigpen1.setFType(2);
            basePigpen1.setParentId(id);
            basePigpen1.setBuildName(buildName + Convert.numberToChinese(integer, false) + "层");
            basePigpen1.setOther1(Convert.numberToChinese(integer, false) + "层");
            basePigpen1.setOther2("0," + id);
            basePigpen1.setFarmId(basePigpen.getFarmId());
            basePigpen1.setStageCode(basePigpen.getStageCode());
            basePigpenMapper.insert(basePigpen1);
        }
        return ResultUtil.addResult(insert);
    }

    @Override
    @Transactional
    public Result updatePigpen(BasePigpen basePigpen) {
        Integer num = basePigpenMapper.selectCount(new QueryWrapper<BasePigpen>().eq("build_name", basePigpen.getBuildName())
                .eq("farm_id", basePigpen.getFarmId()).ne("id", basePigpen.getId()).ne("other3",1));
        if (num > 0) {
            return new Result(10001, "栋舍名称已存在！", false);
        }
        basePigpenMapper.updateById(basePigpen);
        Integer id = basePigpen.getId();
        List<BasePigpen> parentId = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().eq("parent_id", id));
        String buildName = basePigpen.getBuildName();
        if (StringUtils.isNotBlank(buildName)) {
            for (BasePigpen pigpen : parentId) {
                String other1 = pigpen.getOther1();
                pigpen.setBuildName(buildName + other1);
                basePigpenMapper.updateById(pigpen);
            }
        }
        return ResultUtil.updateResult(1);
    }

    @Override
    @Transactional
    public Result deletePigpen(Map<String, Integer> map) {
        Integer integer = map.get("id");
        Integer count1 = energyEnvDeviceMapper.selectCount(new QueryWrapper<EnergyEnvDevice>().eq("unit_id", integer));
        Integer integer1 = envDeviceMapper.selectCount(new QueryWrapper<EnvDevice>().eq("unit_id", integer));
        if (integer1 > 0) {
            return new Result(10001, "删除失败，该栋舍下有温湿度采集器", false);
        }
        if (count1 > 0) {
            return new Result(10001, "删除失败，该栋舍下有水电表", false);
        }
        List<BasePigpen> other2 = basePigpenMapper.selectList(new QueryWrapper<BasePigpen>().like("other2", integer));
        for (BasePigpen basePigpen : other2) {
            Integer count = envDeviceMapper.selectCount(new QueryWrapper<EnvDevice>().eq("unit_id", basePigpen.getId()));
            Integer integer2 = envDeviceMapper.selectCount(new QueryWrapper<EnvDevice>().eq("unit_id", integer));
            if (count > 0) {
                return new Result(10001, "删除失败，该栋舍下有温湿度采集器", false);
            }
            if (integer2 > 0) {
                return new Result(10001, "删除失败，该栋舍下有水电表", false);
            }
            basePigpenMapper.deleteById(basePigpen.getId());
        }
        basePigpenMapper.deleteById(integer);
        return ResultUtil.deleteResult(1);
    }

    @Override
    public Result list(String farmCode, String buildName, String stageCode, String type) {
        QueryWrapper<BasePigpen> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(buildName), "build_name", buildName);
        queryWrapper.like(StringUtils.isNotBlank(stageCode), "stage_code", stageCode);
        queryWrapper.eq(StringUtils.isNotBlank(farmCode), "farm_id", farmCode);
        queryWrapper.eq("other3", type);
        queryWrapper.orderByAsc("sort");
        //创建排序
        List<BasePigpen> basePigpens = basePigpenMapper.selectList(queryWrapper);
        //将结果List改为树
        List<TreeBasePigpen> treeBasePigpens = parseBizBaseArea(basePigpens);
        return new Result(ResultCode.SUCCESS, treeBasePigpens);
    }

    /**
     * 查询结果 转换成树形结构
     *
     * @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.getFarmId());
            baseVo.setParentId(basePigpen.getParentId());
            baseVo.setSort(basePigpen.getSort());
            baseVo.setStageCode(basePigpen.getStageCode());
            baseVo.setPigpenName(basePigpen.getBuildName());
            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;
    }
}
