package org.jeecg.modules.fbsAbnormalWorkingHours.controller;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHours;
import org.jeecg.modules.fbsAbnormalWorkingHours.service.IFbsAbnormalWorkingHoursService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.fbsMomOrder.entity.FbsMomOrder;
import org.jeecg.modules.fbsMomOrder.entity.FbsMomOrderdetail;
import org.jeecg.modules.fbsMomOrder.service.IFbsMomOrderService;
import org.jeecg.modules.fbsMomOrder.service.IFbsMomOrderdetailService;
import org.jeecg.modules.fbsPerson.entity.FbsPerson;
import org.jeecg.modules.fbsPerson.service.IFbsPersonService;
import org.jeecg.modules.fbsWorkshopDispatchList.entity.FbsWorkshopDispatchList;
import org.jeecg.modules.fbsWorkshopDispatchList.service.IFbsWorkshopDispatchListService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;

import static org.jeecg.common.util.oConvertUtils.isEmpty;

/**
 * @Title: Controller
 * @Description: 生产异常信息统计单
 * @author： jeecg-boot
 * @date：   2020-10-13
 * @version： V1.0
 */
@RestController
@RequestMapping("/fbsAbnormalWorkingHours/fbsAbnormalWorkingHours")
@Slf4j
public class FbsAbnormalWorkingHoursController {
	@Autowired
	private IFbsAbnormalWorkingHoursService fbsAbnormalWorkingHoursService;

	@Autowired
	private IFbsPersonService iFbsPersonService;

	@Autowired
	private IFbsMomOrderService iFbsMomOrderService;

	@Autowired
	private IFbsWorkshopDispatchListService iFbsWorkshopDispatchListService;

	@Autowired
	private IFbsMomOrderdetailService iFbsMomOrderdetailService;

	/**
	  * 分页列表查询
	 * @param fbsAbnormalWorkingHours
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<FbsAbnormalWorkingHours>> queryPageList(FbsAbnormalWorkingHours fbsAbnormalWorkingHours,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FbsAbnormalWorkingHours>> result = new Result<IPage<FbsAbnormalWorkingHours>>();
		String start=fbsAbnormalWorkingHours.getStart();
		String end=fbsAbnormalWorkingHours.getEnd();
		if(StringUtils.isNotBlank(start)){
			fbsAbnormalWorkingHours.setStart(null);
		}
		if(StringUtils.isNotBlank(end)){
			fbsAbnormalWorkingHours.setEnd(null);
		}
		QueryWrapper<FbsAbnormalWorkingHours> queryWrapper = QueryGenerator.initQueryWrapper(fbsAbnormalWorkingHours, req.getParameterMap());
		queryWrapper.lambda().eq(FbsAbnormalWorkingHours::getDelFlag,"0");
		queryWrapper.lambda().orderByDesc(FbsAbnormalWorkingHours::getCreateTime);
		if(StringUtils.isNotBlank(start)&&StringUtils.isNotBlank(end)&&!start.equals("null")&&!end.equals("null")){
			queryWrapper.ge("DATE_FORMAT(date,'%Y-%m-%d')",start);
			queryWrapper.le("DATE_FORMAT(date,'%Y-%m-%d')",end);
		}
		Page<FbsAbnormalWorkingHours> page = new Page<FbsAbnormalWorkingHours>(pageNo, pageSize);
		IPage<FbsAbnormalWorkingHours> pageList = fbsAbnormalWorkingHoursService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fbsAbnormalWorkingHours
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<FbsAbnormalWorkingHours> add(@RequestBody FbsAbnormalWorkingHours fbsAbnormalWorkingHours) {
		Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		try {
			fbsAbnormalWorkingHoursService.save(fbsAbnormalWorkingHours);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}


	
	/**
	  *  编辑
	 * @param fbsAbnormalWorkingHours
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<FbsAbnormalWorkingHours> edit(@RequestBody FbsAbnormalWorkingHours fbsAbnormalWorkingHours) {
		Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		FbsAbnormalWorkingHours fbsAbnormalWorkingHoursEntity = fbsAbnormalWorkingHoursService.getById(fbsAbnormalWorkingHours.getId());
		if(fbsAbnormalWorkingHoursEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = fbsAbnormalWorkingHoursService.updateById(fbsAbnormalWorkingHours);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}


	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<FbsAbnormalWorkingHours> delete(@RequestParam(name="id",required=true) String id) {
		Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		FbsAbnormalWorkingHours fbsAbnormalWorkingHours = fbsAbnormalWorkingHoursService.getById(id);
		if(fbsAbnormalWorkingHours==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = fbsAbnormalWorkingHoursService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<FbsAbnormalWorkingHours> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.fbsAbnormalWorkingHoursService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FbsAbnormalWorkingHours> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		FbsAbnormalWorkingHours fbsAbnormalWorkingHours = fbsAbnormalWorkingHoursService.getById(id);
		if(fbsAbnormalWorkingHours==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(fbsAbnormalWorkingHours);
			result.setSuccess(true);
		}
		return result;
	}

  /**
      * 导出excel
   *
   * @param request
   * @param response
   */
  @RequestMapping(value = "/exportXls")
  public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
      // Step.1 组装查询条件
      QueryWrapper<FbsAbnormalWorkingHours> queryWrapper = null;
      try {
          String paramsStr = request.getParameter("paramsStr");
          if (oConvertUtils.isNotEmpty(paramsStr)) {
              String deString = URLDecoder.decode(paramsStr, "UTF-8");
              FbsAbnormalWorkingHours fbsAbnormalWorkingHours = JSON.parseObject(deString, FbsAbnormalWorkingHours.class);
              queryWrapper = QueryGenerator.initQueryWrapper(fbsAbnormalWorkingHours, request.getParameterMap());
          }
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FbsAbnormalWorkingHours> pageList = fbsAbnormalWorkingHoursService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "生产异常信息统计单列表");
      mv.addObject(NormalExcelConstants.CLASS, FbsAbnormalWorkingHours.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("生产异常信息统计单列表数据", "导出人:Jeecg", "导出信息"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
  }

  /**
      * 通过excel导入数据
   *
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
  public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<FbsAbnormalWorkingHours> listFbsAbnormalWorkingHourss = ExcelImportUtil.importExcel(file.getInputStream(), FbsAbnormalWorkingHours.class, params);
              for (FbsAbnormalWorkingHours fbsAbnormalWorkingHoursExcel : listFbsAbnormalWorkingHourss) {
                  fbsAbnormalWorkingHoursService.save(fbsAbnormalWorkingHoursExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFbsAbnormalWorkingHourss.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

	 /**
	  * @Author chenchuang
	  * @Description //TODO 新增子表数据以及子表数据
	  * @Date 2020/10/14 15:36
	  * @Param [fbsAbnormalWorkingHours]
	  * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHours>
	  */
	 @PostMapping(value = "/addAndChild")
	 public Result<FbsAbnormalWorkingHours> addAndChild(@RequestBody FbsAbnormalWorkingHours fbsAbnormalWorkingHours) {
		 Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		 try {
			 fbsAbnormalWorkingHoursService.addAndChild(fbsAbnormalWorkingHours);
			 result.success("添加成功！");
		 } catch (Exception e) {
			 e.printStackTrace();
			 log.info(e.getMessage());
			 result.error500("操作失败");
		 }
		 return result;
	 }

	 /**
	  * @Author chenchuang
	  * @Description //TODO 修改主表和子表数据
	  * @Date 2020/10/14 15:40
	  * @Param [fbsAbnormalWorkingHours]
	  * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHours>
	  */
	 @PutMapping(value = "/updateAndChild")
	 public Result<FbsAbnormalWorkingHours> updateAndChild(@RequestBody FbsAbnormalWorkingHours fbsAbnormalWorkingHours) {
		 Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		 FbsAbnormalWorkingHours fbsAbnormalWorkingHoursEntity = fbsAbnormalWorkingHoursService.getById(fbsAbnormalWorkingHours.getId());
		 if(fbsAbnormalWorkingHoursEntity==null) {
			 result.error500("未找到对应实体");
		 }else {
			 boolean ok = false;
			 try {
				 ok = fbsAbnormalWorkingHoursService.updateAndChild(fbsAbnormalWorkingHours);
			 } catch (Exception e) {
				 result.error500("修改失败："+e.getMessage());
			 }
			 //TODO 返回false说明什么？
			 if(ok) {
				 result.success("修改成功!");
			 }
		 }
		 return result;
	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 删除主表和子表
	 * @Date 2020/10/14 15:45
	 * @Param [id]
	 * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHours>
	 */
	 @DeleteMapping(value = "/deleteAndChild")
	 public Result<FbsAbnormalWorkingHours> deleteAndChild(@RequestParam(name="id",required=true) String id) {
		 Result<FbsAbnormalWorkingHours> result = new Result<FbsAbnormalWorkingHours>();
		 FbsAbnormalWorkingHours fbsAbnormalWorkingHours = fbsAbnormalWorkingHoursService.getById(id);
		 if(fbsAbnormalWorkingHours==null) {
			 result.error500("未找到对应实体");
		 }else {
			 fbsAbnormalWorkingHours.setDelFlag("1");
			 boolean ok = fbsAbnormalWorkingHoursService.updateById(fbsAbnormalWorkingHours);
			 if(ok) {
				 result.success("删除成功!");
			 }
		 }

		 return result;
	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 首页异常工时报表数据
	 * @Date 2020/10/17 15:53
	 * @Param []
	 * @return org.jeecg.common.api.vo.Result<org.jeecg.modules.fbsAbnormalWorkingHours.entity.FbsAbnormalWorkingHours>
	 */
	@GetMapping(value = "/getAbnormalWorkingHoursReport")
	 public Result<FbsAbnormalWorkingHours> getAbnormalWorkingHoursReport(){
		 Result<FbsAbnormalWorkingHours> result =new Result<>();
		 try {
			 result.setResult(fbsAbnormalWorkingHoursService.getAbnormalWorkingHoursReport());
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 根据时间查询派工单产品（月工时分布情况）
	 * @Date 2020/10/20 11:00
	 * @Param [date]
	 * @return org.jeecg.common.api.vo.Result<java.util.List<org.jeecg.modules.fbsWorkshopDispatchList.entity.FbsWorkshopDispatchList>>
	 */
	 @GetMapping(value = "/getDispatchListByDate")
	 public Result<List<FbsWorkshopDispatchList>> getDispatchListByDate(String date){
		 Result<List<FbsWorkshopDispatchList>> result=new Result<>();
		 try {
			 List<FbsWorkshopDispatchList> fbsWorkshopDispatchListList=fbsAbnormalWorkingHoursService.getDispatchListByDate(date);
			 result.setResult(fbsWorkshopDispatchListList);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 月制成质量异常
	 * @Date 2020/10/21 15:36
	 * @Param []
	 * @return org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.Object>>
	 */
     @GetMapping(value = "/getQualityType")
	 public Result<Map<String,Object>> getQualityType(){
         Result<Map<String,Object>> result=new Result<>();
         try {
             Map<String,Object> map=fbsAbnormalWorkingHoursService.getQualityType();
             result.setResult(map);
             result.success("操作成功");
         } catch (Exception e) {
             e.printStackTrace();
             result.error500("操作失败："+e.getMessage());
         }
         return result;
     }

     /**
     * @Author chenchuang
     * @Description //TODO 制造看板/产线看板：月/日 良率
     * @Date 2020/10/27 13:06
     * @Param [type]
     * @return org.jeecg.common.api.vo.Result<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
     */
	 @GetMapping(value = "/getRejectsNumber")
     public Result<List<Map<String,Object>>> getRejectsNumber(String type){
		 Result<List<Map<String,Object>>> result=new Result<>();

		 String dateString="%Y-%m";//月
		 if(type!=null&&type.equals("1")){
		 	dateString="%Y-%m-%d";
		 }

		 //查询当月中的产品的异常数量
		 List<FbsAbnormalWorkingHours> fbsAbnormalWorkingHoursList=fbsAbnormalWorkingHoursService.getRejectsNumber(dateString);
		 //U8完工数量
//		 List<FbsMomOrderdetail> fbsMomOrderdetailList=iFbsMomOrderdetailService.getQualifiedInQty();
		 List<Map<String,Object>> mapList=new ArrayList<>();
		 if(fbsAbnormalWorkingHoursList!=null
//				 &&fbsMomOrderdetailList!=null
				 ){
		 	for(FbsAbnormalWorkingHours fbsAbnormalWorkingHours:fbsAbnormalWorkingHoursList){
				Map<String,Object> map=new HashMap<>();
				map.put("label",fbsAbnormalWorkingHours.getProduct());
//				map.put("sum1",fbsAbnormalWorkingHours.getRejectsNumberTotal());
				BigDecimal rejectsNumberTotal=new BigDecimal("0.0");
				if(StringUtils.isNotBlank(fbsAbnormalWorkingHours.getRejectsNumberTotal())&&isNumber(fbsAbnormalWorkingHours.getRejectsNumberTotal())){
					rejectsNumberTotal=getDecimal(Double.valueOf(fbsAbnormalWorkingHours.getRejectsNumberTotal()));
				}
				map.put("sum1",fbsAbnormalWorkingHours.getPlannedQuantity().subtract(rejectsNumberTotal));
				map.put("sum2",fbsAbnormalWorkingHours.getPlannedQuantity().doubleValue());
//		 		for(FbsMomOrderdetail fbsMomOrderdetail:fbsMomOrderdetailList){
//		 			//找到对应产品的数量
//		 			if(fbsAbnormalWorkingHours.getProduct().equals(fbsMomOrderdetail.getCinvname())){
//						map.put("sum1",Double.valueOf(String.valueOf(fbsMomOrderdetail.getQualifiedinqty())).intValue()-Integer.parseInt(fbsAbnormalWorkingHours.getRejectsNumberTotal()));
//						map.put("sum2",fbsMomOrderdetail.getQualifiedinqty());
//					}
//				}
				mapList.add(map);
			}
		 }
		 result.setResult(mapList);
		 result.success("操作成功");
		 return result;
	 }

	public BigDecimal getDecimal(Double d){
		BigDecimal decimal= new BigDecimal(d);
		return decimal;
	}

	private boolean isNumber(String str){
		if(isEmpty(str)){
			return false;
		}
		String reg = "\\d+(\\.\\d+)?";
		return str.matches(reg);

	}

	public static String formatDouble5(double d) {
		return String.format("%.2f", d);
	}

	 /**
	 * @Author chenchuang
	 * @Description //TODO 产线看板：当日良率
	 * @Date 2020/10/27 11:32
	 * @Param []
	 * @return org.jeecg.common.api.vo.Result<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
	 */
	 @GetMapping(value = "/getRejectsNumberSameDay")
	 public Result<List<Map<String,Object>>> getRejectsNumberSameDay(){
		 Result<List<Map<String,Object>>> result=new Result<>();
		 //查询当月中的产品的异常数量
		 List<FbsAbnormalWorkingHours> fbsAbnormalWorkingHoursList=fbsAbnormalWorkingHoursService.getRejectsNumberSameDay();
		 //U8完工数量
		 List<FbsMomOrderdetail> fbsMomOrderdetailList=iFbsMomOrderdetailService.getQualifiedInQty();
		 List<Map<String,Object>> mapList=new ArrayList<>();
		 if(fbsAbnormalWorkingHoursList!=null&&fbsMomOrderdetailList!=null){
			 for(FbsAbnormalWorkingHours fbsAbnormalWorkingHours:fbsAbnormalWorkingHoursList){
				 Map<String,Object> map=new HashMap<>();
				 map.put("label",fbsAbnormalWorkingHours.getProduct());
				 map.put("sum1",fbsAbnormalWorkingHours.getRejectsNumberTotal());
				 for(FbsMomOrderdetail fbsMomOrderdetail:fbsMomOrderdetailList){
					 //找到对应产品的数量
					 if(fbsAbnormalWorkingHours.getProduct().equals(fbsMomOrderdetail.getCinvname())){
						 map.put("sum2",fbsMomOrderdetail.getQualifiedinqty());
					 }
				 }
				 mapList.add(map);
			 }
		 }
		 result.setResult(mapList);
		 result.success("操作成功");
		 return result;
	 }


	/**
	* @Author chenchuang
	* @Description //TODO  制造看板：人员出勤率
	* @Date 2020/11/11 13:24
	* @Param []
	* @return org.jeecg.common.api.vo.Result<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
	*/
	 @GetMapping(value = "/getMonthAttendance")
	 public Result<List<Map<String,Object>>> getMonthAttendance(){
		 Result<List<Map<String,Object>>> result=new Result<>();
		 try {
			 List<Map<String,Object>> map=fbsAbnormalWorkingHoursService.getMonthAttendance();
			 result.setResult(map);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }
}
