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

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import javax.validation.Valid;

import org.springblade.community.entity.Building;
import org.springblade.community.entity.Residential;
import org.springblade.community.entity.Room;
import org.springblade.community.feign.IBuildingClient;
import org.springblade.community.feign.IResidentialClient;
import org.springblade.community.feign.IRoomClient;
import org.springblade.community.vo.BuildingVO;
import org.springblade.community.vo.ResidentialVO;
import org.springblade.community.vo.RoomVO;
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.person.entity.Aids;
import org.springblade.person.entity.Disabler;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.service.HouseUserService;
import org.springblade.person.service.IDisablerService;
import org.springblade.person.vo.DisablerVO;
import org.springblade.person.wrapper.DisablerWrapper;
import org.springblade.system.expand.feign.IOrgPositionClient;
import org.springblade.system.expand.util.QueryWrapperUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;

import org.springblade.core.boot.ctrl.BladeController;

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

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-04-14
 */
@RestController
@AllArgsConstructor
@RequestMapping("/disabler")
@Api(value = "", tags = "接口")
public class DisablerController extends BladeController {

	private final IDisablerService disablerService;
	private final HouseUserService houseUserService;
	private IResidentialClient residentialClient;
	private IBuildingClient buildingClient;
	private IRoomClient roomClient;
	private final IOrgPositionClient orgPositionClient;

	/**
	 * ById详情
	 */
	@GetMapping("/generatedetail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入allowancesPeople")
	public R<Disabler> generatedetail(Long id) {
		Disabler detail = disablerService.getById(id);
		return R.data(detail);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入disabler")
	public R<DisablerVO> detail(Disabler disabler) {
		Disabler detail = disablerService.getOne(Condition.getQueryWrapper(disabler));
		return R.data(DisablerWrapper.build(houseUserService).entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入disabler")
	public R<IPage<DisablerVO>> list(@RequestParam Map<String, Object> disabler, Query query, BladeUser bladeUser) {
		LambdaQueryWrapper<Disabler> wrapper = new QueryWrapperUtil<Disabler>().getBasicQueryWrapperByMap(Disabler::getOrgPosition, disabler, new Disabler(), bladeUser, orgPositionClient);
		IPage<Disabler> pages = disablerService.page(Condition.getPage(query), wrapper);
		return R.data(DisablerWrapper.build(houseUserService).pageVO(pages));
	}


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

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

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

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

	/**
	 * 标签列表内新增
	 */
	@PostMapping("/addDisabler")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入aids")
	public R addDisabler(@Valid @RequestBody List<Object> disablerAndhouser) {

		//List转对应对象
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(disablerAndhouser.get(0)));
		Disabler disabler = jsonObject.toJavaObject(Disabler.class);
		JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(disablerAndhouser.get(1)));
		HouseUser houseUser = jsonObject1.toJavaObject(HouseUser.class);
		//获取房屋信息和orgPosition
		String orgPositiontemp = null;
		Residential residential = new Residential();
		residential.setId(houseUser.getResidentialId());
		ResidentialVO residentialVO = residentialClient.detail(residential);
		Assert.notNull(residentialVO,"选择的小区不存在");
		houseUser.setAgencyId(residentialVO.getAgencyId());
		houseUser.setAgencyName(residentialVO.getAgencyName());
		houseUser.setResidentialName(residentialVO.getName());

		if (houseUser.getBuildingId()!=null){
			Building building = new Building();
			building.setId(houseUser.getBuildingId());
			BuildingVO buildingVO = buildingClient.detail(building);
			Assert.notNull(buildingVO,"选择的楼栋不存在");
			houseUser.setBuildingName(buildingVO.getName());
		}
		if (houseUser.getRoomId()!=null) {
			Room room = new Room();
			room.setId(houseUser.getRoomId());
			RoomVO roomVO = roomClient.detail(room);
			Assert.notNull(roomVO, "选择的房间不存在");

			houseUser.setFloorId(roomVO.getFloorId());
			houseUser.setFloorName(roomVO.getFloorName());
			houseUser.setRoomName(roomVO.getName());
			//添加房间Orgposition
			orgPositiontemp = roomVO.getOrgPosition()+ "/" +houseUser.getId();
			houseUser.setOrgPosition(roomVO.getOrgPosition()+ "/" +houseUser.getId());
		}
		//设置标签
		houseUser.setTags("残障人士");
		Boolean result = null;
		try {
			Boolean bool = houseUserService.save(houseUser);
			if (bool){
				disabler.setParentId(houseUser.getId());
				disabler.setName(houseUser.getName());
				disabler.setOrgPosition(houseUser.getOrgPosition());
				result = disablerService.save(disabler);
			}
		}catch (Exception e){
			return R.data(fail("异常"));
		}
		return R.data(result);
	}


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		String[] idsStr = ids.split(",");
		Long[] idsLong = new Long[idsStr.length];
		for (int i = 0;i < idsStr.length;i++){
			idsLong[i] = Long.valueOf(idsStr[i]);
		}
		for (int j = 0;j < idsLong.length;j++) {
			Disabler disabler = disablerService.getById(idsLong[j]);
			HouseUser houseUser = houseUserService.getById(disabler.getParentId());
			//删除标签
			String[] tags = houseUser.getTags().split(",");
			StringBuilder sb = new StringBuilder();
			List<String> list = new ArrayList<>();
			if (tags.length >= 2) {
				for (int i = 0; i < tags.length; i++) {
					if (tags[i].equals("残障人士")) {
						continue;
					}
					list.add(tags[i]);
				}
				for (int i = 0; i < list.size() - 1; i++) {
					sb.append(list.get(i)).append(",");
				}
				sb.append(list.get(list.size() - 1));
			}
			houseUser.setTags(sb.toString());
			houseUserService.getBaseMapper().updateById(houseUser);
		}
		return R.status(disablerService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 根据parentId获取对应标签表信息
	 */
	@GetMapping("/detailByParentId")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "详情", notes = "传入disabler")
	public R<DisablerVO> detailByParentId(Long parentId) {
		Disabler detail = disablerService.getBaseMapper().selectOne(new QueryWrapper<Disabler>().eq("parent_id",parentId));
		return R.data(DisablerWrapper.build().entityVO(detail));
	}

}
