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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
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.common.constant.CommonConstant;
import org.springblade.community.dto.AgencymngDTO;
import org.springblade.community.entity.*;
import org.springblade.community.service.*;
import org.springblade.community.vo.AgencyInfoVO;
import org.springblade.community.vo.AgencyVO;
import org.springblade.community.wrapper.AgencyWrapper;
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.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.enterprise.feign.IEnterpriseClient;
import org.springblade.enterprise.feign.IStaffClient;
import org.springblade.estate.feign.IServerUserClient;
import org.springblade.system.expand.feign.IConfClient;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

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

/**
 * 控制器
 *
 * @author BladeX
 * @since 2021-03-29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/agencymng")
@Api(value = "", tags = "接口")
public class AgencymngController extends BladeController {


	private final IResidentialService residentialService;
	private final IBuildingService buildingService;
	private final IUnitService unitService;
	private final IFloorService floorService;
	private final IRoomService roomService;

	/**
	 * 园区管理，批量添加楼栋》房间
	 */
	@PostMapping("/saveBatch")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入agency")
	@Transactional(rollbackFor = Exception.class)
	public R saveBatchMng(@Valid @RequestBody AgencymngDTO agencymngDTO) {
		Assert.notNull(agencymngDTO.getResidentialId(), "操作的区域不能为空");
		Assert.notNull(agencymngDTO.getBuildingBegin(), "起始楼栋不能为空");
		Assert.notNull(agencymngDTO.getBuildingEnd(), "结束楼栋不能为空");
		Assert.notNull(agencymngDTO.getUnitBegin(), "起始单元不能为空");
		Assert.notNull(agencymngDTO.getUnitEnd(), "结束单元不能为空");
		Assert.notNull(agencymngDTO.getFloorBegin(), "起始楼层不能为空");
		Assert.notNull(agencymngDTO.getFloorEnd(), "结束楼层不能为空");
		Assert.notNull(agencymngDTO.getRoomBegin(), "起始房间不能为空");
		Assert.notNull(agencymngDTO.getRoomEnd(), "结束房间不能为空");
		Residential residential = residentialService.getById(agencymngDTO.getResidentialId());
		Assert.notNull(residential, "找不到相应区域");
		agencymngDTO.setResidential(residential);
		this.saveBuilding(agencymngDTO);
		return R.status(true);
	}

	private void saveBuilding(AgencymngDTO agencymngDTO) {
		Integer buildingBegin = agencymngDTO.getBuildingBegin();
		Integer buildingEnd = agencymngDTO.getBuildingEnd();
		Residential residential = agencymngDTO.getResidential();
		for (int i = buildingBegin; i <= buildingEnd; i++) {
			String buildingPrefix = agencymngDTO.getBuildingPrefix();
			String buildingSuffix= StrUtil.isNotBlank(agencymngDTO.getBuildingSuffix()) ? agencymngDTO.getBuildingSuffix() : "栋";
			StringBuilder sb = new StringBuilder();
			String name =sb.append(buildingPrefix).append(i).append(buildingSuffix).toString();
			Building building = new Building();
			building.setName(name);
			building.setAgencyId(residential.getAgencyId());
			building.setAgencyName(residential.getAgencyName());
			building.setResidentialId(residential.getId());
			building.setResidentialName(residential.getName());
			buildingService.save(building);
			this.saveUnit(agencymngDTO, building);
		}
	}

	private void saveUnit(AgencymngDTO agencymngDTO, Building building) {
		Integer begin = agencymngDTO.getUnitBegin();
		Integer end = agencymngDTO.getUnitEnd();
		Residential residential = agencymngDTO.getResidential();
		for (int i = begin; i <=end; i++) {
			String prefix = agencymngDTO.getUnitPrefix();
			String suffix= StrUtil.isNotBlank(agencymngDTO.getUnitSuffix()) ? agencymngDTO.getUnitSuffix() : "单元";
			StringBuilder sb = new StringBuilder();
			String name =sb.append(prefix).append(i).append(suffix).toString();
			Unit unit = new Unit();
			unit.setName(name);
			unit.setAgencyId(residential.getAgencyId());
			unit.setAgencyName(residential.getAgencyName());
			unit.setResidentialId(residential.getId());
			unit.setResidentialName(residential.getName());
			unit.setBuildingId(building.getId());
			unit.setBuildingName(building.getName());
			unitService.save(unit);
			this.saveFloor(agencymngDTO,unit);
		}
	}

	private void saveFloor(AgencymngDTO agencymngDTO, Unit unit) {
		Integer begin = agencymngDTO.getFloorBegin();
		Integer end = agencymngDTO.getFloorEnd();
		Residential residential = agencymngDTO.getResidential();
		for (int i = begin; i <=end; i++) {
			Integer excludeFloor = agencymngDTO.getExcludeFloor();
			if (Objects.nonNull(excludeFloor)&&Objects.equals(i,excludeFloor)) {
				continue;
			}
			Map<String, Object> map = this.getFloorPreSuf(agencymngDTO);
			StringBuilder sb = new StringBuilder();
			String name =sb.append(map.get("prefix")).append(i).append(map.get("suffix")).toString();
			Floor floor = new Floor();
			floor.setName(name);
			floor.setAgencyId(residential.getAgencyId());
			floor.setAgencyName(residential.getAgencyName());
			floor.setResidentialId(residential.getId());
			floor.setResidentialName(residential.getName());
			floor.setBuildingId(unit.getBuildingId());
			floor.setBuildingName(unit.getBuildingName());
			floor.setUnitId(unit.getId());
			floor.setUnitName(unit.getName());
			floorService.save(floor);
			this.saveRoom(agencymngDTO,floor);
		}
	}

	private Map<String,Object> getFloorPreSuf(AgencymngDTO agencymngDTO){
		String prefix = agencymngDTO.getFloorPrefix();
		String suffix= StrUtil.isNotBlank(agencymngDTO.getFloorSuffix()) ? agencymngDTO.getFloorSuffix() : "层";
		Map<String, Object> map = new HashMap<>();
		map.put("prefix", prefix);
		map.put("suffix", suffix);
		return map;
	}

	private void saveRoom(AgencymngDTO agencymngDTO, Floor floor) {
		Integer begin = agencymngDTO.getRoomBegin();
		Integer end = agencymngDTO.getRoomEnd();
		Residential residential = agencymngDTO.getResidential();
		for (int i = begin; i <=end; i++) {
			Integer excludeRoom = agencymngDTO.getExcludeRoom();
			if (Objects.nonNull(excludeRoom)&&Objects.equals(i,excludeRoom)) {
				continue;
			}
			String roomName = this.getRoomName(agencymngDTO, floor, i);
			Room room = new Room();
			room.setName(roomName);
			room.setAgencyId(residential.getAgencyId());
			room.setAgencyName(residential.getAgencyName());
			room.setResidentialId(residential.getId());
			room.setResidentialName(residential.getName());
			room.setBuildingId(floor.getBuildingId());
			room.setBuildingName(floor.getBuildingName());
			room.setUnitId(floor.getUnitId());
			room.setUnitName(floor.getUnitName());
			room.setFloorId(floor.getId());
			room.setFloorName(floor.getName());
			roomService.save(room);
		}
	}

	private String getRoomName(AgencymngDTO agencymngDTO,Floor floor,Integer roomNoInt){
		//获取楼层号
		String floorName = floor.getName();
		Map<String, Object> floorPreSuf = this.getFloorPreSuf(agencymngDTO);
		String tmp = StrUtil.removePrefix(floorName, Convert.toStr(floorPreSuf.get("prefix")));
		String floorNo= StrUtil.removeSuffix(tmp, Convert.toStr(floorPreSuf.get("suffix")));

		String prefix = agencymngDTO.getRoomPrefix();
		String suffix= StrUtil.isNotBlank(agencymngDTO.getRoomSuffix()) ? agencymngDTO.getRoomSuffix() : "";

		String roomNoStr = Convert.toStr(roomNoInt);
		if (roomNoInt < 10) {
			roomNoStr = "0" + roomNoInt;
		}
		StringBuilder sb = new StringBuilder();
		String roomName =sb.append(prefix).append(floorNo+roomNoStr).append(suffix).toString();
		return roomName;
	}


}
