package org.springblade.modules.nh.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;
import jakarta.validation.Valid;

import org.springblade.common.constant.MonitorConstants;
import org.springblade.core.mp.support.SqlKeyword;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.annotation.PreAuth;
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.core.tool.utils.StringUtil;
import org.springblade.modules.nh.pojo.entity.PowerStationEntity;
import org.springblade.modules.nh.service.IDeviceService;
import org.springblade.modules.nh.service.IPowerStationService;
import org.springblade.modules.operation.service.IOperationSiteService;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.modules.nh.pojo.entity.AlarmInfoEntity;
import org.springblade.modules.nh.pojo.vo.AlarmInfoVO;
import org.springblade.modules.nh.excel.AlarmInfoExcel;
import org.springblade.modules.nh.wrapper.AlarmInfoWrapper;
import org.springblade.modules.nh.service.IAlarmInfoService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.constant.RoleConstant;
import java.util.Map;
import java.util.List;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 设备告警信息表 控制器
 *
 * @author AlexWang
 * @since 2024-06-03
 */
@RestController
@AllArgsConstructor
@RequestMapping("nh/alarmInfo")
@Tag(name = "设备告警信息表", description = "设备告警信息表接口")
public class AlarmInfoController extends BladeController {

	private final IAlarmInfoService alarmInfoService;

	private final IPowerStationService powerStationService;

	private final IDeviceService deviceService;

	private final IOperationSiteService operationSiteService;

	/**
	 * 设备告警信息表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@Operation(summary = "详情", description  = "传入alarmInfo")
	public R<AlarmInfoVO> detail(AlarmInfoEntity alarmInfo) {
		AlarmInfoEntity detail = alarmInfoService.getOne(Condition.getQueryWrapper(alarmInfo));
		return R.data(AlarmInfoWrapper.build().entityVO(detail));
	}
	/**
	 * 设备告警信息表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@Operation(summary = "分页", description  = "传入alarmInfo")
	public R<IPage<AlarmInfoVO>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> alarmInfo, Query query) {

		String orderNo = null;
		if(alarmInfo.containsKey("orderNo")){
			orderNo = (String) alarmInfo.get("orderNo");
			alarmInfo.remove("orderNo");
		}
		StringBuilder stationSql = new StringBuilder("select id from nh_power_station WHERE is_deleted=0");
		boolean stationQueryFlag = false;
		if(alarmInfo.containsKey("capitalName")){
			stationSql.append(" AND capital_name='"+alarmInfo.get("capitalName")+"'");
			stationQueryFlag = true;
			alarmInfo.remove("capitalName");
		}
		if(alarmInfo.containsKey("omProviderName")){
			stationSql.append(" AND om_provider_name='"+alarmInfo.get("omProviderName")+"'");
			stationQueryFlag = true;
			alarmInfo.remove("omProviderName");
		}

		QueryWrapper<AlarmInfoEntity> queryWrapper = Condition.getQueryWrapper(alarmInfo, AlarmInfoEntity.class);

		String omid = operationSiteService.getOmProviderId();
		if(StringUtil.isNotBlank(omid)){
			stationSql.append(" AND om_provider_id='"+omid+"'");
			stationQueryFlag = true;
		}
		if(stationQueryFlag){
			queryWrapper.lambda().inSql(AlarmInfoEntity::getStationId,stationSql.toString());
		}

		if(StringUtil.isNotBlank(orderNo)){
			queryWrapper.lambda().inSql(AlarmInfoEntity::getStationId,"SELECT id from nh_power_station WHERE order_number like '%"+orderNo+"%'");

		}

		if (!Func.isEmpty(alarmInfo)) {
			alarmInfo.forEach((k, v) -> {
				if (!Func.hasEmpty(new Object[]{k, v}) && k.endsWith("_ignore")) {
					if (k.endsWith("_ignore")) {
						queryWrapper.in(StringUtil.replace(k,"_ignore",""), Func.toIntList((String) v));
					}
				}
			});
		}

		queryWrapper.orderByDesc("id");
		IPage<AlarmInfoEntity> pages = alarmInfoService.page(Condition.getPage(query), queryWrapper);
		IPage<AlarmInfoVO> page = AlarmInfoWrapper.build().pageVO(pages);
		page.getRecords().forEach(item->{
			item.setDevice(deviceService.getInverterBySn(item.getSn()));
			PowerStationEntity powerStation=powerStationService.getByOutStationId(item.getOutStationId());
			item.setPowerStation(powerStation);
			if(powerStation!= null){
				item.setOrderNo(powerStation.getOrderNumber());
			}
		});
		return R.data(page);
	}

	/**
	 * 设备告警信息表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@Operation(summary = "分页", description  = "传入alarmInfo")
	public R<IPage<AlarmInfoVO>> page(AlarmInfoVO alarmInfo, Query query) {
		IPage<AlarmInfoVO> pages = alarmInfoService.selectAlarmInfoPage(Condition.getPage(query), alarmInfo);
		return R.data(pages);
	}

	/**
	 * 设备告警信息表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@Operation(summary = "新增", description  = "传入alarmInfo")
	public R save(@Valid @RequestBody AlarmInfoEntity alarmInfo) {
		return R.status(alarmInfoService.save(alarmInfo));
	}

	/**
	 * 设备告警信息表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@Operation(summary = "修改", description  = "传入alarmInfo")
	public R update(@Valid @RequestBody AlarmInfoEntity alarmInfo) {
		return R.status(alarmInfoService.updateById(alarmInfo));
	}

	/**
	 * 设备告警信息表 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@Operation(summary = "新增或修改", description  = "传入alarmInfo")
	public R submit(@Valid @RequestBody AlarmInfoEntity alarmInfo) {
		return R.status(alarmInfoService.saveOrUpdate(alarmInfo));
	}

	/**
	 * 设备告警信息表 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "删除", description  = "传入ids")
	public R remove(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		return R.status(alarmInfoService.removeByIds(Func.toLongList(ids)));
	}

	/**
	 * 设备告警信息表 删除
	 */
	@PostMapping("/batchClose")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "批量关闭", description  = "传入ids")
	public R batchClose(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		LambdaUpdateWrapper<AlarmInfoEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(AlarmInfoEntity::getId, Func.toLongList(ids))
			.notIn(AlarmInfoEntity::getStatus,MonitorConstants.ALARM_ST_HANDLING,MonitorConstants.ALARM_ST_SOLVED)
			.set(AlarmInfoEntity::getCloseStatus, MonitorConstants.ALARM_CLOSE_YES);
		boolean result = alarmInfoService.update(updateWrapper);
		if(result){
			return R.success("操作成功");
		}else{
			return R.fail("当前电站状态不可操作关闭");
		}

	}

	/**
	 * 设备告警信息表 删除
	 */
	@PostMapping("/batchUnClose")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "批量关闭", description  = "传入ids")
	public R batchUnClose(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		LambdaUpdateWrapper<AlarmInfoEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(AlarmInfoEntity::getId, Func.toLongList(ids))
			.set(AlarmInfoEntity::getCloseStatus, MonitorConstants.ALARM_CLOSE_NO);
		return R.status(alarmInfoService.update(updateWrapper));
	}

	/**
	 * 设备告警信息
	 */
	@PostMapping("/batchApplyError")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "设备告警信息申报故障", description  = "传入ids")
	public R batchApplyError(@Parameter(name = "主键集合", required = true) @RequestParam String ids) {
		LambdaUpdateWrapper<AlarmInfoEntity> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.in(AlarmInfoEntity::getId, Func.toLongList(ids))
			.eq(AlarmInfoEntity::getStatus, MonitorConstants.ALARM_ST_NOT_CONFIRMED)
			.set(AlarmInfoEntity::getStatus, MonitorConstants.ALARM_ST_UNHANDLED);
		alarmInfoService.update(updateWrapper);
		return R.success("申报故障成功");
	}


	/**
	 * 导出数据
	 */
	@GetMapping("/export-alarmInfo")
	@ApiOperationSupport(order = 9)
	@Operation(summary = "导出数据", description  = "传入alarmInfo")
	public void exportAlarmInfo(@Parameter(hidden = true) @RequestParam Map<String, Object> alarmInfo, BladeUser bladeUser, HttpServletResponse response) {



		//QueryWrapper<AlarmInfoEntity> queryWrapper = Condition.getQueryWrapper(alarmInfo, AlarmInfoEntity.class);
		String orderNo = null;
		if(alarmInfo.containsKey("orderNo")){
			orderNo = (String) alarmInfo.get("orderNo");
			alarmInfo.remove("orderNo");
		}
		StringBuilder stationSql = new StringBuilder("select id from nh_power_station WHERE is_deleted=0");
		boolean stationQueryFlag = false;
		if(alarmInfo.containsKey("capitalName")){
			stationSql.append(" AND capital_name='"+alarmInfo.get("capitalName")+"'");
			stationQueryFlag = true;
			alarmInfo.remove("capitalName");
		}
		if(alarmInfo.containsKey("omProviderName")){
			stationSql.append(" AND om_provider_name='"+alarmInfo.get("omProviderName")+"'");
			stationQueryFlag = true;
			alarmInfo.remove("omProviderName");
		}

		QueryWrapper<AlarmInfoEntity> queryWrapper = Condition.getQueryWrapper(alarmInfo, AlarmInfoEntity.class);

		String omid = operationSiteService.getOmProviderId();
		if(StringUtil.isNotBlank(omid)){
			stationSql.append(" AND om_provider_id='"+omid+"'");
			stationQueryFlag = true;
		}
		if(stationQueryFlag){
			queryWrapper.lambda().inSql(AlarmInfoEntity::getStationId,stationSql.toString());
		}

		if(StringUtil.isNotBlank(orderNo)){
			queryWrapper.lambda().inSql(AlarmInfoEntity::getId,"SELECT alarm_id from sf_operation_order WHERE number like '%"+orderNo+"%'");

		}

		if (!Func.isEmpty(alarmInfo)) {
			alarmInfo.forEach((k, v) -> {
				if (!Func.hasEmpty(new Object[]{k, v}) && k.endsWith("_ignore")) {
					if (k.endsWith("_ignore")) {
						queryWrapper.in(StringUtil.replace(k,"_ignore",""), Func.toIntList((String) v));
					}
				}
			});
		}

		queryWrapper.orderByDesc("id");
		queryWrapper.lambda().eq(AlarmInfoEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<AlarmInfoExcel> list = alarmInfoService.exportAlarmInfo(queryWrapper);
		list.forEach(item->{
			PowerStationEntity powerStation=powerStationService.getByOutStationId(item.getOutStationId());
			if(powerStation!= null){
				item.setCapitalName(powerStation.getCapitalName());
				item.setOrderNumber(powerStation.getOrderNumber());
				item.setOmProviderName(powerStation.getOmProviderName());
			}

		});
		ExcelUtil.export(response, "设备告警信息表数据" + DateUtil.time(), "设备告警信息表数据表", list, AlarmInfoExcel.class);
	}
	/**
	 * 转运维
	*/
	@PostMapping("/turnMaintenance")
	@ApiOperationSupport(order = 7)
	@Operation(summary = "转运维", description  = "传入id")
	public R turnMaintenance(@Parameter(name = "id", required = true) @RequestParam String id) {

		return alarmInfoService.turnMaintenance(id);
	}




}
