/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.community.room.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.floor.entity.Floor;
import org.springblade.community.floor.service.IFloorService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.building.service.IBuildingService;
import org.springblade.community.room.entity.Room;
import org.springblade.community.room.service.IRoomService;
import org.springblade.community.room.vo.RoomVO;
import org.springblade.community.unit.entity.Unit;
import org.springblade.community.unit.service.IUnitService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.system.street.service.IStreetService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 房间表 控制器
 *
 * @author BladeX
 * @since 2020-10-18
 */
@RestController
@AllArgsConstructor
@RequestMapping("community/room")
@Api(value = "房间表", tags = "房间表接口")
public class RoomController extends BladeController {

	private IRoomService roomService;
	private IUnitService unitService;
	private IResidentialService residentialService;
	private IAgencyService agencyService;
	private IOrgPositionService orgPositionService;
	private IStreetService streetService;
	private IFloorService floorService;
	private IBuildingService buildingService;


	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入room")
	public R<Room> detail(Room room) {
		Room detail = roomService.getOne(Condition.getQueryWrapper(room));
		return R.data(detail);
	}

	/**
	 * 获取用户的房屋信息
	 */
	@GetMapping("/getRoomByPersonId")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入room")
	public R getRoomByPersonId(Long personId) {
		List<Room> rooms = roomService.getRoomsByPersonId(personId);
		return R.data(rooms);
	}

	/**
	 * 分页 房间表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入room")
	public R<IPage<Room>> list(Room room, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Room> wrapper = Condition.getQueryWrapper(room).lambda();
		for(int i=0;i<deptIds.length;i++){
			OrgPosition orgPosition = orgPositionService.getOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId,deptIds[i]));
			if (orgPosition == null){
				continue;
			}
			if(i ==0){
				wrapper.like(Room::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Room::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		IPage<Room> pages = roomService.page(Condition.getPage(query), wrapper);
		return R.data(pages);
	}

	/**
	 * 自定义分页 房间表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入room")
	public R<IPage<RoomVO>> page(RoomVO room, Query query) {
		IPage<RoomVO> pages = roomService.selectRoomPage(Condition.getPage(query), room);
		return R.data(pages);
	}

	/**
	 * 新增 房间表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入room")
	@Transactional
	public R save(@Valid @RequestBody Room room) {
		Unit unit = this.unitService.getById(room.getUnitId());
		unit.setRoomNumber(unit.getRoomNumber()+1);
		this.unitService.updateById(unit);
		Residential residential = this.residentialService.getById(room.getResidentialId());
		residential.setRoomNumber(residential.getRoomNumber()+1);
		this.residentialService.updateById(residential);
		Agency agency = this.agencyService.getById(residential.getAgencyId());
		agency.setRoomCount(agency.getRoomCount()+1);
		this.agencyService.updateById(agency);
		roomService.save(room);
		room.setOrgPosition(unit.getOrgPosition()+"/"+room.getFloorId()+"/"+room.getId());
		return R.status(roomService.updateById(room));
	}

	/**
	 * 修改 房间表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入room")
	public R update(@Valid @RequestBody Room room) {
		return R.status(roomService.updateById(room));
	}

	/**
	 * 新增或修改 房间表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入room")
	public R submit(@Valid @RequestBody Room room) {
		return R.status(roomService.saveOrUpdate(room));
	}


	/**
	 * 删除 房间表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		Arrays.stream(ids.split(",")).forEach(id ->{
			Room room = this.roomService.getById(id);
			Unit unit = this.unitService.getById(room.getUnitId());
			unit.setRoomNumber(unit.getRoomNumber()-1);
			this.unitService.updateById(unit);
			Residential residential = this.residentialService.getById(room.getResidentialId());
			residential.setRoomNumber(residential.getRoomNumber()-1);
			this.residentialService.updateById(residential);
			Agency agency = this.agencyService.getById(room.getAgencyId());
			agency.setRoomCount(agency.getRoomCount()-1);
			this.agencyService.updateById(agency);
		});
		return R.status(roomService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 下拉列表
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉列表", notes = "room")
	public R<List<Room>> select(@RequestParam Map<String,Object> room, Integer size, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Room> wrapper = Condition.getQueryWrapper(room,Room.class).lambda();
		for (int i = 0; i < deptIds.length; i++) {
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (i == 0) {
				wrapper.like(Room::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Room::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		wrapper.last(size != null,"limit " + size);
		return R.data(this.roomService.list(wrapper));
	}

	@PostMapping("/setOrgPosition")
	public R setOrgPosition(){
		List<Room> roomList = roomService.getBaseMapper().selectList(new QueryWrapper<>(new Room()).lambda().gt(Room::getId,1335518425358475265L));

		for(int i=0;i<roomList.size();i++){
			Room room = roomList.get(i);
			Floor floor = floorService.getById(room.getFloorId());
			if(room.getOrgPosition().contains(floor.getOrgPosition())){
				continue;
			}
			room.setOrgPosition(floor.getOrgPosition()+"/"+room.getId());
			roomService.updateById(room);
		}



		return  new R();

	}

	@PostMapping("/setAgencyId")
	public R setAgencyId(){
		List<Room> roomList = roomService.getBaseMapper().selectList(new QueryWrapper<>(new Room()));

		roomList.parallelStream().forEach(room -> {
			Residential residential = residentialService.getById(room.getResidentialId());
			if(residential!=null){
				room.setAgencyId(residential.getAgencyId());
				roomService.updateById(room);
			}
		});



		return  new R();

	}




}
