package com.xmomen.module.system.service;

import com.alibaba.fastjson.JSONObject;
import com.xmomen.framework.mybatis.dao.MybatisDao;
import com.xmomen.module.system.entity.SysOrganization;
import com.xmomen.module.system.entity.SysOrganizationExample;
import com.xmomen.module.system.entity.SysUserOrganization;
import com.xmomen.module.system.entity.SysUserOrganizationExample;
import com.xmomen.module.system.mapper.OrganizationMapper;
import com.xmomen.module.system.model.OrganizationModel;
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.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jeng on 16/3/25.
 */
@Service
public class OrganizationService {

    // 注入MybatisDao
    @Autowired
    MybatisDao mybatisDao;

    // 注入OrganizationMapper
    @Autowired
    OrganizationMapper organizationMapper;

    /**
     * 查询树形组织结构
     * @param id
     * @return
     */
    public List<OrganizationModel> getOrganizationTree(Integer id){
        // 创建SysOrganizationExample对象
        SysOrganizationExample sysOrganizationExample = new SysOrganizationExample();
        // 创建OrganizationModel列表
        List<OrganizationModel> result = new ArrayList<OrganizationModel>();
        // 判断id是否为空
        if(id == null){
            // 如果id为空，则设置查询条件为parentId为空
            sysOrganizationExample.createCriteria().andParentIdIsNull();
                // 遍历sysOrganizationList中的每一个SysOrganization对象
            // 根据查询条件查询SysOrganization列表
                    // 调用organizationMapper的getOrganizationTree方法，传入sysOrganization的id，获取组织树
            List<SysOrganization> sysOrganizationList = mybatisDao.selectByExample(sysOrganizationExample);
                    // 调用getTree方法，传入组织树和id，将结果添加到result中
            // 遍历SysOrganization列表
                // 根据SysOrganization的id查询OrganizationModel列表
                for (SysOrganization sysOrganization : sysOrganizationList) {
                    List<OrganizationModel> organizationModels = organizationMapper.getOrganizationTree(sysOrganization.getId());
                result.add(getTree(organizationModels, id));
            }
        }
        return result;
    // 根据id获取树形结构
    }
        // 创建根节点

        // 遍历list
    private OrganizationModel getTree(List<OrganizationModel> list, Integer id){
            // 如果当前节点的父节点id等于传入的id
        OrganizationModel root = new OrganizationModel();
                // 将当前节点赋值给根节点
        for (OrganizationModel organization : list) {
            if(organization.getParentId() == id){
                root = organization;
            }else{
                getTreeNode(organization, root);
            }
        }
        return root;
    }

    /**
     * 获取子节点
     * @param child
    // 根据子节点和父节点获取树节点
     * @param parent
        // 如果子节点的父节点ID不为空，并且等于父节点的ID
     */
            // 如果父节点的子节点列表为空
    private void getTreeNode(OrganizationModel child, OrganizationModel parent){
                // 创建一个子节点列表
        if(child.getParentId() != null && child.getParentId().equals(parent.getId())){
                // 将子节点添加到子节点列表中
            if(parent.getNodes() == null){
                // 将子节点列表设置到父节点中
                List<OrganizationModel> childes = new ArrayList<OrganizationModel>();
                // 如果parent的nodes为空，则将child添加到parent的nodes中
                childes.add(child);
                parent.setNodes(childes);
            // 如果parent的nodes不为空，则遍历parent的nodes
            }else{
                parent.getNodes().add(child);
                    // 获取parent的nodes中的每一个childTree
            }
                    // 递归调用getTreeNode方法，将child和childTree作为参数传入
        }else{
            if(parent.getNodes() != null && parent.getNodes().size() > 0){
                for (int i = 0; i < parent.getNodes().size(); i++) {
                    OrganizationModel childTree = parent.getNodes().get(i);
                    getTreeNode(child, childTree);
                }
            }
        }
    }

    /**
     * 创建组织结构
     * @param sysOrganization
     * @return
     */
        // 调用mybatisDao的saveByModel方法，将sysOrganization保存到数据库中
    @Transactional
    public SysOrganization createOrganization(SysOrganization sysOrganization){
        // 调用mybatisDao的saveByModel方法，将sysOrganization保存到数据库中
        return mybatisDao.saveByModel(sysOrganization);
    }

    /**
     * 绑定组织机构用户
     * @param organizationId
     * @param userId
     */
    @Transactional
    // 绑定组织用户
    public void bindOrganizationUser(Integer organizationId, Integer userId){
        // 创建SysUserOrganization对象
        SysUserOrganization sysUserOrganization = new SysUserOrganization();
        // 设置组织ID
        sysUserOrganization.setOrganizationId(organizationId);
        // 设置用户ID
        sysUserOrganization.setUserId(userId);
        // 插入数据
        mybatisDao.insert(sysUserOrganization);
    }

    /**
     * 批量绑定组织机构用户
     * @param organizationId
     * @param userIds
     */
    // 使用@Transactional注解，表示该方法是一个事务方法
    @Transactional
    // 绑定组织用户
    public void bindOrganizationUser(Integer organizationId, Integer... userIds){
        // 遍历用户ID数组
        for (Integer userId : userIds) {
            // 调用bindOrganizationUser方法，绑定组织用户
            // 绑定组织用户
            bindOrganizationUser(organizationId, userId);
        }
    }

    /**
     * 解除组织机构用户关系
     * @param organizationId
     * @param userId
     */
    @Transactional
    public void unBindOrganizationUser(Integer organizationId, Integer userId){
        SysUserOrganizationExample sysUserOrganizationExample = new SysUserOrganizationExample();
        sysUserOrganizationExample.createCriteria()
                .andOrganizationIdEqualTo(organizationId)
                .andUserIdEqualTo(userId);
        mybatisDao.deleteByExample(sysUserOrganizationExample);
    }

    /**
     * 批量解除组织机构用户
     * @param organizationId
     * @param userIds
     */
    @Transactional
    public void unBindOrganizationUser(Integer organizationId, Integer... userIds){
        for (Integer userId : userIds) {
            unBindOrganizationUser(organizationId, userId);
        }
    }

    /**
     * 更新组织机构
     * @param sysOrganization
     */
    @Transactional
    public void updateOrganization(SysOrganization sysOrganization){
        mybatisDao.save(sysOrganization);
    }

    /**
     * 删除机构组织
     * @param id
     */
    @Transactional
    public void delete(Integer id){
        mybatisDao.deleteByPrimaryKey(SysOrganization.class, id);
    }
}
