package com.unis.crk.basic.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unis.crk.basic.entity.FuncInfo;
import com.unis.crk.basic.entity.OrgInfo;
import com.unis.crk.basic.entity.vo.FuncInfoVo;
import com.unis.crk.basic.service.IFuncInfoService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.unis.crk.utils.ResultUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * <p>
 * 功能信息表 前端控制器
 * </p>
 *
 * @author ghh
 * @since 2021-09-26
 */
@Api(value = "功能信息表",tags = {"功能信息表"})
@RestController
@RequestMapping("funcInfo")
@CrossOrigin
public class FuncInfoController {

    private final static Logger LOGGER = LoggerFactory.getLogger(FuncInfoController.class);


    @Autowired
    private IFuncInfoService funcInfoService;
    /**
     * 查找功能信息
     * @return
     */
    @RequestMapping(value="/getFunc", method = RequestMethod.POST)
    @ApiOperation(value="根据父菜单ID和菜单ID(可传)查询分页信息", notes = "根据父菜单ID和菜单ID(可传)查询分页信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父菜单ID", paramType = "query"),
            @ApiImplicitParam(name = "funcName", value = "菜单名称", paramType = "query")
    })
    public IPage<FuncInfo> getFuncInfo(@RequestBody FuncInfoVo funcInfoVo) {

        QueryWrapper<FuncInfo> funcInfoQueryWrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(funcInfoVo.getParentId() )) {
            funcInfoQueryWrapper.eq("parent_id",funcInfoVo.getParentId());
        }
        if (StrUtil.isNotBlank(funcInfoVo.getFuncName())) {
            funcInfoQueryWrapper.like("func_name",ResultUtil.getQueryWrapperformat(funcInfoVo.getFuncName()));
        }
        Page<FuncInfo> objectPage = new Page<>(funcInfoVo.getPageNum(), funcInfoVo.getPageSize());
        IPage<FuncInfo> page = funcInfoService.page(objectPage, funcInfoQueryWrapper);

        return page;
    }

    /**
     * 获取所有功能权限
     * @return	List<FuncInfo>	功能列表
     */
    @ApiOperation(value="查询", notes="获取所有功能列表")
    @GetMapping("getAllFunc")
    public List<FuncInfo> getAllFunc() {
        List<FuncInfo> funclist1 = new ArrayList<>();
        //根节点
        List<FuncInfo> rootMenu = new ArrayList<FuncInfo>();
        funclist1 =funcInfoService.getAllFuncInfo();
        for(Iterator<FuncInfo> it = funclist1.iterator(); it.hasNext();){
            FuncInfo nav = it.next();
            if(nav !=null){
                //父节点是0的，为根节点。
                if (org.apache.commons.lang.StringUtils.isBlank(nav.getParentId()) || org.apache.commons.lang.StringUtils.equals(nav.getParentId(),"0")) {
                    rootMenu.add(nav);
                }
            }else{
                it.remove();
            }
        }

        /* 根据Menu类的order排序 */
        Collections.sort(rootMenu, order());
        for (FuncInfo nav : rootMenu) {
            /* 获取根节点下的所有子节点 使用getChild方法*/
            List<FuncInfo> childList = getChild(nav.getFuncId(), funclist1);
            nav.setChildren(childList);//给根节点设置子节点
        }

        return rootMenu;

    }
    /*
     * 排序,根据order排序
     */
    public Comparator<FuncInfo> order() {
        Comparator<FuncInfo> comparator = new Comparator<FuncInfo>() {
            @Override
            public int compare(FuncInfo o1, FuncInfo o2) {
                if(o1.getFuncSort() != null && o2.getFuncSort() !=null){
                    if (o1.getFuncSort() != o2.getFuncSort()) {
                        return o1.getFuncSort() - o2.getFuncSort();
                    }
                }
                return 0;
            }
        };
        return comparator;
    }


    /**
     * 获取子节点
     *
     * @param id      父节点id
     * @param allMenu 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    public List<FuncInfo> getChild(String id, List<FuncInfo> allMenu) {
        //子菜单
        List<FuncInfo> childList = new ArrayList<FuncInfo>();
        for (FuncInfo nav : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if (nav.getParentId().equals(id)) {
                childList.add(nav);
            }
        }
        //递归
        for (FuncInfo nav : childList) {
            nav.setChildren(getChild(nav.getFuncId(), allMenu));
        }
        Collections.sort(childList, order());//排序
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<FuncInfo>();
        }
        return childList;
    }



    /**
     * 根据ID查询数据
     * @return
     */
    @ApiOperation(value="根据ID查询菜单信息", notes="根据ID查询菜单信息")
    @RequestMapping(value="/getOne", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ID", value = "数据ID", paramType = "query")
    })
    public ResultUtil getOne(@RequestBody FuncInfoVo funcInfoVo){
        LOGGER.info("入参为:{}",funcInfoVo.getId());
        ResultUtil<FuncInfo> data = new ResultUtil<>();
        if (StringUtils.isEmpty(funcInfoVo.getId())){
            data.failed("传入的主键为空");
            return data;
        }
        data.success(this.funcInfoService.getByFuncId( funcInfoVo.getId() ));
        return data;
    }


    /**
     * 查询全部数据
     * @return
     */
    @ApiOperation(value="查询", notes="查询全部数据")
    @GetMapping("getAll")
    public ResultUtil getAll(){
        ResultUtil<List<FuncInfo>> data = new ResultUtil<>();
        data.success(this.funcInfoService.list());
        return data;
    }


    /**
     * 新增一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="新增", notes="新增一条数据")
    @PostMapping("add")
    public ResultUtil add(@RequestBody FuncInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.funcInfoService.save(param));
        return data;
    }


    /**
     * 修改一条数据
     * @param param
     * @return
     */
    @ApiOperation(value="修改", notes="修改一条数据")
    @PatchMapping("edit")
    public ResultUtil edit(@RequestBody FuncInfo param){
        LOGGER.info("入参为:{}", param);
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (ObjectUtils.isEmpty(param)){
            data.failed("所接收对象为null");
            return data;
        }
        data.success(this.funcInfoService.updateById(param));
        return data;
    }


    /**
     * 根据ID删除数据
     * @return
     */
    @ApiOperation(value="删除", notes="根据ID删除数据")
    @RequestMapping(value="/delete", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ID", value = "数据ID", paramType = "query")
    })
    public ResultUtil delete(@RequestBody FuncInfoVo funcInfoVo){
        LOGGER.info("入参为:{}", funcInfoVo.getId());
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (StringUtils.isEmpty(funcInfoVo.getId())){
            data.failed("所接收id为null");
            return data;
        }
        data.success(this.funcInfoService.removeById(funcInfoVo.getId()));
        return data;
    }


}

