package org.jeecg.modules.fbsPuArrivalvouch.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.appInterface.FileList;
import org.jeecg.modules.fbsPuArrivalvouch.entity.FbsPuArrivalvouch;
import org.jeecg.modules.fbsPuArrivalvouch.service.IFbsPuArrivalvouchService;

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.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.beans.factory.annotation.Value;
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;

 /**
 * @Title: Controller
 * @Description: 采购到货退货单主表（表头）
 * @author： jeecg-boot
 * @date：   2020-10-21
 * @version： V1.0
 */
@RestController
@RequestMapping("/fbsPuArrivalvouch/fbsPuArrivalvouch")
@Slf4j
public class FbsPuArrivalvouchController {
	@Autowired
	private IFbsPuArrivalvouchService fbsPuArrivalvouchService;
	 @Value("${jeecg.path.upAnomalous}")
	 private String upAnomalous;//异常质量信息图片路径

	 /**
	  * 收料待检(仓库管理看板)
	  * @return
	  */
	 @RequestMapping(value = "/getWatingCheckList")
	 public Result<List<Map<String,Object>>> getWatingCheckList(){
		 Result<List<Map<String,Object>>> result=new Result<>();

		 try {
			 List<Map<String,Object>> map=fbsPuArrivalvouchService.getWatingCheckList();
			 result.setResult(map);
			 result.success("操作成功");

		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }

		 return result;
	 }

     /**
      * 收料待检(仓库管理看板)
      * @return
      */
     @RequestMapping(value = "/getCheckSum")
     public int getCheckSum(){
         return fbsPuArrivalvouchService.getCheckSum();
     }

	 /**
	  * 已到货待入库数据(仓库管理看板)
	  * @return
	  */
	 @RequestMapping(value = "/getWatingInList")
	 public Result<List<Map<String,Object>>> getWatingInList(){
		 Result<List<Map<String,Object>>> result=new Result<>();

		 try {
			 List<Map<String,Object>> map=fbsPuArrivalvouchService.getWatingInList();

			 if(map.size() > 0){
				 int i = 1;
				 for(Map o:map){
					 o.put("index",String.valueOf(i));
					 i++;
				 }

			 }

			 result.setResult(map);
			 result.success("操作成功");

		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }

		 return result;
	 }

	 /**
	  * 已入库数据(仓库管理看板)
	  * @return
	  */
     @RequestMapping(value = "/getInSum")
     public int getInSum(){
         return fbsPuArrivalvouchService.getInSum();
     }










	/**
	  * 分页列表查询
	 * @param fbsPuArrivalvouch
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<IPage<FbsPuArrivalvouch>> queryPageList(FbsPuArrivalvouch fbsPuArrivalvouch,
									  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									  HttpServletRequest req) {
		Result<IPage<FbsPuArrivalvouch>> result = new Result<IPage<FbsPuArrivalvouch>>();
		QueryWrapper<FbsPuArrivalvouch> queryWrapper = QueryGenerator.initQueryWrapper(fbsPuArrivalvouch, req.getParameterMap());
		Page<FbsPuArrivalvouch> page = new Page<FbsPuArrivalvouch>(pageNo, pageSize);
		IPage<FbsPuArrivalvouch> pageList = fbsPuArrivalvouchService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}
	
	/**
	  *   添加
	 * @param fbsPuArrivalvouch
	 * @return
	 */
	@PostMapping(value = "/add")
	public Result<FbsPuArrivalvouch> add(@RequestBody FbsPuArrivalvouch fbsPuArrivalvouch) {
		Result<FbsPuArrivalvouch> result = new Result<FbsPuArrivalvouch>();
		try {
			fbsPuArrivalvouchService.save(fbsPuArrivalvouch);
			result.success("添加成功！");
		} catch (Exception e) {
			e.printStackTrace();
			log.info(e.getMessage());
			result.error500("操作失败");
		}
		return result;
	}
	
	/**
	  *  编辑
	 * @param fbsPuArrivalvouch
	 * @return
	 */
	@PutMapping(value = "/edit")
	public Result<FbsPuArrivalvouch> edit(@RequestBody FbsPuArrivalvouch fbsPuArrivalvouch) {
		Result<FbsPuArrivalvouch> result = new Result<FbsPuArrivalvouch>();
		FbsPuArrivalvouch fbsPuArrivalvouchEntity = fbsPuArrivalvouchService.getById(fbsPuArrivalvouch.getId());
		if(fbsPuArrivalvouchEntity==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = fbsPuArrivalvouchService.updateById(fbsPuArrivalvouch);
			//TODO 返回false说明什么？
			if(ok) {
				result.success("修改成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *   通过id删除
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delete")
	public Result<FbsPuArrivalvouch> delete(@RequestParam(name="id",required=true) String id) {
		Result<FbsPuArrivalvouch> result = new Result<FbsPuArrivalvouch>();
		FbsPuArrivalvouch fbsPuArrivalvouch = fbsPuArrivalvouchService.getById(id);
		if(fbsPuArrivalvouch==null) {
			result.error500("未找到对应实体");
		}else {
			boolean ok = fbsPuArrivalvouchService.removeById(id);
			if(ok) {
				result.success("删除成功!");
			}
		}
		
		return result;
	}
	
	/**
	  *  批量删除
	 * @param ids
	 * @return
	 */
	@DeleteMapping(value = "/deleteBatch")
	public Result<FbsPuArrivalvouch> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		Result<FbsPuArrivalvouch> result = new Result<FbsPuArrivalvouch>();
		if(ids==null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		}else {
			this.fbsPuArrivalvouchService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}
	
	/**
	  * 通过id查询
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<FbsPuArrivalvouch> queryById(@RequestParam(name="id",required=true) String id) {
		Result<FbsPuArrivalvouch> result = new Result<FbsPuArrivalvouch>();
		FbsPuArrivalvouch fbsPuArrivalvouch = fbsPuArrivalvouchService.getById(id);
		if(fbsPuArrivalvouch==null) {
			result.error500("未找到对应实体");
		}else {
			result.setResult(fbsPuArrivalvouch);
			result.setSuccess(true);
		}
		return result;
	}

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

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FbsPuArrivalvouch> pageList = fbsPuArrivalvouchService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "采购到货退货单主表（表头）列表");
      mv.addObject(NormalExcelConstants.CLASS, FbsPuArrivalvouch.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<FbsPuArrivalvouch> listFbsPuArrivalvouchs = ExcelImportUtil.importExcel(file.getInputStream(), FbsPuArrivalvouch.class, params);
              for (FbsPuArrivalvouch fbsPuArrivalvouchExcel : listFbsPuArrivalvouchs) {
                  fbsPuArrivalvouchService.save(fbsPuArrivalvouchExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFbsPuArrivalvouchs.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/27 14:50
  * @Param []
  * @return org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.Object>>
  */
  @GetMapping(value = "/getPassRateByVendor")
  public Result<Map<String,Object>> getPassRateByVendor(){
	  Result<Map<String,Object>> result=new Result<>();
	  try {
		  Map<String,Object> map=fbsPuArrivalvouchService.getPassRateByVendor();
		  result.setResult(map);
		  result.success("操作成功");
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败："+e.getMessage());
	  }
	  return result;

  }

  /**
  * @Author chenchuang
  * @Description //TODO 品质看板：当天到货批数
  * @Date 2020/10/27 16:06
  * @Param []
  * @return org.jeecg.common.api.vo.Result<java.lang.Integer>
  */
  @GetMapping(value = "/getTodayArriveSum")
  public Result<Integer> getTodayArriveSum(){
	  Result<Integer> result=new Result<>();
	  try {
		  Integer total=fbsPuArrivalvouchService.getTodayArriveSum();
		  if(total==null){
			  total=0;
		  }
		  result.setResult(total);
		  result.success("操作成功");
	  } catch (Exception e) {
		  e.printStackTrace();
		  result.error500("操作失败："+e.getMessage());
	  }
	  return result;
  }

	 /**
	  * @Author chenchuang
	  * @Description //TODO 品质看板:未来3天的到货总批数
	  * @Date 2020/10/27 16:06
	  * @Param []
	  * @return org.jeecg.common.api.vo.Result<java.lang.Integer>
	  */
	 @GetMapping(value = "/getWillArriveSum")
	 public Result<Integer> getWillArriveSum(){
		 Result<Integer> result=new Result<>();
		 try {
			 Integer total=fbsPuArrivalvouchService.getWillArriveSum();
			 if(total==null){
				 total=0;
			 }
			 result.setResult(total);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }

	 /**
	  * @Author chenchuang
	  * @Description //TODO 品质看板:当月到货总批数
	  * @Date 2020/10/27 16:06
	  * @Param []
	  * @return org.jeecg.common.api.vo.Result<java.lang.Integer>
	  */
	 @GetMapping(value = "/getThisMonthArriveSum")
	 public Result<Integer> getThisMonthArriveSum(){
		 Result<Integer> result=new Result<>();
		 try {
			 Integer total=fbsPuArrivalvouchService.getThisMonthArriveSum();
			 if(total==null){
				 total=0;
			 }
			 result.setResult(total);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 品质看板:未入库批数
	 * @Date 2020/10/28 16:02
	 * @Param []
	 * @return org.jeecg.common.api.vo.Result<java.lang.Integer>
	 */
	 @GetMapping(value = "/getNotInSum")
	 public Result<Integer> getNotInSum(){
		 Result<Integer> result=new Result<>();
		 try {
			 Integer total=fbsPuArrivalvouchService.getNotInSum();
			 if(total==null){
				 total=0;
			 }
			 result.setResult(total);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 品质看板：当月供检验合格率
	 * @Date 2020/10/28 16:05
	 * @Param []
	 * @return org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.Object>>
	 */
	 @GetMapping(value = "/getCheckRateByBatchno")
	 public Result<Map<String,Object>> getCheckRateByBatchno(){
		 Result<Map<String,Object>> result=new Result<>();
		 try {
			 Map<String,Object> map=fbsPuArrivalvouchService.getCheckRateByBatchno();
			 result.setResult(map);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;

	 }

	 /**
	 * @Author chenchuang
	 * @Description //TODO 品质看板质量异常信息
	 * @Date 2020/11/5 19:53
	 * @Param []
	 * @return org.jeecg.common.api.vo.Result<java.util.List<java.util.Map<java.lang.String,java.lang.Object>>>
	 */
	 @GetMapping(value = "/getQualityUnpassList")
	 public Result<List<Map<String,Object>>> getQualityUnpassList(){
		 Result<List<Map<String,Object>>> result=new Result<>();
		 try {
			 List<Map<String,Object>> map=fbsPuArrivalvouchService.getQualityUnpassList();

			 for(Map<String,Object> m:map){
				 ArrayList<String> list = new ArrayList<>();
				 ArrayList<String> list2 = new ArrayList<>();
				 String par = FileList.getAllFileName(upAnomalous+m.get("ccheckcode"),list);
				 if(par.equals("true")){

				 	for(String L:list){
				 		L = m.get("ccheckcode")+ "/" + L;
						list2.add(L);
					}
				 	m.put("images",list2);
				 }
			 }

			 result.setResult(map);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }

}
