package com.bofeng.controller;

import com.bofeng.Consts;
import com.bofeng.entity.Place;
import com.bofeng.entity.Room;
import com.bofeng.service.PlaceService;
import com.bofeng.service.RoomService;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yvan.Model;
import com.yvan.ModelOps;
import com.yvan.PageDb;
import lombok.val;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@RestController
@RequiresPermissions(Consts.USER_TYPE_ADMIN)
public class AdminRoomController {

    @Autowired
    private RoomService roomService;

    @Autowired
    private PlaceService placeService;

    @GetMapping("/admin/room.html")
    public ModelAndView adminRoom() {
        return new ModelAndView("/admin/room.ftl");
    }

    @GetMapping("/admin/room.json")
    public Model<List<Room>> getRoom(PageDb pageDb) {
        return Model.newSuccess(pageDb, roomService.selectAll(pageDb));
    }

    @PostMapping("/admin/room_edit.json")
    public ModelOps roomEdit(@RequestBody Room room) {
        if (room.getRoomCapacity() == null) {
            room.setRoomCapacity(0);
        }
        val msg = roomService.updateById(room);
        if (Strings.isNullOrEmpty(msg)) {
            return ModelOps.newSuccess();
        }
        return ModelOps.newFail(msg);
    }

    @PostMapping("/admin/room_delete.json")
    public ModelOps roomDelete(@RequestParam("roomId") Long roomId) {
        return ModelOps.newSuccess(roomService.deleteById(roomId));
    }

    @PostMapping("/admin/room_addnew.json")
    public ModelOps roomInsert(@RequestBody Room room) {
        if (room.getRoomCapacity() == null) {
            room.setRoomCapacity(0);
        }
        val msg = roomService.insert(room);
        if (Strings.isNullOrEmpty(msg)) {
            return ModelOps.newSuccess();
        }
        return ModelOps.newFail(msg);
    }

    @GetMapping("/admin/get_place.json")
    public Model<Map<String, List<Map>>> getPlace() {
        List<Place> placeList = placeService.selectAllPlace();
        Map<String, List<Map>> map = Maps.newLinkedHashMap();
        List<Map> places = Lists.newArrayList();
        for (int i = 0; i < placeList.size(); i++) {
            Place place = placeList.get(i);
            Map<String, Object> tempMap = Maps.newLinkedHashMap();
            tempMap.put("placeId", place.getPlaceId());
            tempMap.put("placeName", place.getPlaceName());
            places.add(tempMap);
        }
        map.put("place", places);
        return Model.newSuccess(map);
    }

}
