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

import cn.hutool.core.lang.Assert;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 javax.validation.Valid;

import org.springblade.community.residential.entity.Residential;
import org.springblade.community.residential.service.IResidentialService;
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.modules.system.entity.Role;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.openinterface.elevator.bean.ElevatorApiResultBean;
import org.springblade.openinterface.elevator.bean.ElevatorInfoResultBean;
import org.springblade.openinterface.elevator.util.ElevatorUtil;
import org.springblade.system.orgposition.entity.OrgPosition;
import org.springblade.system.orgposition.service.IOrgPositionService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.community.elevator.elevator.entity.Elevator;
import org.springblade.community.elevator.elevator.vo.ElevatorVO;
import org.springblade.community.elevator.elevator.wrapper.ElevatorWrapper;
import org.springblade.community.elevator.elevator.service.IElevatorService;
import org.springblade.core.boot.ctrl.BladeController;

import java.util.*;

/**
 * 云梯-电梯信息 控制器
 *
 * @author BladeX
 * @since 2021-02-04
 */
@RestController
@AllArgsConstructor
@RequestMapping("community/elevator/elevator")
@Api(value = "云梯-电梯信息", tags = "云梯-电梯信息接口")
public class ElevatorController extends BladeController {

	private IElevatorService elevatorService;
	private ElevatorUtil elevatorUtil;
	private IResidentialService residentialService;
	private IOrgPositionService orgPositionService;
	private IRoleService roleService;

	/**
	 * 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R<ElevatorVO> detail(Elevator elevator) {
		Elevator detail = elevatorService.getOne(Condition.getQueryWrapper(elevator));
		return R.data(ElevatorWrapper.build().entityVO(detail));
	}

	/**
	 * 分页 云梯-电梯信息
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入elevator")
	public R<IPage<ElevatorVO>> list(@RequestParam Map<String, Object> elevator, Query query, BladeUser bladeUser) {

		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Elevator> wrapper = Condition.getQueryWrapper(elevator, Elevator.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(i ==0){
				wrapper.like(Elevator::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Elevator::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		//获取角色信息
		Role role = roleService.getById(bladeUser.getRoleId());
		//非超管，根据tenantId租户id过滤
		if (!role.getRoleAlias().equals("administrator")){
			wrapper.eq(Elevator::getTenantId, bladeUser.getTenantId());
		}

		IPage<Elevator> pages = elevatorService.page(Condition.getPage(query), wrapper);
		return R.data(ElevatorWrapper.build().pageVO(pages));
	}

	/**
	 * 自定义分页 云梯-电梯信息
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入elevator")
	public R<IPage<ElevatorVO>> page(ElevatorVO elevator, Query query) {
		IPage<ElevatorVO> pages = elevatorService.selectElevatorPage(Condition.getPage(query), elevator);
		return R.data(pages);
	}

	/**
	 * 新增 云梯-电梯信息
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入elevator")
	public R save(@Valid @RequestBody Elevator elevator) {
		return R.status(elevatorService.save(elevator));
	}

	/**
	 * 修改 云梯-电梯信息
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入elevator")
	public R update(@Valid @RequestBody Elevator elevator) {
		return R.status(elevatorService.updateById(elevator));
	}

	/**
	 * 新增或修改 云梯-电梯信息
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入elevator")
	public R submit(@Valid @RequestBody Elevator elevator) {
		if (elevator.getResidentialId() != null){
			Residential residential = residentialService.getById(elevator.getResidentialId());
			elevator.setResidentialName(residential.getName());
			elevator.setOrgPosition(residential.getOrgPosition());
			elevator.setTenantId(residential.getTenantId());
		}
		return R.status(elevatorService.saveOrUpdate(elevator));
	}


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

	/**
	 * 同步云梯信息
	 * @return
	 */
	@PostMapping("/sync")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "同步云梯信息", notes = "")
	public R syncElevator(){

		List<String> registerCodeList = new ArrayList<>();

		ElevatorApiResultBean liftRegCodes = elevatorUtil.getLiftRegCodes();
		Object data = liftRegCodes.getData();
		if (data != null){
			JSONArray jsonArray = JSONUtil.parseArray(data);
			jsonArray.forEach(item -> {
				JSONObject jsonObject = JSONUtil.parseObj(item);
				Object registerCode = jsonObject.get("registerCode");
				if (registerCode != null){
					registerCodeList.add(registerCode.toString());
				}
			});
		}
		Assert.isTrue(registerCodeList.size() > 0, "暂无同步信息！");

		ElevatorInfoResultBean liftInfo = elevatorUtil.getLiftInfo(registerCodeList);
		List<Elevator> list = liftInfo.getData();

		list.forEach(item -> {
			Elevator wrapper = new Elevator();
			wrapper.setRegisterCode(item.getRegisterCode());
			Elevator one = elevatorService.getOne(Condition.getQueryWrapper(wrapper));
			if (one != null){
				item.setId(one.getId());
			}
			item.setOrgPosition("/640000");
			item.setTenantId("000000");
		});

		boolean saveResult = elevatorService.saveOrUpdateBatch(list);
		return R.status(saveResult);
	}

	/**
	 * 获取电梯实时监控信息
	 */
	@GetMapping("/getRealvideo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getRealvideo(String registerCode) {
		Map<String, String> params = new HashMap<>();
		params.put("registerCode", registerCode);
		return R.data(elevatorUtil.getRealvideoAuthorization(params));
	}

	/**
	 * 获取电梯历史告警信息(云梯接口)
	 */
	@GetMapping("/getLiftHisAlarm")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftHisAlarm(String registerCodes) {
		Map<String, Object> params = new HashMap<>();
		params.put("registerCodes", registerCodes.split(","));

		ElevatorApiResultBean resultBean = elevatorUtil.getLiftHisAlarm(params);

		if (resultBean.getCode() != null && resultBean.getCode().equals(0)){
			return R.data(resultBean.getData());
		}else{
			return R.fail(resultBean.getMessage());
		}
	}

	/**
	 * 获取电梯小区名称select
	 */
	@GetMapping("/getLiftResidentialSelect")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftResidentialSelect(BladeUser bladeUser) {
//		List<Elevator> list = elevatorService.getLiftResidentialSelect();

		String deptId = bladeUser.getDeptId();
		String[] deptIds = deptId.split(",");
		LambdaQueryWrapper<Elevator> wrapper = Condition.getQueryWrapper(new Elevator()).lambda();
		for(int i=0;i<deptIds.length;i++){
			OrgPosition orgPosition = orgPositionService.getOne(new QueryWrapper<>(new OrgPosition()).lambda().eq(OrgPosition::getOrgId,deptIds[i]));
			if(i ==0){
				wrapper.like(Elevator::getOrgPosition,orgPosition.getOrgPosition());
			}else{
				wrapper.or().like(Elevator::getOrgPosition,orgPosition.getOrgPosition());
			}
		}
		//获取角色信息
		Role role = roleService.getById(bladeUser.getRoleId());
		//非超管，根据tenantId租户id过滤
		if (!role.getRoleAlias().equals("administrator")){
			wrapper.eq(Elevator::getTenantId, bladeUser.getTenantId());
		}

		List<Elevator> list = elevatorService.list(wrapper);
		Set hs = new HashSet();
		list.forEach(item -> {
			hs.add(item.getNbhdName());
		});

		return R.data(hs);
	}

	/**
	 * 获取电梯list
	 */
	@GetMapping("/getLiftList")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftList(Elevator elevator) {
		List<Elevator> list = elevatorService.list(Condition.getQueryWrapper(elevator));
		return R.data(list);
	}

	/**
	 * 获取电梯小区列表（去重）
	 */
	@GetMapping("/getListWithYtelevatorXq")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getListWithYtelevatorXq() {
		List<Residential> list = residentialService.getListWithYtelevatorXq();
		return R.data(list);
	}


	/**
	 * 获取电梯实时监控信息
	 */
	@GetMapping("/getAlarmVideo")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getAlarmVideo(String alarmCode) {
		Map<String, String> params = new HashMap<>();
		params.put("alarmCode", alarmCode);
		return R.data(elevatorUtil.getAlarmVideoAuthorization(params));
	}

	/**
	 * 获取电梯当前状态
	 */
	@GetMapping("/getLiftStatus")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftStatus(String registerCode) {
		ElevatorApiResultBean liftStatus = elevatorUtil.getLiftStatus(registerCode);
		return R.data(liftStatus);
	}

	/**
	 * 获取电梯环境监测数据
	 */
	@GetMapping("/getLiftPointData")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入elevator")
	public R getLiftPointData(String registerCode) {
		ElevatorApiResultBean liftPointData = elevatorUtil.getLiftPointData(registerCode);
		return R.data(liftPointData);
	}


}
