package com.repair.controller;


import com.repair.api.RepairAreaControllerAPI;
import com.repair.common.utils.paramUtils;
import com.repair.model.pojo.RepairArea;
import com.repair.model.request.updateRepairAreaRequest;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.model.vo.RepairAreaTreeVo;
import com.repair.model.vo.RepairSchoolVo;
import com.repair.services.RepairAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-12
 */
@RestController
public class RepairAreaController implements RepairAreaControllerAPI {

    @Autowired
    private RepairAreaService repairAreaService;

    /**
     * 添加区域
     * @param repairArea 添加区域参数
     * @param bindingResult 判断是否为空校验
     * @return
     */
    @Override
    public CommonResult InsertRepairArea(RepairArea repairArea, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        RepairArea data = repairAreaService.queryAreaByName(repairArea.getName(), repairArea.getParentId());
        if (data != null) {
            return CommonResult.fail("该区域楼层已存在！");
        }

        int result = repairAreaService.insertRepairArea(repairArea);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 编辑区域数据
     * @param urar 编辑的区域内容
     * @param bindingResult 判断是否为空校验
     * @return
     */
    @Override
    public CommonResult updateRepairAreaById(updateRepairAreaRequest urar, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        RepairArea data = repairAreaService.getRepairById(urar.getId());
        RepairArea otherData = repairAreaService.queryAreaByName(urar.getName(), data.getParentId());
        if (data != null && otherData != null && !data.getId().equals(otherData.getId())) {
            return CommonResult.fail("该区域楼层已存在！");
        }

        RepairArea ra = new RepairArea();
        ra.setId(urar.getId());
        ra.setName(urar.getName());
        int result = repairAreaService.updateRepairArea(ra);

        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

    /**
     * 查询区域分页
     * @param currentPage 当前页
     * @param pageCount 一页数据条数
     * @param name 区域名称
     * @return
     */
    @Override
    public CommonResult queryPageRepairAreas(int currentPage, int pageCount, String name) {
        PageUtils<RepairArea> result = repairAreaService.queryPageRepairAreas(currentPage, pageCount, name);
        return CommonResult.ok(result);
    }

    /**
     * 查询校区
     * @return
     */
    @Override
    public CommonResult queryRepairSchools() {
        List<RepairSchoolVo> result = repairAreaService.queryRepairSchools();
        return CommonResult.ok(result);
    }

    /**
     * 根据ID删除区域
     * @param id 数据ID
     * @return
     */
    @Override
    public CommonResult deleteRepairAreaById(int id) {
        RepairArea data = repairAreaService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairAreaService.deleteRepairAreaById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

    /**
     * 查询对应校区区域树形图数据
     * @param schoolId
     * @return
     */
    @Override
    public CommonResult queryRepairAreaTree(int schoolId) {
        List<RepairArea> result = repairAreaService.getRepairAreas();
        List<RepairAreaTreeVo> datas = QueryAreaTreeRecords(schoolId, result);
        return CommonResult.ok(datas);
    }

    /**
     * 根据父类ID获取树形菜单数据
     * @param parentID 父级ID
     * @param lists 数据集合
     * @return
     */
    private List<RepairAreaTreeVo> QueryAreaTreeRecords(Integer parentID, List<RepairArea> lists) {
        List<RepairAreaTreeVo> newTrees = new ArrayList<>();

        List<RepairArea> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).collect(Collectors.toList());

        for (RepairArea data : datas) {
            RepairAreaTreeVo item = RepairAreaTreeVo.builder()
                    .id(data.getId())
                    .parentId(data.getParentId())
                    .name(data.getName())
                    .build();
            List<RepairAreaTreeVo> news = QueryAreaTreeRecords(item.getId(), lists);
            if (news == null || news.size() == 0) {
                newTrees.add(item);
                continue;
            } else {
                item.setChildren(news);
                newTrees.add(item);
            }
        }

        return newTrees;
    }

    /**
     * 关联楼栋数据获取（总共只获取两级）
     * @param schoolId 校区ID
     * @return
     */
    @Override
    public CommonResult queryRepairAreaSecond(int schoolId) {
        List<RepairArea> result = repairAreaService.getRepairAreas();
        List<RepairAreaTreeVo> datas = QueryAreaTreeRecords(schoolId, result, 2);
        return CommonResult.ok(datas);
    }

    /*
    查询二层楼栋
     */
    private List<RepairAreaTreeVo> QueryAreaTreeRecords(Integer parentID, List<RepairArea> lists, int i) {
        i--;
        List<RepairAreaTreeVo> newTrees = new ArrayList<>();

        List<RepairArea> datas = lists.stream().filter(e -> e.getParentId().equals(parentID)).collect(Collectors.toList());
        if(i < 0){
            datas = new ArrayList<>();
        }
        for (RepairArea data : datas) {
            RepairAreaTreeVo item = RepairAreaTreeVo.builder()
                    .id(data.getId())
                    .parentId(data.getParentId())
                    .name(data.getName())
                    .build();
            List<RepairAreaTreeVo> news = QueryAreaTreeRecords(item.getId(), lists, i);
            if (news == null || news.size() == 0) {
                newTrees.add(item);
                continue;
            } else {
                item.setChildren(news);
                newTrees.add(item);
            }
        }

        return newTrees;
    }

}

