/**
 *
 */
package com.uc.demo;

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.fetcher.HCFetcher;
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.UcAccountEntity;
import com.uc.entity.UserProfileEntity;

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

    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");
    
    /**
     * 
     * @author renmb
     * @time 2017年1月17日
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        try {
            UCDepartmentDemo demo = new UCDepartmentDemo();
            for(int i=0,len=args.length;i<len;i++){
                System.out.println(args[i]);
                List<UserProfileEntity> users = demo.findUserList(args[i]);
                String message = demo.addAccountToUc(users);
                System.out.println("结果： "+message);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        HCFetcher.getInstance().shutdown();
        System.exit(0);
    }
    public List<UserProfileEntity> findUserList(String userId) {
        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("       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("       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.del_flag='0' ");
//            builder.append(" AND a.huawei_num IS NULL ");
            
            if(StringUtils.isNotEmpty(userId)){
                
                builder.append(" AND a.id=? ");
            } else {
                
                builder.append(" AND a.huawei_num IS NULL ");
            }
            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(StringUtils.isNotEmpty(userId)){
                list = run.query(builder.toString(), handler, userId);
            } 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;
    }
    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(); 
    }
    /**
     * 同步用户列表
     * 
     * @author renmb
     * @time  2017年1月17日
     * @param userProfileEntities
     * @return
     */
    public String addAccountToUc(List<UserProfileEntity> userProfileEntities) {
        StringBuffer sb = new StringBuffer();
//        List<UserProfileEntity> userProfileEntities = findUserListAll();
        // 处理用户
        if (userProfileEntities != null && userProfileEntities.size() != 0) {
            for (UserProfileEntity entityTmp : userProfileEntities) {
                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();
    }

    private String updateUserAccountToUcClose(UserProfileEntity userProfileEntity, 
            String accountId) {
        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;
    }

    /**
     * 更新用户账号信息
     *
     * @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");
            // accountUpdateBean.setHomePhone(homePhone);
            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);
        accountInfo.getAccount().setSex(userProfileEntity.getSex().toString().equals("M") ? "0" : "1");
        accountInfo.getAccount().setCellPhone(Util.formatedMobile(userProfileEntity.getMobile()));
        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) {
        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;
    }

    /**
     * 查看当前用户是否已经存在在UC
     *
     * @param id
     *            用户或者席位id
     * @return
     */
    public HuaweiPersonInfoEntity getPersonInfo(String id) {
        // 得到格式化后的华为账号信息
        // 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();
        try {
            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);
            
            Account account = new Account();
            
            account.setAccountId(personInfo.getStaffId());
            account.setBindNum(sipNum);
            
            accountInfo.setAccount(account);
            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) {
        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);
        try {
            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);
            
            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;
    }
}
