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

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

import javax.validation.Valid;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import org.springblade.common.constant.RequestUrlConstant;
import org.springblade.common.utils.BeanMapUtil;
import org.springblade.community.grid.entity.GridResource;
import org.springblade.community.grid.service.IGridResourceService;
import org.springblade.community.grid.vo.*;
import org.springblade.community.grid.dto.GridDTO;
import org.springblade.community.grid.entity.GridResource;
import org.springblade.community.grid.service.IGridResourceService;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.community.grid.excel.GridExcel;
import org.springblade.community.grid.excel.GridImporter;
import org.springblade.system.user.feign.IUserClient;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.community.grid.entity.Grid;
import org.springblade.community.grid.wrapper.GridWrapper;
import org.springblade.community.grid.service.IGridService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;


/**
 * 控制器
 *
 * @author BladeX
 * @since 2021-03-11
 */
@RestController
@AllArgsConstructor
@RequestMapping("/grid-sys")
@Api(tags = "网格接口")
public class GridController extends BladeController {

	private final IGridService gridService;
	private final IUserClient userClient;
	private final IGridResourceService gridResourceService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入grid")
	public R<GridVO> detail(Grid grid) {
		Grid detail = gridService.getOne(Condition.getQueryWrapper(grid));
		return R.data(GridWrapper.build(gridService, userClient).entityVO(detail));
	}

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入grid")
	public R<IPage<GridVO>> list(Grid grid, Query query) {
		String userCode = grid.getUserCode();
		grid.setUserCode(null);
		QueryWrapper<Grid> queryWrapper = Condition.getQueryWrapper(grid);
		if(Func.isNotEmpty(userCode)){
			queryWrapper.lambda().like(Grid::getUserCode,userCode);
		}
		IPage<Grid> pages = gridService.page(Condition.getPage(query),queryWrapper);
		return R.data(GridWrapper.build(gridService, userClient).pageVO(pages));
	}


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

	/**
	 * 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入grid")
	public R save(@Valid @RequestBody GridDTO grid) {
		grid.setAreaCode(IdUtil.simpleUUID());
		Grid pgrid = gridService.getById(grid.getPid());
		grid.setCodePath(pgrid.getCodePath() + "/" + pgrid.getAreaCode());
		gridService.save(grid);
		GridResource gridResource = new GridResource();
		gridResource.setLevel(1);
		gridResource.setGridId(grid.getId());
		gridResource.setResourseIds(grid.getResourceList());
		return R.status(gridResourceService.save(gridResource));
	}

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

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


	/**
	 * 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(gridService.deleteLogic(Func.toLongList(ids)));
	}


	/**
	 * 详情
	 */
	@GetMapping("/getById")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入grid")
	public R<GridVO> getById(@RequestParam("id") Long id) {
		Grid detail = gridService.getById(id);
		return R.data(GridWrapper.build(gridService, userClient).entityVO(detail));
	}

	/**
	 * 导入网格数据
	 */
	@PostMapping("/import-grid")
	@ApiOperation(value = "导入网格数据", notes = "传入excel")
	public R importRegion(MultipartFile file, Integer isCovered) {
		GridImporter regionImporter = new GridImporter(gridService, isCovered == 1);
		ExcelUtil.save(file, regionImporter, GridExcel.class);
		return R.success("操作成功");
	}


	/**
	 * 网格大屏统计
	 */
	@GetMapping("/static")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "网格大屏统计", notes = "传入grid")
	public R<GridStaticVO> staticScreen(Long id) {
		Grid grid1 = gridService.getById(id);
		Assert.notNull(grid1,"网格不存在");
		Map<String, Object> body = BeanMapUtil.beanToMap(grid1);
		if(!"system".equals(grid1.getBoundsType())){
			GridResource gridResource = gridResourceService.getBaseMapper().selectOne(new QueryWrapper<>(new GridResource()).lambda()
				.eq(GridResource::getGridId, grid1.getId()));
			Assert.notNull(gridResource,"该网格没有关联任何资源");
			Integer level = gridResource.getLevel();
			if(level == 1){//园区
				body.put("agencyIds",gridResource.getResourseIds());
			}else if(level == 2){//小区
				body.put("residentialIds",gridResource.getResourseIds());
			}
		}
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

		HttpEntity requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(body), headers);


		ParameterizedTypeReference<R<GridStaticVO>> reference = new ParameterizedTypeReference<R<GridStaticVO>>() {
		};

		String url = RequestUrlConstant.GRID_STATIC;
//		String url = "http://localhost:9527/grid-community/static";
		URI uri = URI.create(url);


		R<GridStaticVO> gridStaticVOR = restTemplate.postForObject(uri,requestEntity, R.class);

		return gridStaticVOR;

	}

	/**
	 * 网格大屏统计
	 */
	@GetMapping("/smartDeviceStatic")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "网格大屏统计", notes = "传入grid")
	public R<SmartDeviceStatic> smartDeviceStaticR(Long id,String deviceType) {
		Grid grid1 = gridService.getById(id);
		Assert.notNull(grid1,"网格不存在");
		Map<String, Object> body = BeanMapUtil.beanToMap(grid1);

		if(!"system".equals(grid1.getBoundsType())){
			GridResource gridResource = gridResourceService.getBaseMapper().selectOne(new QueryWrapper<>(new GridResource()).lambda()
				.eq(GridResource::getGridId, grid1.getId()));
			Assert.notNull(gridResource,"该网格没有关联任何资源");
			Integer level = gridResource.getLevel();
			if(level == 1){//园区
				body.put("agencyIds",gridResource.getResourseIds());
			}else if(level == 2){//小区
				body.put("residentialIds",gridResource.getResourseIds());
			}
		}
		body.put("deviceType",deviceType);
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

		HttpEntity requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(body), headers);


		ParameterizedTypeReference<R<SmartDeviceStatic>> reference = new ParameterizedTypeReference<R<SmartDeviceStatic>>() {
		};

		String url = RequestUrlConstant.DEVICE_STATIC;
//		String url = "http://localhost:9527/grid-community/getDeviceStaticByType";
		URI uri = URI.create(url);


		R<SmartDeviceStatic> smartDeviceStaticR = restTemplate.postForObject(uri,requestEntity, R.class);

		return smartDeviceStaticR;

	}

	/**
	 * 网格大屏统计
	 */
	@GetMapping("/houseuserList")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "网格大屏统计", notes = "传入grid")
	public R<IPage<Houseuser>> getHouseUser(Long gridId,Houseuser houseuser,Query query) {

		if(query.getSize() == null){
			query.setSize(10);
		}
		if(query.getCurrent() == null){
			query.setCurrent(1);
		}


		Grid grid1 = gridService.getById(gridId);
		Assert.notNull(grid1,"网格不存在");
		Map<String, Object> body = BeanMapUtil.beanToMap(grid1);
		body.put("houseuser",houseuser);

		body.put("query",query);
		if(!"system".equals(grid1.getBoundsType())){
			GridResource gridResource = gridResourceService.getBaseMapper().selectOne(new QueryWrapper<>(new GridResource()).lambda()
				.eq(GridResource::getGridId, grid1.getId()));
			Assert.notNull(gridResource,"该网格没有关联任何资源");
			Integer level = gridResource.getLevel();
			if(level == 1){//园区
				body.put("agencyIds",gridResource.getResourseIds());
			}else if(level == 2){//小区
				body.put("residentialIds",gridResource.getResourseIds());
			}
		}else {
			body.put("codePath",grid1.getCodePath());
		}
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

		HttpEntity requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(body), headers);


		ParameterizedTypeReference<R<SmartDeviceStatic>> reference = new ParameterizedTypeReference<R<SmartDeviceStatic>>() {
		};

		String url = RequestUrlConstant.HOUSE_USER_LIST;
//		String url = "http://localhost:9527/grid-community/houseuserlist";
		URI uri = URI.create(url);


		R<IPage<Houseuser>> houseUserList = restTemplate.postForObject(uri,requestEntity, R.class);

		return houseUserList;

	}

	/**
	 * 网格大屏统计
	 */
	@GetMapping("/smartDeviceList")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "网格大屏统计", notes = "传入grid")
	public R<IPage<SmartDevice>> getSmartDevice(Long gridId, SmartDevice smartDevice, Query query) {

		if(query.getSize() == null){
			query.setSize(10);
		}
		if(query.getCurrent() == null){
			query.setCurrent(1);
		}


		Grid grid1 = gridService.getById(gridId);
		Assert.notNull(grid1,"网格不存在");
		Map<String, Object> body = BeanMapUtil.beanToMap(grid1);
		body.put("smartDevice",smartDevice);
		body.put("query",query);
		if(!"system".equals(grid1.getBoundsType())){
			GridResource gridResource = gridResourceService.getBaseMapper().selectOne(new QueryWrapper<>(new GridResource()).lambda()
				.eq(GridResource::getGridId, grid1.getId()));
			Assert.notNull(gridResource,"该网格没有关联任何资源");
			Integer level = gridResource.getLevel();
			if(level == 1){//园区
				body.put("agencyIds",gridResource.getResourseIds());
			}else if(level == 2){//小区
				body.put("residentialIds",gridResource.getResourseIds());
			}
		}else{
			body.put("codePath",grid1.getCodePath());
		}
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity responseEntity = null;
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

		HttpEntity requestEntity = new HttpEntity<>(JSONUtil.toJsonStr(body), headers);


		ParameterizedTypeReference<R<SmartDeviceStatic>> reference = new ParameterizedTypeReference<R<SmartDeviceStatic>>() {
		};

		String url = RequestUrlConstant.DEVICE_LIST;
//		String url = "http://localhost:9527/grid-community/smartDeviceList";
		URI uri = URI.create(url);


		R<IPage<SmartDevice>> smartDeviceList = restTemplate.postForObject(uri,requestEntity, R.class);

		return smartDeviceList;

	}

}
