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

import cn.hutool.core.bean.BeanUtil;
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.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.annotation.ResubmitCheck;
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.RedisKey;
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.elevator.api.enums.SourcesInfoEnum;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.*;
import com.yeejoin.amos.boot.module.elevator.api.dto.*;
import com.yeejoin.amos.boot.module.elevator.api.entity.*;
import com.yeejoin.amos.boot.module.elevator.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.elevator.api.service.TzsAuthService;
import com.yeejoin.amos.boot.module.elevator.biz.utils.AlertBeanDtoVoUtils;
import com.yeejoin.amos.boot.module.elevator.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.boot.module.elevator.flc.biz.service.impl.AlertFormRecordServiceImpl;
import com.yeejoin.amos.component.feign.utils.FeignUtil;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.ObjectUtils;
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.context.RequestContext;
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.SimpleDateFormat;
import java.util.*;

/**
 * 警情接警填报记录
 *
 * @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;

	@Autowired
	TzsAuthService tzsAuthService;

	@Autowired
	TzsCitInfoServiceImpl citInfoService;

	@Autowired
	private ElevatorServiceImpl iElevatorService;

	@Autowired
	private AlertFormRecordServiceImpl alertFormRecordService;

	@Autowired
	CtiServiceImpl ctiService;

	/**
	 * 新增警情接警填报记录
	 *
	 * @return
	 */
	@ResubmitCheck
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增警情接警填报记录", notes = "新增警情接警填报记录")
	public ResponseModel<AlertCalledDto> save(@RequestBody AlertCalledObjsDto alertCalledObjsDto) {
		if (ValidationUtil.isEmpty(alertCalledObjsDto)) {
			throw new BadRequest("参数校验失败.");
		}
        //切换数据源
       //LambdaQueryWrapper<Elevator> queryWrapper = new LambdaQueryWrapper<>();
       //queryWrapper.eq(Elevator::getRescueCode,alertCalledObjsDto.getAlertCalledDto().getDeviceId());
		Elevator elevator = new Elevator();
		elevator.setRescueCode(Integer.valueOf(alertCalledObjsDto.getAlertCalledDto().getDeviceId()));
		Map<String,Object> map =  iElevatorService.selectElevator(elevator);
		if(ObjectUtils.isEmpty(map)) {
			throw new BadRequest("未找到相关电梯.");
		}
		ReginParams reginParams = getSelectedOrgInfo();
		if(ObjectUtils.isEmpty(reginParams)){
			throw new BadRequest("当前登录用户失效，请重新登录.");
		}
		AgencyUserModel userModel = reginParams.getUserModel();
		alertCalledObjsDto = iAlertCalledService.createAlertCalled(alertCalledObjsDto, userModel);
		//更新警情历史记录表
		saveAlertCallRecord(alertCalledObjsDto);

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

		JSONObject jsonObject1 = new JSONObject();
		jsonObject.put("alertId",String.valueOf(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());
	}

	private void saveAlertCallRecord(AlertCalledObjsDto alertCalledObjsDto) {
		try {
			AlertCalledDto alertCalledDto = alertCalledObjsDto.getAlertCalledDto();
			List<AlertFormValue> alertFormValue = alertCalledObjsDto.getAlertFormValue();
			HashMap<String, String> formMap = new HashMap<>();
			alertFormValue.forEach(x-> formMap.put(x.getFieldCode(),x.getFieldValue()));
			AlertFormRecordDto alertFormRecordDto = new AlertFormRecordDto();
			alertFormRecordDto.setAlertCalledId(alertCalledDto.getSequenceNbr());
			alertFormRecordDto.setAlertTypeCode(alertCalledDto.getAlertSourceCode());
			alertFormRecordDto.setName(alertCalledDto.getEmergencyPerson());
			alertFormRecordDto.setPhone(alertCalledDto.getContactPhone());
			if (AlertStageEnums.KRJY.getId().equals(alertCalledDto.getAlarmTypeCode())){
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				alertFormRecordDto.setTrappedTime(sdf.parse(formMap.getOrDefault("trapped_time", new Date().toString())));
				alertFormRecordDto.setTrappedNum(Integer.parseInt(formMap.getOrDefault("trapped_num", "0")));
				alertFormRecordDto.setInjuredNum(Integer.parseInt(formMap.getOrDefault("injured_num", "0")));
				alertFormRecordDto.setDieNum(Integer.parseInt(formMap.getOrDefault("die_num", "0")));
				alertFormRecordDto.setTrappedFloorNum(Integer.parseInt(formMap.getOrDefault("trapped_floor_num", "0")));
				alertFormRecordDto.setIsLight("是".equals(formMap.getOrDefault("is_light","是")) ? 1 : 0);
				alertFormRecordDto.setDescription(formMap.getOrDefault("desc", ""));
			}
			if (AlertStageEnums.GZWX.getId().equals(alertCalledDto.getAlarmTypeCode())){
				alertFormRecordDto.setFaultReport(formMap.getOrDefault("fault_report", ""));
			}
			if (AlertStageEnums.TSZX.getId().equals(alertCalledDto.getAlarmTypeCode())){
				alertFormRecordDto.setComplaintConsulttation(formMap.getOrDefault("complaint_consulttation", ""));
			}
			alertFormRecordDto.setSourcesInfo(SourcesInfoEnum.Submit.getCode().toString());
			alertFormRecordService.saveAlertFormRecord(alertFormRecordDto);
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	/**
	 * 公众号投诉建议与故障报销
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ResubmitCheck
	@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(String.valueOf(elevator.getUseStatus()));
		alertCalledDto.setUseSiteCategory(elevator.getUseSiteCategory());
		alertCalledDto.setAlarmType(AlertStageEnums.getEnumById(alertCalledDto.getAlarmTypeCode()).getValue());
		alertCalledDto.setEquipmentClassification("电梯");
		alertCalledDto.setEquipmentClassificationCode("3000");
		alertCalledDto.setCity(elevator.getCity());
		alertCalledDto.setRegionCode(elevator.getRegionCode());
		alertCalledDto.setDistrict(elevator.getDistrict());
		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);

		Elevator elevator = new Elevator();
		elevator.setOriginalId(alertCalled.getEquipmentId());
		Map<String,Object> map =  iElevatorService.selectElevator(elevator);

		alertPaperInfoDto.setArea(map.get("province") + "" + map.get("city") + map.get("district"));
		alertPaperInfoDto.setAddress(alertCalled.getAddress());
		alertPaperInfoDto.setCallTime(alertCalled.getCallTime());
		alertPaperInfoDto.setLatitude(String.valueOf(map.get("latitude")));
		alertPaperInfoDto.setLongitude(String.valueOf(map.get("longitude")));
		alertPaperInfoDto.setAlarmTypeCode(alertCalled.getAlarmTypeCode());
		alertPaperInfoDto.setRegionCode(String.valueOf(map.get("regionCode")));
		alertPaperInfoDto.setRescueCode(Integer.valueOf(String.valueOf(map.get("rescueCode"))));
		alertPaperInfoDto.setAlertStatus(alertCalled.getAlertStage());
		alertPaperInfoDto.setElevatorId(String.valueOf(map.get("sequenceNbr")));
		alertPaperInfoDto.setElevatorCode(String.valueOf(map.get("registerCode")));

        DispatchPaper paper = dispatchPaperServiceImpl.getOne(new LambdaQueryWrapper<DispatchPaper>().eq(DispatchPaper::getIsDelete,false).eq(DispatchPaper::getAlertId,alertId));
        if(paper != null) {
            alertPaperInfoDto.setFinishTime(paper.getFeedbackFinishTime());
        }
		return ResponseHelper.buildResponse(alertPaperInfoDto);
	}

	/**
	 *
	 * <pre>
	 * 相似警情分页查询
	 * </pre>
	 *
	 * @param
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(value = "相似警情分页查询")
	@PostMapping(value = "/page/similar")
	public ResponseModel<Page<ESAlertCalledDto>> pageBySimilar(@RequestBody ESAlertCalledRequestDto alertCalledVo) {
		Page<ESAlertCalledDto> esAlertCalledDtoPage = eSAlertCalledService.queryByKeys(alertCalledVo);
		return ResponseHelper.buildResponse(esAlertCalledDtoPage);
	}

	/**
	 * 根据id查询
	 *
	 * @param id 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@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() {
		List<AgencyUserModel> userModels = FeignUtil.remoteCall(()->Privilege.agencyUserClient.queryByIds(RequestContext.getExeUserId(),false));
		//由于查询的当前登录的用户信息 所以一定有 未作冗余判空
		AgencyUserModel userModel = userModels.get(0);
		String workOrderNumber = iAlertCalledService.nextId();
		AlertCallInfoDto alertCallInfoDto = new AlertCallInfoDto();
		alertCallInfoDto.setCallTime(DateUtils.stampToDate(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss "));
		alertCallInfoDto.setWorkOrderNumber(workOrderNumber);
		alertCallInfoDto.setRecUserId(userModel.getUserId());
		alertCallInfoDto.setRecUserName(userModel.getRealName());
		return ResponseHelper.buildResponse(alertCallInfoDto);
	}


	/**
	 * 警情统计
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/alertStatistics")
	@ApiOperation(httpMethod = "GET", value = "警情统计", notes = "警情统计")
	public ResponseModel<AlarmStatisticsDto> alertStatistics() {
		AlarmStatisticsDto  alarmStatisticsDto  = new AlarmStatisticsDto();
		ReginParams reginParams = getSelectedOrgInfo();
		if(!ObjectUtils.isEmpty(reginParams)){
			alarmStatisticsDto = iAlertCalledService.getAlertStatistics(reginParams);
		}
		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<>();
		AgencyUserModel userModel = this.getSelectedOrgInfo().getUserModel();

		String groupCode = ctiService.getSkillGroup(userModel.getUserId());
		alertCalledQueryWrapper.eq("skill_group",groupCode);

		setQueryWrapper(alertCalledQueryWrapper, alertCalled, sort);

//		// 添加接警开始时间的查询条件
//		if (alertCalledDto.getCallTimeStart() != null) {
//			alertCalledQueryWrapper.ge("call_time_start", alertCalledDto.getCallTimeStart());
//		}

		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);
		int num= iAlertCalledService.count(alertCalledQueryWrapper);
		pageBean.setTotal(num);
		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);

		//根据当前登陆人的所在区域 找到该区域内的接警人id 再找到相关警情
		Set<String> userIds = new HashSet<>();
		String companyCode = this.getSelectedOrgInfo().getCompany().getCompanyCode();
		List<TzsCitInfo> citInfoList = citInfoService.list(new LambdaQueryWrapper<TzsCitInfo>().eq(TzsCitInfo::getRegionCode,companyCode));
		if(!ValidationUtil.isEmpty(citInfoList)){
			for(TzsCitInfo citInfo : citInfoList){
				userIds.add(citInfo.getCtiUserId());
			}
		}
		if (!ValidationUtil.isEmpty(userIds)) {
			queryWrapper.in("rec_user_id", userIds);
		}

		if(sort!=null) {  // 排序失效
			String[] date=  sort.split(",");
			if(date[1].equals("ascend")) {
				queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
			}else {
				queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
			}
		}else {
			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());
			}
		} 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, String sort ) {
		Page<AlertCalledQueryDto> page = new Page<AlertCalledQueryDto>();
		page.setCurrent(pageNum);
		page.setSize(pageSize);
		String sortParam = "";
		String sortRule = "";
		if (sort != null) {  // 排序失效
			String[] date = sort.split(",");
			if (date[1].equals("ascend")) {
				sortParam = RedisKey.humpToLine(date[0]);
				sortRule = "asc";
			} else {
				sortParam = RedisKey.humpToLine(date[0]);
				sortRule = "desc";
			}
		} else {
			sortParam = "call_time";
			sortRule = "desc";
		}
		AgencyUserModel userModel = this.getSelectedOrgInfo().getUserModel();
		Page<AlertCalledQueryDto> pageBean = iAlertCalledService.queryAlertListByQueryDto(page,
				alertCalledQueryDto.getWorkOrderNumber(), alertCalledQueryDto.getCreator(), alertCalledQueryDto.getEmergency(), alertCalledQueryDto.getEmergencyTimeStart(),
				alertCalledQueryDto.getEmergencyTimeEnd(), alertCalledQueryDto.getEmergencyCall(), alertCalledQueryDto.getDeviceId(), alertCalledQueryDto.getElevatorAddress(),
				alertCalledQueryDto.getDistrict(), alertCalledQueryDto.getAlertType(), alertCalledQueryDto.getAlertSource(), alertCalledQueryDto.getAlertStage(), alertCalledQueryDto.getAlertStatus(),
				sortParam, sortRule, null,userModel);
		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, needAuth = false)
	@ApiOperation(value = "导出警情事件记录", notes = "导出警情事件记录")
	@GetMapping("/exportSelectRecord")
	public void exportAlertCalled(AlertCalledQueryDto alertCalledQueryDto, HttpServletResponse response, String sort ) {
		Page<AlertCalledQueryDto> page = new Page<AlertCalledQueryDto>();
		String sortParam = "";
		String sortRule = "";
		if(sort!=null) {  // 排序失效
			String[] date=  sort.split(",");
			if(date[1].equals("ascend")) {
				sortParam = RedisKey.humpToLine(date[0]);
				sortRule = "asc";
			}else {
				sortParam =RedisKey.humpToLine(date[0]);
				sortRule = "desc";
			}
		}else {
			sortParam = "call_time";
			sortRule = "desc";
		}
		page.setCurrent(0);
		page.setSize(Long.MAX_VALUE);
		AgencyUserModel userModel = this.getSelectedOrgInfo().getUserModel();
		Page<AlertCalledQueryDto> pageBean = iAlertCalledService.queryAlertListByQueryDto(page,
				alertCalledQueryDto.getWorkOrderNumber(),alertCalledQueryDto.getCreator(),alertCalledQueryDto.getEmergency(),alertCalledQueryDto.getEmergencyTimeStart(),
				alertCalledQueryDto.getEmergencyTimeEnd(),alertCalledQueryDto.getEmergencyCall(),alertCalledQueryDto.getDeviceId(),alertCalledQueryDto.getElevatorAddress(),
				alertCalledQueryDto.getDistrict(),alertCalledQueryDto.getAlertType(),alertCalledQueryDto.getAlertSource(),alertCalledQueryDto.getAlertStage(),alertCalledQueryDto.getAlertStatus(),
				sortParam,sortRule, alertCalledQueryDto.getIds(),userModel);

		List<AlertCalledQueryDto> list = pageBean.getRecords();
		String fileName = "处置记录" + System.currentTimeMillis();
		ExcelUtil.createTemplate(response, fileName, "处置记录", list, AlertCalledQueryDto.class, null, false);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(value = "导出接警记录信息", notes = "导出接警记录信息")
	@GetMapping("/exportAlertRecord")
	public void exportAlertRecord(AlertCalledRecordDto alertCalledQueryDto, HttpServletResponse response) {
		//根据当前登陆人的所在区域 找到该区域内的接警人id 再找到相关警情
		Set<String> userIds = new HashSet<>();
		String companyCode = this.getSelectedOrgInfo().getCompany().getCompanyCode();
		List<TzsCitInfo> citInfoList = citInfoService.list(new LambdaQueryWrapper<TzsCitInfo>().eq(TzsCitInfo::getRegionCode, companyCode));
		if (!ValidationUtil.isEmpty(citInfoList)) {
			for (TzsCitInfo citInfo : citInfoList) {
				userIds.add(citInfo.getCtiUserId());
			}
		}
		AgencyUserModel userModel = this.getSelectedOrgInfo().getUserModel();
		String groupCode = ctiService.getSkillGroup(userModel.getUserId());
		List<AlertCalledRecordDto> list  = iAlertCalledService.queryAlertRecordListByQueryDto(
				alertCalledQueryDto.getCallTimeStart() == null ? null
						: DateUtils.date2LongStr(alertCalledQueryDto.getCallTimeStart()),
				alertCalledQueryDto.getCallTimeEnd() == null ? null
						: DateUtils.date2LongStr(alertCalledQueryDto.getCallTimeEnd()),
				alertCalledQueryDto.getType(),
				alertCalledQueryDto.getAlertSource(),
				alertCalledQueryDto.getAlarmType(),
				groupCode,
				alertCalledQueryDto.getIds());
		String fileName = "接警记录" + System.currentTimeMillis();
		ExcelUtil.createTemplate(response, fileName, "接警记录", list, AlertCalledRecordDto.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());
		Boolean flag = iAlertCalledService.update(updateWrapper);
		if(flag) {
			AlertCalledDto alertCalledVo = iAlertCalledService.queryBySeq(alertCalledDto.getSequenceNbr());
			try {
				redisUtils.del(RedisKey.TZS_ALERTCALLED_ID+alertCalledVo.getSequenceNbr());
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("删除redis失败:" + e.getMessage());
			}
			try {
				eSAlertCalledService.updateEsAlertCalled(alertCalledVo);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("更新es失败:" + e.getMessage());
			}
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 工单结案-投诉
	 *
	 * @return
	 */
	@ResubmitCheck
	@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());
		Boolean flag = iAlertCalledService.update(updateWrapper);
		if(flag) {
			AlertCalledDto alertCalledVo = iAlertCalledService.queryBySeq(alertCalledDto.getSequenceNbr());
			try {
				redisUtils.del(RedisKey.TZS_ALERTCALLED_ID+alertCalledVo.getSequenceNbr());
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("删除redis失败:" + e.getMessage());
			}
			try {
				eSAlertCalledService.updateEsAlertCalled(alertCalledVo);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("更新es失败:" + e.getMessage());
			}
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 今日应急统计
	 */
	@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());
	}


	/**
	 *  获取坐席情况
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getSeatInfos")
	@ApiOperation(httpMethod = "GET", value = "获取坐席情况", notes = "获取坐席情况")
	public ResponseModel<List<TzsCitInfoDto>> getSeatInfos() {
		return ResponseHelper.buildResponse(iAlertCalledService.getSeatInfos());
	}


	/**
	 *  根据regionCode 获取区域内实时警情
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getActualAlert")
	@ApiOperation(httpMethod = "GET", value = "根据regionCode 获取区域内实时警情", notes = "根据regionCode 获取区域内实时警情")
	public ResponseModel<List<AlertPaperInfoDto>> getActualAlert(@RequestParam(name = "regionCodes", required = false) List<String> regionCodes) {
		return ResponseHelper.buildResponse(iAlertCalledService.getAlertPaperInfoList(iAlertCalledService.authRegionCodeList(regionCodes),false));
	}



	/**
	 *  根据regionCode 获取区域内历史警情 七日内
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getHistoryAlert")
	@ApiOperation(httpMethod = "GET", value = "根据regionCode 获取区域内七日内历史警情", notes = "根据regionCode 获取区域内七日内历史警情")
	public ResponseModel<List<AlertPaperInfoDto>> getHistoryAlert(@RequestParam(name = "regionCodes", required = false) List<String> regionCodes) {
		// 警情id 警情地址 警情状态 警情类型 警情发生时间
		// 获取自己的regionCode
		List<String> useRegionCode = tzsAuthService.getUserRegionCode();
		if(regionCodes == null) {
			regionCodes = useRegionCode;
		} else {
			// 判断传入regionCodes 是否越权
			List<String> tempList = new ArrayList<>();
			Iterator<String> regionIt =  regionCodes.iterator();
			while(regionIt.hasNext()) {
				String tempCode = regionIt.next();
				String districtCode = tempCode.substring(4,6);
				String provinceCode = tempCode.substring(2,6);
				if("0000".equals(provinceCode)) {// 为省则默认使用用户现有权限查询数据
					regionCodes = useRegionCode;
				} else {
					if("00".equals(districtCode)) { // 为市
						if(!useRegionCode.contains(tempCode)) { // 不包含该市权限 需要移除市搜索条件 添加 该市下区搜索条件
							for(String tempUsercode : useRegionCode) {
								if(tempUsercode.indexOf(tempCode.substring(0,4)) != -1) {
									tempList.add(tempUsercode);
								}
							}
							regionIt.remove();
						}
					} else { // 为区 不会出现越权情况

					}
				}
			}
			for (String t : tempList) {
				regionCodes.add(t);
			}
		}
		return ResponseHelper.buildResponse(iAlertCalledService.getAlertPaperInfoList(regionCodes,true));
	}


	/**
	 * 获取电梯历史事件
	 * 字段：事件类型、设备地址、报送时间。倒序排列，默认加载3条，向下翻动时每次可再加载5条。点击事件主屏打开该事件详情
	 * @param equipmentCode
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getElevatorHistory/{equipmentCode}")
	@ApiOperation(httpMethod = "GET", value = "获取电梯历史事件", notes = "获取电梯历史事件")
	public ResponseModel<Page<AlertPaperInfoDto>> getEquipmentHistory(@PathVariable String equipmentCode, @RequestParam(value = "size") Integer size, @RequestParam(value = "current") Integer current) {
		// 警情id 警情地址 警情状态 警情类型 警情发生时间
		// 获取自己的regionCode
		String equipmentClassCode = "3000";
		Page<AlertPaperInfoDto> result = new Page<>(current, size);
		List<String> useRegionCode = tzsAuthService.getUserRegionCode();
		List<AlertPaperInfoDto> list = iAlertCalledService.getEquipmentHistory(useRegionCode,equipmentClassCode,current, size,equipmentCode);
		result.setRecords(list);
		result.setTotal(iAlertCalledService.getEquipmentHistoryCount(useRegionCode,equipmentClassCode,equipmentCode));
		return ResponseHelper.buildResponse(result);
	}



	/**
	 * 应急大屏使用
	 *
	 * @param id 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/detail/{id}")
	@ApiOperation(httpMethod = "GET", value = "根据id获取详细信息", notes = "根据id获取详细信息")
	public ResponseModel<Object> getDetail(@PathVariable Long id) {
		return ResponseHelper.buildResponse(iAlertCalledService.getDetail(id));
	}

}
