package cn.wise.sc.cement.business.controller;

import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.enumation.FileExt;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.query.*;
import cn.wise.sc.cement.business.model.vo.EntrustVo;
import cn.wise.sc.cement.business.model.vo.SampleDistributionTeamVo;
import cn.wise.sc.cement.business.model.vo.SampleVo;
import cn.wise.sc.cement.business.service.IEntrustService;
import cn.wise.sc.cement.business.util.WordUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ztw
 * @since 2020-08-24
 */
@Api(tags = "委托管理")
@RestController
@RequestMapping("/business/entrust")
public class EntrustController {

	private static final Logger log = LoggerFactory.getLogger("EntrustController");

	@Autowired
	private IEntrustService entrustService;

	@ApiOperation(value = "委托分页列表")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "startDate", value = "开始日期", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endDate", value = "结束日期", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "status",
					value = "状态(0未评审，1已通过，2未通过，" +
							"3样品处理中，4样品处理完成，" +
							"5样品检测中，6样品检测完成，" +
							"7校核中，8校核完成)", paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "clientId", value = "委托单位id", paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "projectName", value = "项目名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "isUrgent", value = "（1加急，0不加急）", paramType = "query", dataType = "Integer")
	})
	@GetMapping("/getPage")
	public BaseResponse getPage(PageQuery pageQuery, String startDate, String endDate, Integer status,
	                            Integer clientId, String projectName, String projectCode, Integer isUrgent) {
		try {
			return entrustService.getPage(pageQuery, startDate, endDate, status, clientId, projectName, projectCode, isUrgent);
		} catch (Exception e) {
			log.debug("委托分页列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation("委托列表导出")
	@PostMapping("/export")
	public void export(String startDate, String endDate, Integer status,
	                   Integer clientId, String projectName, String projectCode,
	                   String fileName, HttpServletResponse response) {
		try {
			entrustService.export(startDate, endDate, status,
					clientId, projectName, projectCode,
					fileName, response);
		} catch (Exception e) {
			log.debug("委托列表导出{}", e);
		}
	}

	@ApiOperation(value = "置顶取消置顶 (createTime = updateTime显示置顶，否则显示取消置顶)")
	@PostMapping("/setTopping")
	public BaseResponse setTopping(Integer id) {
		try {
			return entrustService.setTopping(id);
		} catch (Exception e) {
			log.debug("置顶取消置顶{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "新增委托")
	@PostMapping("/create")
	public BaseResponse create(@RequestBody EntrustQuery query) {
		try {
			return entrustService.create(query);
		} catch (Exception e) {
			log.debug("新增委托{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "委托详情")
	@GetMapping("/{id}")
	public BaseResponse getDtail(@PathVariable Integer id) {
		try {
			return entrustService.getDtail(id);
		} catch (Exception e) {
			log.debug("委托详情{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@PostMapping("/export/{entrustId}")
	@ApiOperation("导出委托单")
	public void getReportDetail(@PathVariable("entrustId") Integer entrustId,
	                            HttpServletResponse response) {
//		EntrustVo entrustVo = entrustService.getDetailCapacity(entrustId).getData();
		EntrustVo entrustVo = entrustService.getBaseDtail(entrustId).getData();
		if (entrustVo == null) {
			return;
		}
		Map<String, Object> beanParams = new HashMap<>(7);
		beanParams.put("clientName", entrustVo.getClientName()==null?"":entrustVo.getClientName());
		beanParams.put("entrustCode", entrustVo.getEntrustCode()==null?"":entrustVo.getEntrustCode());
		beanParams.put("userName", entrustVo.getUserName()==null?"":entrustVo.getUserName());
		beanParams.put("userPhone", entrustVo.getUserPhone()==null?"":entrustVo.getUserPhone());
		beanParams.put("userFax", entrustVo.getUserFax()==null?"":entrustVo.getUserFax());
		beanParams.put("projectName", entrustVo.getProjectName()==null?"":entrustVo.getProjectName());
		beanParams.put("sampleNum", entrustVo.getSampleNum()==null?"":entrustVo.getSampleNum());

		//获取委托单样品列表(不包含平行样)
		List<SampleVo> sampleList = new ArrayList<>(entrustVo.getSampleList().size());
		entrustVo.getSampleList()
				.stream()
				.filter(arg -> arg.getIsParallel() == 0)
				.forEach(arg -> {
					List<SampleDistributionTeamVo> teamVoList = arg.getSampleDistributionTeamVoList();
					arg.setTeamName(getTeamName(teamVoList));
					sampleList.add(arg);
				});
		beanParams.put("list", sampleList);

		WordUtil.writeWordReport(entrustVo.getProjectName() + "(委托单)", "entrust2.ftl",
				beanParams, response, FileExt.DOC);

	}

	@ApiOperation(value = "获取样品表里最大的本所编号")
	@GetMapping("/getMaxCementCode")
	public BaseResponse getMaxCementCode() {
		try {
			return entrustService.getMaxCementCode();
		} catch (Exception e) {
			log.debug("获取样品表里最大的本所编号{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "委托评审+发送样品处理任务")
	@PostMapping("/approval")
	public BaseResponse approval(@RequestBody ApprovalQuery query) {
		try {
			return entrustService.approval(query);
		} catch (Exception e) {
			log.debug("委托评审+发送样品处理任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	/*@ApiOperation(value = "发送样品处理任务")
	@PostMapping("/handle")
	public BaseResponse handle(@RequestBody HandleQuery query) {
		try {
			return entrustService.handle(query);
		} catch (Exception e) {
			log.debug("发送样品处理任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}*/

	@ApiOperation(value = "样品处理任务分页")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", dataType = "String")
	})
	@GetMapping("/getSampleHandlePage")
	public BaseResponse getSampleHandlePage(PageQuery pageQuery, String projectCode) {
		try {
			return entrustService.getSampleHandlePage(pageQuery, projectCode);
		} catch (Exception e) {
			log.debug("样品处理任务分页{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "样品处理任务列表")
	@GetMapping("/getSampleHandleList")
	public BaseResponse getSampleHandleList(Integer id) {
		try {
			return entrustService.getSampleHandleList(id);
		} catch (Exception e) {
			log.debug("样品处理任务列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "接受样品处理任务")
	@PostMapping("/acceptHandle")
	public BaseResponse acceptHandle(@RequestBody Integer[] ids) {
		try {
			return entrustService.acceptHandle(ids);
		} catch (Exception e) {
			log.debug("接受样品处理任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "数据上传列表")
	@GetMapping("/getSampleHandleEnclosureList")
	public BaseResponse getSampleHandleEnclosureList(Integer sampleHandleId) {
		try {
			return entrustService.getSampleHandleEnclosureList(sampleHandleId);
		} catch (Exception e) {
			log.debug("数据上传列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "样品处理数据上传附件")
	@PostMapping("/uploadEnclosureCL")
	public BaseResponse uploadEnclosureCL(SampleHandleEnclosureQuery query) {
		try {
			return entrustService.uploadEnclosureCL(query);
		} catch (Exception e) {
			log.debug("样品处理数据上传附件{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "样品处理详情")
	@GetMapping("/getHandleDtail/{id}")
	public BaseResponse getHandleDtail(@PathVariable Integer id) {
		try {
			return entrustService.getHandleDtail(id);
		} catch (Exception e) {
			log.debug("样品处理详情{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "完成样品处理任务")
	@PostMapping("/finishHandle")
	public BaseResponse finishHandle(@RequestBody Integer[] ids) {
		try {
			return entrustService.finishHandle(ids);
		} catch (Exception e) {
			log.debug("完成样品处理任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "派发检测项目任务")
	@PostMapping("/distribution")
	public BaseResponse distribution(@RequestBody DistributionQuery query) {
		try {
			return entrustService.distribution(query);
		} catch (Exception e) {
			log.debug("派发检测项目任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "派发任务分页列表")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "projectName", value = "项目名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", dataType = "String")
	})
	@GetMapping("/getSampleDistributionPage")
	public BaseResponse getSampleDistributionPage(PageQuery pageQuery, String projectName,
	                                              String projectCode) {
		try {
			return entrustService.getSampleDistributionPage(pageQuery, projectName, projectCode);
		} catch (Exception e) {
			log.debug("派发任务分页列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "检测通知单详情")
	@GetMapping("/getSampleDistributionList/{id}")
	public BaseResponse getSampleDistributionList(@PathVariable Integer id) {
		try {
			return entrustService.getSampleDistributionList(id);
		} catch (Exception e) {
			log.debug("检测通知单详情{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "详情-基本信息")
	@GetMapping("/getBaseDtail/{id}")
	public BaseResponse getBaseDtail(@PathVariable Integer id) {
		try {
			return entrustService.getBaseDtail(id);
		} catch (Exception e) {
			log.debug("详情-基本信息{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "详情-样品处理信息")
	@GetMapping("/getSampleHandleDtail/{id}")
	public BaseResponse getSampleHandleDtail(@PathVariable Integer id) {
		try {
			return entrustService.getSampleHandleDtail(id);
		} catch (Exception e) {
			log.debug("详情-样品处理信息{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "详情-样品处理信息-附件列表")
	@GetMapping("/getSampleHandleDtailEnclosureList")
	public BaseResponse getSampleHandleDtailEnclosureList(Integer sampleHandleId) {
		try {
			return entrustService.getSampleHandleDtailEnclosureList(sampleHandleId);
		} catch (Exception e) {
			log.debug("详情-样品处理信息-附件列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "详情-检测任务信息")
	@GetMapping("/getSampleCheckDtail/{id}")
	public BaseResponse getSampleCheckDtail(@PathVariable Integer id) {
		try {
			return entrustService.getSampleCheckDtail(id);
		} catch (Exception e) {
			log.debug("详情-检测任务信息{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "接受检测项目任务")
	@PostMapping("/acceptDistribution")
	public BaseResponse acceptDistribution(@RequestBody Integer[] ids) {
		try {
			return entrustService.acceptDistribution(ids);
		} catch (Exception e) {
			log.debug("接受检测项目任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "检测项目上传附件")
	@PostMapping("/uploadEnclosurePF")
	public BaseResponse uploadEnclosurePF(SampleDistributionEnclosureQuery query) {
		try {
			return entrustService.uploadEnclosurePF(query);
		} catch (Exception e) {
			log.debug("检测项目上传附件{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "完成检测项目任务")
	@PostMapping("/finishDistribution")
	public BaseResponse finishDistribution(@RequestBody Integer[] ids) {
		try {
			return entrustService.finishDistribution(ids);
		} catch (Exception e) {
			log.debug("完成检测项目任务{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "数据校核分页")
	@ApiImplicitParams(value = {
			@ApiImplicitParam(name = "startDate", value = "开始日期", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "endDate", value = "结束日期", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "status",
					value = "状态(6样品检测完成，7校核中，8校核完成)", paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "clientId", value = "委托单位id", paramType = "query", dataType = "Integer"),
			@ApiImplicitParam(name = "projectName", value = "项目名称", paramType = "query", dataType = "String"),
			@ApiImplicitParam(name = "projectCode", value = "项目编号", paramType = "query", dataType = "String")
	})
	@GetMapping("/getCheckPage")
	public BaseResponse getCheckPage(PageQuery pageQuery, String startDate, String endDate, Integer status,
	                                 Integer clientId, String projectName, String projectCode) {
		try {
			return entrustService.getCheckPage(pageQuery, startDate, endDate, status, clientId, projectName, projectCode);
		} catch (Exception e) {
			log.debug("数据校核分页{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "数据校核详情列表")
	@GetMapping("/getCheckList/{id}")
	public BaseResponse getCheckList(@PathVariable Integer id) {
		try {
			return entrustService.getCheckList(id);
		} catch (Exception e) {
			log.debug("数据校核详情列表{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "样品检测项校核详情")
	@GetMapping("/getCheckDetail")
	public BaseResponse getCheckDetail(String cementCode) {
		try {
			return entrustService.getCheckDetail(cementCode);
		} catch (Exception e) {
			log.debug("样品检测项校核详情{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "查询任务检测附件信息")
	@GetMapping("/getEnclosureList")
	public BaseResponse getEnclosureList(Integer sampleId, Integer teamGroupId, Integer userId) {
		try {
			return entrustService.getEnclosureList(sampleId, teamGroupId, userId);
		} catch (Exception e) {
			log.debug("查询任务检测附件信息{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}

	@ApiOperation(value = "校核计算")
	@PostMapping("/checkCount")
	public BaseResponse checkCount(@RequestBody CheckCountQuery query) {
		try {
			return entrustService.checkCount(query);
		} catch (Exception e) {
			log.debug("校核计算{}", e);
		}
		return BaseResponse.errorMsg("失败!");
	}


   /* @ApiOperation(value = "数据校核")
    @PostMapping("/check")
    public BaseResponse check(@RequestBody CheckQuery query) {
        try {
            return entrustService.check(query);
        } catch (Exception e) {
            log.debug("数据校核{}", e);
        }
        return BaseResponse.errorMsg("失败!");
    }*/

	private String getTeamName(List<SampleDistributionTeamVo> teamVos) {
		if (teamVos.size() == 0) {
			return "";
		}

		StringBuffer rts = new StringBuffer();

		teamVos.forEach(arg -> {
			rts.append(arg.getTeamName()).append("、");
		});
		return rts.substring(0, rts.toString().length() - 1);
	}

}

