package com.yeejoin.amos.boot.module.tzs.biz.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.SystemClock;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.excel.ExcelUtil;
import com.yeejoin.amos.boot.module.common.biz.service.impl.MaintenanceCompanyServiceImpl;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlarmStatisticsDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCallInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertCalledQueryDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.AlertPaperInfoDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.ESAlertCalledDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.ESAlertCalledRequestDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.tzs.api.entity.Elevator;
import com.yeejoin.amos.boot.module.tzs.api.entity.WechatRelation;
import com.yeejoin.amos.boot.module.tzs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.AlertCalledServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.AlertFormValueServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.DispatchPaperServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.ESAlertCalledService;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.ElevatorServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.WechatRelationServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.utils.AlertBeanDtoVoUtils;
import com.yeejoin.amos.boot.module.tzs.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 警情接警填报记录
 *
 * @author litw
 * @date 2021-08-03
 */
@RestController
@Api(tags = "警情接警填报记录Api")
@RequestMapping(value = "/alert-called")
public class AlertCalledController extends BaseController {

	private final Logger logger = LoggerFactory.getLogger(AlertCalledController.class);

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	AlertCalledServiceImpl iAlertCalledService;

	@Autowired
	ESAlertCalledService eSAlertCalledService;

	@Autowired
	DispatchPaperServiceImpl dispatchPaperServiceImpl;

	@Autowired
	AlertFormValueServiceImpl iAlertFormValueService;

	@Autowired
	ElevatorServiceImpl elevatorServiceImpl;

	@Autowired
	MaintenanceCompanyServiceImpl maintenanceCompanyService;

	@Autowired
	WechatRelationServiceImpl wechatRelationService;

	@Autowired
	ElevatorServiceImpl elevatorService;

	@Autowired
	private EmqKeeper emqKeeper;

	@Value("${mqtt.topic.alertReport.push}")
	private String alertReportpushTopic;

	@Value("${mqtt.topic.alertInfo.push}")
	private String alertInfopushTopic;

	/**
	 * 新增警情接警填报记录
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增警情接警填报记录", notes = "新增警情接警填报记录")
	public ResponseModel<AlertCalledDto> save(@RequestBody AlertCalledObjsDto alertCalledObjsDto) {
		if (ValidationUtil.isEmpty(alertCalledObjsDto)
				|| ValidationUtil.isEmpty(alertCalledObjsDto.getAlertCalledDto())) {
			throw new BadRequest("参数校验失败.");
		}
		ReginParams reginParams = getSelectedOrgInfo();
		alertCalledObjsDto = iAlertCalledService.createAlertCalled(alertCalledObjsDto, reginParams.getUserModel());

		// 坐席接警后，辅屏由常态化切换为处置态
		AgencyUserModel user =getUserInfo();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("userId",user.getUserId());
		jsonObject.put("alertId",alertCalledObjsDto.getAlertCalledDto().getSequenceNbr());

		JSONObject jsonObject1 = new JSONObject();
		jsonObject.put("alertId",alertCalledObjsDto.getAlertCalledDto().getSequenceNbr());

		try {
			emqKeeper.getMqttClient().publish(alertReportpushTopic, jsonObject.toString().getBytes("UTF-8"), 1, false);
			// 跑马灯消息提醒
			if(null != alertCalledObjsDto.getAlertCalledDto().getFatherAlert()) {
				emqKeeper.getMqttClient().publish(alertInfopushTopic, jsonObject1.toString().getBytes("UTF-8"), 1, false);
			}
		} catch (MqttException e) {
			logger.error("mqtt发送失败" +jsonObject );
		} catch (UnsupportedEncodingException e) {
			logger.error("mqtt发送失败" +jsonObject );
		}
		return ResponseHelper.buildResponse(alertCalledObjsDto.getAlertCalledDto());
	}

	/**
	 * 公众号投诉建议与故障报销
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/saveMobile")
	@ApiOperation(httpMethod = "POST", value = "新增警情接警填报记录", notes = "新增警情接警填报记录")
	public ResponseModel<AlertCalledDto> saveMobile(@RequestBody AlertCalledDto alertCalledDto
			) {
		if (ValidationUtil.isEmpty(alertCalledDto)) {
			throw new BadRequest("参数校验失败.");
		}

		if (ValidationUtil.isEmpty(alertCalledDto.getEmergencyCall())) {
			throw new BadRequest("参数校验失败.");
		}

		// 校验手机号 是否存在
		LambdaQueryWrapper<WechatRelation> queryWrapper = new LambdaQueryWrapper();
		queryWrapper.eq(WechatRelation::getPhone, alertCalledDto.getEmergencyCall());
		WechatRelation wechatRelation = wechatRelationService.getOne(queryWrapper);
		if (null == wechatRelation) {
			throw new BadRequest("手机号未注册");
		}

		// 校验电梯id是否正确
		LambdaQueryWrapper<Elevator> queryWrapper1 = new LambdaQueryWrapper();
		queryWrapper1.eq(Elevator::getSequenceNbr, Long.valueOf(alertCalledDto.getEquipmentId()));
		Elevator elevator = elevatorServiceImpl.getOne(queryWrapper1);
		if (null == elevator) {
			throw new BadRequest("电梯不存在");
		}
		// 将电梯地址设置到警情地址
		alertCalledDto.setAddress(elevator.getAddress());
		alertCalledDto.setRegistrationCode(elevator.getRegisterCode());
		alertCalledDto.setDeviceId(String.valueOf(elevator.getRescueCode()));
		alertCalledDto.setUseStatus(elevator.getUseStatus());
		alertCalledDto.setUseSiteCategory(elevator.getUseSiteCategory());
		alertCalledDto.setAlarmType(AlertStageEnums.getEnumById(alertCalledDto.getAlarmTypeCode()).getValue());

		AlertCalledDto alertCalledDtoReturn = iAlertCalledService.createAlertCalled(alertCalledDto);
		return ResponseHelper.buildResponse(alertCalledDtoReturn);
	}


	/**
	 * 警情信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getAlertInfo")
	@ApiOperation(httpMethod = "GET", value = "警情信息", notes = "警情信息")
	public ResponseModel<AlertPaperInfoDto> getAlertInfo(@RequestParam Long alertId
	) {
		AlertCalled alertCalled = iAlertCalledService.getById(alertId);
		AlertPaperInfoDto alertPaperInfoDto = new AlertPaperInfoDto();
		alertPaperInfoDto.setAlertId(alertCalled.getSequenceNbr());

		iAlertCalledService.selectAlertCalledByIdNew(alertPaperInfoDto);

		LambdaQueryWrapper<Elevator> queryWrapper1= new LambdaQueryWrapper<>();
		queryWrapper1.eq(Elevator::getSequenceNbr,alertCalled.getEquipmentId());
		Elevator elevator = elevatorService.getOne(queryWrapper1);

		alertPaperInfoDto.setArea(elevator.getProvince() + elevator.getCity() + elevator.getDistrict());
		alertPaperInfoDto.setAddress(alertCalled.getAddress());
		alertPaperInfoDto.setCallTime(alertCalled.getCallTime());
		alertPaperInfoDto.setLatitude(elevator.getLatitude());
		alertPaperInfoDto.setLongitude(elevator.getLongitude());
		alertPaperInfoDto.setAlarmTypeCode(alertCalled.getAlarmTypeCode());
		alertPaperInfoDto.setRegionCode(elevator.getRegionCode());
		alertPaperInfoDto.setRescueCode(elevator.getRescueCode());
		alertPaperInfoDto.setAlertStatus(alertCalled.getAlertStage());

		return ResponseHelper.buildResponse(alertPaperInfoDto);
	}

	/**
	 *
	 * <pre>
	 * 相似警情分页查询
	 * </pre>
	 *
	 * @param
	 * @param current
	 * @param size
	 * @return
	 * @throws Exception
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(value = "相似警情分页查询")
	@PostMapping(value = "/page/similar")
	public ResponseModel<Page<ESAlertCalledDto>> pageBySimilar(@RequestBody ESAlertCalledRequestDto alertCalledVo,
			@RequestParam(value = "current") int current, @RequestParam(value = "size") int size) throws Exception {

		Page<ESAlertCalledDto> esAlertCalledDtoPage = eSAlertCalledService.queryByKeys(alertCalledVo, current, size);
		return ResponseHelper.buildResponse(esAlertCalledDtoPage);
	}

	/**
	 * 根据id查询
	 *
	 * @param id 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{id}")
	@ApiOperation(httpMethod = "GET", value = "根据id查询单个警情接警填报记录", notes = "根据id查询单个警情接警填报记录")
	public ResponseModel<Object> selectOne(@PathVariable Long id) {
		return ResponseHelper.buildResponse(iAlertCalledService.selectAlertCalledById(id));
	}

	/**
	 * 生成工单编号报警人及报警时间
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getWorkOderNumber")
	@ApiOperation(httpMethod = "GET", value = "生成工单编号报警人及报警时间", notes = "生成工单编号报警人及报警时间")
	public ResponseModel<AlertCallInfoDto> selectOne() throws ParseException {
		String workOrderNumber = nextId();
		AlertCallInfoDto alertCallInfoDto = new AlertCallInfoDto();
		alertCallInfoDto.setCallTime(DateUtils.stampToDate(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss "));
		alertCallInfoDto.setWorkOrderNumber(workOrderNumber);
		alertCallInfoDto.setRecUserId(getUserInfo().getUserId());
		alertCallInfoDto.setRecUserName(getUserInfo().getRealName());
		return ResponseHelper.buildResponse(alertCallInfoDto);
	}

	/**
	 * 获取下一个 工单编号
	 *
	 * @return 下一个 工单编号
	 */
	public synchronized String nextId() throws ParseException {

		String number = DateUtils.stampToDate(SystemClock.now(), "yyyy-MM-dd HH:mm:ss SSS");
		String newNumber = number.replace("-", "").replace(" ", "").replace(":", "");
		ReginParams reginParams = getSelectedOrgInfo();
		AgencyUserModel user = reginParams.getUserModel();
		String orgCode = ValidationUtil.isEmpty(user.getCompanys()) ? null : user.getCompanys().get(0).getOrgCode();

		Map<String, Object> map = iAlertCalledService.getAlertInfoList(
				DateUtils.stampToDate(System.currentTimeMillis(), DateUtils.DATE_TIME_PATTERN),
				DateUtils.stampToDate(System.currentTimeMillis(), DateUtils.DATE_TIME_PATTERN), orgCode,
				user.getUserId());

		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(newNumber);
		String workOrderNumber = stringBuilder.append(map.get("calledCount") == null ? "1"
				: String.valueOf(Integer.parseInt(map.get("calledCount").toString()) + 1)).toString();
		return workOrderNumber;
	}

	/**
	 * 警情统计
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/alertStatistics")
	@ApiOperation(httpMethod = "GET", value = "警情统计", notes = "警情统计")
	public ResponseModel<AlarmStatisticsDto> alertStatistics() {
		ReginParams reginParams = getSelectedOrgInfo();

		// 我的待办数量
		QueryWrapper<AlertCalled> todoNumQueryWrapper = new QueryWrapper<>();
		// 全部待办数量
		QueryWrapper<AlertCalled> allNumQueryWrapper = new QueryWrapper<>();

		AlarmStatisticsDto alarmStatisticsDto = new AlarmStatisticsDto();
		todoNumQueryWrapper.eq("alert_status", false);
		allNumQueryWrapper.eq("alert_status", false);
		if (null != reginParams) {
			todoNumQueryWrapper.eq("rec_user_id", reginParams.getUserModel().getUserId());
			todoNumQueryWrapper.or(true);
			todoNumQueryWrapper.eq("org_code", reginParams.getCompany().getOrgCode());

			alarmStatisticsDto.setTodoNum(iAlertCalledService.list(todoNumQueryWrapper).size());
			alarmStatisticsDto.setAllNum(iAlertCalledService.list(allNumQueryWrapper).size());

			Map<String, Object> map = iAlertCalledService.getAlertInfoList(
					DateUtils.stampToDate(System.currentTimeMillis(), DateUtils.DATE_PATTERN),
					DateUtils.stampToDate(DateUtils.dateAddDays(new Date(), 1).getTime(), DateUtils.DATE_PATTERN), null,
					getUserInfo().getUserId());

			// 当天接警
			alarmStatisticsDto.setTodayAlarmNum(
					map.get("calledCount") == null ? 0 : Integer.valueOf(map.get("calledCount").toString()));
			// 当天提交
			alarmStatisticsDto.setSubmitNum(
					map.get("majorAlertCount") == null ? 0 : Integer.valueOf(map.get("majorAlertCount").toString()));
			// 投诉咨询数量
			alarmStatisticsDto.setSuggestions(
					map.get("suggestionsCount") == null ? 0 : Integer.valueOf(map.get("suggestionsCount").toString()));
			// 故障维修数量
			alarmStatisticsDto.setFaultRescue(
					map.get("faultRescueCount") == null ? 0 : Integer.valueOf(map.get("faultRescueCount").toString()));
			// 困人救援数量
			alarmStatisticsDto.setSleepyIncident(map.get("sleepyIncidentCount") == null ? 0
					: Integer.valueOf(map.get("sleepyIncidentCount").toString()));

			LinkedHashMap<String, Integer> recordMap = new LinkedHashMap<>();
			// 近七天办理数量
			Map<String, Object> nearlySevenDaysMap = iAlertCalledService.getNearlyInfo(
					DateUtils.stampToDate(System.currentTimeMillis(), DateUtils.DATE_PATTERN),
					DateUtils.stampToDate(DateUtils.dateAddDays(new Date(), 1).getTime(), DateUtils.DATE_PATTERN), null,
					getUserInfo().getUserId());

			for (int i = 0; i < nearlySevenDaysMap.size() / 2; i++) {
				recordMap.put(DateUtils.dateToString(nearlySevenDaysMap.get("dateTime" + i).toString()),
						Integer.parseInt(nearlySevenDaysMap.get("majorAlertCount" + i).toString()));
			}
			alarmStatisticsDto.setNearlySevenDaysNum(recordMap);
		}
		return ResponseHelper.buildResponse(alarmStatisticsDto);
	}

	/**
	 * 列表分页查询
	 *
	 * @param pageNum  当前页
	 * @param pageSize 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/list")
	@ApiOperation(httpMethod = "GET", value = "警情接警填报记录分页查询", notes = "警情接警填报记录分页查询")
	public ResponseModel<IPage<AlertCalledDto>> queryForPage(String pageNum, String pageSize, String sort,
			AlertCalledDto alertCalledDto) {
		AlertCalled alertCalled = BeanDtoVoUtils.convert(alertCalledDto, AlertCalled.class);
		Page<AlertCalled> pageBean;
		IPage<AlertCalled> page;
		QueryWrapper<AlertCalled> alertCalledQueryWrapper = new QueryWrapper<>();

		setQueryWrapper(alertCalledQueryWrapper, alertCalled, sort);

		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		page = iAlertCalledService.page(pageBean, alertCalledQueryWrapper);
		IPage<AlertCalledDto> calledVoIPage = AlertBeanDtoVoUtils.alertCalledIPageDto(page);
		return ResponseHelper.buildResponse(calledVoIPage);
	}

	private QueryWrapper<AlertCalled> setQueryWrapper(QueryWrapper<AlertCalled> queryWrapper, AlertCalled alertCalled,
			String sort) {
		queryWrapper.eq("is_delete", 0);

		queryWrapper.orderByDesc("call_time");

		if (!ValidationUtil.isEmpty(alertCalled.getIsAuxiliaryScreen())) {
			if (!ValidationUtil.isEmpty(alertCalled.getCallTimeStart())
					&& !ValidationUtil.isEmpty(alertCalled.getCallTimeEnd())) {
				queryWrapper.between("call_time", alertCalled.getCallTimeStart(),
						alertCalled.getCallTimeEnd().getTime());
			}
		} else {
			queryWrapper.between("call_time", DateUtils.stampToDate(System.currentTimeMillis(), DateUtils.DATE_PATTERN),
					DateUtils.stampToDate(DateUtils.dateAddDays(new Date(), 1).getTime(), DateUtils.DATE_PATTERN));
		}

		if (alertCalled.getIsFatherAlert()) { // 0：接警；1：处警
			queryWrapper.isNull("father_alert");
		}

		if (!ValidationUtil.isEmpty(alertCalled.getType())) {
			queryWrapper.eq("type", alertCalled.getType());
		}

		if (!ValidationUtil.isEmpty(alertCalled.getAlarmType())) {
			queryWrapper.eq("alarm_type", alertCalled.getAlarmType());
		}

		if (!ValidationUtil.isEmpty(alertCalled.getAlertSource())) {
			queryWrapper.eq("alert_source", alertCalled.getAlertSource());
		}
		return queryWrapper;
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "查询警情事件记录", notes = "查询警情事件记录")
	@GetMapping("/selectRecord")
	public ResponseModel<Page<AlertCalledQueryDto>> queryAlertCalledByPager(AlertCalledQueryDto alertCalledQueryDto,
			@RequestParam(value = "pageNum") int pageNum, @RequestParam(value = "pageSize") int pageSize) {
		Page<AlertCalledQueryDto> page = new Page<AlertCalledQueryDto>();
		page.setCurrent(pageNum);
		page.setSize(pageSize);

		Page<AlertCalledQueryDto> pageBean = iAlertCalledService.queryAlertListByQueryDto(page,
				alertCalledQueryDto.getWorkOrderNumber(), alertCalledQueryDto.getCreator(),
				alertCalledQueryDto.getEmergency(),
				alertCalledQueryDto.getEmergencyTimeStart() == null ? null
						: DateUtils.date2LongStr(alertCalledQueryDto.getEmergencyTimeStart()),
				alertCalledQueryDto.getEmergencyTimeEnd() == null ? null
						: DateUtils.date2LongStr(alertCalledQueryDto.getEmergencyTimeEnd()),
				alertCalledQueryDto.getEmergencyCall(), alertCalledQueryDto.getDeviceId(),
				alertCalledQueryDto.getElevatorAddress(), alertCalledQueryDto.getAlertType(),
				alertCalledQueryDto.getAlertSource(), alertCalledQueryDto.getAlertStage(),
				alertCalledQueryDto.getAlertStatus());
		Page<AlertCalledQueryDto> result = new Page<AlertCalledQueryDto>(alertCalledQueryDto.getPageNum(),
				alertCalledQueryDto.getPageSize());
		long totle = pageBean.getTotal();
		result.setRecords(pageBean.getRecords());
		result.setTotal(totle);
		return ResponseHelper.buildResponse(result);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出警情事件记录", notes = "导出警情事件记录")
	@GetMapping("/exportSelectRecord")
	public void exportAlertCalled(AlertCalledQueryDto alertCalledQueryDto, HttpServletResponse response) {
		Page<AlertCalledQueryDto> page = new Page<AlertCalledQueryDto>();

		Page<AlertCalledQueryDto> pageBean = iAlertCalledService.queryAlertListByQueryDto(page,
				alertCalledQueryDto.getWorkOrderNumber(), alertCalledQueryDto.getCreator(),
				alertCalledQueryDto.getEmergency(),
				alertCalledQueryDto.getEmergencyTimeStart() == null ? null
						: DateUtils.date2LongStr(alertCalledQueryDto.getEmergencyTimeStart()),
				alertCalledQueryDto.getEmergencyTimeEnd() == null ? null
						: DateUtils.date2LongStr(alertCalledQueryDto.getEmergencyTimeEnd()),
				alertCalledQueryDto.getEmergencyCall(), alertCalledQueryDto.getDeviceId(),
				alertCalledQueryDto.getElevatorAddress(), alertCalledQueryDto.getAlertType(),
				alertCalledQueryDto.getAlertSource(), alertCalledQueryDto.getAlertStage(),
				alertCalledQueryDto.getAlertStatus());
		List<AlertCalledQueryDto> list = pageBean.getRecords();

		String fileName = "警情事件记录" + System.currentTimeMillis();
		ExcelUtil.createTemplate(response, fileName, "警情事件记录", list, AlertCalledQueryDto.class, null, false);
	}

	/**
	 * 冻结工单-维修
	 * 
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/saveForzen")
	@ApiOperation(httpMethod = "POST", value = "冻结工单-维修", notes = "冻结工单-维修")
	public ResponseModel<Boolean> forzenAlertById(@RequestBody AlertCalledDto alertCalledDto) {
		if (ValidationUtil.isEmpty(alertCalledDto.getSequenceNbr())
				|| ValidationUtil.isEmpty(alertCalledDto.getForzenResult())) {
			throw new BadRequest("参数校验失败.");
		}
		LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.set(AlertCalled::getForzenResult, alertCalledDto.getForzenResult());
		updateWrapper.set(AlertCalled::getAlertStatus, true);
		updateWrapper.eq(AlertCalled::getSequenceNbr, alertCalledDto.getSequenceNbr());
		return ResponseHelper.buildResponse(iAlertCalledService.update(updateWrapper));
	}

	/**
	 * 工单结案-投诉
	 * 
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/saveFinalReason")
	@ApiOperation(httpMethod = "POST", value = "工单结案-投诉", notes = "工单结案-投诉")
	public ResponseModel<Boolean> finishAlertById(@RequestBody AlertCalledDto alertCalledDto) {
		if (ValidationUtil.isEmpty(alertCalledDto.getFinalReason())
				|| ValidationUtil.isEmpty(alertCalledDto.getSequenceNbr())) {
			throw new BadRequest("参数校验失败.");
		}
		LambdaUpdateWrapper<AlertCalled> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.set(AlertCalled::getFinalReason, alertCalledDto.getFinalReason());
		updateWrapper.set(AlertCalled::getAlertStatus, true);
		updateWrapper.eq(AlertCalled::getSequenceNbr, alertCalledDto.getSequenceNbr());
		return ResponseHelper.buildResponse(iAlertCalledService.update(updateWrapper));
	}

	/**
	 * 今日应急统计
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getTodayEmergencyCount")
	@ApiOperation(httpMethod = "GET", value = "今日应急统计", notes = "今日应急统计")
	public ResponseModel<Object> getTodayEmergencyCount(@RequestParam String regionCode) {
		return ResponseHelper.buildResponse(iAlertCalledService.getTodayEmergencyCount(regionCode));

	}
//
//	/**
//	 * 重大事件
//	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY)
//	@GetMapping(value = "/getImportantEventCount")
//	@ApiOperation(httpMethod = "GET", value = "重要大事件统计", notes = "重要大事件统计")
//	public ResponseModel<Object> getImportantEventCount() {
//		return ResponseHelper.buildResponse(iAlertCalledService.getImportantEventCount());
//
//	}

	/**
	 * 获取重大事件或者今日应急的统计详情信息
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getImportantEventOrTodayEmergencyCount")
	@ApiOperation(httpMethod = "GET", value = "重要大事件统计", notes = "重要大事件统计")
	public ResponseModel<Object> getImportantEventOrTodayEmergencyCount(@RequestParam String type,@RequestParam String regionCode) {
		return ResponseHelper.buildResponse(iAlertCalledService.getImportantEventOrTodayEmergencyCount(type,regionCode));

	}


	/**
	 *  警情处置流程信息
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getHandlerInfo")
	@ApiOperation(httpMethod = "GET", value = "警情处置流程信息", notes = "警情处置流程信息")
	public ResponseModel<Object> getHandlerInfo(@RequestParam String alertId) {
		return ResponseHelper.buildResponse(iAlertCalledService.getHandlerInfo(alertId));
	}


	/**
	 *  获取接警未派遣事件
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getCalledInfo")
	@ApiOperation(httpMethod = "GET", value = "获取接警未派遣事件", notes = "获取接警未派遣事件")
	public ResponseModel<Object> getCalledInfo() {
		return ResponseHelper.buildResponse(iAlertCalledService.getCalledInfo());
	}
}
