package org.jeecg.modules.fbsMomOrder.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.fbsInventory.entity.FbsInventory;
import org.jeecg.modules.fbsInventory.service.IFbsInventoryService;
import org.jeecg.modules.fbsMomOrder.entity.FbsMomOrder;
import org.jeecg.modules.fbsMomOrder.service.IFbsMomOrderService;

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.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.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-16
 * @version： V1.0
 */
@RestController
@RequestMapping("/fbsMomOrder/fbsMomOrder")
@Slf4j
public class FbsMomOrderController {
	@Autowired
	private IFbsMomOrderService fbsMomOrderService;
	@Autowired
	private IFbsWorkshopDispatchListService iFbsWorkshopDispatchListService;
	@Autowired
	private IFbsInventoryService iFbsInventoryService;

	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;

	 /**
	  * 查询任务数据（E-SOP看板）
	  * @return
	  */
	@RequestMapping(value = "getEsopTaskList")
	public Result<List<Map<String,Object>>> getEsopTaskList(){

		Result<List<Map<String,Object>>> result = new Result<>();

		try {
//			List<Map<String,Object>> map = fbsMomOrderService.getEsopTaskList();

			List<Map<String,Object>> map = iFbsWorkshopDispatchListService.getEsopList();
			ArrayList<String> list = new ArrayList<>();
//			String par = FileList.getAllFileName(upLoadPath,list);
			for(Map<String,Object> mapEn:map){
//				//获取图纸号
//				List<String> drawingCodeList=new ArrayList<>();
//				//母件图纸
//				FbsInventory fbsInventory=iFbsInventoryService.getInventory(mapEn.get("materialCode").toString());
//				if(fbsInventory!=null){
//					drawingCodeList.add(fbsInventory.getCinvdefine6());
//				}
//				//子件图纸号
//				List<FbsInventory> fbsInventoryList=iFbsInventoryService.getDrawingCode(mapEn.get("orderSheetCode").toString());
//				if(fbsInventoryList!=null){
//					for(FbsInventory fbsInventory1:fbsInventoryList){
//						drawingCodeList.add(fbsInventory1.getCinvdefine6());
//					}
//				}
//				boolean isQuery=false;
//				for(String drawingCode:drawingCodeList){
//					for (String o:list){
//						//是否找到图纸号
//						if(drawingCode!=null&&o.indexOf(drawingCode)>=0){
//							isQuery=true;
//						}
//					}
//				}
				String par = FileList.getAllFileName(upLoadPath+mapEn.get("materialCode"),list);
				if(par.equals("false")){//没有文件
					mapEn.put("color","darkgray");
				}else{//有文件
					mapEn.put("color","goldenrod");
				}
			}
			result.setResult(map);
			result.success("操作成功");

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

		return result;
	}









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

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

      //Step.2 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      List<FbsMomOrder> pageList = fbsMomOrderService.list(queryWrapper);
      //导出文件名称
      mv.addObject(NormalExcelConstants.FILE_NAME, "生产订单列表");
      mv.addObject(NormalExcelConstants.CLASS, FbsMomOrder.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<FbsMomOrder> listFbsMomOrders = ExcelImportUtil.importExcel(file.getInputStream(), FbsMomOrder.class, params);
              for (FbsMomOrder fbsMomOrderExcel : listFbsMomOrders) {
                  fbsMomOrderService.save(fbsMomOrderExcel);
              }
              return Result.ok("文件导入成功！数据行数：" + listFbsMomOrders.size());
          } catch (Exception e) {
              log.error(e.getMessage());
              return Result.error("文件导入失败！");
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.ok("文件导入失败！");
  }

}
