/*
 *      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 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.Disabler;
import org.springblade.person.entity.HouseUser;
import org.springblade.person.service.HouseUserService;
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.person.entity.Drug;
import org.springblade.person.vo.DrugVO;
import org.springblade.person.wrapper.DrugWrapper;
import org.springblade.person.service.IDrugService;
import org.springblade.core.boot.ctrl.BladeController;

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

/**
 *  控制器
 *
 * @author BladeX
 * @since 2021-05-28
 */
@RestController
@AllArgsConstructor
@RequestMapping("/drug")
@Api(value = "", tags = "接口")
public class DrugController extends BladeController {

	private final IDrugService drugService;
	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<Drug> generatedetail(Long id) {
		Drug detail = drugService.getById(id);
		return R.data(detail);
	}

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入drug")
	public R<DrugVO> detail(Drug drug) {
		Drug detail = drugService.getOne(Condition.getQueryWrapper(drug));
		return R.data(DrugWrapper.build(houseUserService).entityVO(detail));
	}

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


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

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

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

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

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

		//List转对应对象
		JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(drugAndhouser.get(0)));
		Drug drug = jsonObject.toJavaObject(Drug.class);
		JSONObject jsonObject1 = JSON.parseObject(JSON.toJSONString(drugAndhouser.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){
				drug.setParentId(houseUser.getId());
				drug.setName(houseUser.getName());
				drug.setOrgPosition(houseUser.getOrgPosition());
				result = drugService.save(drug);
			}
		}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++) {
			Drug drug = drugService.getById(idsLong[j]);
			HouseUser houseUser = houseUserService.getById(drug.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(drugService.deleteLogic(Func.toLongList(ids)));
	}


}
