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

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.patrol.business.constants.XJConstant;
import com.yeejoin.amos.patrol.business.dao.mapper.PlanMapper;
import com.yeejoin.amos.patrol.business.dao.mapper.PlanTaskMapper;
import com.yeejoin.amos.patrol.business.dao.repository.*;
import com.yeejoin.amos.patrol.business.entity.mybatis.PointCheckDetailBo;
import com.yeejoin.amos.patrol.business.param.PlanInfoPageParam;
import com.yeejoin.amos.patrol.business.service.intfc.ICheckService;
import com.yeejoin.amos.patrol.business.service.intfc.IPlanService;
import com.yeejoin.amos.patrol.core.common.response.AppCheckInputRespone;
import com.yeejoin.amos.patrol.core.common.response.AppPointCheckRespone;
import com.yeejoin.amos.patrol.core.util.DateUtil;
import com.yeejoin.amos.patrol.core.util.StringUtil;
import com.yeejoin.amos.patrol.dao.entity.Check;
import com.yeejoin.amos.patrol.dao.entity.CheckInput;
import com.yeejoin.amos.patrol.dao.entity.CheckShot;
import com.yeejoin.amos.patrol.dao.entity.Plan;
import liquibase.pro.packaged.L;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
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 java.util.*;
import java.util.stream.Collectors;

@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;
	}
	@Autowired
	private ICheckDao checkDao;

	@Autowired
	private ICheckService checkService;

	@Autowired
	PlanTaskMapper planTaskMapper;

	@Autowired
	private ICheckShotDao iCheckShotDao;
	@Override
	public AppPointCheckRespone queryPointPlanTaskDetail(String toke, String product, String appKey, Long planTaskId, Long pointId) {
		AppPointCheckRespone pointCheckRespone = new AppPointCheckRespone();
		Check check = checkDao.findByPlanTaskIdAndPointId(planTaskId, pointId);

		if (check != null) {
			pointCheckRespone = checkService.queryCheckPointDetailInVersion2(toke, product, appKey, check.getId(), planTaskId, pointId);
		} else {
			PointCheckDetailBo planPointInfo = planTaskMapper.getPointPlanTaskInfo(planTaskId, pointId);
			pointCheckRespone.setTaskStatus(planPointInfo.getTaskStatus());
			pointCheckRespone.setPointStatus(planPointInfo.getPointStatus());
			if (planPointInfo != null) {
				if(check != null) {
					List<CheckShot> checkShots = iCheckShotDao.findAllByCheckIdAndCheckInputId(check.getId(),
							0L);
					List<String> photos = new ArrayList<>();
					if (!org.springframework.util.CollectionUtils.isEmpty(checkShots)) {
						photos = checkShots.stream().map(e -> {
							if (e != null) {
								return  e.getPhotoData().replaceAll("\\\\", "/");
							} else {
								return "";
							}
						}).collect(Collectors.toList());
					}
					pointCheckRespone.setPointImgUrls(photos);
				}
				pointCheckRespone.setId(planPointInfo.getId());
				pointCheckRespone.setPlanTaskId(Long.valueOf(planPointInfo.getPlanTaskId()));
				pointCheckRespone.setPointId(pointId);
				pointCheckRespone.setPointName(planPointInfo.getPointName());
				pointCheckRespone.setPointNo(planPointInfo.getPointNo());
				pointCheckRespone.setBeginTime(planPointInfo.getBeginTime());
				pointCheckRespone.setEndTime(planPointInfo.getEndTime());
				pointCheckRespone.setPlanName(planPointInfo.getPlanName());
				pointCheckRespone.setShortMaxNumber(planPointInfo.getShortMaxNumber());
				pointCheckRespone.setShortMinNumber(planPointInfo.getShortMinNumber());
				List<PointCheckDetailBo> pointInputs = planTaskMapper.getPointInputByRouteIdAndPointId(planPointInfo.getRouteId(), planPointInfo.getPointId());
				JSONObject appResponeMap = new JSONObject();
				List<AppCheckInputRespone> appCheckInputResponeList = new ArrayList<AppCheckInputRespone>();
				pointInputs.forEach(action -> {
					AppCheckInputRespone input = new AppCheckInputRespone();
					input.setInputName(action.getInputName());
					input.setCheckInputId(action.getCheckInputId());
					input.setDefaultValue(action.getDefaultValue());
					input.setDataJson(action.getDataJson());
					input.setIsMultiline(action.getIsMultiline());
					input.setIsMust(action.getIsMust());
					input.setInputValue(null);
					if(null != check) {
						for (CheckInput ck :check.getCheckInput()
						) {
							if(ck.getInputId().toString().equals(String.valueOf(action.getCheckInputId()))) {
								input.setInputValue(ck.getInputValue());
							}
						}

						List<CheckShot> checkShotsNew = iCheckShotDao.findAllByCheckIdAndCheckInputId(check.getId(),
								action.getCheckInputId());
						List<String> photosNew = new ArrayList<>();
						if (!org.springframework.util.CollectionUtils.isEmpty(checkShotsNew)) {
							photosNew = checkShotsNew.stream().map(e -> {
								if (e != null) {
									return  e.getPhotoData().replaceAll("\\\\", "/");
								} else {
									return "";
								}
							}).collect(Collectors.toList());
						}
						input.setPointInputImgUrls(photosNew);
					}

					input.setItemType(action.getItemType());
					input.setOrderNo(action.getOrderNo());
					input.setPictureJson(action.getPictureJson());
					input.setClassifyId(action.getClassifyId());
					input.setClassifyName(action.getClassifyName());
					appCheckInputResponeList.add(input);

				});

				appResponeMap.put("items", appCheckInputResponeList);
				pointCheckRespone.setAppCheckInput(appResponeMap);
			}
		}
		return pointCheckRespone;
	}
	@Override
	public Plan addPlan(HashMap<String, Object> map) {
		Plan param =  (Plan) map.get("param");


		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(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"));
		}
		return planDao.save(param);
	}

	@Override
	@Transactional
	public void delPlanById(Long[] 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(Long[] param) {
        for (Long aLong : param) {
            Plan plan = planMapper.getPlanEntityById(aLong.toString());
            Long longId = planMapper.getMaxId();
            plan.setName(plan.getName() + "复制");
            plan.setId(longId + 1);
            planDao.saveAndFlush(plan);
        }

	}

	@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);
	}





}
