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

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.Set;
import java.util.TreeSet;

import org.apache.commons.collections.CollectionUtils;
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.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.foc.conf.GConstants;
import com.foc.util.DBHelper;
import com.foc.util.Util;
import com.huawei.esdk.uc.professional.local.bean.RestRequestMessage;
import com.huawei.esdk.uc.professional.local.bean.RestResponse;
import com.huawei.esdk.uc.professional.local.bean.south.Account;
import com.huawei.esdk.uc.professional.local.bean.south.AddAccountRequest;
import com.huawei.esdk.uc.professional.local.bean.south.AddDepartmentResult;
import com.huawei.esdk.uc.professional.local.bean.south.DepartmentRequest;
import com.huawei.esdk.uc.professional.local.bean.south.QueryDepartmentInfo;
import com.huawei.esdk.uc.professional.local.bean.south.QueryDepartmentInfoList;
import com.huawei.esdk.uc.professional.local.bean.south.SipAccount;
import com.huawei.esdk.uc.professional.local.bean.south.SipAuth;
import com.huawei.esdk.uc.professional.local.bean.south.SipList;
import com.huawei.esdk.uc.professional.local.bean.south.SipQueryRequest;
import com.huawei.esdk.uc.professional.local.bean.south.SipRequest;
import com.huawei.esdk.uc.professional.local.factory.ServiceFactoryEx;
import com.huawei.esdk.uc.professional.local.service.UserProfileServiceEx;
import com.huawei.esdk.uc.professional.local.utils.RestUtils;
import com.uc.entity.HuaweiAccountUpdateBean;
import com.uc.entity.HuaweiPersonInfoEntity;
import com.uc.entity.HuaweiPersonInfoResult;
import com.uc.entity.HuaweiQueryResponseEntity;
import com.uc.entity.HuaweiSipDelBean;
import com.uc.entity.Office;
import com.uc.entity.SeatEntity;
import com.uc.entity.UcAccountEntity;
import com.uc.entity.UserProfileEntity;

/**
 * 
 * @team BBDTEK IT Team
 * @author renmb
 * @version 1.0
 * @time 2017年1月17日
 */
public class UCUserService {

//    private RestUtils restUtils = RestUtils.getInstance();
    private String personInfoUrl="/ec/appserver/person_info";// huawei.uc.personInfoUrl=/ec/appserver/person_info
    private String accountRestUrl="/ec/bmu/account";// huawei.uc.accountRestUrl=/ec/bmu/account
    private String sipDelUrl="/ec/bmu/sipcondition/delete_sip";
    
    private String userId = "123";
    private String mailRegex = "^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.([a-zA-Z0-9_-])+)+$";
    private String gwIp = GConstants.getValue("gwIp", "10.73.253.252");
    
    public List<UserProfileEntity> findUserListBySql(String sql) {
        try {
            ResultSetHandler<List<UserProfileEntity>> handler = new BeanListHandler<UserProfileEntity>(UserProfileEntity.class);
            List<UserProfileEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
//            System.out.println(sql);
            list = run.query(sql, handler);
            if (list != null && list.size() > 0) {

                for(UserProfileEntity p:list){
                    p.setCompany(getParentOfficeInfo(p.getCompanyId()));
                    p.setOffice(getParentOfficeInfo(p.getOfficeId()));
                }
                return list;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    public List<UserProfileEntity> findUserList(Object[] userIdList) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT a.id, ");
            builder.append("       a.login_name AS loginName, ");
            builder.append("       a.no, ");
            builder.append("       a.name, ");
            builder.append("       a.email, ");
//            builder.append("       a.phone, ");
//            builder.append("       a.mobile, ");
            
            builder.append("       '' AS phone, ");
            builder.append("       '' AS mobile, ");
            
            builder.append("       a.photo, ");
            builder.append("       a.huawei_num AS huaweiNum, ");
            builder.append("       a.full_office_name AS officeFullName, ");
            builder.append("       c.id AS companyId, ");
            builder.append("       c.name AS companyName, ");
            builder.append("       o.name AS officeName, ");
            builder.append("       a.office_id AS officeId, ");
            builder.append("       p.duty_name AS dutyName,  ");
            builder.append("       a.login_flag AS loginFlag, ");
            builder.append("       a.user_type AS userType, ");
            builder.append("       p.huawei_status AS huaweiStatus, ");
            builder.append("       p.jiewen_status AS jiewenStatus, ");
            builder.append("       p.sex, ");
//            builder.append("       a.mobile_nubmer AS mobileNubmer, ");
//            builder.append("       a.mobile_province AS mobileProvince, ");
//            builder.append("       a.mobile_city AS mobileCity, ");
            
            builder.append("       '' AS mobileNubmer, ");
            builder.append("       '' AS mobileProvince, ");
            builder.append("       '' AS mobileCity, ");
            
            builder.append("       a.del_flag AS delFlag, ");
            builder.append("       a.mobile_sp AS mobileSp ");
            builder.append("FROM sys_user a ");
            builder.append("LEFT JOIN sys_office c ");
            builder.append("  ON c.id = a.company_id ");
            builder.append("LEFT JOIN sys_office o ");
            builder.append("  ON o.id = a.office_id ");
            builder.append("LEFT JOIN sys_user_profiles p ");
            builder.append("  ON a.id = p.user_id ");
            builder.append("LEFT JOIN sys_user_settings ut ");
            builder.append("  ON a.id = ut.user_id ");
            builder.append("WHERE a.user_type !='1' ");
            
//            builder.append("WHERE a.del_flag='0' ");
//            builder.append(" AND a.huawei_num IS NULL ");
//            builder.append(" AND a.user_type !='1' ");
            
            if(userIdList != null && userIdList.length>0){
                builder.append(" AND a.id IN ( ");
                for(int i=0,len=userIdList.length;i<len;i++){
                    if(i == 0){
                        builder.append("?");
                    } else{
                        builder.append(", ?");
                    }
                }
                builder.append(" ) ");
            }
            ResultSetHandler<List<UserProfileEntity>> handler = new BeanListHandler<UserProfileEntity>(UserProfileEntity.class);
            List<UserProfileEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            System.out.println(builder.toString());
            if(userIdList != null && userIdList.length>0){
                list = run.query(builder.toString(), handler, userIdList);
            } else {
                list = run.query(builder.toString(), handler);
            }
            if (list != null && list.size() > 0) {

                for(UserProfileEntity p:list){
                    p.setCompany(getParentOfficeInfo(p.getCompanyId()));
                    p.setOffice(getParentOfficeInfo(p.getOfficeId()));
                }
                return list;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    
    
    
    public List<SeatEntity> findSeatList(Object[] idList) {
        try {
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT `id`,  ");
            builder.append("       `seat_name`  AS seatName,  ");
            builder.append("       `seat_phone` AS seatPhone,  ");
            builder.append("       `seat_phone_number` AS seatPhoneNumber,  ");
            builder.append("       `status`,  ");
            builder.append("       `del_flag` AS delFlag,  ");
            builder.append("       `huawei_num` AS huaweiNum,  ");
            builder.append("       `photo`  ");
            builder.append("FROM `foc_seats`  ");
            
            if(idList != null && idList.length>0){
                builder.append(" WHERE id IN ( ");
                for(int i=0,len=idList.length;i<len;i++){
                    if(i == 0){
                        builder.append("?");
                    } else{
                        builder.append(", ?");
                    }
                }
                builder.append(" ) ");
            }
            ResultSetHandler<List<SeatEntity>> handler = new BeanListHandler<SeatEntity>(SeatEntity.class);
            List<SeatEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            System.out.println(builder.toString());
            if(idList != null && idList.length>0){
                
                list = run.query(builder.toString(), handler, idList);
            } 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 List<SeatEntity> findSeatListBySql(String sql) {
        try {
            if(StringUtils.isEmpty(sql))
                return null;
            ResultSetHandler<List<SeatEntity>> handler = new BeanListHandler<SeatEntity>(SeatEntity.class);
//            List<SeatEntity> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            System.out.println(sql);
            List<SeatEntity> list = run.query(sql, handler);
            if (list != null && list.size() > 0) {

                return list;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    private Office getParentOfficeInfo(String officeId) {
        if(StringUtils.isEmpty(officeId)){
            return null;
        }
        try {
            
            StringBuilder builder = new StringBuilder();
            builder.append("SELECT o1.id, ");
            builder.append("       o1.name, ");
            builder.append("       o2.id AS parentId, ");
            builder.append("       o2.name AS parentName ");
            builder.append("FROM sys_office o1 ");
            builder.append("LEFT JOIN sys_office o2 ");
            builder.append("  ON o1.parent_id = o2.id ");
            builder.append("WHERE o1.id = ? ");

            ResultSetHandler<List<Office>> handler = new BeanListHandler<Office>(Office.class);
            List<Office> list = null;
            QueryRunner run = new QueryRunner(DBHelper.getDataSource());
            list = run.query(builder.toString(), handler, officeId);
            if (list != null && list.size() > 0) {

                return list.get(0);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 同步某一个人的信息
     * 
     * @author renmb
     * @time  2017年1月17日
     * @param entityTmp
     * @return
     */
    public String addAccountToUc(UserProfileEntity entityTmp) {
        StringBuffer sb = new StringBuffer();
        HuaweiPersonInfoEntity personInfo = getPersonInfo(entityTmp.getId());
        // 如果该账号已经存在UC服务器中，则更新该条数据
        if (personInfo != null && StringUtils.isNotBlank(personInfo.getStaffId())) {
            String result = updateUserAccountToUcClose(entityTmp, personInfo.getStaffId());
            sb.append(result);
        } else {
            // 添加用户账号到uc服务器中，包括外部联系人，新增的账号的UC状态为关闭
            String result = addUserAccountToUcClose(entityTmp);
            sb.append(result);
        }
        return sb.toString(); 
    }
    /**
     * 添加或者更新UC的席位信息
     * 
     * @author renmb
     * @time  2017年3月11日
     * @param seatList
     */
    public void addSeatAccountToUc(List<SeatEntity> seatList) {
        if (seatList != null && seatList.size() != 0) {
            int count = 1;
            int size = seatList.size();
            for (SeatEntity entityTmp : seatList) {
                try {
                    if(entityTmp.getStatus() != 1){// 删除账号
                        
                        boolean result = this.deleteUCAccount(entityTmp.getId());
                        System.out.println("【"+count+"/"+size+"】【DELETE】【"+entityTmp.getId()+"】【"+entityTmp.getSeatName()+"】"+result);
                        if(entityTmp.getHuaweiNum() != null){
                            
                            this.deleteSipNum(String.valueOf(entityTmp.getHuaweiNum()));
                        }
                    }  else if(entityTmp.getHuaweiNum() > 0){// 只同步没有华为账号的
                        
                        boolean result = this.updateAccountInfo(entityTmp, null, true);
                        System.out.println("【"+count+"/"+size+"】【UPDATE】【"+entityTmp.getId()+"】【"+entityTmp.getSeatName()+"】"+result);
                    } else{
                        
                        System.out.println("【"+count+"/"+size+"】【IGNORE】【"+entityTmp.getId()+"】【"+entityTmp.getSeatName()+"】"+entityTmp.getHuaweiNum());
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                count++;
            }
        }
    }
    /**
     * 同步用户列表
     * 
     * @author renmb
     * @time  2017年1月17日
     * @param userProfileEntities
     * @return
     */
    public void addAccountToUc(List<UserProfileEntity> userProfileEntities) {
        
        if (userProfileEntities != null && userProfileEntities.size() != 0) {// 处理用户
            int count = 1;
            int size = userProfileEntities.size();
            for (UserProfileEntity entityTmp : userProfileEntities) {
                try {
                    if("1".equals(entityTmp.getDelFlag())){// 删除账号
                        
                        boolean result = this.deleteUCAccount(entityTmp.getId());
                        System.out.println("【"+count+"/"+size+"】【DELETE】【"+entityTmp.getId()+"】【"+entityTmp.getName()+"】"+result);
                        if(entityTmp.getHuaweiNum() != null){
                            
                            this.deleteSipNum(String.valueOf(entityTmp.getHuaweiNum()));
                        }
                    } else if(entityTmp.getHuaweiNum() == null){// 只同步没有华为账号的
                        HuaweiPersonInfoEntity personInfo = getPersonInfo(entityTmp.getId());
                        // 如果该账号已经存在UC服务器中，则更新该条数据
                        if (personInfo != null && StringUtils.isNotBlank(personInfo.getStaffId())) {
//                            String result = updateUserAccountToUcClose(entityTmp, personInfo.getStaffId());
                            boolean result = this.updateAccountInfo(entityTmp, personInfo, false);
//                            sb.append(result);
                            System.out.println("【"+count+"/"+size+"】【UPDATE】【"+entityTmp.getId()+"】【"+entityTmp.getName()+"】"+result);
                        } else {
                            // 添加用户账号到uc服务器中，包括外部联系人，新增的账号的UC状态为关闭
                            String result = addUserAccountToUcClose(entityTmp);
//                            sb.append(result);
                            System.out.println("【"+count+"/"+size+"】【ADD】【"+entityTmp.getId()+"】【"+entityTmp.getName()+"】"+result);
                        }
                    } else if(entityTmp.getHuaweiNum() > 0){// 同步有华为账号的
                        
                        boolean result = this.updateAccountInfo(entityTmp, null, true);
                        System.out.println("【"+count+"/"+size+"】【UPDATE】【"+entityTmp.getId()+"】【"+entityTmp.getName()+"】"+result);
                    } else{
                        
                        System.out.println("【"+count+"/"+size+"】【IGNORE】【"+entityTmp.getId()+"】【"+entityTmp.getName()+"】"+entityTmp.getHuaweiNum());
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
                count++;
            }
        }
//        return sb.toString();
    }

    private String updateUserAccountToUcClose(UserProfileEntity userProfileEntity, 
            String accountId) {
        try {
            List<Office> officeInfos = getDepInfo(userProfileEntity);
            // 得到父UC部门id
            String departmentId = syncUCUserDepart(userProfileEntity, officeInfos);
            UcAccountEntity ucAccountEntity = new UcAccountEntity(userProfileEntity.getId(), "USER");
            boolean updateResult = updateAccountInfo(userProfileEntity, accountId, departmentId, false);
            String message = null;
            if (updateResult) { // 添加UC账号成功
                message = "更新UC账号 成功 （电话，邮箱等信息）,UC业务为关闭。    ";
                ucAccountEntity.setHuaweiPassword(
                        userProfileEntity.getId().length() > 1 ? userProfileEntity.getId().substring(0, 2) + "@foc2016"
                                : String.format("%02d", userProfileEntity.getId()) + "@foc2016");
                ucAccountEntity.setHuaweiId(accountId);

                ucAccountEntity.setSyncMessage(message);
            } else {
                message = new StringBuilder("id为").append(userProfileEntity.getId()).append("的用户，")
                        .append("更新UC账号 失败 （电话，邮箱等信息）。   ").toString();
            }
            ucAccountEntity.setBindStatus("UNBIND");
            ucAccountEntity.setUpdateDate(new Date());
            // huaweiUCSyncDao.saveUcAccount(ucAccountEntity);
            return message;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return new StringBuilder("id为").append(userProfileEntity.getId()).append("的用户，")
                .append("更新UC账号 失败 （电话，邮箱等信息）。   ").toString();
    }

    /**
     * 更新用户账号信息
     *
     * @param userProfileEntity
     * @param ucOpen
     *            是否开启UC业务
     */
//    private boolean updateAccountInfo(UserProfileEntity userProfileEntity, String staffId,
//            String departmentId, boolean ucOpen) {
//        return updateAccountInfo(userProfileEntity, personInfo.getStaffId(), departmentId, ucOpen);
//    }

    /**
     * 更新用户账号信息
     *
     * @param userProfileEntity
     * @param ucOpen
     *            是否开启UC业务
     */
    private boolean updateAccountInfo(UserProfileEntity userProfileEntity, String accountId, String departmentId,
            boolean ucOpen) {
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            HuaweiAccountUpdateBean accountUpdateBean = new HuaweiAccountUpdateBean();
            accountUpdateBean.setAccountType(ucOpen ? "2" : "0");
            if(userProfileEntity.getHuaweiNum() != null){
                accountUpdateBean.setAccountType("2");
            }
            accountUpdateBean.setAccountId(accountId);
            accountUpdateBean.setName(StringUtils.isBlank(userProfileEntity.getName()) ? "未填写" : userProfileEntity.getName());
//            accountUpdateBean.setSex(userProfileEntity.getSex().toString().equals("M") ? "0" : "1");
            if(StringUtils.isNotEmpty(userProfileEntity.getSex())){
                
                accountUpdateBean.setSex("M".equals(userProfileEntity.getSex()) ? "0" : "1");
            }
            // accountUpdateBean.setHomePhone(homePhone);
            if(StringUtils.isEmpty(userProfileEntity.getMobileNubmer())){
                
                accountUpdateBean.setCellPhone(Util.formatedMobile(userProfileEntity.getMobile()));
            } else {
                
                accountUpdateBean.setCellPhone(userProfileEntity.getMobileNubmer());
            }
//            accountUpdateBean.setCellPhone(Util.formatedMobile(userProfileEntity.getMobile()));
            accountUpdateBean.setOfficePhone(Util.formatedWorkPhone(userProfileEntity.getPhone()));
            // accountUpdateBean.setShortPhone(shortPhone);
            // accountUpdateBean.setOtherPhone(otherPhone);
            accountUpdateBean.setFax(userProfileEntity.getFax());
            if (StringUtils.isNotBlank(userProfileEntity.getEmail())
                    && userProfileEntity.getEmail().matches(mailRegex)) {
                accountUpdateBean.setEmail(userProfileEntity.getEmail());
            }
            accountUpdateBean.setAddr(Util.getAbsoluteUrl(userProfileEntity.getPhoto()));
            accountUpdateBean.setTitle(userProfileEntity.getDutyName());
            accountUpdateBean.setDepartmentId(departmentId);
            accountUpdateBean.setUserLevel("1");
            accountUpdateBean.setRoleId("1");
            params.put("userId", userId);
            params.put("account", accountUpdateBean);
            RestRequestMessage restRequestMessage = new RestRequestMessage();
            restRequestMessage.setHttpMethod("PUT");
            restRequestMessage.setPayload(params);
            RestUtils restUtils = RestUtils.getInstance();
            try {
                String res = restUtils.sendMessage(restRequestMessage, accountRestUrl);
                System.out.println(res);
                if (StringUtils.isNoneBlank(res)) {
                    HuaweiQueryResponseEntity responseEntity = JSONObject.parseObject(res,
                            HuaweiQueryResponseEntity.class);
                    if (responseEntity.getResultCode().equals("0")) {
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询用户部门信息
     *
     * @param userProfileEntity
     * @return
     */
    private List<Office> getDepInfo(UserProfileEntity userProfileEntity) {
        List<Office> offices = new ArrayList<Office>();
        Office office = userProfileEntity.getOffice();
        while (office != null && !office.getId().trim().equals("0")) {
            offices.add(office);
            office = getParentOfficeInfo(office.getParentId()); // 查询父部门信息
        }
        Collections.reverse(offices);
        return offices;
    }

    /**
     * 添加账号到UC当中
     *
     * @param departmentId
     * @param userProfileEntity
     * @param ucOpen
     *            是否开启UC业务
     * @return
     * @author liuyw
     * @time 2016年9月23日
     */
    public String addUserAccountToUC(String departmentId, UserProfileEntity userProfileEntity, boolean ucOpen) {
        AddAccountRequest accountInfo = new AddAccountRequest();
        accountInfo.setUserId(userId);
        accountInfo.setAccount(new Account());
        // 帐号类型 ，是否开启EC：
        // 0：不开通
        // 2：开通
        accountInfo.getAccount().setAccountType(ucOpen ? "2" : "0");
        // 设置UC账号
        accountInfo.getAccount().setLoginName(userProfileEntity.getId());
        accountInfo.getAccount().setPassword(
                userProfileEntity.getId().length() > 1 ? userProfileEntity.getId().substring(0, 2) + "@foc2016"
                        : String.format("%02d", userProfileEntity.getId()) + "@foc2016");
        // accountInfo.getAccount().setPassword(userProfileEntity.getId().substring(0,2)
        // + "@foc2016");
        accountInfo.getAccount()
                .setName(StringUtils.isBlank(userProfileEntity.getName()) ? "未填写" : userProfileEntity.getName());
        accountInfo.getAccount().setRoleId("1");
        accountInfo.getAccount().setUserLevel("1");
        accountInfo.getAccount().setUserState("0");
        accountInfo.getAccount().setDepartmentId(departmentId);
        if(StringUtils.isNotEmpty(userProfileEntity.getSex())){
            
            accountInfo.getAccount().setSex("M".equals(userProfileEntity.getSex()) ? "0" : "1");
        }
        
        if(StringUtils.isEmpty(userProfileEntity.getMobileNubmer())){
            
            accountInfo.getAccount().setCellPhone(Util.formatedMobile(userProfileEntity.getMobile()));
        } else {
            
            accountInfo.getAccount().setCellPhone(userProfileEntity.getMobileNubmer());
        }
        
        accountInfo.getAccount().setWebsite(userProfileEntity.getName());
        accountInfo.getAccount().setOfficePhone(Util.formatedWorkPhone(userProfileEntity.getPhone()));
        accountInfo.getAccount().setFax(userProfileEntity.getFax());
        if (StringUtils.isNotBlank(userProfileEntity.getEmail()) && userProfileEntity.getEmail().matches(mailRegex)) {
            accountInfo.getAccount().setEmail(userProfileEntity.getEmail());
        }
        accountInfo.getAccount().setAddr(Util.getAbsoluteUrl(userProfileEntity.getPhoto()));
        accountInfo.getAccount().setTitle(userProfileEntity.getDutyName());

        UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);
        // 调用userProfileServiceEx服务中的addAccount方法，返回错误码
        RestResponse<String> res = userProfileServiceEx.addAccount(accountInfo);
        if ("0".equals(res.getResultCode())) {
            // 增加成功
            return res.getResult();
        }
        return null;
    }

    /**
     * 添加用户信息到UC服务器中，UC状态为关闭
     *
     * @param
     */
    private String addUserAccountToUcClose(UserProfileEntity userProfileEntity) {
        try {
            List<Office> officeInfos = getDepInfo(userProfileEntity);
            // 得到父UC部门id
            String departmentId = syncUCUserDepart(userProfileEntity, officeInfos);
            UcAccountEntity ucAccountEntity = new UcAccountEntity(userProfileEntity.getId(), "USER");
            String accountId = addUserAccountToUC(departmentId, userProfileEntity, false);
            String message = null;
            if (accountId != null) { // 添加UC账号成功
                message = "添加UC账号 成功 （电话，邮箱等信息）,UC业务为关闭。    ";
                ucAccountEntity.setHuaweiPassword(
                        userProfileEntity.getId().length() > 1 ? userProfileEntity.getId().substring(0, 2) + "@foc2016"
                                : String.format("%02d", userProfileEntity.getId()) + "@foc2016");
                ucAccountEntity.setHuaweiId(accountId);

                ucAccountEntity.setSyncMessage(message);
            } else {
                message = new StringBuilder("id为").append(userProfileEntity.getId()).append("的用户，")
                        .append("添加UC账号 失败 （电话，邮箱等信息）。   ").toString();
            }
            ucAccountEntity.setBindStatus("UNBIND");
            ucAccountEntity.setUpdateDate(new Date());
            // huaweiUCSyncDao.saveUcAccount(ucAccountEntity);
            return message;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return new StringBuilder("id为").append(userProfileEntity.getId()).append("的用户，")
        .append("添加UC账号 失败 （电话，邮箱等信息）。   ").toString();
    }

    /**
     * 查看当前用户是否已经存在在UC
     *
     * @param id
     *            用户或者席位id
     * @return
     */
    public HuaweiPersonInfoEntity getPersonInfo(String id) {

        // RestUtils restUtils = RestUtils.getInstance();
        try {
            // 得到格式化后的华为账号信息
            // id = Util.getUcAccount(id);
            RestRequestMessage restRequestMessage = new RestRequestMessage();
            restRequestMessage.setHttpMethod("GET");

            Map<String, String> params = new HashMap<String, String>();
            params.put("staffAccount", id);
            restRequestMessage.setParameters(params);
            RestUtils restUtils = RestUtils.getInstance();
            String res = restUtils.sendMessage(restRequestMessage, personInfoUrl);
            HuaweiPersonInfoResult result = JSON.parseObject(res, HuaweiPersonInfoResult.class);
            if (result.getResultCode().equals("0")) {
                return result.getPersonInfo();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 同步当前用户部门信息：逻辑为若当前用户的部门不在UC中，则在UC中新增,并返回新增部门的id，用来添加账号，密码,否则返回对应UC部门的id
     *
     * @author liuyw
     * @time 2016年9月23日
     */
    public String syncUCUserDepart(UserProfileEntity userProfileEntity, List<Office> officeInfos) {
        // 没有部门信息，直接放在根部门下
        if (userProfileEntity.getOffice() == null || StringUtils.isBlank(userProfileEntity.getOffice().getName())) {
            return "1";
        }

        // 开始进行检索，先查找第一级即首航下面一级的所有部门信息，然后与参数传递的officeInfos当前用户的所有
        // 部门信息的第一级进行字段匹配（逐级增加），如果第一级匹配，则进行第二级匹配(直到officeInfos都走过)。
        // 如果第一级没有匹配，则需要把用户所有部门信息添加进去，如果第一级匹配，第二级没有匹配，则直接将第一级的
        // departmentId作为parentId进行第二级部门的添加，更多部门如下
        int dindex = 0; // 循环索引
        String parentId = "1"; // 查询用到的parentId
        String pageCount = "99";

        while (dindex < officeInfos.size()) {
            List<QueryDepartmentInfo> queryDepartmentInfosTmp = new ArrayList<QueryDepartmentInfo>();
            int i = 1; // 查询索引
            do {
                UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);
                // 查询开始
                RestResponse<QueryDepartmentInfoList> res = userProfileServiceEx.queryDeptListInfo(userId, parentId,
                        pageCount, String.valueOf(i));
                if ("0".equals(res.getResultCode())) {
                    // 查询成功，则返回部门列表
                    QueryDepartmentInfoList depts = res.getResult();

                    // 本次查询到的部门信息
                    List<QueryDepartmentInfo> departmentInfosTmp2 = depts.getDepartmentInfoList();

                    if (departmentInfosTmp2 != null) {
                        queryDepartmentInfosTmp.addAll(departmentInfosTmp2);
                    }
                }

            } while (Integer.parseInt(pageCount) * i++ == queryDepartmentInfosTmp.size()); // 如果还有下一页信息

            boolean stopFlag = true;
            // 对查询结果进行检索
            for (int j = 0; j < queryDepartmentInfosTmp.size(); j++) {
                if (queryDepartmentInfosTmp.get(j).getDepartmentName().equals(officeInfos.get(dindex).getName())) {
                    stopFlag = false;
                    dindex++;
                    parentId = queryDepartmentInfosTmp.get(j).getDepartmentId();
                    break;
                }
            }

            if (stopFlag) {
                break;
            }
        }

        if (dindex < officeInfos.size()) {
            for (int i = dindex; i < officeInfos.size(); i++) {
                parentId = addUCDepart(officeInfos.get(i).getName(), parentId, userId);
            }
        } else {
            return parentId;
        }
        return parentId == null ? "1" : parentId;
    }

    public String addUCDepart(String departmentName, String parentId, String userId) {
        try {
            DepartmentRequest dept = new DepartmentRequest();
            dept.setUserId(userId);
            dept.setParentId(parentId);
            dept.setDepartmentName(departmentName);
            UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);
            // 调用userProfileServiceEx服务中的addDept方法，返回错误码
            RestResponse<AddDepartmentResult> res = userProfileServiceEx.addDept(dept);

            if ("0".equals(res.getResultCode())) {
                // getUCDepartInfo(userProfileServiceEx, departmentInfos, "123",
                // "1", "99");
                return res.getResult().getDepartmentId();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 得到所有的sip号码
     * @return
     */
    public List<SipAccount> getAllSipAccounts() {
        SipQueryRequest req = new SipQueryRequest();
        req.setUserId(userId);
        req.setExactSearch("0");
        req.setPageCount("99");
        req.setType("0");
        req.setValue(".");
        int pageNum = 1;
        RestResponse<SipList> res = null;
        //第一个sip号码账号
        SipAccount sipAccountFirst = null;
        //用来存储所有的sip账号
        List<SipAccount> sipAccounts = new ArrayList<>();
        //继续循环的一个标记
        boolean continueFlag = true;
        do {
            UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);
            req.setPageNum(String.valueOf(pageNum));
            //调用userProfileServiceEx服务中的queryNumber方法，返回错误码
            res = userProfileServiceEx.queryNumber(req);
            if ("0".equals(res.getResultCode()) && res.getResult() != null && res.getResult().getSips() != null && res.getResult().getSips().size() > 0) {
                if (pageNum == 1) {
                    sipAccountFirst = res.getResult().getSips().get(0);
                }
                //如果当前不是第一页，但是返回了第一页的内容，那么就不需要进行再次查询了
                if (pageNum != 1  && (sipAccountFirst == null || res.getResult().getSips().get(0).getSipUe().equals(sipAccountFirst.getSipUe()))) {
                    continueFlag = false;
                }
                if (continueFlag) {
                    sipAccounts.addAll(res.getResult().getSips());
                }
            }
            //下一页
            pageNum ++;
        } while (continueFlag && res.getResult() != null && res.getResult().getAmount() == 99); //继续循环查询的条件要同时满足：1.当前查询有结果，且返回的数据的个数为99。2.continueFlag为true
        return sipAccounts;
    }
    
    public Integer getSipNumIgnoreMaxSipNum() {
        //得到所有的sip号码
        List<SipAccount> sipAccounts = getAllSipAccounts();
        //所有的sip号码按照大小正序排序去重
        Set<Integer> numbers = new TreeSet<>();
        if (sipAccounts != null && sipAccounts.size()>0) {
            for (SipAccount accountTmp : sipAccounts) {
                numbers.add(Integer.parseInt(accountTmp.getNumber()));
            }
        }
        // 得到需要的空闲的sip号码
        if (!CollectionUtils.isEmpty(numbers)) {
            Integer [] numberArr = numbers.toArray(new Integer[]{});
            for (int i = 0; i < numberArr.length - 1; i ++) {
                //如果 当前号码+1 等于 下一个号码，则跳过，否则就用 当前号码+1
                if (numberArr[i] + 1 != numberArr[i + 1]) {
                    return numberArr[i] + 1;
                }
            }
            //若循环完都没有,则使用最后（最大）一个号码+1作为当前使用的号码
            return numberArr[numberArr.length - 1] + 1;
        }

        return null;
    }
    private boolean addUCNumber() {
        try {
            UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);

            SipRequest numberInfo = new SipRequest();
            numberInfo.setUserId(userId);
            numberInfo.setSip(new SipAccount());
            numberInfo.getSip().setGwIp(gwIp);
            numberInfo.getSip().setSubPbx("1");
            numberInfo.getSip().setLocalGwIp("");
            numberInfo.getSip().setJoint("0");
            //是否忽略系统最大的sip号码，忽略的话只根据配置进行处理，得到sip号码，包括号码之间的空隙，若没有空隙则sip号码最大值+1
            Integer maxSipNum = getSipNumIgnoreMaxSipNum();

//            numberInfo.getSip().setSipUe(String.valueOf(ignoreNum != null && ignoreNum.equals(maxSipNum)  ? ++ maxSipNum : maxSipNum));
            numberInfo.getSip().setSipUe(String.valueOf(maxSipNum));
            numberInfo.getSip().setUeType("2");
            numberInfo.getSip().setNumber(String.valueOf(maxSipNum));
//            numberInfo.getSip().setLongNum("6000" + String.valueOf(maxSipNum));
            numberInfo.getSip().setLongNum("");
            numberInfo.getSip().setRightLevel("2");
//            numberInfo.getSip().setAddPrefix("1");
            numberInfo.getSip().setAddPrefix("0");
            numberInfo.getSip().setbOutgoingRights("1111000000000000");
//            numberInfo.getSip().setcOutgoingRights("11111111111111111111111111111111");
            numberInfo.getSip().setSipAuth(new SipAuth());
            numberInfo.getSip().getSipAuth().setType("1");
            numberInfo.getSip().getSipAuth().setPassword(maxSipNum + "@foc2016");
            //调用userProfileServiceEx服务中的addNumber方法，返回错误码
            Integer res = userProfileServiceEx.addNumber(numberInfo);

            if (0 == res) {
                return true;
            } else {
                maxSipNum--;
                return false;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
    
    public boolean bindSipNumWithAccount(String accountId, String sipNum) {
        try {
            HuaweiPersonInfoEntity personInfo = getPersonInfo(accountId);
            
            UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);
            AddAccountRequest accountInfo = new AddAccountRequest();
            accountInfo.setUserId(userId);
            accountInfo.setAccount(new Account());
            accountInfo.getAccount().setAccountId(personInfo.getStaffId());
            accountInfo.getAccount().setBindNum(sipNum);
            Integer res = userProfileServiceEx.numberBind(accountInfo);
            if (res != null && 0 == res) {
                return true;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
    /**
     * 删除sip号码
     *
     * @param bindNum
     * @return
     */
    private boolean deleteSipNum(String bindNum) {
        
        try {
            RestRequestMessage restRequestMessage = new RestRequestMessage();
            restRequestMessage.setHttpMethod("POST");
            HuaweiSipDelBean delBean = new HuaweiSipDelBean();
            delBean.setNumber(bindNum);
            delBean.setGwIp(gwIp);
            delBean.setDeleteSipUe("1");
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", userId);
            params.put("sip", delBean);
            restRequestMessage.setPayload(params);
            
            RestUtils restUtils = RestUtils.getInstance();
            String res = restUtils.sendMessage(restRequestMessage, sipDelUrl);
            if (StringUtils.isNoneBlank(res)) {
                HuaweiQueryResponseEntity responseEntity = JSONObject.parseObject(res, HuaweiQueryResponseEntity.class);
                if (responseEntity.getResultCode().equals("0")) {
                    
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public boolean deleteUCAccount(String accountId) {
        
        try {
            HuaweiPersonInfoEntity personInfo = getPersonInfo(accountId);
            
            RestRequestMessage restRequestMessage = new RestRequestMessage();
            restRequestMessage.setHttpMethod("DELETE");
            Map<String, String> params = new HashMap<String, String>();
            params.put("userId", userId);
            params.put("accountId", personInfo.getStaffId());
            restRequestMessage.setParameters(params);
            
            RestUtils restUtils = RestUtils.getInstance();
            String res = restUtils.sendMessage(restRequestMessage, accountRestUrl);
            if (StringUtils.isNotBlank(res)) {
                HuaweiQueryResponseEntity queryResponseEntity = JSONObject.parseObject(res, HuaweiQueryResponseEntity.class);
                if (queryResponseEntity.getResultCode().equals("0")) {
                    return true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    
    /**
     * 添加席位信息到UC服务器中
     * 
     * @param departmentId
     * @param seatEntity
     * @param ucOpen
     * @return
     */
    private String addSeatAccountToUC(SeatEntity seatEntity, boolean ucOpen) {
        
        AddAccountRequest accountInfo = new AddAccountRequest();
        accountInfo.setUserId(userId);
        accountInfo.setAccount(new Account());
        accountInfo.getAccount().setAccountType(ucOpen ? "2" : "0");
        accountInfo.getAccount().setLoginName(Util.getUcAccount(seatEntity.getId()));
        accountInfo.getAccount().setPassword(seatEntity.getId().length() > 1 ? seatEntity.getId().substring(0, 2) + "@foc2016" : String.format("%02d", seatEntity.getId()) + "@foc2016");
        accountInfo.getAccount().setName(StringUtils.isBlank(seatEntity.getSeatName()) ? "未填写" : seatEntity.getSeatName());
        accountInfo.getAccount().setRoleId("1");
        accountInfo.getAccount().setUserLevel("1");
        accountInfo.getAccount().setUserState("0");
        accountInfo.getAccount().setDepartmentId("1");
        accountInfo.getAccount().setOfficePhone(Util.formatedWorkPhone(seatEntity.getSeatPhone()));
        UserProfileServiceEx userProfileServiceEx = ServiceFactoryEx.getService(UserProfileServiceEx.class);
        //调用userProfileServiceEx服务中的addAccount方法，返回错误码
        RestResponse<String> res = userProfileServiceEx.addAccount(accountInfo);

        if ("0".equals(res.getResultCode())) {
            //增加成功
            return res.getResult();
        }
        return null;
    }
    
    /**
     * 更新席位信息
     * 
     * @author renmb
     * @time  2017年3月11日
     * @param seatEntity
     * @param ucOpen
     * @return
     */
    public boolean updateAccountInfo(SeatEntity seatEntity, HuaweiPersonInfoEntity personInfo, boolean ucOpen) {

        try {
            
            if(personInfo == null){
                
                personInfo = getPersonInfo(seatEntity.getId());
            }
            if (personInfo == null || StringUtils.isNotBlank(personInfo.getStaffId())) {// 如果该账号已经存在UC服务器中，则更新该条数据
                
                return false;
            }
            String name = StringUtils.isBlank(seatEntity.getSeatName()) ? "未填写" : seatEntity.getSeatName();
            String phone = Util.formatedWorkPhone(seatEntity.getSeatPhone());
            if(name.equals(personInfo.getName()) 
                    && StringUtils.isNotEmpty(phone) 
                        && phone.equals(personInfo.getOfficePhone())){// 信息未发生变化
                
                System.out.println("席位信息未发生变化：【"+personInfo.getName()+"】【"+personInfo.getOfficePhone()+"】");
                return true;
            }
            String accountId = personInfo.getStaffId();
            String departmentId = "1"; 
            
            Map<String, Object> params = new HashMap<String, Object>();
            HuaweiAccountUpdateBean accountUpdateBean = new HuaweiAccountUpdateBean();
            accountUpdateBean.setAccountType(ucOpen ? "2" : "0");
            accountUpdateBean.setAccountId(accountId);
            accountUpdateBean.setName(name);
            accountUpdateBean.setOfficePhone(phone);
            accountUpdateBean.setDepartmentId(departmentId);
            accountUpdateBean.setUserLevel("1");
            accountUpdateBean.setRoleId("1");
            params.put("userId", userId);
            params.put("account", accountUpdateBean);
            RestRequestMessage restRequestMessage = new RestRequestMessage();
            restRequestMessage.setHttpMethod("PUT");
            restRequestMessage.setPayload(params);
            try {
                RestUtils restUtils = RestUtils.getInstance();
                String res = restUtils.sendMessage(restRequestMessage, accountRestUrl);
                System.out.println(res);
                if (StringUtils.isNoneBlank(res)) {
                    HuaweiQueryResponseEntity responseEntity = JSONObject.parseObject(res, HuaweiQueryResponseEntity.class);
                    if (responseEntity.getResultCode().equals("0")) {
                        
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return false;
    }
    
    
    /**
     * 更新用户信息
     * 
     * @author renmb
     * @time  2017年3月11日
     * @param userProfileEntity
     * @param ucOpen
     * @return
     */
    public boolean updateAccountInfo(UserProfileEntity userProfileEntity, HuaweiPersonInfoEntity personInfo, boolean ucOpen) {
        try {
            if(personInfo == null){
                
                personInfo = getPersonInfo(userProfileEntity.getId());
            }
            if (personInfo == null || StringUtils.isNotBlank(personInfo.getStaffId())) {// 如果该账号已经存在UC服务器中，则更新该条数据
                
                return false;
            }
            String accountId = personInfo.getStaffId();
            List<Office> officeInfos = getDepInfo(userProfileEntity);
            // 得到父UC部门id
            String departmentId = syncUCUserDepart(userProfileEntity, officeInfos);
            
            HuaweiAccountUpdateBean accountUpdateBean = new HuaweiAccountUpdateBean();
            accountUpdateBean.setAccountType(ucOpen ? "2" : "0");
            if(userProfileEntity.getHuaweiNum() != null){
                accountUpdateBean.setAccountType("2");
            }
            accountUpdateBean.setAccountId(accountId);
            accountUpdateBean.setName(StringUtils.isBlank(userProfileEntity.getName()) ? "未填写" : userProfileEntity.getName());
            if(StringUtils.isNotEmpty(userProfileEntity.getSex())){
                
                accountUpdateBean.setSex("M".equals(userProfileEntity.getSex()) ? "0" : "1");
            }
            if(StringUtils.isEmpty(userProfileEntity.getMobileNubmer())){
                
                accountUpdateBean.setCellPhone(Util.formatedMobile(userProfileEntity.getMobile()));
            } else {
                
                accountUpdateBean.setCellPhone(userProfileEntity.getMobileNubmer());
            }
            accountUpdateBean.setOfficePhone(Util.formatedWorkPhone(userProfileEntity.getPhone()));
            accountUpdateBean.setFax(userProfileEntity.getFax());
            if (StringUtils.isNotBlank(userProfileEntity.getEmail())
                    && userProfileEntity.getEmail().matches(mailRegex)) {
                accountUpdateBean.setEmail(userProfileEntity.getEmail());
            }
            accountUpdateBean.setAddr(Util.getAbsoluteUrl(userProfileEntity.getPhoto()));
            accountUpdateBean.setTitle(userProfileEntity.getDutyName());
            accountUpdateBean.setDepartmentId(departmentId);
            accountUpdateBean.setUserLevel("1");
            accountUpdateBean.setRoleId("1");
            
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("userId", userId);
            params.put("account", accountUpdateBean);
            
            
            RestRequestMessage restRequestMessage = new RestRequestMessage();
            restRequestMessage.setHttpMethod("PUT");
            restRequestMessage.setPayload(params);
            RestUtils restUtils = RestUtils.getInstance();
            try {
                String res = restUtils.sendMessage(restRequestMessage, accountRestUrl);
                System.out.println(res);
                if (StringUtils.isNoneBlank("updateAccountInfo res"+res)) {
                    HuaweiQueryResponseEntity responseEntity = JSONObject.parseObject(res,
                            HuaweiQueryResponseEntity.class);
                    if (responseEntity.getResultCode().equals("0")) {
                        return true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return false;
    }
}
