package com.unis.crk.basic.controller;

import cn.hutool.core.util.IdUtil;
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.ButtonInfo;
import com.unis.crk.basic.entity.FuncInfo;
import com.unis.crk.basic.entity.vo.ButtonInfoVo;
import com.unis.crk.basic.entity.vo.FuncButtonVo;
import com.unis.crk.basic.service.IButtonInfoService;
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("buttonInfo")
@CrossOrigin
public class ButtonInfoController {

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

    @Autowired
    private IFuncInfoService funcInfoService;
    @Autowired
    private IButtonInfoService buttonInfoService;


    /**
     * 查找按钮信息
     * @param buttonInfoVo	页码
     * @return	PageInfo
     */
    @RequestMapping(value="/getButton", method = RequestMethod.POST)
    @ApiOperation(value="查询按钮信息列表，支持分页", notes = "查询按钮信息列表，支持分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query"),
            @ApiImplicitParam(name = "funcId", value = "功能编号", paramType = "query")
    })
    public IPage<ButtonInfo> getButtonInfo( @RequestBody ButtonInfoVo buttonInfoVo) {
        QueryWrapper<ButtonInfo> buttonInfoQueryWrapper = new QueryWrapper<>();
//        if (buttonInfoVo.getFuncId() != null) {
        if (StrUtil.isNotBlank(buttonInfoVo.getFuncId())) {
            buttonInfoQueryWrapper.eq("func_id",buttonInfoVo.getFuncId());
        }
        Page<ButtonInfo> objectPage = new Page<>(buttonInfoVo.getPageNum(),buttonInfoVo.getPageSize());
        IPage<ButtonInfo> page = buttonInfoService.page(objectPage, buttonInfoQueryWrapper);
        return page;
    }


    /**
     * 根据ID查询数据
     * @param buttonInfoVo	页码
     * @return	ButtonInfo
     */
    @RequestMapping(value="getOne",  method = RequestMethod.POST )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "数据ID", paramType = "query")
    })
    @ApiOperation(value="根据ID查询按钮信息(只传ID即可)", notes = "根据ID查询按钮信息(只传ID即可)")
    public ResultUtil getOne(@RequestBody ButtonInfoVo buttonInfoVo){
        LOGGER.info("入参为:{}",buttonInfoVo.getId());
        ResultUtil<ButtonInfo> data = new ResultUtil<>();
        if (StringUtils.isEmpty(buttonInfoVo.getId())){
            data.failed("传入的主键为空");
            return data;
        }
        data.success(this.buttonInfoService.getById(buttonInfoVo.getId()));
        return data;
    }


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


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


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


    /**
     * 根据ID删除数据
     * @return
     */
    @ApiOperation(value="删除", notes="根据ID删除数据")
    @PostMapping("delete")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "数据ID")
    })
    public ResultUtil delete(@RequestBody ButtonInfoVo buttonInfoVo){

        LOGGER.info("入参为:{}", buttonInfoVo.getId());
        ResultUtil<Boolean> data = new ResultUtil<>();
        if (StringUtils.isEmpty(buttonInfoVo.getId())){
            data.failed("所接收id为null");
            return data;
        }
        data.success(this.buttonInfoService.removeById(buttonInfoVo.getId()));
        return data;
    }
    /**
     * 获取所有功能权限
     * @return	List<FuncInfo>	功能列表
     */
    @ApiOperation(value="查询", notes="获取所有功能列表")
    @GetMapping("getAllFuncButton")
    public List<FuncButtonVo> getAllFunc() {
        List<FuncInfo> funclist1 = new ArrayList<>();
        //根节点
        List<FuncButtonVo> rootMenu = new ArrayList<FuncButtonVo>();
        List<FuncButtonVo> funcButtonVo = new ArrayList<FuncButtonVo>();
        funclist1 =funcInfoService.getAllFuncInfo();
        for(Iterator<FuncInfo> it = funclist1.iterator(); it.hasNext();){
            FuncInfo nav1 = it.next();
            List<ButtonInfo> ButtonInfoList=buttonInfoService.getByFuncId(nav1.getFuncId());
            FuncButtonVo nav = new FuncButtonVo();
            nav.setFuncId(nav1.getFuncId());
            nav.setBchildren(ButtonInfoList);
            nav.setFuncName(nav1.getFuncName());
            nav.setFuncSort(nav1.getFuncSort());
            nav.setParentId(nav1.getParentId());
            funcButtonVo.add(nav);

            if(nav !=null){
                //父节点是0的，为根节点。
                if (StrUtil.isBlank(nav.getParentId()) || StrUtil.equals(nav.getParentId(),"0")) {
                    rootMenu.add(nav);
                }
            }else{
                it.remove();
            }
        }

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

        return rootMenu;

    }


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

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


}

