/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package easydo.technology.system.rest;

import com.alibaba.fastjson.JSONObject;
import easydo.technology.annotation.WebLog;
import easydo.technology.exception.BadRequestException;
import easydo.technology.system.domain.Menu;
import easydo.technology.system.dto.MenuDto;
import easydo.technology.system.dto.MenuQueryParam;
import easydo.technology.system.service.MenuService;
import easydo.technology.utils.PageUtil;
import easydo.technology.utils.SecurityUtils;
import lombok.Delegate;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-12-03
 */

@RestController
@RequiredArgsConstructor
@RequestMapping("/menus")
public class MenuController {

    private final MenuService menuService;
    // private final MenuMapper menuMapper;
    private static final String ENTITY_NAME = "menu";

    @WebLog
    @GetMapping
    public ResponseEntity<Object> query(MenuQueryParam criteria) throws Exception {
        List<MenuDto> menuDtoList = menuService.queryAll(criteria, true);
        return new ResponseEntity<>(PageUtil.toPage(menuDtoList, menuDtoList.size()), HttpStatus.OK);
    }

    @WebLog
    @GetMapping(value = "/lazy")
    public ResponseEntity<Object> query(@RequestParam Long pid, @RequestParam String platformType) {
        return new ResponseEntity<>(menuService.getMenus(pid, platformType), HttpStatus.OK);
    }

    @WebLog
    @GetMapping(value = "/build")
    public ResponseEntity<Object> buildMenus() {
        List<MenuDto> menuDtoList = menuService.findByUser(SecurityUtils.getCurrentUserId());
        List<MenuDto> menuDtos = menuService.buildTree(menuDtoList);
        return new ResponseEntity<>(menuService.buildMenus(menuDtos), HttpStatus.OK);
    }


//    @RequestMapping(value = "/appletsMenus")
//    @ApiOperation("获取前端所需小程序菜单")
//    public ResponseEntity<Object> appletsMenus() {
//        List<MenuDto> menuDtoList = menuService.findByUser(SecurityUtils.getCurrentUserId());
//        menuDtoList = menuDtoList.stream().filter(model -> model.getPlatformType().equals("easydo-mini-iot")).collect(Collectors.toList());
//        return new ResponseEntity<>(menuService.buildMenus(menuDtoList), HttpStatus.OK);
//    }

//    @GetMapping(value = "/buildTransfer")
//    public ResponseEntity<Object> buildTransfer() {
//    @ApiOperation("获取前端所需菜单")
//        List<MenuDto> menuDtoList = menuService.findByUser(SecurityUtils.getCurrentUserId(), "easydo-transfer");
//        menuDtoList = menuDtoList.stream().filter(model -> model.getType() < 2).collect(Collectors.toList());
//        List<MenuDto> menuDtos = menuService.buildTree(menuDtoList);
//        return new ResponseEntity<>(menuService.buildMenus(menuDtos), HttpStatus.OK);
//    }

    @WebLog
    @PostMapping("/superior")
    public ResponseEntity<Object> getSuperior(@RequestBody List<Long> ids) throws Exception {
        Set<MenuDto> menuDtos = new LinkedHashSet<>();
        if (ids != null && !ids.isEmpty()) {
            for (Long id : ids) {
                MenuDto menuDto = menuService.findById(id);
                menuDtos.addAll(menuService.getSuperior(menuDto, new ArrayList<>()));
            }
            return new ResponseEntity<>(menuService.buildTree(new ArrayList<>(menuDtos)), HttpStatus.OK);
        }
        throw new Exception("参数缺失");
    }

    @WebLog
    @PostMapping
    public ResponseEntity<Object> create(@Validated @RequestBody Menu resources) {
        if (resources.getId() != null) {
            throw new BadRequestException("A new " + ENTITY_NAME + " cannot already have an ID");
        }
        menuService.save(resources);
        return new ResponseEntity<>(resources, HttpStatus.OK);
    }

    @WebLog
    @PutMapping
    public ResponseEntity<Object> update(@Validated(Menu.Update.class) @RequestBody Menu resources) {
        menuService.updateById(resources);
        return new ResponseEntity<>(resources, HttpStatus.OK);
    }

    @WebLog
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Set<Long> ids) {
        Set<Menu> menuSet = new HashSet<>();
        List<Menu> menuList = new ArrayList<>();
        for (Long id : ids) {
            Menu menu = menuService.getById(id);
            menuList.add(menu);
        }
        menuSet = menuService.getDeleteMenus(menuList, menuSet);
        ids = menuSet.stream().map(Menu::getId).collect(Collectors.toSet());
        menuService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @WebLog
    @GetMapping(value = "/download")
    public void download(HttpServletResponse response, MenuQueryParam criteria) throws Exception {
        menuService.download(menuService.queryAll(criteria, false), response);
    }

}
