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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
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.dto.AttachmentDto;
import com.yeejoin.amos.boot.module.common.api.service.ISourceFileService;
import com.yeejoin.amos.boot.module.tzs.api.dto.SignatureDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatAccessDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatMyBusinessListDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatMyBussinessDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatMyTaskListDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatRelationDto;
import com.yeejoin.amos.boot.module.tzs.api.dto.WechatTaskLatLonDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.tzs.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.tzs.api.entity.WechatRelation;
import com.yeejoin.amos.boot.module.tzs.api.service.IDispatchTaskService;
import com.yeejoin.amos.boot.module.tzs.api.service.IWechatService;
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.DispatchTaskServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.service.impl.WechatRelationServiceImpl;
import com.yeejoin.amos.boot.module.tzs.biz.utils.HttpUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.IdPasswordAuthModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.digest.DigestUtils;
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.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
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.springframework.web.multipart.MultipartFile;
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 org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号controller
 */
@RestController
@Api(tags = "微信公众号Api")
@RequestMapping(value = "/wechatBack")
public class WechatController extends BaseController {

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

	private long time = 600l;

	@Value("${tzs.wechat.token}")
	private String WECHAT_TOKEN;

	@Value("${tzs.wechat.ticketurl}")
	private String WECHAT_TICKETURL;

	@Autowired
	private EmqKeeper emqKeeper;
	@Value("${mqtt.topic.task.personinfo}")
	private String personInfoTopic;

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	private IWechatService wechatService;

	@Autowired
	WechatRelationServiceImpl wechatRelationServiceImpl;

	@Autowired
	IDispatchTaskService dispatchTaskService;

	@Autowired
	AlertFormValueServiceImpl iAlertFormValueService;

	@Autowired
	DispatchTaskServiceImpl dispatchTaskServiceImpl;

	@Autowired
	AlertCalledServiceImpl iAlertCalledService;

	@Autowired
	ISourceFileService sourceFileService;

	private Long TOKEN_TIME = 1209600l;

	/**
	 * 获取微信回调信息返回验证是否通过
	 * 
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.ANONYMOUS, needAuth = false)
	@GetMapping(value = "/getInfo")
	@ApiOperation(httpMethod = "GET", value = "获取微信传回的get信息", notes = "获取微信传回的get信息")
	public String getWechatInfo(@RequestParam String signature, @RequestParam String timestamp,
			@RequestParam String nonce, @RequestParam String echostr) {
		List<String> params = new ArrayList<String>();
		params.add(WECHAT_TOKEN);
		params.add(timestamp);
		params.add(nonce);
		Collections.sort(params);
		String tokenStr = StringUtils.join(params, "");
		tokenStr = DigestUtils.sha1Hex(tokenStr);
		System.out.println("=============回调get消息start=============");
		System.out.println(echostr);
		System.out.println("=============回调get消息end=============");
		if (tokenStr.equals(signature)) {
			return echostr;
		} else {
			return "";
		}
	}

	@TycloudOperation(ApiLevel = UserType.ANONYMOUS, needAuth = false)
	@PostMapping(value = "/getSignature")
	@ApiOperation(httpMethod = "POST", value = "获取微信签名", notes = "获取微信签名")
	public ResponseModel<String> getSignature(@RequestBody SignatureDto signatureDto) {
		List<String> params = new ArrayList<String>();

		try {
			String ticket = null;
			if (redisUtils.hasKey(RedisKey.WECHAT_JS_TOKEN)) {
				ticket = redisUtils.get(RedisKey.WECHAT_JS_TOKEN).toString();
			} else {
				if (!redisUtils.hasKey(RedisKey.WECHAT_TOKEN)) {
					this.getAccessToken();
				}
				String token = redisUtils.get(RedisKey.WECHAT_TOKEN).toString();
				String result = HttpUtils.doGet(WECHAT_TICKETURL + token + "&type=jsapi");
				JSONObject jsonObject = JSONObject.parseObject(result);
				ticket = jsonObject.get("ticket").toString();
				redisUtils.set(RedisKey.WECHAT_JS_TOKEN, ticket, 600l);
			}
			params.add("jsapi_ticket=" + ticket);
			params.add("noncestr=" + signatureDto.getNoncestr());
			params.add("timestamp=" + signatureDto.getTimestamp());
			params.add("url=" + signatureDto.getUrl());
			logger.error("jsapi_ticket=" + ticket);
			logger.error("noncestr=" + signatureDto.getNoncestr());
			logger.error("timestamp=" + signatureDto.getTimestamp());
			logger.error("url=" + signatureDto.getUrl());

			Collections.sort(params, new Comparator<String>() {
				@Override
				public int compare(String o1, String o2) {
					char[] chars1 = o1.toCharArray();
					char[] chars2 = o2.toCharArray();
					int i = 0;
					while (i < chars1.length && i < chars2.length) {
						if (chars1[i] > chars2[i]) {
							return 1;
						} else if (chars1[i] < chars2[i]) {
							return -1;
						} else {
							i++;
						}
					}
					if (i == chars1.length) { // o1到头
						return -1;
					}
					if (i == chars2.length) { // o2到头
						return 1;
					}
					return 0;
				}
			});

			String tokenStr = StringUtils.join(params, "&");
			logger.error(tokenStr);
			tokenStr = DigestUtils.sha1Hex(tokenStr);
			return ResponseHelper.buildResponse(tokenStr);
		} catch (Exception e) {
			throw new BadRequest(e.getMessage());
		}
	}

	/**
	 * 获取微信推送的操作通知
	 * 
	 * @param xml
	 * @param resp
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.ANONYMOUS, needAuth = false)
	@PostMapping(value = "/getInfo")
	@ApiOperation(httpMethod = "POST", value = "获取微信传回的post信息", notes = "获取微信传回的post信息")
	public String getWechatInfoPost(@RequestBody String xml, HttpServletResponse resp) {
		Map<String, String> requtstMap = xmlToMap(xml);
		System.out.println("=============回调post消息start=============");
		System.out.println(xml);
		System.out.println("=============回调post消息end=============");
		return "1";
	}

	/**
	 * XML格式字符串转换为Map
	 *
	 * @param xml XML字符串
	 * @return XML数据转换后的Map
	 * @throws Exception
	 */
	public static Map<String, String> xmlToMap(String xml) {
		try {
			Map<String, String> data = new HashMap<>();
			DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
			InputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
			org.w3c.dom.Document doc = documentBuilder.parse(stream);
			doc.getDocumentElement().normalize();
			NodeList nodeList = doc.getDocumentElement().getChildNodes();
			for (int idx = 0; idx < nodeList.getLength(); ++idx) {
				Node node = nodeList.item(idx);
				if (node.getNodeType() == Node.ELEMENT_NODE) {
					org.w3c.dom.Element element = (org.w3c.dom.Element) node;
					data.put(element.getNodeName(), element.getTextContent());
				}
			}
			stream.close();
			return data;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取wechatToken信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getAccessToken")
	@ApiOperation(httpMethod = "GET", value = "获取token信息", notes = "获取token信息")
	public ResponseModel<String> getAccessToken() {
		String token = wechatService.getAccessToken();
		return ResponseHelper.buildResponse(token);
	}

	/**
	 * 根据手机号发送短信验证码
	 * 
	 * @param tel
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/sendSms/{tel}")
	@ApiOperation(httpMethod = "GET", value = "根据手机号发送短信验证码", notes = "根据手机号发送短信验证码")
	public ResponseModel<Boolean> sendSmsCode(@PathVariable String tel) {
		Boolean flag = false;
		HashMap<String, String> params = new HashMap<>();
		params.put("smsType", "MOBILE_REGISTER");
		params.put("mobile", tel);
		FeignClientResult<SmsRecordModel> result = Systemctl.smsClient.sendVerifyCode(params);
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 新增微信公众号openid与电话号对应关系表
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/addUser")
	@ApiOperation(httpMethod = "POST", value = "新增微信公众号openid与电话号对应关系表", notes = "新增微信公众号openid与电话号对应关系表")
	@Transactional
	public ResponseModel<WechatAccessDto> addUser(@RequestBody WechatRelationDto model) {
		if (ValidationUtil.isEmpty(model.getOpenId()) || ValidationUtil.isEmpty(model.getPhone())
				|| ValidationUtil.isEmpty(model.getCode()))
			throw new BadRequest("参数校验失败.");
		AgencyUserModel agencyUserModel = new AgencyUserModel();
		String passwd = DesUtil.encode("a_" + model.getPhone(), "qaz");
		agencyUserModel.setUserName(model.getPhone());
		agencyUserModel.setRealName(model.getPhone());
		agencyUserModel.setLockStatus("UNLOCK");
		agencyUserModel.setPassword(passwd);
		agencyUserModel.setRePassword(passwd);
		agencyUserModel.setAgencyCode("tzs");
		agencyUserModel.setMobile(model.getPhone());
		agencyUserModel.setVerifyCode(model.getCode());
		FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient.mobileRegister(agencyUserModel);
		agencyUserModel = result.getResult();
		if (agencyUserModel != null && StringUtils.isNotBlank(agencyUserModel.getUserId())) {
			model.setUserId(agencyUserModel.getUserId());
			wechatRelationServiceImpl.createWithModel(model);
		} else {
			throw new BadRequest("注册失败");
		}
		WechatAccessDto dto = new WechatAccessDto();
		dto.setOpenId(model.getOpenId());
		dto.setTel(model.getPhone());
		IdPasswordAuthModel loninData = new IdPasswordAuthModel();
		loninData.setLoginId(model.getPhone());
		loninData.setPassword(passwd);
		FeignClientResult loginResult = Privilege.authClient.idpassword(loninData);
		if (loginResult.getStatus() == 200) {
			HashMap resultMap = (HashMap) loginResult.getResult();
			dto.setToken(resultMap.get("token").toString());
			redisUtils.set(model.getPhone() + "_token", resultMap.get("token").toString(), TOKEN_TIME);
		}

		return ResponseHelper.buildResponse(dto);
	}

	public String login(String tel) {
		String token = "";
		IdPasswordAuthModel loninData = new IdPasswordAuthModel();
		loninData.setLoginId(tel);
		String passwd = DesUtil.encode("a_" + tel, "qaz");
		loninData.setPassword(passwd);
		FeignClientResult loginResult = Privilege.authClient.idpassword(loninData);
		if (loginResult.getStatus() == 200) {
			HashMap resultMap = (HashMap) loginResult.getResult();
			token = resultMap.get("token").toString();
			redisUtils.set(tel + "_token", resultMap.get("token").toString(), TOKEN_TIME);
		}
		return token;
	}

	/**
	 * 根据微信code获取openId和手机号接口
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getOpenIdTel/{code}")
	@ApiOperation(httpMethod = "GET", value = "根据微信code获取openId和手机号接口", notes = "根据微信code获取openId和手机号接口")
	public ResponseModel<WechatAccessDto> getOpenIdTel(@PathVariable String code) {
		logger.info("公众号登录" + code);
		System.out.println("公众号登录" + code);
		WechatAccessDto wechatAccessDto = new WechatAccessDto();
		String openId = wechatService.getOpenId(code);
		logger.info("公众号登录openId" + openId);
		System.out.println("公众号登录openId" + openId);
		if (StringUtils.isNotEmpty(openId)) {
			JSONObject userInfo = wechatService.getUserInfo(openId);
			wechatAccessDto.setOpenId(openId);
			if (userInfo != null && userInfo.get("nickname") != null && userInfo.get("sex") != null) {
				wechatAccessDto.setNickname(userInfo.getString("nickname"));
				wechatAccessDto.setSex(userInfo.getString("sex"));
			}
			WechatRelation temp = wechatRelationServiceImpl
					.getOne(new LambdaQueryWrapper<WechatRelation>().eq(WechatRelation::getOpenId, openId));
			System.out.println("公众号登录temp" + temp);
			logger.info("公众号登录temp" + temp);
			if (temp != null) {
				wechatAccessDto.setTel(temp.getPhone());
				if (redisUtils.hasKey(temp.getPhone() + "_token")
						&& redisUtils.getExpire(temp.getPhone() + "_token") > 1) {
					System.out.println(
							temp.getPhone() + "_token redis: " + redisUtils.get(temp.getPhone() + "_token").toString());
					wechatAccessDto.setToken(redisUtils.get(temp.getPhone() + "_token").toString());
				} else {
					String token = this.login(temp.getPhone());
					System.out.println(temp.getPhone() + "_token login: " + token);
					wechatAccessDto.setToken(token);
				}
			}
			else 
			{
				wechatAccessDto.setToken("");
			}
		}
		System.out.println("公众号登录wechatAccessDto" + wechatAccessDto);
		logger.info("公众号登录wechatAccessDto" + wechatAccessDto);
		return ResponseHelper.buildResponse(wechatAccessDto);
	}

	/**
	 * 根据任务id 经纬度 返回现在距离任务距离
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/returnDistance")
	@ApiOperation(httpMethod = "POST", value = "根据任务id 经纬度 返回现在距离任务距离", notes = "根据任务id 经纬度 返回现在距离任务距离")
	public ResponseModel<String> returnDistance(@RequestBody WechatTaskLatLonDto dto) {
		if (ValidationUtil.isEmpty(dto) || ValidationUtil.isEmpty(dto.getTaskId())
				|| ValidationUtil.isEmpty(dto.getLatitude()) || ValidationUtil.isEmpty(dto.getLongitude())) {
			throw new BadRequest("参数校验失败.");
		}
		// 推送经纬度 人员姓名 电话 警情id
		JSONObject jsonObject = new JSONObject();
		DispatchTask task = dispatchTaskServiceImpl.getById(dto.getTaskId());
		jsonObject.put("personName", task.getResponseUserName());
		jsonObject.put("personTel", task.getResponseUserTel());
		jsonObject.put("latitude", dto.getLatitude());
		jsonObject.put("longitude", dto.getLongitude());
		jsonObject.put("alertId", task.getAlertId());
		try {
			emqKeeper.getMqttClient().publish(personInfoTopic, jsonObject.toString().getBytes("UTF-8"), 1, false);
		} catch (MqttException e) {
			logger.error("mqtt发送失败" + jsonObject);
		} catch (UnsupportedEncodingException e) {
			logger.error("mqtt发送失败" + jsonObject);
		}

		String distance = dispatchTaskService.returnDistanceByTaskId(dto.getTaskId(), dto.getLongitude(),
				dto.getLatitude());
		return ResponseHelper.buildResponse(distance);
	}

	/**
	 * 获取业务详情
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getBussinessInfo/{bussinessId}")
	@ApiOperation(httpMethod = "GET", value = "获取业务详情", notes = "获取业务详情")
	public ResponseModel<WechatMyBussinessDto> getBussinessInfo(@PathVariable Long bussinessId) {
		if (ValidationUtil.isEmpty(bussinessId)) {
			throw new BadRequest("参数校验失败.");
		}
		return ResponseHelper.buildResponse(getBussinessDtoById(bussinessId));
	}

	/**
	 * 获取任务列表
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getTaskList")
	@ApiOperation(httpMethod = "GET", value = "根据用户手机号获取任务列表", notes = "根据用户手机号获取任务列表")
	public ResponseModel<List<WechatMyTaskListDto>> getTaskList(
			@ApiParam(value = "电话号码", required = true) @RequestParam String phone,
			@ApiParam(value = "任务类别", required = true) @RequestParam String taskType,
			@ApiParam(value = "当前页码", required = true) @RequestParam Long currentPage) {
		if (ValidationUtil.isEmpty(phone) || ValidationUtil.isEmpty(taskType) || ValidationUtil.isEmpty(currentPage)) {
			throw new BadRequest("参数校验失败.");
		}
		return ResponseHelper.buildResponse(dispatchTaskService.getTaskListByPhonePager(phone, taskType, currentPage));
	}

	/**
	 * 获取我的业务列表
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/getBussinessList")
	@ApiOperation(httpMethod = "GET", value = "根据用户手机号获取业务列表", notes = "根据用户手机号获取业务列表")
	public ResponseModel<List<WechatMyBusinessListDto>> getBussinessList(
			@ApiParam(value = "电话号码", required = true) @RequestParam String phone,
			@ApiParam(value = "业务类别", required = true) @RequestParam String businessType,
			@ApiParam(value = "当前页码", required = true) @RequestParam Long currentPage) {
		if (ValidationUtil.isEmpty(phone) || ValidationUtil.isEmpty(businessType)
				|| ValidationUtil.isEmpty(currentPage)) {
			throw new BadRequest("参数校验失败.");
		}
		return ResponseHelper
				.buildResponse(iAlertCalledService.getBussinessListByPhonePager(phone, businessType, currentPage));
	}

	/**
	 * 微信端图片上传
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/uploadImage")
	@ApiOperation(httpMethod = "POST", value = "微信公众号上传图片", notes = "微信公众号上传图片")
	public ResponseModel<String> uploadImage(
			@ApiParam(value = "图片", required = true) @RequestParam MultipartFile file) {
		if (ValidationUtil.isEmpty(file)) {
			throw new BadRequest("参数校验失败.");
		}

		FeignClientResult<Map<String, String>> date = Systemctl.fileStorageClient.updateCommonFile(file);
		String urlString = "";
		if (date != null) {
			Map<String, String> map = date.getResult();
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				urlString = it.next();
			}
		}
		return ResponseHelper.buildResponse(urlString);
	}

	/**
	 * 微信端图片上传
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/downloadWechatPic/{mediaId}")
	@ApiOperation(httpMethod = "GET", value = "微信公众号从微信服务器下载图片到自己服务器", notes = "微信公众号从微信服务器下载图片到自己服务器")
	public ResponseModel<String> uploadImage(@PathVariable String mediaId) {
		if (ValidationUtil.isEmpty(mediaId)) {
			throw new BadRequest("参数校验失败.");
		}
		String urlString = wechatService.getWechatPicByMediaId(mediaId);
		return ResponseHelper.buildResponse(urlString);
	}

	private WechatMyBussinessDto getBussinessDtoById(Long alertId) {
		WechatMyBussinessDto temp = iAlertCalledService.getBussinessInfoById(alertId);
		List<AlertFormValue> paperList = null;
		Map<String, List<AttachmentDto>> imgMap = null;
		List<AttachmentDto> imgDtos = null;
		Map<String, List<AttachmentDto>> errorImgMap = null;
		List<AttachmentDto> errorImgDtos = null;
		List<AttachmentDto> feedbackDtos = null;
		LambdaQueryWrapper<AlertFormValue> queryWrapper = new LambdaQueryWrapper<>();
		switch (temp.getTaskTypeCode()) {
		case "960": // 困人救援
			temp.setHasDeadHurt("无");
			queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getSequenceNbr());
			// 警情动态表单数据
			List<AlertFormValue> alertList = iAlertFormValueService.list(queryWrapper);
			alertList.stream().forEach(t -> {
				String value = t.getFieldValue();
				if ("trapped_floor_num".equals(t.getFieldCode())) {
					// 被困楼层
					temp.setTrappedFloorNum(value);
				} else if ("trapped_num".equals(t.getFieldCode())) {
					// 被困人数
					temp.setTrappedNum(value);
				} else if ("injured_num".equals(t.getFieldCode())) {
					// 受伤人数
					if (StringUtils.isNotEmpty(value)) {
						temp.setHasDeadHurt("有");
					}
				} else if ("die_num".equals(t.getFieldCode())) {
					// 死亡人数
					if (StringUtils.isNotEmpty(value)) {
						temp.setHasDeadHurt("有");
					}
				}
			});
			queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
			// 派遣动态表单
			paperList = iAlertFormValueService.list(queryWrapper);
			paperList.stream().forEach(t -> {
				String value = t.getFieldValue();
				if ("error_result".equals(t.getFieldCode())) {
					// 故障原因
					temp.setErrorResult(value);
				} else if ("fix_result".equals(t.getFieldCode())) {
					// 维修结果
					temp.setFixResult(value);
				} else if ("fix_remark".equals(t.getFieldCode())) {
					// 维修备注
					temp.setRemark(value);
				}
			});

			imgMap = sourceFileService.getAttachments(temp.getPaperId());
			imgDtos = imgMap.get("imgs");
			temp.setFixImgs(imgDtos);

			break;
		case "961": // 故障维修
			queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
			// 派遣动态表单
			paperList = iAlertFormValueService.list(queryWrapper);
			paperList.stream().forEach(t -> {
				String value = t.getFieldValue();
				if ("error_result".equals(t.getFieldCode())) {
					// 故障原因
					temp.setErrorResult(value);
				} else if ("fix_result".equals(t.getFieldCode())) {
					// 维修结果
					temp.setFixResult(value);
				} else if ("fix_remark".equals(t.getFieldCode())) {
					// 维修备注
					temp.setRemark(value);
				} else if ("feedback_result".equals(t.getFieldCode())) {
					// 反馈结果
					temp.setFeedbackResult(value);
				}
			});

			imgMap = sourceFileService.getAttachments(temp.getPaperId());
			imgDtos = imgMap.get("imgs");
			temp.setFixImgs(imgDtos);
			errorImgMap = sourceFileService.getAttachments(temp.getSequenceNbr());
			errorImgDtos = errorImgMap.get("imgs");
			temp.setErrorImgs(errorImgDtos);
			feedbackDtos = errorImgMap.get("feedbacks");
			temp.setFeedBackImgs(feedbackDtos);
			break;
		case "962": // 投诉建议
			queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(AlertFormValue::getAlertCalledId, temp.getPaperId());
			// 派遣动态表单
			paperList = iAlertFormValueService.list(queryWrapper);
			paperList.stream().forEach(t -> {
				String value = t.getFieldValue();
				if ("action_result".equals(t.getFieldCode())) {
					// 处置结果
					temp.setActionResult(value);
				} else if ("main_feedback_result".equals(t.getFieldCode())) {
					// 维修结果
					temp.setRemark(value);
				} else if ("feedback_result".equals(t.getFieldCode())) {
					// 维修结果
					temp.setFeedbackResult(value);
				}
			});
			imgMap = sourceFileService.getAttachments(temp.getPaperId());
			imgDtos = imgMap.get("imgs");
			temp.setFixImgs(imgDtos);
			errorImgMap = sourceFileService.getAttachments(temp.getSequenceNbr());
			errorImgDtos = errorImgMap.get("imgs");
			temp.setErrorImgs(errorImgDtos);
			feedbackDtos = errorImgMap.get("feedbacks");
			temp.setFeedBackImgs(feedbackDtos);
			break;
		}
		return temp;
	}

	/**
	 * 微信端图片上传
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/testWechatFile")
	@ApiOperation(httpMethod = "POST", value = "微信公众号上传图片", notes = "微信公众号上传图片")
	public ResponseModel<String> testWechatFile(
			@ApiParam(value = "图片", required = true) @RequestParam MultipartFile file) {
		if (ValidationUtil.isEmpty(file)) {
			throw new BadRequest("参数校验失败.");
		}
		String accessToken = wechatService.getAccessToken();
		String getPicUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=" + accessToken + "&type=image";
		String url = HttpUtils.doPostWithFile(getPicUrl, file, "media", accessToken, "image");
		return ResponseHelper.buildResponse(url);
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/test/templateMsg/warning")
	@ApiOperation(httpMethod = "GET", value = "测试发送公众号预警消息", notes = "测试发送公众号预警消息")
	public ResponseModel testSendTemplateMsgWarning() {
		return ResponseHelper.buildResponse(wechatService.sendTestTemplateMsgWarning());
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/test/templateMsg/supervise")
	@ApiOperation(httpMethod = "GET", value = "测试发送公众号督查整改消息", notes = "测试发送公众号督查整改消息")
	public ResponseModel testSendTemplateMsgSupervise() {
		return ResponseHelper.buildResponse(wechatService.sendTestTemplateMsgSupervise());
	}

}
