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

import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.annotation.ResubmitCheck;
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.elevator.api.dto.MainPersonDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatDispatchFeedbackDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatUserFeedbackDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatMyBussinessDto;
import com.yeejoin.amos.boot.module.elevator.api.dto.WechatMyTaskDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.elevator.api.service.IDispatchTaskService;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.AlertFormValueServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
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 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.RedisUtils;
import com.yeejoin.amos.boot.module.elevator.api.dto.DispatchTaskDto;
import com.yeejoin.amos.boot.module.elevator.api.entity.DispatchTask;
import com.yeejoin.amos.boot.module.elevator.biz.service.impl.DispatchTaskServiceImpl;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 派遣任务
 *
 * @author system_generator
 * @date 2021-08-03
 */
@RestController
@Api(tags = "派遣任务Api")
@RequestMapping(value = "/dispatch-task")
public class DispatchTaskController extends BaseController {

    @Autowired
    DispatchTaskServiceImpl dispatchTaskServiceImpl;

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	ISourceFileService sourceFileService;

	@Autowired
	IDispatchTaskService dispatchTaskService;

	@Autowired
	AlertFormValueServiceImpl iAlertFormValueService;

	/**
	 * 根据派遣单位类型和警情id 获取任务模板
	 * @param orgTypeCode
	 * @param alertId
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{orgTypeCode}/alert/{alertId}")
	@ApiOperation(httpMethod = "GET",value = "根据派遣单位类型和警情id 获取任务信息",  notes = "根据派遣单位类型和警情id 获取任务信息")
	public ResponseModel<DispatchTaskDto> selectOne(@PathVariable String orgTypeCode, @PathVariable Long alertId) {
		return ResponseHelper.buildResponse(dispatchTaskServiceImpl.getTaskInfo(orgTypeCode,alertId));
	}

    /**
     * 新增派遣任务
     *
     * @return
     */
	@ResubmitCheck
    @TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增派遣任务", notes = "新增派遣任务")
	public ResponseModel<Boolean> save(@RequestBody DispatchTaskDto model) {
		ReginParams reginParams =getSelectedOrgInfo();
		Boolean flag = dispatchTaskServiceImpl.createDispatchTask(model,reginParams.getUserModel());
	    return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 根据警情id 查找力量调派信息
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "根据警情id 查找力量调派信息",   notes = "根据警情id 查找力量调派信息")
	@GetMapping(value = "/list/alert/{alertId}")
	public ResponseModel<List<DispatchTask>> selectForListByAlertId(@PathVariable Long alertId) {
		LambdaQueryWrapper<DispatchTask> queryWrapper = new LambdaQueryWrapper<DispatchTask>();
		queryWrapper.eq(DispatchTask::getAlertId, alertId);
		List<DispatchTask> list = dispatchTaskServiceImpl.list(queryWrapper);
	    return ResponseHelper.buildResponse(list);
	}

	/**
	 * 微信公众号维修反馈接口
	 *
	 * @return
	 */
	@ResubmitCheck
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/saveWechatFeed")
	@ApiOperation(httpMethod = "POST", value = "微信公众号维修反馈接口", notes = "微信公众号维修反馈接口")
	public ResponseModel<WechatMyTaskDto> saveWechatFeedBack(@RequestBody WechatDispatchFeedbackDto model) {
		return ResponseHelper.buildResponse(dispatchTaskServiceImpl.saveWechatFeedBack(model));
	}

	/**
	 * 查找当日派遣人员信息
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "查找当日派遣人员信息",   notes = "查找当日派遣人员信息")
	@GetMapping(value = "/list/todayTaskPerson")
	public ResponseModel<List<MainPersonDto>> todayTaskPerson() {
		List<MainPersonDto> list = dispatchTaskServiceImpl.todayTaskPerson();
		return ResponseHelper.buildResponse(list);
	}


	/**
	 * 微信公众号维修反馈接口
	 *
	 * @return
	 */
	@ResubmitCheck
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/saveUserFeed")
	@ApiOperation(httpMethod = "POST", value = "微信公众号上报人反馈接口", notes = "微信公众号上报人反馈接口")
	public ResponseModel<WechatMyBussinessDto> saveUserFeed(@RequestBody WechatUserFeedbackDto model) {
		return ResponseHelper.buildResponse(dispatchTaskServiceImpl.saveUserFeed(model));
	}

	/**
	 * 点击到达触发事件
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/taskArrive/{taskId}")
	@ApiOperation(httpMethod = "GET", value = "点击到达触发事件", notes = "点击到达触发事件")
	public ResponseModel<WechatMyTaskDto> taskArrive(@PathVariable Long taskId) {
		if (ValidationUtil.isEmpty(taskId)){
			throw new BadRequest("参数校验失败.");
		}
		if(dispatchTaskServiceImpl.taskArrive(taskId)) {
			return ResponseHelper.buildResponse(getTaskDtoByTaskId(taskId));
		} else {
			return ResponseHelper.buildResponse(new WechatMyTaskDto());
		}
	}


	/**
	 * 点击救援完成触发事件
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/saveFinish/{taskId}")
	@ApiOperation(httpMethod = "GET", value = "点击救援完成触发事件", notes = "点击救援完成触发事件")
	public ResponseModel<WechatMyTaskDto> saveFinish(@PathVariable Long taskId) {
		if (ValidationUtil.isEmpty(taskId)){
			throw new BadRequest("参数校验失败.");
		}
		if(dispatchTaskServiceImpl.saveFinish(taskId)) {
			return ResponseHelper.buildResponse(getTaskDtoByTaskId(taskId));
		} else {
			return ResponseHelper.buildResponse(new WechatMyTaskDto());
		}
	}


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




	private WechatMyTaskDto getTaskDtoByTaskId(Long taskId) {
		WechatMyTaskDto temp = dispatchTaskService.getTaskInfoByTaskId(taskId);
		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.getAlertId());
				// 警情动态表单数据
				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);

				errorImgMap = sourceFileService.getAttachments(temp.getAlertId());
				feedbackDtos = errorImgMap.get("feedbacks");
				temp.setFeedBackImgs(feedbackDtos);
				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.getAlertId());
				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.getAlertId());
				errorImgDtos = errorImgMap.get("imgs");
				temp.setErrorImgs(errorImgDtos);
				feedbackDtos = errorImgMap.get("feedbacks");
				temp.setFeedBackImgs(feedbackDtos);
				break;
		}




		return temp;
	}
}
