/***文档注释***********************************************
 * 作者            ：
 * 创建日期     ：2018-10-24
 * 描述            ：SERIAL_NO
 * 注意事项     ：
 * 遗留BUG   ：
 * 修改日期     ：
 * 修改人员     ：
 * 修改内容     ：
***********************************************************/
package market.Mes.Repair.impl;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import market.Api.Mes.impl.Utils;
import market.Com.vo.CommonPage;
import market.Com.vo.ResultModel;
import market.Mes.Repair.mapper.PlnRepairPlanMapper;
import market.Mes.Repair.service.PlnRepairPlanService;
import market.Mes.Repair.vo.PlnRepairPlan;

import org.springframework.transaction.annotation.Transactional;

import com.hnshituo.basic.service.impl.BaseServiceImpl;
import com.hnshituo.basic.service.support.PageModel;
import com.hnshituo.basic.spring.remoting.annotation.RemoteService;
import com.hnshituo.core.auth.service.HomeService;

@RemoteService(path="PlnRepairPlanService")
public class PlnRepairPlanServiceImpl extends BaseServiceImpl<PlnRepairPlan,Object> implements PlnRepairPlanService {
	
	/**
	 * 查询检修计划
	 * @param sum
	 * @return
	 */
	public ResultModel queryRepairPlan(CommonPage<PlnRepairPlan> sum){
		ResultModel rm=new ResultModel();
		try{
			PageModel<PlnRepairPlan> pm=new PageModel<PlnRepairPlan>(sum.getPageIndex(),sum.getPageSize());
			PlnRepairPlan repair = sum.getObject();
			String sWhere="";
			if(Utils.isNotEmpty(sum.getStartTime())){
				sWhere+=" and prp.task_end_time >= to_date('"+sum.getStartTime()+"','yyyy-MM-dd ') ";
			}
			if(Utils.isNotEmpty(sum.getEndTime())){
				sWhere+=" and prp.task_begin_time <= to_date('"+sum.getEndTime()+"','yyyy-MM-dd ')";
			}
			Date today = new Date();
			Calendar c = Calendar.getInstance();
			List<PlnRepairPlan> prp = this.getMapper(PlnRepairPlanMapper.class).queryRepairPlan(repair, sWhere, (sum.getPageIndex()-1)*sum.getPageSize(),sum.getPageIndex()*sum.getPageSize());
			for (PlnRepairPlan pln : prp) {
				if (Utils.isNotEmpty(pln.getPlan_date())) {
				String[] temp = pln.getPlan_date().split("\\,|\\，");
				switch (pln.getTask_type()) {
				// 周任务
				case "200402":
						c.setTime(today);
						int weekday = c.get(Calendar.DAY_OF_WEEK)-1;
						if (weekday==0) {
							weekday = 7;
						}
						Integer []  week = new Integer [temp.length] ;
						for (int i = 0; i < temp.length; i++) {
							week[i] = Integer.parseInt(temp[i]);
						}
						
						pln.setNext_time(getNext_Time(7, weekday, week));
//						int diff = weekday - Integer.parseInt(temp[0]);
//						// 周计划第一个星期是今天
//						if (diff == 0) {
//							if (temp.length == 1) {
//								c.add(Calendar.DAY_OF_MONTH, 7);
//							} else {
//								c.add(Calendar.DAY_OF_MONTH,
//										Math.abs(weekday
//												- Integer.parseInt(temp[1])));
//							}
//							pln.setNext_time(c.getTime());
//						// 周计划第一个星期在今天之后
//						} else if (diff < 0) {
//							c.add(Calendar.DAY_OF_MONTH, Math.abs(diff));
//							pln.setNext_time(c.getTime());
//						//	周计划第一个星期在今天之前
//						} else {
//								c.add(Calendar.DAY_OF_MONTH, 7 - diff);
//								if (temp.length > 1) {
//								for (String str : temp) {
//									if (weekday - Integer.parseInt(str)<0) {
//										diff = weekday - Integer.parseInt(str);
//										c.add(Calendar.DAY_OF_MONTH, Math.abs(diff));
//										break;
//									}
//								}
//							}
//							pln.setNext_time(c.getTime());
//						}
					break;
				// 月计划	
				case"200403":
					// 今天是这个月第几天
					int day_of_month = c.get(Calendar.DAY_OF_MONTH);
					// 这个月一共多少天
					int total = c.getActualMaximum(Calendar.DATE);
					Integer []  month = new Integer [temp.length] ;
					for (int i = 0; i < temp.length; i++) {
						month[i] = Integer.parseInt(temp[i]);
					}
					
					pln.setNext_time(getNext_Time(total, day_of_month, month));
//					int diffy = day_of_month - Integer.parseInt(temp[0]);
//					// 月计划就是今天
//					if (diffy == 0) {
//						if (temp.length == 1) {
//							c.add(Calendar.DAY_OF_MONTH,total);
//						} else {
//							c.add(Calendar.DAY_OF_MONTH,
//									Math.abs(day_of_month
//											- Integer.parseInt(temp[1])));
//						}
//					// 月计划第一个天在今天之后
//					} else if (diffy < 0) {
//						c.add(Calendar.DAY_OF_MONTH, Math.abs(diffy));
//					// 月计划第一个天在今天之前
//					} else {
//							c.add(Calendar.DAY_OF_MONTH, total - diffy);
//							if (temp.length > 1) {
//							for (String str : temp) {
//								if (day_of_month - Integer.parseInt(str)<0) {
//									diff = day_of_month - Integer.parseInt(str);
//									c.add(Calendar.DAY_OF_MONTH, Math.abs(diffy));
//									break;
//								}
//							}
//						}
//					}
//					pln.setNext_time(c.getTime());
					break;
				// 年计划	
				case"200404":
					Integer [] days = new Integer [temp.length];
					// 今天是今年第几天
					int day_of_year = c.get(Calendar.DAY_OF_YEAR);
					// 今年一共多少天
					int totalY = c.getActualMaximum(Calendar.DAY_OF_YEAR);
					// 某年某月某日是今年的第多少天
					for (int i = 0; i < temp.length; i++) {
						days[i] = getDayOfYear(temp[i]);
					}
					pln.setNext_time(getNext_Time(totalY, day_of_year, days));
					break;

				default:
					break;
				}
			}
		}
			long count=this.getMapper(PlnRepairPlanMapper.class).queryRepairPlanCount(sum.getObject(), sWhere);
			pm.setRows(prp);
			pm.setTotal(count);
			rm.setState("200");
			rm.setData(pm);
		}catch(Exception ex){
			rm.setState("500");
			rm.setMsgInfo("查询失败！");
			ex.printStackTrace();
			rm.setErrorInfo(ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 更新检修计划
	 * @param sum
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel updateRapairPlan(CommonPage<PlnRepairPlan> sum){
		ResultModel rm=new ResultModel("200", null);
		if (Utils.isEmpty(sum)) {
			rm.setState("500");
			rm.setMsgInfo("请传入数据！");
			return rm;
		}
		PlnRepairPlan prp = sum.getObject();
		if (prp.getTask_type().equals("200404")) {
			String regex ="^[0-9]{4}([\\,|\\，][0-9]{4})*$";
			boolean isMatch = Pattern.matches(regex,prp.getPlan_date());
			if (!isMatch) {
				rm.setState("500");
				rm.setMsgInfo("年任务维护的执行日期格式不正确,正确格式[0101,0102]");
				return rm;
			}
		}
		try {
			// 更新
			if (Utils.isNotEmpty(prp.getSerial_no())) {
				if (prp.getTask_type().equals(200401)) {
					prp.setPlan_date("");
				}else {
					prp.setPlan_date(prp.getPlan_date() == null ? "" :prp.getPlan_date().replaceAll("\\，",","));
				}
				this.getMapper(PlnRepairPlanMapper.class).update(prp);
				// 新增
			}else {
				String serial_no = "1";
				List<PlnRepairPlan> ppp = this.getMapper(PlnRepairPlanMapper.class).findWithCondition(null, "nvl(INVALID_FLG,0) = '0'", " nvl(to_number(serial_no),0) desc", 0, 1);
				if (Utils.isNotEmpty(ppp)) {
					serial_no = Integer.parseInt(ppp.get(0).getSerial_no()) + 1+"";
				}
				if (prp.getTask_type().equals("200401")) {
					prp.setPlan_date(new SimpleDateFormat("yyyy-MM-dd").format(prp.getTask_begin_time()));
				}
				prp.setSerial_no(serial_no);
				prp.setCreate_time(new Date());
				//添加审批人。
				prp.setStrength(prp.getStrength());
				prp.setCreate_man_name((String)this.getSession().getAttribute(HomeService.SESSION_USER_NAME));
				this.getMapper(PlnRepairPlanMapper.class).insert(prp);
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("检修计划编辑失败!");
			ex.printStackTrace();
			rm.setErrorInfo(ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 删除计划
	 * @param sum
	 * @return
	 */
	@Transactional(value="tm", rollbackFor=Exception.class)
	public ResultModel deleteRapairPlan(CommonPage<PlnRepairPlan> sum){
		ResultModel rm=new ResultModel("200", null);
		if (Utils.isEmpty(sum)) {
			rm.setState("500");
			rm.setMsgInfo("请传入数据！");
			return rm;
		}
		List<PlnRepairPlan> prp =sum.getObjectList();
		try {
			for (PlnRepairPlan pln : prp) {
				this.getMapper(PlnRepairPlanMapper.class).delete(pln.getSerial_no());
			}
		} catch (Exception ex) {
			rm.setState("500");
			rm.setMsgInfo("删除检修计划失败!");
			ex.printStackTrace();
			rm.setErrorInfo(ex.getMessage());
		}
		return rm;
	}
	
	/**
	 * 获取日期是当前的多少天
	 * @param str
	 * @return
	 */
	public int getDayOfYear(String str){
//		Format format =  new SimpleDateFormat("yyyy");
//		String year = format.format(new Date());
		 //1、创建实例
        Calendar c = Calendar.getInstance();

        //设置时间 month月 对应的 0-11
        c.set(c.get(Calendar.YEAR), Integer.parseInt(str.substring(0, 2)), Integer.parseInt(str.substring(2)));

        //3、得到对应的第几天
         return c.get(Calendar.DAY_OF_YEAR);
		
	}
	
	/**
	 * 获取下一个检修日
	 * @param total 总天数
	 * @param today 今天是第几天
	 * @param days  计划天数数组
	 * @return
	 */
	public Date getNext_Time( int total , int today ,Integer[] days){
		Calendar c = Calendar.getInstance();
		int diff =  today -days[0];
		// 计划第一天就是今天
		if (diff == 0) {
			if (days.length == 1) {
				c.add(Calendar.DAY_OF_MONTH,total);
			} else {
				c.add(Calendar.DAY_OF_MONTH,
						Math.abs(today - days[1]));
			}
		// 计划第一个天在今天之后
		} else if (diff < 0) {
			c.add(Calendar.DAY_OF_MONTH, Math.abs(diff));
		// 月计划第一个天在今天之前
		} else {
				c.add(Calendar.DAY_OF_MONTH, total - diff);
				if (days.length > 1) {
				for (Integer str : days) {
					if (today - str <0) {
						diff = today - str;
						c.add(Calendar.DAY_OF_MONTH, Math.abs(diff));
						break;
					}
				}
			}
		}
		return c.getTime();
	}
	
}
