package com.community.huiju.service.impl;

import com.community.commom.constant.Constant;
import com.community.huiju.dao.*;
import com.community.huiju.model.*;
import com.community.huiju.service.CommunityServiceI;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author FXF
 * @date 2018-10-31
 */
@Service("communityService")
@Transactional(rollbackFor = Exception.class)
public class CommunityServiceImpl implements CommunityServiceI {
	
	@Autowired
	private ToCommunitiesMapper toCommunitiesMapper;
	
	@Autowired
	private TpUserMapper tpUserMapper;
	
	@Autowired
	private TpUserCommunityMapper tpUserCommunityMapper;
	
	@Autowired
	private TaSysMenuMapper taSysMenuMapper;

	@Autowired
	private TpCarouselSettingMapper tpCarouselSettingMapper;

	@Autowired
	private TpEquipmentTreeMapper tpEquipmentTreeMapper;

	@Autowired
	private TaUserMapper taUserMapper;
	/**
	 * 分页获取小区列表
	 * @param toCommunities
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@Override
	public Map<String,Object> getCommunitys(ToCommunities toCommunities, Integer pageNum, Integer pageSize) {
		//使用分页插件
		Page page = PageHelper.startPage(pageNum, pageSize);
		//获取数据
		List<ToCommunities> list = toCommunitiesMapper.selectByCommunityName(toCommunities);
		Map<String,Object> map = new HashMap<>();
		map.put("items",list);
		map.put("total",page.getTotal());
		return map;
	}
	
	@Override
	public Integer addCommunity(ToCommunities toCommunities) {
		toCommunities.setCreateDate(new Date());
		Integer size = toCommunitiesMapper.insertSelective(toCommunities);
		if (size < 1){
			return 0;
		}


		Map<String,Object> map = Maps.newHashMap();
		map.put("loginName", toCommunities.getLoginName());
		TaUser taUser = taUserMapper.selectByLoginName(map);
		if (null == taUser) {
			//时维护ta_user（发帖需要）
			taUser= new TaUser();
			taUser.setLoginName(toCommunities.getLoginName());
			taUser.setCreateDate(new Date());
			taUser.setUserName(toCommunities.getUserName());
			taUser.setStatus("1");
			taUserMapper.insert(taUser);
		}





		//构建用户信息
		TpUser tpUser = new TpUser();
		tpUser.setUserName(toCommunities.getUserName());
		tpUser.setLoginName(toCommunities.getLoginName());
		tpUser.setCreateDate(new Date());
		tpUser.setCreateUser(1);
		tpUser.setCommunityId(toCommunities.getId());
		tpUser.setStatus(Constant.EFFECTIVE);
		tpUser.setTaUserId(taUser.getId());
		//插入用户信息
		tpUserMapper.insertSelective(tpUser);
		//维护此用户的角色
		addUserAndRole(tpUser.getId(), toCommunities.getId());
		//维护这个小区的APP端的图标
		addAppMenu(toCommunities.getId());
		// 默认创建 banner轮播数  3
		addBannerNum(toCommunities.getId(), 3);
		// 创建默认的设备树
		addEquipmentTree(toCommunities.getId(), toCommunities.getCommunityName(), tpUser.getId());
		return size;
	}

	/**
	 * 创建默认的设备树
	 * @param communityId
	 * @param communityName
	 */
	private void addEquipmentTree(Integer communityId, String communityName, Integer userId) {
		TpEquipmentTree tpEquipmentTree = new TpEquipmentTree();
		tpEquipmentTree.setCommunityId(communityId);
		tpEquipmentTree.setEquipmentName(communityName);
		tpEquipmentTree.setPid(0);
		tpEquipmentTree.setSort(0);
		tpEquipmentTree.setCreateTime(new Date());
		tpEquipmentTree.setCreateUser(userId);

		tpEquipmentTreeMapper.insertSelective(tpEquipmentTree);
	}

	/**
	 * 创建 banner轮播数
	 * @param communityId
	 * @param num
	 */
	private void addBannerNum(Integer communityId, Integer num){
		TpCarouselSetting activity = new TpCarouselSetting();
		activity.setCommunityId(communityId);
		activity.setCarouselType(Constant.ACTIVITY);
		activity.setCarouselNum(num);
		tpCarouselSettingMapper.insert(activity);
		TpCarouselSetting announcement = new TpCarouselSetting();
		announcement.setCommunityId(communityId);
		announcement.setCarouselType(Constant.ANNOUNCEMENT);
		announcement.setCarouselNum(num);
		tpCarouselSettingMapper.insert(announcement);
	}

	/**
	 * 维护这个小区的APP端的菜单和图标
	 * @param communityId
	 */
	private void addAppMenu(Integer communityId) {
		List<TaSysMenu>  list = taSysMenuMapper.getTaSysMenuListByCommunityId();
		AtomicReference<Integer> menuIndex = new AtomicReference<>(1);
		list.stream().forEach(e -> {
			//插入APP菜单
			TaSysMenu taSysMenu = new TaSysMenu();
			taSysMenu.setCommunityId(communityId);
			taSysMenu.setExplain(e.getExplain());
			taSysMenu.setMenuName(e.getMenuName());
			taSysMenu.setMenuType(e.getMenuType());
			taSysMenu.setMenuUrl(e.getMenuUrl());
			taSysMenu.setRemark(e.getRemark());
			taSysMenu.setSort(e.getSort());
			taSysMenu.setStatus("0");
			if (menuIndex.get() > 8) {
				taSysMenu.setStatus("1");
			}
			taSysMenuMapper.insertTaSysMenu(taSysMenu);
			//插入图标
			List<TaSysMenuImg> imgList =  taSysMenuMapper.selectTaSysMenuImgById(e.getId());
			imgList.stream().forEach(img -> {
				img.setTaMenuId(taSysMenu.getId());
			});
			taSysMenuMapper.batchInsertImg(imgList);

			menuIndex.getAndSet(menuIndex.get() + 1);
		});
		
	}
	
	/**
	 * 维护住户端用户与社区关系表
	 * @param tpUserId
	 * @param communitiesId
	 */
	private void addUserAndCommunity(Integer tpUserId, Integer communitiesId) {
		//维护住户端用户与社区关系表
		TpUserCommunity tpUserCommunity = new TpUserCommunity();
		tpUserCommunity.setTpUserId(tpUserId);
		tpUserCommunity.setCommunityId(communitiesId);
		tpUserCommunityMapper.insertSelective(tpUserCommunity);
	}

	/**
	 * 添加 用户 和 角色的关系
	 * 	如果存在则添加,不存在则不添加
	 * @param userId
	 */
	private void addUserAndRole(Integer userId, Integer communityId){
		//插入此小区的admin角色
		TpSysRole params = new TpSysRole();
		params.setCommunityId(communityId);
		tpUserMapper.insertCommunityRole(params);
		//维护这个角色的菜单权限
		List<TpSysMenu> tpSysMenuList = tpUserMapper.selectMenuList();
		List<TpSysRoleMenu> tpSysRoleMenuList = new ArrayList<>();
		tpSysMenuList.stream().forEach(e -> {
			TpSysRoleMenu tpSysRoleMenu = new TpSysRoleMenu();
			tpSysRoleMenu.setCommunityId(communityId);
			tpSysRoleMenu.setMenuId(e.getId());
			tpSysRoleMenu.setRoleId(params.getId());
			tpSysRoleMenuList.add(tpSysRoleMenu);
		});
		//批量插入
		tpUserMapper.batchInsertRoleMenu(tpSysRoleMenuList);
		
		int count = tpUserMapper.countUserRole(userId,params.getId(),communityId);
		if (count > 0) {
			return;
		}
		//维护此用户的角色
		tpUserMapper.insertUserRole(userId,params.getId(),communityId);
	}
	
	/**
	 * 根据详情获取小区数据
	 * @param id
	 * @return
	 */
	@Override
	public ToCommunities getCommunityById(Integer id) {
		return toCommunitiesMapper.selectByPrimaryKey(id);
	}
	
	/**
	 * 根据小区id更新数据
	 * @param toCommunities
	 * @return
	 */
	@Override
	public String updateCommunityById(ToCommunities toCommunities) {
		ToCommunities oldCommunities = toCommunitiesMapper.selectByPrimaryKey(toCommunities.getId());
		//未修改前的电话号码
		String oldTel = oldCommunities.getLoginName();
		//修改手机号码
		tpUserMapper.updateByTel(toCommunities.getId(),toCommunities.getLoginName(),toCommunities.getUserName(),oldTel);
		toCommunitiesMapper.updateByPrimaryKeySelective(toCommunities);
		return Constant.SUCCESS;
	}
}
