package com.persagy.calendar.handle;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.persagy.calendar.pojo.dto.WorkCalendar;
import com.persagy.calendar.pojo.dto.WorkCalendarDate;
import com.persagy.calendar.pojo.dto.WorkCalendarDict;
import com.persagy.calendar.pojo.dto.WorkCalendarLabel;
import com.persagy.calendar.pojo.dto.WorkCalendarRule;
import com.persagy.calendar.service.IWorkCalendarDateService;
import com.persagy.calendar.service.IWorkCalendarDictService;
import com.persagy.calendar.service.IWorkCalendarLabelService;
import com.persagy.calendar.service.IWorkCalendarRuleService;
import com.persagy.calendar.service.RwdObjectService;
import com.persagy.common.utils.IdGenerator;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 
 * @version 1.0.0
 * @company persagy 
 * @author zhangqiankun
 * @date 2021年11月13日 下午6:16:25
 */
@Component
public class CommonHandler {

	@Autowired
	private RwdObjectService rwdObjectService;
	
	@Autowired
	private IWorkCalendarLabelService workCalendarLabelService;
	
    @Autowired
    private IWorkCalendarRuleService workCalendarRuleService;
    
    @Autowired
    private IWorkCalendarDateService workCalendarDateService;
    
    @Autowired
    private IWorkCalendarDictService workCalendarDictService;
    
    /**
     * 初始化项目ID的字典数据
     * 
     * @param groupCode
     * @param dictTypes
     * @return 不为null，返回错误信息
     */
	public String initProjectDict(String groupCode, Set<String> dictTypes) {
		try {
			// 1.获取运维系统中的项目数据
			Set<String> allProjects = this.rwdObjectService.queryAllProjects(groupCode);
			if (CollectionUtil.isEmpty(allProjects)) {
				return null;
			}
			// 2.更新工作历这边的字典表信息
			List<WorkCalendarDict> calendarDicts = new ArrayList<WorkCalendarDict>();
			for (String projectId : allProjects) {
				// 删除这个项目下的已有信息
				LambdaQueryWrapper<WorkCalendarDict> queryWrapper = new WorkCalendarDict.BuilderQueryWrapper()
						.projectIdEq(projectId, null).dictTypeIn(dictTypes).builder();
				this.workCalendarDictService.remove(queryWrapper);
				
				// 每个项目添加六条
				calendarDicts.add(this.getWorkCalendarDict(groupCode, projectId, "ACSeason", "ACSeason-1", "供冷"));
				calendarDicts.add(this.getWorkCalendarDict(groupCode, projectId, "ACSeason", "ACSeason-2", "供暖"));
				calendarDicts.add(this.getWorkCalendarDict(groupCode, projectId, "ACSeason", "ACSeason-3", "过渡"));
				calendarDicts.add(this.getWorkCalendarDict(groupCode, projectId, "shop", "2", "开店时间"));
				calendarDicts.add(this.getWorkCalendarDict(groupCode, projectId, "shop", "3", "商业闭店时间"));
				calendarDicts.add(this.getWorkCalendarDict(groupCode, projectId, "shop", "4", "娱乐闭店时间"));
			}
			
			this.workCalendarDictService.batchCreateCalendarDict(calendarDicts);
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
		
		return null;
	}
    
	/**
	 * 
	 * @param groupCode
	 * @param projectId
	 * @param dictType
	 * @param dictCode
	 * @param dictDesc
	 * @return
	 */
	private WorkCalendarDict getWorkCalendarDict(String groupCode, String projectId, String dictType, String dictCode, String dictDesc) {
		WorkCalendarDict calendarDict = new WorkCalendarDict();
		calendarDict.setId(IdGenerator.getUUID());
		calendarDict.setCalendarId("0");
		calendarDict.setProjectId(projectId);
		calendarDict.setGroupCode(groupCode);
		calendarDict.setDictType(dictType);
		calendarDict.setDictCode(dictCode);
		calendarDict.setDictDesc(dictDesc);
		return calendarDict;
	}
	
	
	/**
	 * 数据转换
	 * 
	 * @param workCalendars
	 * @param groupCode
	 */
    public void switchData(List<WorkCalendar> workCalendars, String groupCode) {
    	// 获取唯一的项目ID和对应的工作历类型
    	Map<String, List<String>> projectId2CalendarId = new HashMap<String, List<String>>();
    	for (WorkCalendar workCalendar : workCalendars) {
    		if (projectId2CalendarId.containsKey(workCalendar.getProjectId())) {
    			projectId2CalendarId.get(workCalendar.getProjectId()).add(workCalendar.getId());
			} else {
				projectId2CalendarId.put(workCalendar.getProjectId(), Lists.newArrayList(workCalendar.getId()));
			}
		}
    	
    	// 遍历map，修改shop类型的规则和date数据，修改ACSeason类型label数据
    	Set<String> keySet = projectId2CalendarId.keySet();
    	for (String projectId : keySet) {
    		List<String> calendarIds = projectId2CalendarId.get(projectId);
    		if (CollectionUtil.isEmpty(calendarIds)) {
				continue;
			}
    		if (calendarIds.size() == 1) {
				// 此项目下就这一个工作历
    			this.switchData(groupCode, projectId, calendarIds.get(0));
    			continue;
			}
    		
    		// 一个项目下多个工作历时
    		Collections.sort(calendarIds);
    		int size = calendarIds.size();
    		for (int i = 0; i < size; i++) {
    			String calendarId = calendarIds.get(i);
				if (i == 0) {
					this.switchData(groupCode, projectId, calendarId);
					continue;
				}
				// 
				this.deleteData(groupCode, projectId, calendarId);
			}
		}
    }
    
	/**
	 * 转换数据
	 * 
	 * @param groupCode
	 * @param projectId
	 * @param calendarId
	 */
    private void switchData(String groupCode, String projectId, String calendarId) {
    	UpdateWrapper<WorkCalendarRule> ruleWrapper = new WorkCalendarRule.Builder().createUpdateWrapper().groupCodeEq(groupCode)
				.projectIdEq(projectId, null).calendarIdEq(calendarId, null).dictTypeEq("shop").builderUpdateWrapper();
		ruleWrapper.setSql("CALENDAR_ID = '0'");
		this.workCalendarRuleService.update(ruleWrapper);
		
		UpdateWrapper<WorkCalendarDate> calendarWrapper = new WorkCalendarDate.Builder().createUpdateWrapper().groupCodeEq(groupCode)
				.projectIdEq(projectId, null).calendarIdEq(calendarId, null).dictTypeEq("shop").builderUpdateWrapper();
		calendarWrapper.setSql("CALENDAR_ID = '0', CALENDAR_NAME = NULL, CALENDAR_DESC = NULL");
		this.workCalendarDateService.update(calendarWrapper);
		
		UpdateWrapper<WorkCalendarLabel> labelWrapper = new WorkCalendarLabel.Builder().createUpdateWrapper().groupCodeEq(groupCode)
				.projectIdEq(projectId, null).calendarIdEq(calendarId, null).dictTypeEq("ACSeason").builderUpdateWrapper();
		labelWrapper.setSql("CALENDAR_ID = '0'");
		this.workCalendarLabelService.update(labelWrapper);
    }
    
    /**
     * 删除数据
     * 
     * @param groupCode
     * @param projectId
     * @param calendarId
     */
    private void deleteData(String groupCode, String projectId, String calendarId) {
    	QueryWrapper<WorkCalendarRule> ruleWrapper = new WorkCalendarRule.Builder().createQueryWrapper().groupCodeEq(groupCode)
				.projectIdEq(projectId, null).calendarIdEq(calendarId, null).dictTypeEq("shop").builderQueryWrapper();
		this.workCalendarRuleService.remove(ruleWrapper);
		
		QueryWrapper<WorkCalendarDate> calendarWrapper = new WorkCalendarDate.Builder().createQueryWrapper().groupCodeEq(groupCode)
				.projectIdEq(projectId, null).calendarIdEq(calendarId, null).dictTypeEq("shop").builderQueryWrapper();
		this.workCalendarDateService.remove(calendarWrapper);
		
		QueryWrapper<WorkCalendarLabel> labelWrapper = new WorkCalendarLabel.Builder().createQueryWrapper().groupCodeEq(groupCode)
				.projectIdEq(projectId, null).calendarIdEq(calendarId, null).dictTypeEq("ACSeason").builderQueryWrapper();
		this.workCalendarLabelService.remove(labelWrapper);
    }
    
}
