/**
 *
 */
package com.uc.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang3.StringUtils;

import com.foc.util.DBHandler;
import com.foc.util.DBHelper;
import com.foc.util.Util;
import com.uc.entity.FOCImGroupEntity;
import com.uc.entity.FOCImGroupUserEntity;
import com.uc.entity.FocUserTypeEntity;
import com.uc.entity.UCImGroupEntity;
import com.uc.entity.UCImGroupUserEntity;

/**
 * 
 * @team BBDTEK IT Team
 * @author renmb
 * @version 1.0
 * @time  2017年3月2日
 */
public class FOCImGroupService {
    
    /**
     * 查询群组列表
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param ids
     * @return
     */
    public List<UCImGroupEntity> findGroupList(Object[] ids) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT id,  ");
            builder.append("       group_type AS groupType,  ");
            builder.append("       group_name AS groupName,  ");
            builder.append("       group_avatar AS groupAvatar,  ");
            builder.append("       flight_no AS flightNo,  ");
            builder.append("       user_count AS userCount,  ");
            builder.append("       user_md5 AS userMd5,  ");
            builder.append("       create_by AS createBy,  ");
            builder.append("       create_date AS createDate,  ");
            builder.append("       del_flag AS delFlag,  ");
            builder.append("       seat_code AS seatCode ");
            builder.append("FROM foc_user_group  ");
            
            if(ids != null && ids.length>0){
                builder.append("WHERE id IN ( ");
                for(int i=0,len=ids.length;i<len;i++){
                    if(i == 0){
                        builder.append("?");
                    } else{
                        builder.append(", ?");
                    }
                }
                builder.append(" ) ");
            }
            ResultSetHandler<List<UCImGroupEntity>> handler = new BeanListHandler<UCImGroupEntity>(UCImGroupEntity.class);
            List<UCImGroupEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
//            System.out.println(builder.toString());
            if(ids != null && ids.length>0){
                list = run.query(builder.toString(), handler, ids);
            } else {
                list = run.query(builder.toString(), handler);
            }
            if (list != null && list.size() > 0) {

                return list;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    public Map<String, FOCImGroupEntity> findAllGroupListToMap() {
        
        List<FOCImGroupEntity> groupList = this.findAllGroupList();
        if(groupList == null || groupList.size() == 0)
            return null;
        Map<String, FOCImGroupEntity> map = new HashMap<String, FOCImGroupEntity>();
        for(FOCImGroupEntity group:groupList){
            map.put(group.getId(), group);
        }
        return map;
    }
    public List<FOCImGroupEntity> findAllGroupList() {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT id,  ");
            builder.append("       group_type AS groupType,  ");
            builder.append("       group_name AS groupName,  ");
            builder.append("       group_avatar AS groupAvatar,  ");
            builder.append("       flight_no AS flightNo,  ");
            builder.append("       user_count AS userCount,  ");
            builder.append("       user_md5 AS userMd5,  ");
            builder.append("       create_by AS createBy,  ");
            builder.append("       create_date AS createDate,  ");
            builder.append("       del_flag AS delFlag,  ");
            builder.append("       seat_code AS seatCode ");
            builder.append("FROM foc_user_group  ");
            ResultSetHandler<List<FOCImGroupEntity>> handler = new BeanListHandler<FOCImGroupEntity>(FOCImGroupEntity.class);
            List<FOCImGroupEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
//            System.out.println(builder.toString());
            list = run.query(builder.toString(), handler);
            if (list != null && list.size() > 0) {

                return list;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 更加用户ID查询我们系统
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param groupid
     * @return
     */
    public FOCImGroupEntity findGroupListById(String groupid) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT id,  ");
            builder.append("       group_type AS groupType,  ");
            builder.append("       group_name AS groupName,  ");
            builder.append("       group_avatar AS groupAvatar,  ");
            builder.append("       flight_no AS flightNo,  ");
            builder.append("       user_count AS userCount,  ");
            builder.append("       user_md5 AS userMd5,  ");
            builder.append("       create_by AS createBy,  ");
            builder.append("       create_date AS createDate,  ");
            builder.append("       del_flag AS delFlag,  ");
            builder.append("       seat_code AS seatCode ");
            builder.append("FROM foc_user_group  ");
            builder.append("WHERE id = ? ");
            ResultSetHandler<List<FOCImGroupEntity>> handler = new BeanListHandler<FOCImGroupEntity>(FOCImGroupEntity.class);
            List<FOCImGroupEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
//            System.out.println(builder.toString());
            list = run.query(builder.toString(), handler, groupid);
            if (list != null && list.size() > 0) {

                return list.get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 解散群组
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param groupid
     * @return
     */
    public boolean deleteGroupById(String groupid) {
        
        return this.updateGroupFlagById(groupid, "1");
    }
    public boolean updateGroupFlagById(String groupid, String delFlag) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("UPDATE foc_user_group SET del_flag=? ");
            builder.append("WHERE id = ? ");
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            
//            System.out.println(builder.toString());
            int count = run.update(builder.toString(), delFlag, groupid);
            return count > 0;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
    public boolean updateGroupNameById(String groupId, String groupName) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("UPDATE foc_user_group SET group_name=? ");
            builder.append("WHERE id = ? ");
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            
//            System.out.println(builder.toString());
            int count = run.update(builder.toString(), groupName, groupId);
            return count > 0;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 创建群组
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param focGroup
     */
    public void createGroup(FOCImGroupEntity focGroup){
        try {
            Map<String, Object> columnMap = new TreeMap<String, Object>();

            columnMap.put("id",          focGroup.getId());
            columnMap.put("group_type",  focGroup.getGroupType());
            columnMap.put("group_name",  focGroup.getGroupName());
            columnMap.put("user_count",  focGroup.getUserCount());
            columnMap.put("seat_code",   focGroup.getSeatCode());
            columnMap.put("create_by",   focGroup.getCreateBy());
            columnMap.put("create_date", focGroup.getCreateDate());
            columnMap.put("del_flag",    focGroup.getDelFlag());
            columnMap.put("user_md5",    focGroup.getUserMd5());
            
            columnMap.put("app_code",    focGroup.getAppCode());
            columnMap.put("platform",    focGroup.getPlatform());
            
            List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
            columnMapList.add(columnMap);
            // 批量插入数据
            DBHandler dBHandler = new DBHandler();
            dBHandler.batchInsert("foc_user_group", columnMapList);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    /**
     * 添加一个群成员
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param focGroupUser
     */
    public void addGroupUser(FOCImGroupUserEntity focGroupUser){
        try {
            
            Map<String, Object> columnMap = new TreeMap<String, Object>();

            columnMap.put("user_id",       focGroupUser.getUserId());
            columnMap.put("group_id",      focGroupUser.getGroupId());
            columnMap.put("user_type",     focGroupUser.getUserType());
            columnMap.put("inviter_id",    focGroupUser.getInviterId());
            columnMap.put("create_date",   focGroupUser.getCreateDate());
            
            List<Map<String, Object>> columnMapList = new ArrayList<Map<String, Object>>();
            columnMapList.add(columnMap);
            // 批量插入数据
            DBHandler dBHandler = new DBHandler();
            dBHandler.batchInsert("foc_user2group", columnMapList);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
    public FOCImGroupUserEntity findGroupUser(String groupId, String userId){
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT user_id AS userId,  ");
            builder.append("       group_id AS groupId,  ");
            builder.append("       user_type AS userType,  ");
            builder.append("       inviter_id AS inviterId,  ");
            builder.append("       create_date AS createDate ");
            builder.append("FROM foc_user2group  ");
            builder.append("WHERE group_id = ? ");
            builder.append("  AND user_id = ? ");
            ResultSetHandler<List<FOCImGroupUserEntity>> handler = new BeanListHandler<FOCImGroupUserEntity>(FOCImGroupUserEntity.class);
            List<FOCImGroupUserEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
//            System.out.println(builder.toString());
            list = run.query(builder.toString(), handler, groupId, userId);
            if (list != null && list.size() > 0) {

                return list.get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 创建群
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param ucGroup
     * @param ucGroupUserList
     */
    public void createGroup(UCImGroupEntity ucGroup, int userCount){
        
        Date createDate = null;
        try {
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");// 2017-03-14 16:12:49
            createDate = sdf.parse(ucGroup.getCreatetime());
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(createDate == null){
            
            createDate = new Date();
        }
        FOCImGroupEntity focGroup = new FOCImGroupEntity();
        focGroup.setCreateBy(ucGroup.getStaffaccount());
        focGroup.setCreateDate(createDate);
        focGroup.setFlightNo("");
        focGroup.setGroupName(ucGroup.getName());
        focGroup.setGroupType("02");
        focGroup.setId(ucGroup.getId());
        focGroup.setUserCount(userCount);
        focGroup.setSeatCode("");
        focGroup.setDelFlag(userCount <=1 ? "1" : ucGroup.getState());// 只有一个用户是自动关闭群组
        focGroup.setUserMd5(ucGroup.getUserMd5());
        
        this.createGroup(focGroup);
    }
    /**
     * 删除不在群组里面的用户
     * 
     * @author renmb
     * @time  2017年3月14日
     * @param groupid
     * @param userIdList
     * @return
     */
    public boolean deleteNotInGroupUser(String groupid, List<String> userIdList){
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("DELETE FROM foc_user2group ");
            builder.append("WHERE group_id = ? ");
            
            Object[] params = new Object[userIdList.size()+1];
            params[0] = groupid;
            if(userIdList != null && userIdList.size()>0){
                builder.append(" AND user_id NOT IN ( ");
                for(int i=0,len=userIdList.size();i<len;i++){
                    if(i == 0){
                        builder.append("?");
                    } else{
                        builder.append(", ?");
                    }
                    params[i+1] = userIdList.get(i);
                }
                builder.append(" ) ");
            }
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            int count = run.update(builder.toString(), params);
            return count > 0;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
    public boolean deleteGroupNotInId(List<String> groupIdList) {
        try {
            if(groupIdList == null || groupIdList.size() == 0)
                return false;
            
            Object[] params = new Object[groupIdList.size()];
            if(groupIdList != null && groupIdList.size()>0){
                StringBuilder builder = new StringBuilder();
                builder.append("UPDATE foc_user_group SET del_flag='1' ");
                builder.append("WHERE del_flag='0' AND group_type IN ('01', '02', '03', '04') AND id NOT IN ( ");
                for(int i=0,len=groupIdList.size();i<len;i++){
                    if(i == 0){
                        builder.append("?");
                    } else{
                        builder.append(", ?");
                    }
                    params[i] = groupIdList.get(i);
                }
                builder.append(" ) ");
                QueryRunner run = new QueryRunner(DBHelper.getDataSource());
                int count = run.update(builder.toString(), params);
                return count > 0;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
    
    public FocUserTypeEntity getUserTypeById(String userId){
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT `id`,`name`,'USER' AS type FROM `sys_user` WHERE `id`= ? ");
            builder.append("UNION ");
            builder.append("SELECT `id`, `seat_name` AS name,'SEAT' AS type FROM `foc_seats` WHERE `id`= ? ");
            ResultSetHandler<List<FocUserTypeEntity>> handler = new BeanListHandler<FocUserTypeEntity>(FocUserTypeEntity.class);
            List<FocUserTypeEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
//            System.out.println(builder.toString());
            list = run.query(builder.toString(), handler, userId, userId);
            if (list != null && list.size() > 0) {

                return list.get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    public void updateGroup(FOCImGroupEntity focGroup, UCImGroupEntity ucGroup, List<UCImGroupUserEntity> ucGroupUserList) {
        
//        FOCImGroupEntity focGroup = this.findGroupListById(ucGroup.getId());
        
        List<String> userIdList = new ArrayList<String>();
        if(ucGroupUserList != null && ucGroupUserList.size() > 0){// 生成群成员MD5编码
            
            for(UCImGroupUserEntity gu:ucGroupUserList){
                if("0".equals(gu.getState())){
                    
                    userIdList.add(gu.getStaffaccount());
                }
            }
            if(userIdList.size()>0){
                Collections.sort(userIdList);
                StringBuilder builder = new StringBuilder();
                for(String userId:userIdList){
                    
                    builder.append(userId+">");
                }
                ucGroup.setUserMd5(DigestUtils.md5Hex(builder.toString()));
            }
        }
        if(StringUtils.isEmpty(ucGroup.getUserMd5())){// 群已经解散
            if(focGroup != null){// 如果我们系统的群存在则修改
                
                this.deleteGroupById(ucGroup.getId());
                return ;
            }
        }
        if(focGroup == null){// FOC系统不存在此群，需要创建群
            if("0".equals(ucGroup.getState())){
                FocUserTypeEntity createUserType = this.getUserTypeById(ucGroup.getStaffaccount());
                if(createUserType == null){// 非我们系统的用户，或者只有一个用户则返回
                    return ;
                }
                this.createGroup(ucGroup, ucGroupUserList.size());// 创建一个群组
                for(UCImGroupUserEntity gu:ucGroupUserList){
                    if("0".equals(gu.getState())){// 成员为有效状态
                        
                        FOCImGroupUserEntity userEntity = this.findGroupUser(ucGroup.getId(), gu.getStaffaccount());
                        if(userEntity == null){// 用户在此群组不存在，则添加进去
                            FOCImGroupUserEntity focGroupUser = new FOCImGroupUserEntity();
                            focGroupUser.setCreateDate(new Date());
                            focGroupUser.setGroupId(ucGroup.getId());
                            focGroupUser.setInviterId("");
                            focGroupUser.setUserId(gu.getStaffaccount());
                            FocUserTypeEntity userType = this.getUserTypeById(focGroupUser.getUserId());
                            if(userType != null){// 此用户在我们的系统存在
                                
                                focGroupUser.setUserType(userType.getType());
                                this.addGroupUser(focGroupUser);
                            }
                        }
                    }
                }
                String status = Util.updateGroupAvatar(ucGroup.getId(), ucGroup.getStaffaccount());
                System.out.println("【NEW】【"+ucGroup.getId()+"】【"+ucGroup.getName()+"】【updateGroupAvatar】【"+status+"】");
            }
            return ;
        }
        if(ucGroup.getName().equals(focGroup.getGroupName()) == false){// 群名称不一致不一样
            
            this.updateGroupNameById(ucGroup.getId(), ucGroup.getName());
        }
        if(ucGroup.getUserMd5().equals(focGroup.getUserMd5()) 
                && ucGroup.getState().equals(focGroup.getDelFlag())){// 群信息是同步的
            
            return ;
        }
        if(ucGroup.getState().equals(focGroup.getDelFlag()) == false){// 群状态不一样
            
            focGroup.setDelFlag(ucGroup.getState());
            this.updateGroupFlagById(ucGroup.getId(), ucGroup.getState());
        }
        if("0".equals(focGroup.getDelFlag()) 
                && ucGroup.getUserMd5().equals(focGroup.getUserMd5()) == false){// 群成员不一样
            
            this.deleteNotInGroupUser(ucGroup.getId(), userIdList);// 删除不在群组里面的用户列表
            for(UCImGroupUserEntity gu:ucGroupUserList){// 循环查看
                if("0".equals(gu.getState())){
                    
                    FOCImGroupUserEntity userEntity = this.findGroupUser(ucGroup.getId(), gu.getStaffaccount());
                    if(userEntity == null){// 用户在此群组不存在，则添加进去
                        FOCImGroupUserEntity focGroupUser = new FOCImGroupUserEntity();
                        focGroupUser.setCreateDate(new Date());
                        focGroupUser.setGroupId(ucGroup.getId());
                        focGroupUser.setInviterId("");
                        focGroupUser.setUserId(gu.getStaffaccount());
//                        focGroupUser.setUserType("");
                        FocUserTypeEntity typeEntity = this.getUserTypeById(focGroupUser.getUserId());
                        if(typeEntity != null){
                            
                            focGroupUser.setUserType(typeEntity.getType());
                            this.addGroupUser(focGroupUser);
                        }
                    }
                }
            }
            String status = Util.updateGroupAvatar(ucGroup.getId(), ucGroup.getStaffaccount());
            System.out.println("【UPDATE】【"+ucGroup.getId()+"】【"+ucGroup.getName()+"】【updateGroupAvatar】【"+status+"】");
        }
    }
}
