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

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONUtil;
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.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.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.community.unit.vo.UnitVO;
import org.springblade.community.unit.wrapper.UnitWrapper;
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.Func;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springblade.system.street.service.IStreetService;
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.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-18
 */
@RestController
@AllArgsConstructor
@RequestMapping("community/unit")
@Api(value = "单元表", tags = "单元表接口")
public class UnitController extends BladeController {

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

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

	/**
	 * 分页 单元表
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入unit")
	public R<IPage<UnitVO>> list(@RequestParam Map<String, Object> unit, Query query, BladeUser bladeUser) {
		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Unit> wrapper = Condition.getQueryWrapper(unit, Unit.class).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(Unit::getOrgPosition, orgPosition.getOrgPosition());
			} else {
				wrapper.or().like(Unit::getOrgPosition, orgPosition.getOrgPosition());
			}
		}

		IPage<Unit> pages = unitService.page(Condition.getPage(query), wrapper);
		return R.data(UnitWrapper.build(agencyService, residentialService).pageVO(pages));
	}

	/**
	 * 自定义分页 单元表
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入unit")
	public R<IPage<UnitVO>> page(UnitVO unit, Query query) {
		IPage<UnitVO> pages = unitService.selectUnitPage(Condition.getPage(query), unit);
		return R.data(pages);
	}

	/**
	 * 新增 单元表
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入unit")
	@Transactional
	public R save(@Valid @RequestBody Unit unit) {
		Long residentialId = unit.getResidentialId();
		Long buildingId = unit.getBuildingId();
		Assert.notNull(residentialId, "归属id为空！");
		Assert.notNull(buildingId, "楼栋id为空！");
		Residential residential = residentialService.getById(residentialId);
		Assert.notNull(residential, "找不到对应的归属！");
		Building building = buildingService.getById(buildingId);
		Assert.notNull(building, "找不到对应的楼栋！");

		if (unit.getId() == null) {
			Integer unitNumberResi = residential.getUnitNumber();
			Integer unitNumberBuild = building.getUnitNumber();
			residential.setUnitNumber(unitNumberResi + 1);
			building.setUnitNumber(unitNumberBuild + 1);
			residentialService.updateById(residential);
			buildingService.updateById(building);
			unit.setResidentialName(residential.getName());
			unit.setBuildingName(building.getName());
			unitService.save(unit);
		}

		unit.setOrgPosition(building.getOrgPosition() + "/" + unit.getId());
		return R.status(unitService.updateById(unit));
	}

	/**
	 * 修改 单元表
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入unit")
	public R update(@Valid @RequestBody Unit unit) {
		return R.status(unitService.updateById(unit));
	}

	/**
	 * 新增或修改 单元表
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入unit")
	public R submit(@Valid @RequestBody Unit unit) {
		Assert.notNull(unit.getAgencyId(), "归属不能为空！");
		Agency agency = agencyService.getById(unit.getAgencyId());
		unit.setAgencyName(agency.getAgencyName());
		return R.status(unitService.saveOrUpdate(unit));
	}


	/**
	 * 删除 单元表
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@Transactional
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> list = Func.toLongList(ids);
		list.forEach(id -> {
			Unit unit = this.unitService.getById(id);
			Residential residential = this.residentialService.getById(unit.getResidentialId());
			residential.setUnitNumber(residential.getUnitNumber() - 1);
			this.residentialService.updateById(residential);
			/*Agency agency = this.agencyService.getById(unit.getAgencyId());
			agency.setUnitCount(agency.getUnitCount()-1);
			this.agencyService.updateById(agency);*/
		});
		return R.status(unitService.deleteLogic(list));
	}

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

	/**
	 * 同步亲邻智能物联网平台单元数据
	 *
	 * @return
	 */
	@PostMapping("/tongbu")
	public R tongbu(Long residentialId) {
		Residential residential = residentialService.getById(residentialId);
//		IResidentialService residentialService =new ResidentialServiceImpl();
		List<Building> buildingList = buildingService.getBaseMapper().selectList(new QueryWrapper<>(new Building()).lambda().eq(Building::getResidentialId, residentialId));
		for (int j = 0; j < buildingList.size(); j++) {
			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=2760822c16041156819701506e1f0df2b6797f5010bb8a47e5c8d932fa360e");
			Map<String, Object> map = new HashMap<>();
//			{
//				"communityId": "9463",
//				"id": 122792,
//				"nodeType": 1,
//				"requestSource": 2}
			map.put("communityId", residential.getOldId());
			map.put("id", buildingList.get(j).getOldId());
			map.put("nodeType", 1);
			map.put("requestSource", 2);

			HttpEntity requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(map), headers);
			ParameterizedTypeReference<Object> reference = new ParameterizedTypeReference<Object>() {
			};
			String url = "https://qiotapi.qinlinkeji.com/admin/building/house/findChildList?sessionId=admin:2c94812e75fa974901760cfeea2e011d";
			URI uri = URI.create(url);
			responseEntity = restTemplate.exchange(uri, HttpMethod.POST, requestEntity, reference);


			Map map1 = (Map) responseEntity.getBody();
			List<Map> list = (List<Map>) map1.get("data");

			for (int i = 0; i < list.size(); i++) {
				Unit unit = new Unit();

				Integer integer = (Integer) list.get(i).get("id");
				unit.setOldId(Long.valueOf(integer.toString()));
				unit.setName((String) list.get(i).get("label"));
				unit.setBuildingId(Long.valueOf((Integer) list.get(i).get("parentId")));

				Unit unit1 = unitService.getOne(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getOldId, unit.getOldId()));
				if (unit1 != null) {
					unit.setId(unit1.getId());
				} else {
					Building building = buildingList.get(j);
					building.setUnitNumber(building.getUnitNumber() + 1);
				}
				boolean b = unitService.saveOrUpdate(unit);

//			boolean save = residentialService.saveOrUpdate(residential);
				System.out.println(b);
			}
			System.out.println("楼栋id为" + buildingList.get(j).getOldId() + "的单元：" + list);

		}
		return new R();
	}

	@PostMapping("/setOrgPosition")
	public R setOrgPosition() {
		List<Unit> unitList = unitService.getBaseMapper().selectList(new QueryWrapper<>(new Unit()));
		unitList.parallelStream().forEach(unit -> {
			Building building = buildingService.getById(unit.getBuildingId());
			unit.setOrgPosition(building.getOrgPosition() + "/" + unit.getId());
			unitService.updateById(unit);
		});

		return new R();

	}

	//阅海万家D区
	@PostMapping("/addYhwjDUnit")
	public void addYhwjDUnit(String residentialName) {
		Residential residential = residentialService.getBaseMapper().selectOne(new QueryWrapper<>(new Residential()).lambda().eq(Residential::getName, residentialName));
		List<Building> buildingList = buildingService.getBaseMapper().selectList(new QueryWrapper<>(new Building()).lambda().eq(Building::getResidentialId, residential.getId()));
		for (int j = 0; j < buildingList.size(); j++) {
			Building building = buildingList.get(j);

			for (int i = 0; i < 2; i++) {
				Unit unit = new Unit();
				unit.setName((i + 1) + "单元");
				unit.setBuildingId(building.getId());
				unit.setResidentialId(residential.getId());
				unit.setResidentialName(residentialName);
				unit.setAgencyId(residential.getAgencyId());
//				unit.setAgencyName(residential.getAgencyName());
				unit.setBuildingName(building.getName());
				unit.setFloorNumber(6);
				unit.setRoomNumber(12);
				unitService.getBaseMapper().insert(unit);

			}
		}

	}

	@PostMapping("/setYDOrgPosition")
	public R setYDOrgPosition() {
		List<Unit> unitList = unitService.getBaseMapper().selectList(new QueryWrapper<>(new Unit()).lambda().eq(Unit::getResidentialName, "阅海万家D区"));
		unitList.parallelStream().forEach(unit -> {
			Building building = buildingService.getById(unit.getBuildingId());
			unit.setOrgPosition(building.getOrgPosition() + "/" + unit.getId());
			unitService.updateById(unit);
		});

		return new R();

	}

}
