package com.persagy.calendar.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.persagy.calendar.constant.WorkCalendarConstant;
import com.persagy.calendar.mapper.OldWorkCalendarMapper;
import com.persagy.calendar.mapper.WorkCalendarDateMapper;
import com.persagy.calendar.mapper.WorkCalendarMapper;
import com.persagy.calendar.mapper.WorkCalendarRuleMapper;
import com.persagy.calendar.pojo.dto.OldWorkCalendar;
import com.persagy.calendar.pojo.dto.WorkCalendar;
import com.persagy.calendar.pojo.dto.WorkCalendarDate;
import com.persagy.calendar.pojo.dto.WorkCalendarRule;
import com.persagy.calendar.pojo.dto.WorkCalendarRule.Builder;
import com.persagy.calendar.pojo.old.DataRangeVO;
import com.persagy.calendar.pojo.old.OldCalendarIntervalCreateVO;
import com.persagy.calendar.pojo.old.OldCalendarIntervalDeleteVO;
import com.persagy.calendar.pojo.old.OldCalendarIntervalsByTag;
import com.persagy.calendar.pojo.old.OldCalendarRuleCreateVO;
import com.persagy.calendar.pojo.old.OldCalendarRuleDeleteVO;
import com.persagy.calendar.pojo.old.OldCalendarRuleVO;
import com.persagy.calendar.pojo.old.OldCalendarSetIntervalVO;
import com.persagy.calendar.pojo.old.OldCalendarTagQueryVO;
import com.persagy.calendar.pojo.old.OldCalendarTagVO;
import com.persagy.calendar.service.OldWorkCalendarDateService;
import com.persagy.common.enums.ResponseCode;
import com.persagy.common.exception.BusinessException;

/**
 * @version 
 * @description 老版服务接口
 * @company persagy
 * @author zhangqiankun
 * @since 2020年10月3日:	下午4:18:48
 */
@Service
public class OldWorkCalendarDateServiceImpl implements OldWorkCalendarDateService {
	
	@Autowired
	private OldWorkCalendarMapper oldWorkCalendarMapper;
	
	@Autowired
	private WorkCalendarMapper workCalendarMapper;
	
	@Autowired
	private WorkCalendarRuleMapper workCalendarRuleMapper;
	
	@Autowired
	private WorkCalendarDateMapper workCalendarDateMapper;
	
	@Override
	public List<OldWorkCalendar> queryOldCalendarList(OldWorkCalendar oldWorkCalendar) {
		oldWorkCalendar.setDelFlag(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR);
		return oldWorkCalendarMapper.queryOldCalendarList(oldWorkCalendar);
	}
	
	
	@Override
	@Transactional
	public boolean createOldCalendarRule(OldCalendarRuleVO<OldCalendarRuleCreateVO> requestData) {
		List<OldCalendarRuleCreateVO> rules = requestData.getRules();
		Integer result = null;
		Long selectCount = null;
		WorkCalendarRule calendarRule = null;
		QueryWrapper<WorkCalendarRule> queryWrapper = null;
		WorkCalendar calendar = null;
		for (OldCalendarRuleCreateVO rule : rules) {
			// 判断工作历信息是否存在
			calendar = this.workCalendarMapper.selectById(rule.getId());
			if (calendar == null) {
				throw new BusinessException(ResponseCode.C0320.getCode(), rule.getId() + "的工作历信息不存在");
			}
			// 判断id tag 的唯一性
	    	queryWrapper = new WorkCalendarRule.Builder().createQueryWrapper()
	    			.calendarIdEq(rule.getId(), null).dictTypeEq(rule.getTag()).projectIdEq(rule.getProjectId(), null)
	    			.delFlagEq(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR).builderQueryWrapper();
	    	selectCount = workCalendarRuleMapper.selectCount(queryWrapper);
			if (selectCount == null || selectCount < 1) {
				calendarRule = new WorkCalendarRule();
				calendarRule.setCalendarId(rule.getId());
				calendarRule.setDictType(rule.getTag());
				calendarRule.setDictCode(rule.getType());
				calendarRule.setValue(rule.getValue());
				calendarRule.setProjectId(rule.getProjectId());
				calendarRule.setRuleFlag(rule.getRuleFlag());
				result = workCalendarRuleMapper.insert(calendarRule);
				if (result == null || result < 1) {
					throw new BusinessException(ResponseCode.B0001.getCode(), "创建规则信息失败");
				}
			} else {
				throw new BusinessException(ResponseCode.C0341.getCode(), rule.getId() + "-" + rule.getTag() + "的数据已存在");
			}
		}
		return SqlHelper.retBool(result);
	}

	@Override
	@Transactional
	public boolean deleteOldCalendarRule(OldCalendarRuleVO<OldCalendarRuleDeleteVO> requestData) {
		List<OldCalendarRuleDeleteVO> rules = requestData.getRules();
		Integer result = null;
		Builder builder = new WorkCalendarRule.Builder();
		UpdateWrapper<WorkCalendarRule> updateWrapper = null;
		
		// 要更新的字段值
		WorkCalendarRule calendarRule = new WorkCalendarRule();
		calendarRule.setDelFlag(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_DEL);
		
		for (OldCalendarRuleDeleteVO rule : rules) {
			// where 条件
			builder = new WorkCalendarRule.Builder().createUpdateWrapper();
			updateWrapper = builder.calendarIdEq(rule.getId(), null)
					.projectIdEq(rule.getProjectId(), null).dictTypeEq(rule.getTag())
					.delFlagEq(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR)
					.ruleFlagEq(rule.getRuleFlag()).builderUpdateWrapper();
			result = this.workCalendarRuleMapper.update(calendarRule, updateWrapper);
			if (result == null || result < 1) {
				throw new BusinessException(ResponseCode.B0001.getCode(), "删除规则信息失败");
			}
		}
		return SqlHelper.retBool(result);
	}


	@Override
	@Transactional
	public boolean updateOldCalendarRule(OldCalendarRuleCreateVO requestData) {
		WorkCalendarRule calendarRule = new WorkCalendarRule();
		calendarRule.setCalendarId(requestData.getId());
		calendarRule.setDictType(requestData.getTag());
		calendarRule.setDictCode(requestData.getType());
		calendarRule.setValue(requestData.getValue());
		calendarRule.setProjectId(requestData.getProjectId());
		calendarRule.setRuleFlag(requestData.getRuleFlag());
		
		// where条件
		UpdateWrapper<WorkCalendarRule> updateWrapper = new WorkCalendarRule.Builder().createUpdateWrapper()
				.calendarIdEq(requestData.getId(), null).dictTypeEq(requestData.getTag())
				.projectIdEq(requestData.getProjectId(), null).ruleFlagEq(requestData.getRuleFlag())
    			.delFlagEq(WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR).builderUpdateWrapper();
		Integer result = workCalendarRuleMapper.update(calendarRule, updateWrapper);
		return SqlHelper.retBool(result);
	}

	@Override
	public List<OldWorkCalendar> queryOldCalendarRuleList(String id, String tag, String groupId) {
		return this.oldWorkCalendarMapper.queryOldCalendarRuleList(id, tag, groupId,  
				WorkCalendarConstant.WORK_CALENDAR_DEL_FLAG_NOR,
				WorkCalendarConstant.WORK_CALENDAR_RULE_FLAG_OLD);
	}


	@Override
	@Transactional
	public boolean setTags(String id, List<OldCalendarTagVO> tags) {
		Integer result = null;
		WorkCalendarDate calendarDate = null;
		for (OldCalendarTagVO tag : tags) {
			calendarDate = new WorkCalendarDate();
			calendarDate.setCalendarId(id);
			calendarDate.setDictType(tag.getTag());
			calendarDate.setProjectId(tag.getProjectId());
			
			List<DataRangeVO> dates = tag.getDates();
			for (DataRangeVO date : dates) {
				calendarDate.setWorkDateStart(date.getFrom());
				calendarDate.setWorkDateEnd(date.getTo());
				// 逐条插入
				result = workCalendarDateMapper.insert(calendarDate);
				if (result == null || result < 1) {
					throw new BusinessException(ResponseCode.B0001.getCode(), "设置作息日期失败");
				}
			}
		}
		
		return SqlHelper.retBool(result);
	}


	@Override
	@Transactional
	public boolean unsetTags(String id, List<OldCalendarTagVO> tags) {
		Integer result = null;
		QueryWrapper<WorkCalendarDate> queryWrapper = null;
		for (OldCalendarTagVO tag : tags) {
			List<DataRangeVO> dates = tag.getDates();
			for (DataRangeVO date : dates) {
				// 组装where条件语句
				queryWrapper = new WorkCalendarDate.Builder().createQueryWrapper()
						.calendarIdEq(id, null).dictTypeEq(tag.getTag())
						.projectIdEq(tag.getProjectId(), null)
						.workDateStartEq(date.getFrom()).workDateEndEq(date.getTo())
		    			.builderQueryWrapper();
				// 更新
				result = workCalendarDateMapper.delete(queryWrapper);
				if (result == null || result < 1) {
					throw new BusinessException(ResponseCode.B0001.getCode(), "删除作息日期失败");
				}
			}
		}
		
		return SqlHelper.retBool(result);
	}


	@Override
	@Transactional
	public boolean setIntervals(String id, List<OldCalendarIntervalCreateVO> intervals) {
		Integer result = null;
		WorkCalendarDate calendarDate = null;
		
		UpdateWrapper<WorkCalendarDate> updateWrapper = null;
		
		for (OldCalendarIntervalCreateVO interval : intervals) {
			// 组装要更新的字段值
			calendarDate = new WorkCalendarDate();
			calendarDate.setDictCode(interval.getCode());
			calendarDate.setWorkTime(interval.getTime().stream().collect(Collectors.joining(",")));
			
			List<DataRangeVO> dates = interval.getDates();
			for (DataRangeVO date : dates) {
				// 组装where条件语句
				updateWrapper = new WorkCalendarDate.Builder().createUpdateWrapper()
						.calendarIdEq(id, null).projectIdEq(interval.getProjectId(), null)
						.workDateStartEq(date.getFrom()).workDateEndEq(date.getTo())
		    			.builderUpdateWrapper();
				// 更新
				result = workCalendarDateMapper.update(calendarDate, updateWrapper);
				if (result == null || result < 1) {
					throw new BusinessException(ResponseCode.B0001.getCode(), "设置作息时间段失败");
				}
			}
		}
		
		return SqlHelper.retBool(result);
	}


	@Override
	@Transactional
	public boolean unsetIntervals(String id, List<OldCalendarIntervalDeleteVO> intervals) {
		Integer result = null;
		// 需要更新的字段
		QueryWrapper<WorkCalendarDate> queryWrapper = null;
		for (OldCalendarIntervalDeleteVO interval : intervals) {
			List<DataRangeVO> dates = interval.getDates();
			for (DataRangeVO date : dates) {
				// 组装where条件语句
				queryWrapper = new WorkCalendarDate.Builder().createQueryWrapper()
						.calendarIdEq(id, null).dictTypeEq(interval.getCode())
						.projectIdEq(interval.getProjectId(), null)
						.workDateStartEq(date.getFrom()).workDateEndEq(date.getTo())
		    			.builderQueryWrapper();
				// 更新
				result = workCalendarDateMapper.delete(queryWrapper);
				if (result == null || result < 1) {
					throw new BusinessException(ResponseCode.B0001.getCode(), "删除作息时间段失败");
				}
			}
		}
		
		return SqlHelper.retBool(result);
	}

	
	@Override
	@Transactional
	public boolean setIntervalsByTag(OldCalendarIntervalsByTag requestData) {
		OldCalendarTagQueryVO query = requestData.getQuery();
		OldCalendarSetIntervalVO interval = requestData.getSet_interval();
		// 组装where条件语句
		UpdateWrapper<WorkCalendarDate> updateWrapper = new WorkCalendarDate.Builder().createUpdateWrapper()
				.calendarIdEq(requestData.getId(), null)
				.projectIdEq(requestData.getProjectId(), null).dictTypeEq(query.getTag())
				.workDateStartEq(query.getDates().getFrom()).workDateEndEq(query.getDates().getTo())
    			.builderUpdateWrapper();
		// 组装 要更新的字段值
		WorkCalendarDate calendarDate = new WorkCalendarDate();
		calendarDate.setDictCode(interval.getCode());
		calendarDate.setWorkTime(interval.getTime().stream().collect(Collectors.joining(",")));
		// 更新
		Integer result = workCalendarDateMapper.update(calendarDate, updateWrapper);
		return SqlHelper.retBool(result);
	}

}
