/*
 *      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.floor.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.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.community.agency.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.building.entity.Building;
import org.springblade.community.building.service.IBuildingService;
import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
import org.springblade.community.unit.entity.Unit;
import org.springblade.community.unit.service.IUnitService;
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.entity.Street;
import org.springblade.system.street.service.IStreetService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.community.floor.entity.Floor;
import org.springblade.community.floor.vo.FloorVO;
import org.springblade.community.floor.wrapper.FloorWrapper;
import org.springblade.community.floor.service.IFloorService;
import org.springblade.core.boot.ctrl.BladeController;

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

/**
 *  控制器
 *
 * @author BladeX
 * @since 2020-11-06
 */
@RestController
@AllArgsConstructor
@RequestMapping("floor/floor")
@Api(value = "楼层接口", tags = "楼层接口")
public class FloorController extends BladeController {

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

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入floor")
	public R<FloorVO> detail(Floor floor) {
		Floor detail = floorService.getOne(Condition.getQueryWrapper(floor));
		return R.data(FloorWrapper.build().entityVO(detail));
	}

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


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

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入floor")
	@Transactional
	public R save(@Valid @RequestBody Floor floor) {
/*		Agency agency = this.agencyService.getById(floor.getAgencyId());
		Assert.notNull(agency,"选择的社区不存在");*/
		Residential residential = this.residentialService.getById(floor.getResidentialId());
		Assert.notNull(residential,"选择的小区不存在");
		Building building = this.buildingService.getById(floor.getBuildingId());
		Assert.notNull(building,"选择的楼栋不存在");
		Unit unit = this.unitService.getById(floor.getUnitId());
		Assert.notNull(unit,"选择的单元不存在");
		if (this.floorService.save(floor)){
			residential.setFloorNumber(residential.getFloorNumber() == null ? 0 + 1 : residential.getFloorNumber() +1);
			this.residentialService.updateById(residential);
			building.setFloorNumber(building.getFloorNumber() == null ? 0 + 1 : building.getFloorNumber() + 1);
			this.buildingService.updateById(building);
			unit.setFloorNumber(unit.getFloorNumber() == null ? 0 + 1 : unit.getFloorNumber() +1);
			this.unitService.updateById(unit);
		}else {
			return R.status(false);
		}
		floor.setResidentialName(residential.getName());
		floor.setBuildingName(building.getName());
		floor.setUnitName(unit.getName());
		floor.setOrgPosition(unit.getOrgPosition() + "/" + floor.getId());
		return R.status(this.floorService.updateById(floor));
//		return R.status(floorService.save(floor));
	}

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

	/**
	 * 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入floor")
	public R submit(@Valid @RequestBody Floor floor) {
		return R.status(floorService.saveOrUpdate(floor));
	}


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

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

	@PostMapping("/setOrgPosition")
	public R setOrgPosition(){

		List<Floor> floorList = floorService.getBaseMapper().selectList(new QueryWrapper<>(new Floor()));
		floorList.parallelStream().forEach(floor -> {
			Unit unit = unitService.getById(floor.getUnitId());
			floor.setOrgPosition(unit.getOrgPosition()+"/"+floor.getId());
			floorService.updateById(floor);
		});
		return  new R();

	}


}
