/*
 *      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.building.controller;


import cn.hutool.core.lang.Assert;
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.service.IAgencyService;
import org.springblade.community.building.entity.BatchAddInfo;
import org.springblade.community.building.entity.Building;
import org.springblade.community.building.service.IBuildingService;
import org.springblade.community.building.vo.BuildingVO;
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.room.service.IRoomService;
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.web.bind.annotation.*;

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


/**
 *  控制器
 *
 * @author BladeX
 * @since 2020-10-31
 */
@RestController
@AllArgsConstructor
@RequestMapping("building/building")
@Api(value = "楼栋接口", tags = "楼栋接口")
public class BuildingController extends BladeController {

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

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

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入building")
	public R<IPage<Building>> list(Building building, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Building> wrapper = Condition.getQueryWrapper(building).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(Building::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Building::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		IPage<Building> pages = buildingService.page(Condition.getPage(query), wrapper.eq(Building::getTenantId,bladeUser.getTenantId()));

		return R.data(pages);
	}

	/**
	 * 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入building")
	public R<IPage<BuildingVO>> page(BuildingVO building, Query query) {
		IPage<BuildingVO> pages = buildingService.selectBuildingPage(Condition.getPage(query), building);
		return R.data(pages);
	}

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入building")
	public R save(@Valid @RequestBody Building building) {
		return R.status(buildingService.save(building));
	}

	/**
	 * 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入building")
	public R update(@Valid @RequestBody Building building) {
		return R.status(buildingService.updateById(building));
	}

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入building")
	public R submit(@Valid @RequestBody Building building) {

		Long residentialId = building.getResidentialId();
		Assert.notNull(residentialId, "小区id为空！！！");
		Residential residential = residentialService.getById(residentialId);
		Assert.notNull(residential, "找不到该小区！！！");

		if (building.getId() == null){
			Integer buildingNumber = residential.getBuildingNumber();
			if ("null".equals(buildingNumber + "")){
				buildingNumber = 0;
			}
			residential.setBuildingNumber(buildingNumber + 1);
			if (buildingService.save(building)){
				residentialService.updateById(residential);
			}
		}

		building.setResidentialName(residential.getName());
		building.setOrgPosition(residential.getOrgPosition() + "/" + building.getId());
		return R.status(buildingService.saveOrUpdate(building));
	}

	/**
	 * 批量新增
	 */
	@PostMapping("/batchAdd")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "批量添加", notes = "batchAddInfo")
	public R batchAdd(@Valid @RequestBody BatchAddInfo batchAddInfo) {
		return R.status(buildingService.batchAddBuilding(batchAddInfo));
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(buildingService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 下拉列表
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉列表", notes = "building")
	public R<List<Building>> select(@RequestParam Map<String,Object> building, Integer size, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Building> wrapper = Condition.getQueryWrapper(building,Building.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(Building::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Building::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		wrapper.last(size != null,"limit " + size);
		return R.data(this.buildingService.list(wrapper));
	}

	@PostMapping("/setOrgPosition")
	public R setOrgPosition(){
		List<Building> buildingList = buildingService.getBaseMapper().selectList(new QueryWrapper<>(new Building()));
		buildingList.parallelStream().forEach(building -> {
			Residential residential = residentialService.getById(building.getResidentialId());
			building.setOrgPosition(residential.getOrgPosition()+"/"+building.getId());
			buildingService.updateById(building);
		});

		return  new R();

	}

}
