package org.jeecg.modules.appInterface.controller;

import java.io.File;
import java.io.InputStream;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
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 javax.xml.namespace.QName;
import javax.xml.ws.Service;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
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.appInterface.ImageUtil;
import org.jeecg.modules.appInterface.ResHttpStatus;
import org.jeecg.modules.appInterface.entity.FbsWorkingStatistics;
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.appInterface.service.IFbsWorkingStatisticsService;
import org.jeecg.modules.fbsBasedate.entity.FbsPersonnel;
import org.jeecg.modules.fbsBasedate.service.IFbsPersonnelService;
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.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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-15
 * @version： V1.0
 */
@RestController
@RequestMapping("/workingStatistics/fbsWorkingStatistics")
@Slf4j
public class FbsWorkingStatisticsController {
	@Autowired
	private IFbsWorkingStatisticsService fbsWorkingStatisticsService;
	 @Autowired
	 private IFbsWorkshopDispatchListService fbsWorkshopDispatchListService;
	 @Autowired
	 private IFbsPersonService fbsPersonService;
	 @Autowired
	 private IFbsPersonnelService iFbsPersonnelService;
	 @Value("${jeecg.path.upload}")
	 private String upLoadPath;
	 @Value("${jeecg.path.upvedioAAA}")
	 private String upVedioAAA;
	 @Value("${jeecg.path.upvedioABB}")
	 private String upVedioABB;
	 @Value("${jeecg.path.uppersonnel}")
	 private String upPersonnel;

	 public static void main1(String[] srg) {
		 String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
		 //加载JDBC驱动
		 String dbURL = "jdbc:sqlserver://47.103.119.148;DatabaseName=UFDATA_100_2019";
		 //连接服务器和数据库
		 String userName = "sa"; //默认用户名
		 String userPwd = "Wakeup@123"; //密码
		 Connection dbConn;
		 PreparedStatement ps = null;
		 ResultSet rs = null;
		 String targetPath = "D:/img/1.png";
		 try {
			 Class.forName(driverName);
			 dbConn = DriverManager.getConnection(dbURL, userName, userPwd);

			 String sql = "select * from VoucherAccessories where voucherID ='1000000003'";
			 ps = dbConn.prepareStatement(sql);
//			 ps.setInt(1, 1);
			 rs = ps.executeQuery();
			 while (rs.next()) {
				 InputStream in = rs.getBinaryStream("FileContent");
				 ImageUtil.readBin2Image(in, targetPath);
			 }

			 System.out.println("Connection Successful!");
			 //如果连接成功 控制台输出Connection  Successful!
		 } catch (Exception e) {
			 e.printStackTrace();
		 }
	 }



	 /**
	  * 开工接口
	  * @param entity
	  * @return
	  */
	 @RequestMapping(value = "/startOperation")
	 @ResponseBody
	 public ResponseEntity<ResHttpStatus> startOperation(FbsWorkingStatistics entity){
		 ResHttpStatus res = new ResHttpStatus();
		 if(entity == null){
			 res.setCode("1");
			 res.setMsg("参数不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isNotBlank(entity.getId())){
			 entity.setId(null);
		 }
		 if(StringUtils.isBlank(entity.getPersonnelCode())){
			 res.setCode("1");
			 res.setMsg("人员编码不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getPersonnelName())){
			 res.setCode("1");
			 res.setMsg("人员名称不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getOrderNumber())){
			 res.setCode("1");
			 res.setMsg("订单号不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		if(StringUtils.isBlank(entity.getRowNumber())){
			 res.setCode("1");
			 res.setMsg("行号不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 //状态（0初始，1接单,2暂停，3完成）
		 QueryWrapper<FbsWorkshopDispatchList> ypffscSaleorderBQueryWrapper = new QueryWrapper<>();
		 ypffscSaleorderBQueryWrapper.like("personnel_id_u8", entity.getPersonnelCode()).eq("del_flag", 0);
		 ypffscSaleorderBQueryWrapper.eq("production_order_number_name", entity.getOrderNumber());
//		 ypffscSaleorderBQueryWrapper.in("state", 0,1,2,3);
		 List<FbsWorkshopDispatchList> list = fbsWorkshopDispatchListService.list(ypffscSaleorderBQueryWrapper);
		 if(list.size() < 1){
			 res.setCode("1");
			 res.setMsg("该订单还没有派工"+entity.getOrderNumber());
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
//		 if(list.get(0).getPlannedQuantity().doubleValue()==Double.valueOf(list.get(0).getLatestCompletedQuantity())){
//			 res.setCode("1");
//			 res.setMsg("该订单计划数量已经全部入库"+entity.getOrderNumber());
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }

		 QueryWrapper<FbsWorkingStatistics> workingStatisticsQueryWrapper = new QueryWrapper<>();
		 workingStatisticsQueryWrapper.eq("personnel_Code", entity.getPersonnelCode()).eq("del_flag", 0);
		 workingStatisticsQueryWrapper.eq("order_number", entity.getOrderNumber());
		 workingStatisticsQueryWrapper.eq("final_State", 1);
		 List<FbsWorkingStatistics> list2 = fbsWorkingStatisticsService.list(workingStatisticsQueryWrapper);
		 if(list2.size()>0){
			 res.setCode("1");
			 res.setMsg("该订单已开工，请勿再次操作"+entity.getOrderNumber());
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

		 FbsWorkshopDispatchList workshopDispatchList = list.get(0);
		 //0初始，1接单,2暂停，3完成
//		 if(StringUtils.isNotBlank(workshopDispatchList.getState()) && !workshopDispatchList.getState().equals("0") &&
//                 !workshopDispatchList.getState().equals("2")&&
//				 !workshopDispatchList.getState().equals("3")){
//             res.setCode("1");
//             res.setMsg("该订单已开工，请勿再次操作"+entity.getOrderNumber());
//             return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//         }

		 entity.setStartDate(workshopDispatchList.getPlannedStartTime());//计划时间
		 entity.setEndDate(workshopDispatchList.getPlannedEndTime());//计划时间
		 entity.setMaterielCode(workshopDispatchList.getProductId());//物料编码
		 entity.setMaterielName(workshopDispatchList.getProduct());//物料名称

		 entity.setFirstTime(entity.getCutTime());//获取当前时间
		 entity.setFinalInfo("开工");
		 entity.setFinalState("1");//完结状态（1-开工，2-下岗/暂停，3-实时报工）
		 entity.setPkWorkshopDispatchList(list.get(0).getId());


		 fbsWorkingStatisticsService.save(entity);
         fbsWorkshopDispatchListService.updateState("1",list.get(0).getId());

		 res.setCode("0");
		 res.setMsg("成功");
		 res.setData(entity);
		 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
	 }



	 /**
	  * 下岗/暂停
	  * @param entity
	  * @return
	  */
	 @RequestMapping(value = "/suspendOperation")
	 @ResponseBody
	 public ResponseEntity<ResHttpStatus> suspendOperation(FbsWorkingStatistics entity){
		 ResHttpStatus res = new ResHttpStatus();

		 long nd = 1000 * 24 * 60 * 60;
		 long nh = 1000 * 60 * 60;
		 long nm = 1000 * 60;

		 if(entity == null){
			 res.setCode("1");
			 res.setMsg("参数不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

		 //完结状态（1-开工，2-下岗/暂停，3-实时报工）
		 QueryWrapper<FbsWorkingStatistics> workingStatisticsQueryWrapper = new QueryWrapper<>();
		 workingStatisticsQueryWrapper.eq("personnel_Code", entity.getPersonnelCode()).eq("del_flag", 0);
		 workingStatisticsQueryWrapper.eq("order_number", entity.getOrderNumber());
		 workingStatisticsQueryWrapper.eq("final_State", 1);

		 List<FbsWorkingStatistics> list2 = fbsWorkingStatisticsService.list(workingStatisticsQueryWrapper);

		 if(list2.size() < 1){
			 res.setCode("1");
			 res.setMsg("人员编码或者订单号不正确");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }else{
//			 FbsWorkingStatistics par = fbsWorkingStatisticsService.getById(entity.getId());
			 FbsWorkingStatistics par = list2.get(0);
			 if(par != null){
			 	Date firstTime = par.getFirstTime();
//				 long diff = new Date().getTime() - firstTime.getTime();
				 long diff = entity.getCutTime().getTime() - firstTime.getTime();
				 // 计算差多少天
//				 long day = diff / nd;
				 // 计算差多少小时
				 long hour = diff % nd / nh;
				 // 计算差多少分钟
				 long min = diff / nm;
				 BigDecimal aa = new BigDecimal(min).divide(new BigDecimal("60"), 2, BigDecimal.ROUND_HALF_UP);
				 entity.setWorkingHours(aa);
			 }
		 }
		 if(StringUtils.isBlank(entity.getPersonnelCode())){
			 res.setCode("1");
			 res.setMsg("人员编码不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getPersonnelName())){
			 res.setCode("1");
			 res.setMsg("人员名称不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getOrderNumber())){
			 res.setCode("1");
			 res.setMsg("订单号不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		//状态（0初始，1接单,2暂停，3完成）
		 QueryWrapper<FbsWorkshopDispatchList> ypffscSaleorderBQueryWrapper = new QueryWrapper<>();
		 ypffscSaleorderBQueryWrapper.like("personnel_id_u8", entity.getPersonnelCode()).eq("del_flag", 0);
		 ypffscSaleorderBQueryWrapper.eq("production_order_number_name", entity.getOrderNumber());
//		 ypffscSaleorderBQueryWrapper.eq("state", 1);

		 List<FbsWorkshopDispatchList> list = fbsWorkshopDispatchListService.list(ypffscSaleorderBQueryWrapper);
//		 if(list.size() < 1){
//			 res.setCode("1");
//			 res.setMsg("该订单还没有上岗"+entity.getOrderNumber());
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }


		 FbsWorkshopDispatchList workshopDispatchList = list.get(0);

         //状态（0初始，1接单,2暂停，3完成）
         if(StringUtils.isNotBlank(workshopDispatchList.getState()) && workshopDispatchList.getState().equals("3")){
             res.setCode("1");
             res.setMsg("该订单目前不在可暂停状态，无法暂停"+entity.getOrderNumber());
             return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
         }
		 entity.setStartDate(workshopDispatchList.getPlannedStartTime());//计划时间
		 entity.setEndDate(workshopDispatchList.getPlannedStartTime());//计划时间
		 entity.setFinalTime(entity.getCutTime());//获取当前时间
		 entity.setFinalInfo("下岗/暂停");
		 entity.setFinalState("2");//完结状态（1-开工，2-下岗/暂停，3-实时报工）
		 entity.setPkWorkshopDispatchList(list.get(0).getId());
		 entity.setId(list2.get(0).getId());
		 fbsWorkingStatisticsService.updateById(entity);
         fbsWorkshopDispatchListService.updateState("2",entity.getPkWorkshopDispatchList());

		 QueryWrapper<FbsWorkingStatistics> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("pk_Workshop_Dispatch_List", entity.getPkWorkshopDispatchList()).eq("del_flag", 0);
		 List<FbsWorkingStatistics> list1 = fbsWorkingStatisticsService.list(queryWrapper);
		 BigDecimal allHors = new BigDecimal("0");
		 BigDecimal allNum = new BigDecimal("0");
		 for (FbsWorkingStatistics o:list1){
			 if(o.getWorkingHours()!=null){
				 allHors = allHors.add(o.getWorkingHours());
			 }
			 if(StringUtils.isNotBlank(o.getQualifiedNumber())){
				 allNum = allNum.add(new BigDecimal(o.getQualifiedNumber()));
			 }
		 }
		 if(allNum.compareTo(new BigDecimal(0)) == 0){
			 fbsWorkshopDispatchListService.writeBackManHoursCompleted(allHors.toString(),null,entity.getPkWorkshopDispatchList());
		 }else{
		 	 fbsWorkshopDispatchListService.writeBackManHoursCompleted(allHors.toString(),allNum.toString(),entity.getPkWorkshopDispatchList());
		 }

		 res.setCode("0");
		 res.setMsg("成功");
		 res.setData(entity);
		 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
	 }

	 /**
	  * 实时报工
	  * @param entity
	  * @return
	  */
	 @RequestMapping(value = "/finishDoing")
	 @ResponseBody
	 public ResponseEntity<ResHttpStatus> finishDoing(FbsWorkingStatistics entity){
		 ResHttpStatus res = new ResHttpStatus();

		 long nd = 1000 * 24 * 60 * 60;
		 long nh = 1000 * 60 * 60;
		 long nm = 1000 * 60;

		 if(entity == null){
			 res.setCode("1");
			 res.setMsg("参数不能为空 ");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getPersonnelCode())){
			 res.setCode("1");
			 res.setMsg("人员编码不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getPersonnelName())){
			 res.setCode("1");
			 res.setMsg("人员名称不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

//		 if(StringUtils.isBlank(entity.getQualifiedNumber())){
//			 res.setCode("1");
//			 res.setMsg("合格数量不能为空");
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }
		 if(StringUtils.isBlank(entity.getBatchCode())){
			 res.setCode("1");
			 res.setMsg("批次号不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

//		 String[] batchCode = entity.getBatchCode().split(",");
//		 if(batchCode.length > 0){
//			 entity.setQualifiedNumber(String.valueOf(batchCode.length));
//		 }

		 if(StringUtils.isBlank(entity.getState())){
			 res.setCode("1");
			 res.setMsg("状态不能为空0保存，1提交");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if(StringUtils.isBlank(entity.getOrderNumber())){
			 res.setCode("1");
			 res.setMsg("订单号不能为空");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

		 //完结状态（1-开工，2-下岗/暂停，3-实时报工）
		 QueryWrapper<FbsWorkingStatistics> workingStatisticsQueryWrapper = new QueryWrapper<>();
		 workingStatisticsQueryWrapper.eq("personnel_Code", entity.getPersonnelCode()).eq("del_flag", 0);
		 workingStatisticsQueryWrapper.eq("order_number", entity.getOrderNumber());
		 workingStatisticsQueryWrapper.in("final_State", 1);

		 List<FbsWorkingStatistics> list2 = fbsWorkingStatisticsService.list(workingStatisticsQueryWrapper);
		 if(list2.size() < 1){
			 res.setCode("1");
			 res.setMsg("没有查到可以报工的数据");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 FbsWorkingStatistics par = list2.get(0);
		 if(par != null){
			if(par.getState().equals("1")){
				res.setCode("1");
				res.setMsg("该次已完成报工入库，请勿再次操作");
				return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
			}

			if( par.getFinalTime() == null){
				Date firstTime = par.getFirstTime();
				long diff = new Date().getTime() - firstTime.getTime();
				// 计算差多少分钟
				long min = diff / nm;
				BigDecimal aa = new BigDecimal(min).divide(new BigDecimal("60"), 2, BigDecimal.ROUND_HALF_UP);
				if(aa.doubleValue()>8.0){//超过八小时按照8小时计算
					aa=new BigDecimal("8.0");
				 }
				entity.setWorkingHours(aa);
				entity.setFinalTime(new Date());//获取当前时间

			}

		 }else{
			 res.setCode("1");
			 res.setMsg("数据异常，没有查询到数据");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

//		 QueryWrapper<FbsWorkshopDispatchList> ypffscSaleorderBQueryWrapper = new QueryWrapper<>();
//		 //状态（0初始，1接单,2暂停，3完成）
//		 ypffscSaleorderBQueryWrapper.eq("personnel_id_u8", entity.getPersonnelCode()).eq("del_flag", 0);
//		 ypffscSaleorderBQueryWrapper.eq("production_order_number_id", entity.getOrderNumber());
//		 ypffscSaleorderBQueryWrapper.eq("state", 1);
//
//		 List<FbsWorkshopDispatchList> list = fbsWorkshopDispatchListService.list(ypffscSaleorderBQueryWrapper);
//		 if(list.size() < 1){
//			 res.setCode("1");
//			 res.setMsg("该订单还没有上岗"+entity.getOrderNumber());
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }
//		 FbsWorkshopDispatchList workshopDispatchList = list.get(0);
		 FbsWorkshopDispatchList workshopDispatchList = fbsWorkshopDispatchListService.getById(par.getPkWorkshopDispatchList());
         if(workshopDispatchList == null){
			 res.setCode("1");
			 res.setMsg("该订单还没有上岗"+entity.getOrderNumber());
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 //状态（0初始，1接单,2暂停，3完成）
//		 if(workshopDispatchList.getState().equals("0") || workshopDispatchList.getState().equals("2")){
//			 res.setCode("1");
//			 res.setMsg("该订单目前正在进行中，无法报工"+entity.getOrderNumber());
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }

		 entity.setStartDate(workshopDispatchList.getPlannedStartTime());//计划时间
		 entity.setEndDate(workshopDispatchList.getPlannedStartTime());//计划时间

		 entity.setFinalInfo("实时报工");
		 entity.setPkWorkshopDispatchList(workshopDispatchList.getId());
		 entity.setFinalState("3");//完结状态（1-开工，2-下岗/暂停，3-实时报工）
		 entity.setId(list2.get(0).getId());


		 fbsWorkingStatisticsService.updateById(entity);
         fbsWorkshopDispatchListService.updateState("3",entity.getPkWorkshopDispatchList());

		 QueryWrapper<FbsWorkingStatistics> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("pk_Workshop_Dispatch_List", entity.getPkWorkshopDispatchList()).eq("del_flag", 0);
		 List<FbsWorkingStatistics> list1 = fbsWorkingStatisticsService.list(queryWrapper);
		 BigDecimal allHors = new BigDecimal("0");
		 BigDecimal allNum = new BigDecimal("0");
		 for (FbsWorkingStatistics o:list1){
			 if(o.getWorkingHours()!=null){
				 allHors = allHors.add(o.getWorkingHours());
			 }
			 if(StringUtils.isNotBlank(o.getQualifiedNumber())){
				 allNum = allNum.add(new BigDecimal(o.getQualifiedNumber()));
			 }
		 }
//		 if(allHors.doubleValue()>8.0){//超过八小时按照8小时计算
//			 allHors=new BigDecimal("8.0");
//		 }

         if(entity.getState().equals("1")){
			 //把数据传入u8数据库
			 Object[] objectR=saveU8(entity,workshopDispatchList,allHors);
			 Map map= JSONObject.parseObject(objectR[0].toString());
			 if(map.get("Result").equals("F")){
				 FbsWorkingStatistics fbsWorkingStatistics=new FbsWorkingStatistics();
				 fbsWorkingStatistics.setId(list2.get(0).getId());
				 fbsWorkingStatistics.setState("0");
				 fbsWorkingStatistics.setFinalState("1");
				 fbsWorkingStatistics.setWorkingHours(new BigDecimal("0.0"));
				 fbsWorkingStatistics.setQualifiedNumber("0");
				 fbsWorkingStatisticsService.updateById(fbsWorkingStatistics);
				 fbsWorkshopDispatchListService.updateState("1",entity.getPkWorkshopDispatchList());
				 res.setCode("1");
				 res.setMsg(map.get("Description").toString());
				 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
			 }
		 }
		 fbsWorkshopDispatchListService.writeBackManHoursCompleted(allHors.toString(),allNum.toString(),entity.getPkWorkshopDispatchList());

         res.setCode("0");
		 res.setMsg("成功");
		 res.setData(entity);
		 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
	 }

	//入库接口
	 public Object[] saveU8(FbsWorkingStatistics entity,FbsWorkshopDispatchList workshopDispatchList,BigDecimal allHors){
		 Object[] mapR=new Object[]{};
	 	if(StringUtils.isNotBlank(entity.getBatchCode())){
			List<Map<String,Object>> mapList=new ArrayList<>();
			//获取批号json数组
			JSONArray jsonArray = JSONArray.parseArray(entity.getBatchCode());
			for(int i=0;i<jsonArray.size();i++){
				//明细
				Map<String,Object> itemMap=new LinkedHashMap<>();
				itemMap.put("CINVCODE",workshopDispatchList.getProductId());//成品存货编码
				itemMap.put("IQUANTITY",jsonArray.getJSONObject(i).get("value"));//数量
				itemMap.put("MOCODE",workshopDispatchList.getProductionOrderNumberName());//订单号
				itemMap.put("MOROWMO",entity.getRowNumber());//行号
				itemMap.put("CBATCH",jsonArray.getJSONObject(i).get("key"));//批号
				itemMap.put("cDefine27",allHors.doubleValue());//实际工时
				Double number=Double.valueOf(entity.getQualifiedNumber());//数量
				Double working=Double.valueOf(workshopDispatchList.getStandardWorkingHoursZ());//U8标准工时
				DecimalFormat df = new DecimalFormat("#.00");
				String workingTatol=df.format(number*working);
				itemMap.put("cDefine26",workingTatol);//实际总工时
				mapList.add(itemMap);
			}

//			String[] batchCodes=entity.getBatchCode().split(",");//解析逗号分隔的批号
//			for(String batchCode:batchCodes){
//				int i=1;
//				//明细
//				Map<String,Object> itemMap=new LinkedHashMap<>();
//				itemMap.put("CINVCODE",workshopDispatchList.getProductId());//成品存货编码
//				itemMap.put("IQUANTITY",1);//数量
//				itemMap.put("MOCODE",workshopDispatchList.getProductionOrderNumberName());//订单号
//				itemMap.put("MOROWMO",entity.getRowNumber());//行号
//				itemMap.put("CBATCH",batchCode);//批号
//				itemMap.put("cDefine27",allHors.doubleValue());//实际工时
//				Double number=Double.valueOf(entity.getQualifiedNumber());//数量
//				Double working=Double.valueOf(workshopDispatchList.getStandardWorkingHoursZ());//U8标准工时
//				DecimalFormat df = new DecimalFormat("#.00");
//				String workingTatol=df.format(number*working);
//				itemMap.put("cDefine26",workingTatol);//实际总工时
//				mapList.add(itemMap);
//				i++;
//			}
			//表头
			Map<String,Object> map=new LinkedHashMap<>();
			map.put("CSTORENAME","100");//账套号
			Random random = new Random();
			int nextInt = random.nextInt(9000000);
			nextInt=nextInt+1000000;
			String str=nextInt+"";
			map.put("CVOUCHCODE",str);//单号UUID.randomUUID()
			Date date=new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			map.put("DDATE",sdf.format(date));//入库日期
			map.put("CWHCODE","01");//仓库编码
			map.put("CDEPCODE","07");//部门编码
			map.put("CMAKER",entity.getPersonnelName());//制单人
			map.put("CRDCODE","103");//入库类型编码
			map.put("DETAILList",mapList);
			//调用WebService接口
			mapR=getWebService(map);
		}
		return mapR;
	 }

	 //调用WebService接口
	 public Object[] getWebService(Map<String,Object> mapR) {
//		 if (args.length < 1) {
//			 args = new String[]{""};
//		 }
		 String jsonObject = JSONUtils.toJSONString(mapR);
		 System.out.println(jsonObject);
		 // 创建动态客户端
		 JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//		 Client client = dcf.createClient("http://10.1.191.191:8090/WebService.asmx");
		 Client client = dcf.createClient("http://47.103.119.148:8090/WebService.asmx?WSDL");
		 // 需要密码的情况需要加上用户名和密码
		 // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,PASS_WORD));
		 // 命名空间，方法名
		 QName name = new QName("http://tempuri.org/", "U8_CreateRdrecord10");
		 HashMap<String, Object> map = new HashMap<>();
		 Object[] objectR=new Object[]{};
		 try {
			 // invoke("方法名",参数1,参数2,参数3....);
			 Object[] objects = client.invoke(name, jsonObject);
			 map.put("result", objects);
			 System.out.println(map.get("result"));
			 System.out.println(Arrays.toString(objects));
			 objectR=objects;
			 return objectR;
		 } catch (java.lang.Exception e) {
			 e.printStackTrace();
			 map.put("result", "接口调用异常");
			 return objectR;
		 }
	 }

	 /**
	  * 通过人员编码查询人员信息
	  * @param userId
	  * @return
	  */

	 @RequestMapping(value = "getPersonByCode")
	 @ResponseBody
	 public ResponseEntity<ResHttpStatus> getPersonByCode(String userId){

		 ResHttpStatus res = new ResHttpStatus();
		 if(StringUtils.isBlank(userId)){
			 res.setCode("1");
			 res.setMsg("人员编码不能为空-userId");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
//		 List<FbsPerson> entity = fbsPersonService.getPerByCode(userId);
//
//		 if(entity.size() < 1){
//			 res.setCode("1");
//			 res.setMsg("人员编码不正确"+userId);
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }
//
//		 Map<String,String> map = new HashMap<>();
//		 map.put("userCode",entity.get(0).getCpersoncode());
//		 map.put("realName",entity.get(0).getCpersonname());


		 //web
		 LambdaQueryWrapper<FbsPersonnel> lambdaQueryWrapper=new LambdaQueryWrapper<>();
		 lambdaQueryWrapper.eq(FbsPersonnel::getPersonnelCode,userId);
		 lambdaQueryWrapper.eq(FbsPersonnel::getDelFlag,"0");
		 List<FbsPersonnel> fbsPersonnelList=iFbsPersonnelService.list(lambdaQueryWrapper);

		 if(fbsPersonnelList.size() < 1){
			 res.setCode("1");
			 res.setMsg("人员编码不正确"+userId);
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 Map<String,String> map = new HashMap<>();
		 map.put("userCode",fbsPersonnelList.get(0).getPersonnelCode());
		 map.put("realName",fbsPersonnelList.get(0).getPersonnelName());

		 res.setCode("0");
		 res.setMsg("成功");
		 res.setData(map);

		 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
	 }

	 /**
	  * 根据工单id（条码）获取工单信息
	  * @param sheetId
	  * @return
	  */
	 @RequestMapping(value = "getOrderBySheetId")
	 @ResponseBody
	 public ResponseEntity<ResHttpStatus> getOrderBySheetId(String sheetId,String userId) {

		 ResHttpStatus res = new ResHttpStatus();
		 if (StringUtils.isBlank(sheetId)) {
			 res.setCode("1");
			 res.setMsg("订单号不能为空-sheetId");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
		 if (StringUtils.isBlank(userId)) {
			 res.setCode("1");
			 res.setMsg("人员编码不能为空-userId");
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }
//		 QueryWrapper<FbsWorkingStatistics> queryWrapper = new QueryWrapper<>();
//		 queryWrapper.eq("order_number", sheetId).eq("del_flag", 0);
//		 queryWrapper.eq("personnel_code", userId);
//		 List<FbsWorkingStatistics> list = fbsWorkingStatisticsService.list(queryWrapper);
//		 if(list.size() < 1){
//			 res.setCode("1");
//			 res.setMsg("订单号或人员编码不正确"+sheetId);
//			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
//		 }
//
//		 FbsWorkingStatistics entity = list.get(0);
//		 Map<String,Object> map = new HashMap<>();
//		 map.put("orderCode",entity.getOrderNumber());
//		 map.put("rowNumber",entity.getRowNumber());
//		 map.put("materialCode",entity.getMaterielCode());
//		 map.put("materialName",entity.getMaterielName());
//		 map.put("startDate",entity.getStartDate());
//		 map.put("endDate",entity.getEndDate());

		 QueryWrapper<FbsWorkshopDispatchList> queryWrapper = new QueryWrapper<>();
		 queryWrapper.eq("production_order_number_name", sheetId).eq("del_flag", 0);
		 queryWrapper.like("personnel_id_u8", userId);
		 List<FbsWorkshopDispatchList> list = fbsWorkshopDispatchListService.list(queryWrapper);
		 if(list.size() < 1){
			 res.setCode("1");
			 res.setMsg("订单号或人员编码不正确"+sheetId);
			 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);
		 }

		 FbsWorkshopDispatchList entity = list.get(0);
		 Map<String,Object> map = new HashMap<>();
		 map.put("orderCode",entity.getProductionOrderNumberName());
		 map.put("rowNumber",entity.getRowNumber());
		 map.put("materialCode",entity.getProductId());
		 map.put("materialName",entity.getProduct());
		 map.put("startDate",entity.getPlannedStartTime());
		 map.put("endDate",entity.getPlannedEndTime());
		 map.put("plannedQuantity",entity.getPlannedQuantity());
		 res.setCode("0");
		 res.setMsg("成功");
		 res.setData(map);

		 return new ResponseEntity<ResHttpStatus>(res, HttpStatus.OK);

	 }

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

	 /**
	  * esop文件获取
	  * @param code
	  * @return
	  */
	 @RequestMapping(value = "getEsopFileList")
	 public Result<List<Map<String,Object>>> getEsopFileList(String code){
		 Result<List<Map<String,Object>>> result=new Result<>();
	 	 ArrayList<String> list = new ArrayList<>();
		 String par = FileList.getAllFileName(upLoadPath+code,list);

		 if(par.equals("false")){
			 result.error500("文件为空");
			 return result;
		 }

		 List<Map<String,Object>> resuleMap = new ArrayList<>();
		 try {

		 	for (String o:list){
				Map<String,Object> map = new HashMap<>();
				map.put("fileName",o);
				map.put("fileType",getFileOf(o).toLowerCase());
				resuleMap.add(map);
			}
			result.setResult(resuleMap);
			result.success("操作成功");

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

		 return result;
	 }

	 /**
	  * 空白看板文件获取
	  * @return
	  */
	 @RequestMapping(value = "getVedioFileList")
	 public Result<List<Map<String,Object>>> getVedioFileList(){
		 Result<List<Map<String,Object>>> result=new Result<>();
		 ArrayList<String> list = new ArrayList<>();
		 FileList.getAllFileName(upVedioAAA,list);
		 if(list == null || list.size() < 1){
			 FileList.getAllFileName(upVedioABB,list);
			 result.setAddMes("ABB");
		 }else{
			 result.setAddMes("AAA");
		 }
		 List<Map<String,Object>> resuleMap = new ArrayList<>();
		 try {
			 Collections.sort(list); // 升序排列
			 for (String o:list){
				 Map<String,Object> map = new HashMap<>();
				 map.put("fileName",o);
				 map.put("upVideo",result.getAddMes());
				 map.put("fileType",getFileOf(o).toLowerCase());
				 String fileType = getFileOf(o).toLowerCase();
				 if(fileType.equals("jpg") || fileType.equals("jpeg") || fileType.equals("png")){
					 map.put("isImg",true);
				 }else if(fileType.equals("avi") || fileType.equals("mov") || fileType.equals("rmvb") || fileType.equals("rm")
						 || fileType.equals("flv") || fileType.equals("mp4") || fileType.equals("3gp")){
					 map.put("isVideo",true);
				 }else if(fileType.equals("pdf")){
					 map.put("isPdf",true);
				 }else{
				 	continue;
				 }
				 resuleMap.add(map);
			 }
			 result.setResult(resuleMap);
			 result.success("操作成功");

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

		 return result;
	 }

	 /**
	  * 获取仓库人员图片信息
	  */
	 @RequestMapping(value = "/getFilePersonList")
	 public Result<List<Map<String,Object>>> getFilePersonList(String code){
		 Result<List<Map<String,Object>>> result=new Result<>();
		 ArrayList<String> list = new ArrayList<>();
		 String par = FileList.getAllFileName(upPersonnel+code,list);
		 List<Map<String,Object>> resuleMap = new ArrayList<>();
		 if(par.equals("false")){
//			 result.error500("文件为空");
			 result.setResult(resuleMap);
			 return result;
		 }


		 try {

			 for (String o:list){
				 Map<String,Object> map = new HashMap<>();
				 map.put("fileName",o);
				 map.put("fileRealName",getFileBefore(o).toLowerCase());
				 map.put("fileType",getFileOf(o).toLowerCase());
				 resuleMap.add(map);
			 }
			 result.setResult(resuleMap);
			 result.success("操作成功");

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

		 return result;
	 }


	 /**
          * 获取文件后缀名
          * @param fileName
          * @return
          */
	 public String getFileOf(String fileName) {
		 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
		 return suffix;
	 }
     public static String getFileBefore(String fileName) {
         String suffix = fileName.substring(0,fileName.lastIndexOf("."));
         return suffix;
     }

//	 public static void main(String[] args) {
//		 File file = new File("HelloWorld.java");
//		 String fileName = file.getName();
//		 System.out.println(fileName.lastIndexOf(".") + 1);
//		 System.out.println("======================");
//		 System.out.println(fileName.lastIndexOf("."));
//		 System.out.println("======================");
//		 String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
//		 System.out.println(suffix);
//	 }

	 /**
	  * @Author chenchuang
	  * @Description //TODO 制造看板/产线看板： 月/日工时分布情况
	  * @Date 2020/10/28 13:20
	  * @Param []
	  * @return org.jeecg.common.api.vo.Result<java.util.Map<java.lang.String,java.lang.Object>>
	  */
	 @GetMapping(value = "/getByMaterial")
	 public Result<Map<String,Object>> getByMaterial(String type){
//		 getWebService(ceshi());
		 Result<Map<String,Object>> result=new Result<>();
		 try {
			 String dateString="%Y-%m";//月
			 if(type!=null&&type.equals("1")){
				 dateString="%Y-%m-%d";
			 }
			 Map<String,Object> map=fbsWorkingStatisticsService.getByMaterial(dateString);
			 result.setResult(map);
			 result.success("操作成功");
		 } catch (Exception e) {
			 e.printStackTrace();
			 result.error500("操作失败："+e.getMessage());
		 }
		 return result;
	 }


	 public Map<String,Object> ceshi(){
		 List<Map<String,Object>> mapList=new ArrayList<>();
		 //明细
		 Map<String,Object> itemMap=new LinkedHashMap<>();
		 itemMap.put("CINVCODE","660001155");//成品存货编码
		 itemMap.put("IQUANTITY","1");//数量
		 itemMap.put("MOCODE","WO20090015");//订单号
		 itemMap.put("MOROWMO","1");//行号
		 itemMap.put("CBATCH","1");//批号
//			 itemMap.put("cDefine27",allHors.doubleValue());//实际工时
//			 Double number=Double.valueOf(entity.getQualifiedNumber());//数量
//			 Double working=Double.valueOf(workshopDispatchList.getStandardWorkingHoursZ());//U8标准工时
//			 DecimalFormat df = new DecimalFormat("#.00");
//			 String workingTatol=df.format(number*working);
//			 itemMap.put("cDefine26",workingTatol);//实际总工时
		 mapList.add(itemMap);
		 //表头
		 Map<String,Object> map=new LinkedHashMap<>();
		 map.put("CSTORENAME","100");//账套号
//		 UUID uuid=UUID.randomUUID();
//		 String uuidStr=uuid.toString().replace("-","");
		 Random random = new Random();
		 int nextInt = random.nextInt(9000000);
		 nextInt=nextInt+1000000;
		 String str=nextInt+"";
		 map.put("CVOUCHCODE",str);//单号
		 Date date=new Date();
		 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		 map.put("DDATE",sdf.format(date));//入库日期
		 map.put("CWHCODE","01");//仓库编码
		 map.put("CDEPCODE","07");//部门编码
		 map.put("CMAKER","AA");//制单人
		 map.put("CRDCODE","103");//入库类型编码
		 map.put("DETAILList",mapList);



		 getWebService(map);
		 return map;
	 }


	 public static void main(String[] args) {
		 /*Map<String, String> map = new TreeMap<String, String>();
		 map.put("d", "44");
		 map.put("b", "2");
		 map.put("a", "3");
		 map.put("c", "4");

		 //这里将map.entrySet()转换成list
		 List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
		 //然后通过比较器来实现排序
		 Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
			 //升序排序
			 public int compare(Map.Entry<String, String> o1,
								Map.Entry<String, String> o2) {
				 return o1.getValue().compareTo(o2.getValue());
			 }

		 });

		 for(Map.Entry<String,String> mapping:list){
			 System.out.println(mapping.getKey()+":"+mapping.getValue());
		 }*/

//		 List<Integer> list = Arrays.asList(10,1,6,4,8,7,9,3,2,5);
//		 Collections.sort(list); // 升序排列
//		 list.forEach(n ->{System.out.print(n+", ");});
//         System.out.println(getFileBefore("sssss.jpj"));
	 }

 }
