package com.yeejoin.amos.patrol.business.service.impl;

import java.util.*;

import com.yeejoin.amos.patrol.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.dao.mapper.PlanMapper;
import com.yeejoin.amos.patrol.business.dao.repository.IPlanDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPlanTaskDao;
import com.yeejoin.amos.patrol.business.dao.repository.IPlanTaskDetailDao;
import com.yeejoin.amos.patrol.business.param.PlanInfoPageParam;
import com.yeejoin.amos.patrol.business.service.intfc.IPlanService;
import com.yeejoin.amos.patrol.core.util.DateUtil;
import com.yeejoin.amos.patrol.dao.entity.Plan;

@Service("planService")
public class PlanServiceImpl implements IPlanService {
	@Autowired
	private IPlanDao planDao;
	@Autowired
	private PlanMapper planMapper;

	@Autowired
	private IPlanTaskDao planTaskDao;

	@Autowired
	private IPlanTaskDetailDao planTaskDetailDao;

	private static final Logger logger = LoggerFactory.getLogger(PlanServiceImpl.class);

	@Override
	public Page<HashMap<String, Object>> getPlanInfo(PlanInfoPageParam param) {
		long total = planMapper.countPlanInfoData(param);
		List<HashMap<String, Object>> content = planMapper.getPlanInfo(param);
		Page<HashMap<String, Object>> result = new PageImpl<HashMap<String, Object>>(content, param, total);
		return result;
	}

	@Override
	public void addPlan(HashMap<String, Object> map) {
		Plan param =  (Plan) map.get("param");

		String userDept = param.getUserDept();
		String[] userDeptArr = userDept.split(",");
		StringBuilder stringBuilder = new StringBuilder();
		for(String str : userDeptArr) {
			if(stringBuilder.length() > 0){
				stringBuilder.append("," + str.split("@")[0]);
			}else{
				stringBuilder.append(str.split("@")[0]);
			}

		}
		param.setUserId(stringBuilder.toString());

		String org_code = map.get("org_code") == null ? "":map.get("org_code").toString();
		String user_id = map.get("user_id")== null ? "":map.get("user_id").toString();
		//        if (param.getDeptId() > 0) {
//            org_code = org_code + "-" + param.getDeptId();
//        }
		if(StringUtil.isNotEmpty(map.get("dept_id"))){
			param.setDeptId(map.get("dept_id").toString());
		}
		param.setOrgCode(org_code);
		param.setStatus(Byte.parseByte(XJConstant.PLAN_STATUS_START));
		param.setNextGenDate(DateUtil.getIntervalDate(new Date(),0));
		param.setCreateBy(user_id);
		if(param.getId() > 0){//编辑计划
			Plan oriPlan = planDao.findById(param.getId()).get();
			param.setCreateDate(oriPlan.getCreateDate());
			param.setCreateBy(oriPlan.getCreateBy());
			param.setLastUpdBy(user_id);
			param.setFirstFlag(XJConstant.PLAN_FIRST_STATUS_YES);
		}
		if(XJConstant.FIX_DATE_NO.equals(param.getIsFixedDate()) && (XJConstant.PLAN_TYPE_MONTH.equals(param.getPlanType()) ||XJConstant.PLAN_TYPE_YEAR.equals(param.getPlanType()) )){
			param.setDayBegin(DateUtil.formatStrToTime("00:00:00"));
			param.setDayEnd(DateUtil.formatStrToTime("23:59:59"));
		}
		planDao.save(param);
	}

	@Override
	@Transactional
	public void delPlanById(Integer[] param) {
		List<Long> ids = new ArrayList<Long>();
		for(int i=0;i<param.length;i++){
			ids.add(Long.parseLong(param[i].toString()));
		}
		planDao.updatePlanDel(ids);
		// 删除对应该计划今天往后的所有计划执行信息
		Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
		List<Long> taskIdList = planTaskDao.getPlanTaskIdByPlanIdAndDate(ids, zero);
		if(taskIdList.size()>0){
			planTaskDao.deletePlanTaskByIdAndDate(ids, zero);

			// 删除对应该计划的计划执行详情新
			planTaskDetailDao.deletePlanTaskDetailByTaskNo(taskIdList);
		}

	}

	@Override
	public void planSaveAs(Integer[] param) {
		for(int i=0;i<param.length;i++){
			planMapper.saveAs(param[i].toString());
		}

	}

	@Override
	public List<Plan> getPlanByRouteId(Long routeId) {
		List<Plan> planList = planMapper.getPlanByRouteId(routeId);
		return planList;
	}

	@Override
	public void disablePlan(Long[] planIds) {
		// plan表中status字段置为1
		for (long planId : planIds) {
			List<Plan> planList = getPlanByRouteId(planId);
			for (Plan plan : planList) {
				plan.setStatus((byte) 1);
				planDao.save(plan);
			}
		}
	}

	@Override
	public Plan queryPlanById(Long id) {
		Optional<Plan> plan = planDao.findById(id);
         if(Optional.ofNullable(plan).isPresent()){
			 return plan.get();
		 }else{
			 return null;

		 }


	}

	@Override
	public List<HashMap<String, Object>> getPlanInfoNoPage(PlanInfoPageParam param) {
		List<HashMap<String, Object>> content = planMapper.getPlanInfoNoPage(param);
		return content;
	}

	@Override
	public List<HashMap<String, Object>> queryPlanListByOrgCode(String loginOrgCode) {
		return planMapper.queryPlanListByOrgCode(loginOrgCode);
	}





}
