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

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.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.entity.Agency;
import org.springblade.community.agency.service.IAgencyService;
import org.springblade.community.building.service.IBuildingService;
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.residential.vo.ResidentialVO;
import org.springblade.community.residential.wrapper.ResidentialWrapper;
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.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.system.entity.Role;
import org.springblade.modules.system.service.IRoleService;
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.springblade.utils.QueryWrapperUtil;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.validation.Valid;
import java.net.URI;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号 控制器
 *
 * @author BladeX
 * @since 2020-10-16
 */
@RestController
@AllArgsConstructor
@RequestMapping("community/residential")
@Api(value = "小区接口", tags = "小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号接口")
public class ResidentialController extends BladeController {

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


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

	/**
	 * 分页 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入residential")
	public R<IPage<ResidentialVO>> list(@RequestParam Map<String,Object> residential, Query query, BladeUser bladeUser) {
//	public R<IPage<ResidentialVO>> list(Residential residential, Query query, BladeUser bladeUser) {
//		LambdaQueryWrapper<Residential> wrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapper(Residential::getOrgPosition,residential,bladeUser,orgPositionService);
		LambdaQueryWrapper<Residential> wrapper = new QueryWrapperUtil<Residential>().getBasicQueryWrapperByMap(Residential::getOrgPosition,residential, new Residential(),bladeUser,orgPositionService);

		//获取角色信息
		Role role = roleService.getById(bladeUser.getRoleId());
		if(role == null){
			return R.data(new Page<>());
		}
		//非超管，根据tenantId租户id过滤
		if (!role.getRoleAlias().equals("administrator")){
			wrapper.eq(Residential::getTenantId,bladeUser.getTenantId());
		}


		/*LambdaQueryWrapper<Residential> wrapper = Condition.getQueryWrapper(residential, Residential.class).lambda().eq(Residential::getTenantId,bladeUser.getTenantId());
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		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(Residential::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Residential::getOrgPosition,orgPosition.getOrgPosition());
			}
		}*/
		query.setDescs("create_time");
		IPage<Residential> pages = residentialService.page(Condition.getPage(query),wrapper);
//		pages.getRecords().parallelStream().forEach(residential1 -> {
//			//统计该小区下的楼栋总数,单元总数，楼层总数，房间总数
//			int buildingCount = buildingService.count(new QueryWrapper<>(new Building()).lambda().eq(Building::getResidentialId, residential1.getId()));
//			int unitCount = unitService.count(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getResidentialId,residential1.getId()));
//			int floorCount = floorService.count(new QueryWrapper<>(new Floor()).lambda().eq(Floor::getResidentialId,residential1.getId()));
//			int roomCount = roomService.count(new QueryWrapper<>(new Room()).lambda().eq(Room::getResidentialId,residential1.getId()));
//
//			residential1.setBuildingNumber(buildingCount);
//			residential1.setUnitNumber(unitCount);
//			residential1.setFloorNumber(floorCount);
//			residential1.setRoomNumber(roomCount);
//		});
		return R.data(ResidentialWrapper.build(agencyService).pageVO(pages));
	}

	/**
	 * 自定义分页 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入residential")
	public R<IPage<ResidentialVO>> page(ResidentialVO residential, Query query) {
		IPage<ResidentialVO> pages = residentialService.selectResidentialPage(Condition.getPage(query), residential);
		return R.data(pages);
	}

	/**
	 * 新增 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入residential")
	public R save(@Valid @RequestBody Residential residential) {
		Agency agency = this.agencyService.getById(residential.getAgencyId());
		Assert.notNull(agency,"选择的社区不存在");
		agency.setResidentialCount(agency.getResidentialCount()+1);
		boolean saveAgency = this.agencyService.updateById(agency);
		if (!saveAgency){
			return R.status(false);
		}
		Assert.notNull(agency.getRegionStreet(),"选择的社区暂无街道信息，请先完善社区的街道信息");
		Street street = streetService.getBaseMapper().selectOne(new QueryWrapper<>(new Street()).lambda().eq(Street::getCode,agency.getRegionStreet()));
		Assert.notNull(street,"社区的街道信息不存在");
		boolean save = residentialService.save(residential);
		if(save){
			residential.setOrgPosition(agency.getOrgPosition()+"/"+residential.getId());
			residentialService.updateById(residential);
		}else{
			return R.status(false);
		}

		return R.status(true);
	}

	/**
	 * 修改 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入residential")
	public R update(@Valid @RequestBody Residential residential) {
		Agency agency = this.agencyService.getById(residential.getAgencyId());
		Assert.notNull(agency,"选择的社区不存在");
		Assert.notNull(agency.getRegionStreet(),"选择的社区暂无街道信息，请先完善社区的街道信息");
		Street street = streetService.getBaseMapper().selectOne(new QueryWrapper<>(new Street()).lambda().eq(Street::getCode,agency.getRegionStreet()));
		Assert.notNull(street,"社区的街道信息不存在");
		residential.setOrgPosition("/"+street.getId()+"/"+agency.getId()+"/"+residential.getId());
		return R.status(residentialService.updateById(residential));
	}

	/**
	 * 新增或修改 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入residential")
	public R submit(@Valid @RequestBody Residential residential) {
		Agency agency = this.agencyService.getById(residential.getAgencyId());
		Assert.notNull(agency,"选择的社区不存在");
		Assert.notNull(agency.getRegionStreet(),"选择的社区暂无街道信息，请先完善社区的街道信息");
		Street street = streetService.getBaseMapper().selectOne(new QueryWrapper<>(new Street()).lambda().eq(Street::getCode,agency.getRegionStreet()));
		Assert.notNull(street,"社区的街道信息不存在");

		residential.setRegionProvince(agency.getRegionProvince());
		residential.setRegionCity(agency.getRegionCity());
		residential.setRegionArea(agency.getRegionArea());

		if(residential.getId()!= null){
			residential.setOrgPosition(agency.getOrgPosition()+"/"+residential.getId());
			return R.status(residentialService.updateById(residential));
		}else {
			residentialService.save(residential);
			residential.setOrgPosition(agency.getOrgPosition()+"/"+residential.getId());
			boolean update = residentialService.updateById(residential);
			if(update){
				String tenantId = AuthUtil.getTenantId();
				if(StringUtil.isNotBlank(tenantId) && !"000000".equals(tenantId)){ //只允许园区区域注册小区到第三方
					return residentialService.registerToThird(residential);
				}else{
					return R.status(true);
				}
			}else{
				return R.fail("保存注册区域失败");
			}
		}

	}


	/**
	 * 删除 小区表，新建小区的时候，小区也要作为一个机构存入到机构表里面，机构的编号就使用当前小区的编号
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@Transactional
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		Arrays.stream(ids.split(",")).parallel().forEach(id->{
			Residential residential = this.residentialService.getById(id);
			Agency agency = this.agencyService.getById(residential.getAgencyId());
			agency.setResidentialCount(agency.getResidentialCount()-1);
			this.agencyService.updateById(agency);
		});
		return R.status(residentialService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 下拉列表
	 */
	@GetMapping("/select")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "下拉列表", notes = "传入residential")
	public R<List<Residential>> select(@RequestParam Map<String,Object> residential,Integer size, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Residential> wrapper = Condition.getQueryWrapper(residential,Residential.class).lambda();
		//获取角色信息
		Role role = roleService.getById(bladeUser.getRoleId());
		//非超管，根据tenantId租户id过滤
		if (!role.getRoleAlias().equals("administrator")){
			wrapper.eq(Residential::getTenantId,bladeUser.getTenantId());
		}

		for (int i = 0; i < deptIds.length; i++) {
			OrgPosition orgPosition = orgPositionService.getBaseMapper().selectOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId, deptIds[i]));
			if (orgPosition != null){
				if (i == 0) {
					wrapper.like(Residential::getOrgPosition,orgPosition.getOrgPosition());
				}else{
					wrapper.or().like(Residential::getOrgPosition,orgPosition.getOrgPosition());
				}
			}

		}
		wrapper.last(size != null,"limit " + size);
		return R.data(residentialService.list(wrapper));
	}



	/**
	 * 同步亲邻智能物联网平台小区数据
	 * @return
	 */
	@GetMapping("/tongbu")
	public R test() {
//		IResidentialService residentialService =new ResidentialServiceImpl();
		RestTemplate restTemplate = new RestTemplate();
//		HttpHeaders httpHeaders =
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, "text/plain");
		headers.add(HttpHeaders.HOST, "qiotapi.qinlinkeji.com");
		headers.add("Cookie", "acw_tc=2760821216040233709218017edfed503c3f299563c0716431831777dc716e");
		Map<String, Object> map = new HashMap<>();
		map.put("pageNum", 1);
		map.put("pageSize", 134);

		HttpEntity<String> requestEntity = new HttpEntity<String>(JsonUtil.toJson(map), headers);
		ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
		};
		String url = "https://qiotapi.qinlinkeji.com/admin/community/findListPage?sessionId=admin:2c9480c2754b743701757db8397102ac";
		URI uri = URI.create(url);
		responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


		Map map1 = (Map) responseEntity.getBody();
		Map map2 = (Map) map1.get("data");
		List<Map> list = (List<Map>) map2.get("list");
//		IResidentialService residentialService = new ResidentialServiceImpl();
		for (int i = 0; i < list.size(); i++) {
			Residential residential = new Residential();
			Integer integer = (Integer) list.get(i).get("id");
			residential.setOldId(Long.valueOf(integer.toString()));
			residential.setName((String)list.get(i).get("communityName"));
			residential.setRegion((String) list.get(i).get("address"));
			residential.setAddress((String) list.get(i).get("address"));
			residential.setRegionCity((String) list.get(i).get("cityName"));
			residential.setRegionArea((String) list.get(i).get("districtName"));
			residential.setPersonName((String) list.get(i).get("propertyName"));
			residential.setPersonTel((String) list.get(i).get("propertyPhone"));
			residential.setRegionProvince((String) list.get(i).get("provinceName"));
			Residential residential1 = residentialService.getOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getOldId, residential.getOldId()));
			if(residential1 != null){
				residential.setId(residential1.getId());
			}
			boolean save = residentialService.saveOrUpdate(residential);
			System.out.println(save);
		}
		System.out.println(list);
		return new R();
	}




	@GetMapping("/setOrgPosition")
	public R setOrgPosition(){
		List<Residential> residentialList = residentialService.getBaseMapper().selectList(new QueryWrapper<>(new Residential()));

		residentialList.parallelStream().forEach(residential -> {
			Agency agency = agencyService.getById(residential.getAgencyId());
			residential.setOrgPosition(agency.getOrgPosition()+"/"+residential.getId());
			residentialService.updateById(residential);
		});
		return new R();
	}

	/**
	 * 分页
	 */
	@GetMapping("/listByAgencyId")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "按园区id分页", notes = "传入agencyid")
	public R<IPage<ResidentialVO>> list(Residential residential, Query query) {
		IPage<Residential> pages = residentialService.page(Condition.getPage(query), Condition.getQueryWrapper(residential));
		return R.data(ResidentialWrapper.build(agencyService).pageVO(pages));
	}

	/**
	 * 分页
	 */
	@GetMapping("/updateNumber")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "传入小区ids", notes = "传入小区ids")
	public R updateNumber(String ids) {

		if (ids == null){
			List<Residential> list = residentialService.list();
			list.forEach(item -> {
				residentialService.updateNumberById(item.getId().toString());
			});
		}else {
			List<String> idslist = Func.toStrList(ids);
			idslist.forEach(item -> {
				residentialService.updateNumberById(item);
			});
		}

		return R.status(true);
	}

}
