package com.gic.haoban.manage.service.service.impl;

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

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

import com.gic.haoban.common.utils.StringUtil;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanTemplateApplicationRelatedMapper;
import com.gic.haoban.manage.service.entity.TabHaobanTemplateApplicationRelated;
import com.gic.haoban.manage.service.service.TemplateApplicationRelatedService;

@Service
public class TemplateApplicationRelatedServiceImpl implements TemplateApplicationRelatedService {

	@Autowired
	private TabHaobanTemplateApplicationRelatedMapper mapper;
	
	@Override
	public void insert(TabHaobanTemplateApplicationRelated tab) {
		tab.setTemplateApplicationRelatedId(StringUtil.randomUUID());
		tab.setStatusFlag(1);
		tab.setCreateTime(new Date());
		tab.setUpdateTime(new Date());
		mapper.insertSelective(tab);
		
	}

	@Override
	public void update(String applicationTemplateId, String applicationIds) {
		
		List<TabHaobanTemplateApplicationRelated> list = mapper.listTemplicationApplicationByTemplateId(applicationTemplateId);
		List<String> idList = list.stream().map(TabHaobanTemplateApplicationRelated::getApplicationId).collect(Collectors.toList());
		List<String> delIdList = new ArrayList<String>();
		for (String string : idList) {
			if(applicationIds.contains(string)){
				continue;
			}
			delIdList.add(string);
		}
		
		//删除应用
		for (String applicationId : delIdList) {
			TabHaobanTemplateApplicationRelated tab = mapper.selectByTemplateIdAndApplicationId(applicationTemplateId,applicationId);
			if(tab != null){
				tab.setStatusFlag(0);
				tab.setUpdateTime(new Date());
				mapper.updateByPrimaryKeySelective(tab);
			}
		}
		
		//新增应用
		String[] applicationIdArr = applicationIds.split(",");
		for (String applicationId : applicationIdArr) {
			TabHaobanTemplateApplicationRelated tab = mapper.selectByTemplateIdAndApplicationId(applicationTemplateId,applicationId);
			if(tab != null){
				continue;
			}
			tab  = new TabHaobanTemplateApplicationRelated();
			tab.setTemplateId(applicationTemplateId);
			tab.setApplicationId(applicationId);
			this.insert(tab);
		}
	}

	@Override
	public List<TabHaobanTemplateApplicationRelated> listByTemplateId(String applicationTemplateId) {
		return mapper.listTemplicationApplicationByTemplateId(applicationTemplateId);
	}

}
