package com.yeejoin.precontrol.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.yeejoin.precontrol.common.annotations.OpsLog;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.TaskRiskControlDto;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.TaskRiskControl;
import com.yeejoin.precontrol.common.entity.TaskRiskControlTech;
import com.yeejoin.precontrol.common.entity.publics.CommonPageable;
import com.yeejoin.precontrol.common.enums.OpsLogEnum;
import com.yeejoin.precontrol.common.enums.SmallProPageEnum;
import com.yeejoin.precontrol.common.enums.TaskRiskControlStatusEnum;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlTechService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.NameUtils;
import com.yeejoin.precontrol.common.vo.TaskRiskControlAppVo;
import com.yeejoin.precontrol.common.vo.TaskRiskControlVo;
import com.yeejoin.precontrol.common.vo.TaskWorkPersonVo;
import com.yeejoin.precontrol.controller.publics.BaseController;

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

/**
 * 风险管控任务表
 *
 * @author duanwei
 * @date 2021-01-28
 */
@RestController
@Api(tags = "风险管控任务表Api")
@RequestMapping(value = "/task-risk-control", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TaskRiskControlController extends BaseController {

	@Autowired
	ITaskRiskControlService iTaskRiskControlService;
	
	@Autowired
	ITaskRiskControlTechService iTaskRiskControlTechService;

	@Autowired
	IProjectService iProjectService;

	/**
	 * 小程序二维码服务
	 */
	@Autowired
	SmallProService smallProService;

	@Autowired
	IPersonService personService;

	/**
	 * 新增风险管控任务表
	 *
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增风险管控任务表", notes = "新增风险管控任务表")
	public boolean saveTaskRiskControl(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		iTaskRiskControlService.save(taskRiskControlVo);
		return true;
	}

	/**
	 * 根据id批量删除
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/{ids}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id批量删除", notes = "根据id批量删除")
	@OpsLog(value=OpsLogEnum.DELETE_RISKCONTROL)
	public String deleteById(HttpServletRequest request, @PathVariable String ids) {
		String[] idArray = ids.split(",");
		Optional.ofNullable(idArray).orElseThrow(() -> new BadRequest("参数错误"));
		return iTaskRiskControlService.deleteByIds(Arrays.asList(idArray));
	}

	/**
	 * 修改风险管控任务表
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateById", method = RequestMethod.PUT)
	@OpsLog(value=OpsLogEnum.EDIT_RISKCONTROL)
	@ApiOperation(httpMethod = "PUT", value = "修改风险管控任务表", notes = "修改风险管控任务表")
	public boolean updateByIdTaskRiskControl(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		TaskRiskControl taskRiskControl = new TaskRiskControl();
		BeanUtils.copyProperties(taskRiskControlVo, taskRiskControl);
		iTaskRiskControlService.nullFiledCheck(taskRiskControl);
		Optional.ofNullable(taskRiskControl.getId()).orElseThrow(() -> new BadRequest("风险任务计划不存在"));
		if(taskRiskControlVo.getRiskControlTechVo()!=null) 
		{
			TaskRiskControlTech taskRiskControlTech = new TaskRiskControlTech();
			BeanUtils.copyProperties(taskRiskControlVo.getRiskControlTechVo(), taskRiskControlTech);
			iTaskRiskControlTechService.updateById(taskRiskControlTech);
		}
		return iTaskRiskControlService.updateById(taskRiskControl);
	}


	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public TaskRiskControlVo selectById(HttpServletRequest request, @PathVariable Long id) {
		return iTaskRiskControlService.getDetailById(id);
	}

	/**
	 * 风险作业计划列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/page/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public IPage<TaskRiskControlVo> listByPage(Integer pageNumber, Integer pageSize,
			TaskRiskControlDto taskRiskControlDto) {
		String orgCode = null;
		Person loginPerson = getPerson();
		orgCode = loginPerson.getOrgCode();
		taskRiskControlDto.setOrgCode(orgCode);
		return iTaskRiskControlService.listByPage(pageNumber, pageSize, taskRiskControlDto);
	}

	/**
	 * 风险计划二维码
	 */
	@RequestMapping(value = "/getQrCode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取风险计划二维码", notes = "获取风险计划二维码")
	public void getTaskRiskControlQrCode(
			@RequestParam(value = "fileType", required = false, defaultValue = "png") String fileType,
			@RequestParam(value = "width", required = false) String width,
			@RequestParam(value = "taskRiskControlId") Long taskRiskControlId, HttpServletResponse response) {
		String page = SmallProPageEnum.personQr.getPath();
		String token = smallProService.getSmallProToken();
		String bizId = taskRiskControlId.toString();
		smallProService.getSmallProQrCodeResponse(token, bizId, page, Long.valueOf(width), null, null, null, response,
				String.valueOf(taskRiskControlId), fileType);
	}

	/**
	 * 获取“我的安全码”
	 */
	@RequestMapping(value = "/safety/qrCode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取“我的安全码”", notes = "获取“我的安全码”")
	public Map<String, Object> getSafetyQrCode(@RequestParam(value = "taskRiskControlId") Long taskRiskControlId,
			@RequestParam(value = "personId") Long personId, HttpServletResponse response) {
		return iTaskRiskControlService.getRiskWorkTrajectory(taskRiskControlId, personId);
	}

	@RequestMapping(value = "/status/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "计划状态列表", notes = "计划状态列表")
	public Map<String, String> getTaskRiskControlStatusEnum() {
		Map<String, String> enumMap = Maps.newHashMap();
		for (TaskRiskControlStatusEnum _enum : TaskRiskControlStatusEnum.values()) {
			enumMap.put(_enum.getCode(), _enum.getName());
		}
		return enumMap;
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public IPage<TaskRiskControl> listPage(String pageNum, String pageSize, TaskRiskControl taskRiskControl) {

		Page<TaskRiskControl> pageBean;
		QueryWrapper<TaskRiskControl> taskRiskControlQueryWrapper = new QueryWrapper<>();
		Class<? extends TaskRiskControl> aClass = taskRiskControl.getClass();
		Arrays.stream(aClass.getDeclaredFields()).forEach(field -> {
			try {
				field.setAccessible(true);
				Object o = field.get(taskRiskControl);
				if (o != null) {
					Class<?> type = field.getType();
					String name = NameUtils.camel2Underline(field.getName());
					if (type.equals(Integer.class)) {
						Integer fileValue = (Integer) field.get(taskRiskControl);
						taskRiskControlQueryWrapper.eq(name, fileValue);
					} else if (type.equals(Long.class)) {
						Long fileValue = (Long) field.get(taskRiskControl);
						taskRiskControlQueryWrapper.eq(name, fileValue);
					} else if (type.equals(String.class)) {
						String fileValue = (String) field.get(taskRiskControl);
						taskRiskControlQueryWrapper.eq(name, fileValue);
					} else {
						String fileValue = (String) field.get(taskRiskControl);
						taskRiskControlQueryWrapper.eq(name, fileValue);
					}
				}
			} catch (Exception e) {
			}
		});
		IPage<TaskRiskControl> page;
		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 = iTaskRiskControlService.page(pageBean, taskRiskControlQueryWrapper);
		return page;
	}

	/**
	 * 新增风险管控任务表(江西电建)
	 *
	 * @return
	 */
	@RequestMapping(value = "/createTask", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增风险管控任务表", notes = "新增风险管控任务表")
	public TaskRiskControlVo createTask(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		Person person = getPerson();
		taskRiskControlVo.setOrgCode(person != null ? person.getOrgCode() : null);
		taskRiskControlVo.setCreatePersonId(person.getId());
		TaskRiskControlVo riskControlVo = iTaskRiskControlService.createTask(taskRiskControlVo);
		iTaskRiskControlService.taskRiskNotice(riskControlVo, riskControlVo.getCompanyPersonId()); // 消息通知--给分包商主管发消息
		return riskControlVo;
	}

	/**
	 * 新增风险管控任务表(分包商)
	 *
	 * @return
	 */
	@RequestMapping(value = "/createTaskByFbs", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增风险管控任务表", notes = "新增风险管控任务表")
	public TaskRiskControlVo createTaskByFbs(HttpServletRequest request,
			@RequestBody TaskRiskControlVo taskRiskControlVo) {
		return iTaskRiskControlService.createTaskByFbs(taskRiskControlVo);
	}

	/**
	 * 下一步
	 *
	 * @return
	 */
	@RequestMapping(value = "/next", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增风险管控任务表", notes = "新增风险管控任务表")
	public TaskRiskControlVo next(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		return iTaskRiskControlService.nextStage(taskRiskControlVo);
	}

	/**
	 * 上一步
	 *
	 * @return
	 */
	@RequestMapping(value = "/previous", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增风险管控任务表", notes = "新增风险管控任务表")
	public TaskRiskControlVo previous(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		return iTaskRiskControlService.previousStage(taskRiskControlVo);
	}

	/**
	 * 做现场检查
	 *
	 * @return
	 */
	@RequestMapping(value = "/doCheck", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "检查", notes = "检查")
	public TaskRiskControlVo doCheck(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		return iTaskRiskControlService.doCheck(taskRiskControlVo);
	}

	/**
	 * 做考试
	 *
	 * @return
	 */
	@RequestMapping(value = "/doExam", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "检查", notes = "检查")
	public TaskRiskControlVo doExam(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo,
			boolean qualified) {
		return iTaskRiskControlService.doExam(taskRiskControlVo, qualified);
	}

	/**
	 * 做知识
	 *
	 * @return
	 */
	@RequestMapping(value = "/doKnowledge", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "检查", notes = "检查")
	public TaskRiskControlVo doKnowledge(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		Person person = getPerson();
		return iTaskRiskControlService.doKnowledge(taskRiskControlVo);
	}

	/**
	 * 再次发起
	 *
	 * @return
	 */
	@RequestMapping(value = "/reCreate", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "检查", notes = "检查")
	public TaskRiskControlVo reCommit(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		Person person = getPerson();
		return iTaskRiskControlService.reCreate(taskRiskControlVo);
	}

	/**
	 * 再次发起
	 *
	 * @return
	 */
	@RequestMapping(value = "/reCreateBySec", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "检查", notes = "检查")
	public TaskRiskControlVo reCreateBySec(HttpServletRequest request,
			@RequestBody TaskRiskControlVo taskRiskControlVo) {
		Person person = getPerson();
		return iTaskRiskControlService.reCreateBySec(taskRiskControlVo);
	}

	/**
	 * 取消
	 *
	 * @return
	 */
	@RequestMapping(value = "/cancel", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "检查", notes = "检查")
	public boolean cancel(HttpServletRequest request, @RequestBody TaskRiskControlVo taskRiskControlVo) {
		return iTaskRiskControlService.cancel(taskRiskControlVo);
	}

	/**
	 * 获取我的风险预控列表
	 *
	 * @return
	 */
	@RequestMapping(value = "/myList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取我的风险预控列表", notes = "获取我的风险预控列表")
	public Page<TaskRiskControlVo> createTask(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "查询参数") TaskRiskControlDto taskRiskControl, HttpServletResponse response) {
		Person person = personService.getById(getPerson().getId());
		// 分包商只看自己的----userId;江西电建查看项目部的----orgCode
		if (person.getIsJxdj() == 0) {
			//taskRiskControl.setOrgCode("");
			taskRiskControl.setPersonId(person.getId());
		} else {
			taskRiskControl.setPersonId(person.getId());
			taskRiskControl.setOrgCode(person.getOrgCode());
		}
		return iTaskRiskControlService.myListByPage(pageable, person.getId(), taskRiskControl);
	}

	/**
	 * 获取我的风险预控详情
	 *
	 * @return
	 */
	@RequestMapping(value = "/taskDetail", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取我的风险预控详情", notes = "获取我的风险预控详情")
	public TaskRiskControlVo taskDetail(@ApiParam(value = "查询参数") Long id,Long taskPersonId) {
		Person person = getPerson();
		return iTaskRiskControlService.taskDetail(id, taskPersonId);
	}

	/**
	 * 获取我的风险预控详情
	 *
	 * @return
	 */
	@RequestMapping(value = "/taskDetailByTaskId", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取我的风险预控详情", notes = "获取我的风险预控详情")
	public TaskRiskControlVo taskDetailByTaskId(@ApiParam(value = "查询参数") Long taskId,Long taskPersonId) {
		//Person person = getPerson();
		TaskRiskControl taskRiskControl = iTaskRiskControlService
				.getOne(new LambdaQueryWrapper<TaskRiskControl>().eq(TaskRiskControl::getTaskId, taskId));
		return iTaskRiskControlService.taskDetail(taskRiskControl.getId(), taskPersonId);
	}

	@ApiOperation("查询有风险管控任务数据的年")
	@GetMapping("/year/list")
	public List<String> getYearData(@RequestParam(required = false) String level) {
		Person person = getPerson();
		String orgCode = person.getOrgCode();
		return iTaskRiskControlService.listYear(orgCode, level);
	}

	@ApiOperation("按照年分页查询，风险管控任务")
	@GetMapping("/year/page/list")
	public Page<TaskRiskControlAppVo> yearStatisticsPage(CommonPageable pageable,
			@RequestParam(required = false) Integer level, @RequestParam(required = false) String name,
			@RequestParam(required = false) String status, @RequestParam String beginDate,
			@RequestParam String endDate) {
		Person person = getPerson();
		String orgCode = person.getOrgCode();
		return iTaskRiskControlService.listTaskByYearPage(pageable, level, name, status, beginDate, endDate, orgCode);
	}

	@ApiOperation("按照等级统计风险管控任务")
	@GetMapping("/level/statistics")
	public Object statisticsByLevel(@RequestParam(required = false) String name,
			@RequestParam(required = false) String status, @RequestParam(required = false) String beginDate,
			@RequestParam(required = false) String endDate) {
		Person person = getPerson();
		String orgCode = person.getOrgCode();
		Map<String, Object> param = new HashMap<>(5);
		param.put("name", name);
		param.put("status", status);
		param.put("beginDate", beginDate);
		param.put("endDate", endDate);
		param.put("orgCode", orgCode);
		return iTaskRiskControlService.statisticsByLevel(param);
	}

	@ApiOperation("进出风险区域")
	@PostMapping("/region")
	public Object inOutRiskRegion(@RequestParam Integer operate, @RequestParam Long taskPersonId,
			@RequestParam Long taskRiskControlId) {
		iTaskRiskControlService.entryOrExitRiskRegion(operate, taskPersonId, taskRiskControlId);
		return true;
	}

	@ApiOperation(value = "风险作业任务人数统计", notes = "小程序使用")
	@GetMapping("/person/{taskRiskControlId}/statistics")
	public Object personStatistics(@PathVariable Long taskRiskControlId) {
		return iTaskRiskControlService.personStatistics(taskRiskControlId);
	}

	@ApiOperation(value = "任务下人员列表", notes = "小程序使用")
	@GetMapping("/person/{taskRiskControlId}/list")
	public List<TaskWorkPersonVo> personListInTaskRisk(@PathVariable Long taskRiskControlId,
			@RequestParam(required = false) Integer status) {
		return iTaskRiskControlService.personListInTaskRisk(taskRiskControlId, status);
	}

	@ApiOperation(value = "任务阅读", notes = "任务阅读")
	@PostMapping("/read")
	public TaskRiskControlVo read(@RequestBody TaskRiskControlVo taskRiskControlVo) {
		return iTaskRiskControlService.read(taskRiskControlVo);
	}

	@ApiOperation(value = "小程序首页-项目部-风险作业列表", notes = "小程序首页-项目部-风险作业列表")
	@GetMapping("/home/list")
	public List<TaskRiskControlVo> getListByConfig() {
		Person person = getPerson();
		return iTaskRiskControlService.listByConfig(person.getOrgCode());
	}
}
