package com.artfess.xqxt.meeting.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.base.util.EncryptUtil;
import com.artfess.base.util.StringUtil;
import com.artfess.uc.exception.BaseException;
import com.artfess.xqxt.meeting.dto.MeetingDTO;
import com.artfess.xqxt.meeting.m900.bean.*;
import com.artfess.xqxt.meeting.m900.request.*;
import com.artfess.xqxt.meeting.m900.response.*;
import com.artfess.xqxt.meeting.manager.BizSiteParamExManager;
import com.artfess.xqxt.meeting.manager.BizTerminalManager;
import com.artfess.xqxt.meeting.manager.MeetingManager;
import com.artfess.xqxt.meeting.manager.ZTEManager;
import com.artfess.xqxt.meeting.model.BizSiteParamEx;
import com.artfess.xqxt.meeting.model.BizTerminal;
import com.artfess.xqxt.meeting.model.MeetingPlace;
import com.artfess.xqxt.meeting.model.ZTEErrorCode;
import com.artfess.xqxt.meeting.vo.BizSiteParamExVO;
import com.artfess.xqxt.meeting.vo.HistoryConferenceVO;
import com.artfess.xqxt.meeting.vo.MeetingVO;
import com.artfess.xqxt.meeting.zteService.MultimediaConferenceServiceLocator;
import com.artfess.xqxt.meeting.zteService.MultimediaConferenceSoapBindingStub;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.SOAPHeaderElement;
import org.apache.commons.lang3.StringUtils;
import org.docx4j.wml.P;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.util.calendar.Gregorian;

import javax.annotation.Resource;
import javax.xml.namespace.QName;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.*;

@Service
public class ZTEManagerImpl implements ZTEManager {



    @Value("${zte.userName}")
    private String userName;

    @Value("${zte.password}")
    private String password;

    @Value("${zte.url}")
    private String url;

    @Resource
    private BizSiteParamExManager siteParamExManager;

    @Resource
    private BizTerminalManager terminalManager;

    @Resource
    private BizSiteParamExManager bizSiteParamExManager;

    @Resource
    private MeetingManager meetingManager;


    @Override
    public CreateConferenceResponse sendMeeting(MeetingDTO dto) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            CreateConferenceRequest request = new CreateConferenceRequest();
            request.setConferenceName(dto.getTheme());
            // 会 议 开 始 时 间 (即时会议此字段 不填) 如 ： 2014/03/10 11:06:44
            long minutes = 0L;
            if(null != dto.getStartTime()){
                Duration duration = Duration.between(LocalDateTime.now(),dto.getStartTime());
                minutes = duration.toMinutes();//相差的分钟数
                if(minutes > 5L){
                    request.setStartTime(GregorianCalendar.from(ZonedDateTime.of(dto.getStartTime(), ZoneId.systemDefault())));
                }else {

                }
            }else {
                dto.setStartTime(LocalDateTime.now());
            }
            request.setAccount(userName);
            // 计算时长
            Duration dur = Duration.between(dto.getStartTime(),dto.getEndTime() );
            // 会议时长，不填或 填 0 则使用系统 默认配置的上限 值为准)，单位： 分钟
            int duration = 0;
            // 如果是及时会议，需要补充结束时间的差值
            if(minutes <=5 && minutes > 0){
                duration = (int)(dur.toMinutes() + minutes);
            }
            request.setDuration(duration);
            // 多画面最大画面数据
            int multiViewNumber = dto.getPlaces().size();
            if(multiViewNumber > 8){
                multiViewNumber = 8;
            }
            request.setMultiViewNumber(multiViewNumber);
            //会议多画面模式： auto:自动控制多画面(默认)；manual:手动控制
            request.setMultiPicControl("manual");
            // 允许最多会议成 员的数量，不填默 认为 1
            request.setMaxParticipants(10000);
            // 是否支持 Sip 主 叫带 SDP 0：不支持 1：支持
            request.setInviteWithSDP(1);
            RecordParam recordParam = new RecordParam();
            // 是否支持录制
            recordParam.setIfRecord(true);
            // 是否支持直播
            recordParam.setIfLive(true);
            // 会议编号
            if(StringUtils.isNotBlank(dto.getConferenceNumber())){
                request.setConferenceNumber(dto.getConferenceNumber());
            }

            request.setRecord(recordParam);
            Participant[] participants = new Participant[dto.getPlaces().size()];
            for (int i =0;i<dto.getPlaces().size();i++){
                Participant participant = new Participant();
                BeanUtils.copyProperties(dto.getPlaces().get(i),participant);
                participants[i] = participant;
            }
            request.setParticipants(participants);
            CreateConferenceResponse response = mStub.createConference(request);
            return response;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    //获取token
    @Override
    public String getToken() {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            header.addChild(element);
            mStub.clearHeaders();
            mStub.setHeader(header);
            LoginRequest request = new LoginRequest();
            LoginResponse response ;
            request.setUserName(userName);
            request.setPassword(EncryptUtil.encryptMd5Hash(password));
            response = mStub.login(request);
            String token = EncryptUtil.encryptMd5Hash(password+response.getRandomKey()).toLowerCase();
            return token;
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
    }

    //同步终端地址薄
    @Override
    public String getAddresBook() {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetAddressBookRequest request = new GetAddressBookRequest();
            request.setAccount(userName);
            request.setPage(1);
            request.setNumPerPage(100);
            GetAddressBookResponse response = mStub.getAddressBook(request);
            if ("200".equals(response.getResult())){
                TerminalSimpleInfo[] reList = response.getTerminalInfo();
                for (TerminalSimpleInfo info : reList){
                    BizTerminal bizTerminal = new BizTerminal();
                    BeanUtils.copyProperties(info,bizTerminal);
                    QueryWrapper<BizTerminal> queryWrapper = new QueryWrapper<>();
                    bizTerminal.setTerType(String.valueOf(info.getTerType()));
                    bizTerminal.setTerminalId(String.valueOf(info.getTerminalId()));
                    bizTerminal.setCallMode(String.valueOf(info.getCallMode()));
                    queryWrapper.eq("TERMINAL_ID_",bizTerminal.getTerminalId());
                    List<BizTerminal> bizTerminalList = terminalManager.list(queryWrapper);
                    if (null != bizTerminalList && bizTerminalList.size() > 0){

                        BizTerminal old = bizTerminalList.get(0);
                        QueryWrapper<BizSiteParamEx> bizSiteQueryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("TERMINAL_ID_",bizTerminal.getTerminalId());
                        bizTerminal.setId(old.getId());
                        BeanUtils.copyProperties(bizTerminal,old);
                        List<BizSiteParamEx> bizSiteParamExList = bizSiteParamExManager.list(bizSiteQueryWrapper);
                        if (null != bizSiteParamExList && bizSiteParamExList.size() > 0){
                            BizSiteParamEx bizSiteParamEx = bizSiteParamExList.get(0);
                            BeanUtils.copyProperties(bizTerminal, bizSiteParamEx);
                            bizSiteParamEx.setName(bizTerminal.getTerminalName());
                            bizSiteParamEx.setIpAddress(bizTerminal.getIpAddress());
                            bizSiteParamEx.setRate(bizTerminal.getRate());
                            bizSiteParamEx.setUri(bizTerminal.getTerminalNumber());
                            bizSiteParamEx.setRegPassword(bizTerminal.getPassword());
                            bizSiteParamEx.setRegUser(bizTerminal.getContactName());
                            bizSiteParamEx.setTenantId("-1");
                            bizSiteParamExManager.update(bizSiteParamEx);
                        }
                        old.setTenantId("-1");
                        old.setIsDele("0");
                        terminalManager.update(old);
                    }else {
                        terminalManager.create(bizTerminal);
                        BizSiteParamEx bizSiteParamEx = new BizSiteParamEx();
                        BeanUtils.copyProperties(bizTerminal, bizSiteParamEx);
                        bizSiteParamEx.setName(bizTerminal.getTerminalName());
//                        bizSiteParamEx.setDeviceStatusId(bizTerminal.getId());
                        bizSiteParamEx.setType("2");
                        bizSiteParamEx.setGroupId("1");
                        bizSiteParamEx.setIpAddress(bizTerminal.getIpAddress());
                        bizSiteParamEx.setRate(bizTerminal.getRate());

                        HashMap<String, Object> map = new HashMap<>();
                        map.put("type","2");

                        Integer nextSequence = siteParamExManager.getNextSequence(map);
                        bizSiteParamEx.setSequence(nextSequence);




                        bizSiteParamEx.setUri(bizTerminal.getTerminalNumber());
                        bizSiteParamEx.setRegPassword(bizTerminal.getPassword());
                        bizSiteParamEx.setRegUser(bizTerminal.getContactName());
                        bizSiteParamExManager.create(bizSiteParamEx);
                    }
                }
            }
            return response.getResult();

        }catch (Exception e){
            e.printStackTrace();
            return "500";
        }
    }


    //同步终端
    @Override
    @Transactional
    public void getTerList() {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetTerListRequest request = new GetTerListRequest();
            GetTerminalListResponse response = mStub.getTerList(request);
            if ("200".equals(response.getResult())){
                TerminalStatus[] reList = response.getTerminalInfo();
                for (TerminalStatus terminalStatus : reList){
                    BizTerminal bizTerminal = new BizTerminal();
                    BeanUtils.copyProperties(terminalStatus,bizTerminal);
                    QueryWrapper<BizTerminal> queryWrapper = new QueryWrapper<>();
//                    queryWrapper.eq("TER_ID_",bizTerminal.getTerId());
                    if (terminalManager.getOne(queryWrapper)==null){
                        terminalManager.create(bizTerminal);
                        BizSiteParamEx bizSiteParamEx = new BizSiteParamEx();
                        bizSiteParamEx.setName(bizTerminal.getTerminalName());
                        bizSiteParamEx.setDeviceStatusId(bizTerminal.getId());
                        bizSiteParamEx.setType("2");
                        bizSiteParamEx.setGroupId("1");
                        bizSiteParamExManager.create(bizSiteParamEx);
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    public GetConferenceStatusResponse updateMeeting(String id) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetConferenceStatusRequest request = new GetConferenceStatusRequest();
            request.setConferenceIdentifier(id);
            GetConferenceStatusResponse response = mStub.getConferenceStatus(request);
            return response;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String endMeeting(String id) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            EndConferenceRequest request = new EndConferenceRequest();
            request.setConferenceIdentifier(id);
            EndConferenceResponse response = mStub.endConference(request);
            if ("200".equals(response.getResult())){
                return "1";
            }
            return response.getResult();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public String quiet(String id, String terId , boolean isSleep) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            QuietParticipantRequest request = new QuietParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(terId);
            QuietParticipantResponse response = mStub.quietParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                if(isSleep){
                    Thread.sleep(2000);
                }
                return "1";
            }
            return response.getResult();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public String cancelQuiet(String id, String terId, boolean isSleep) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            CancelQuietParticipantRequest request = new CancelQuietParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(terId);
            CancelQuietParticipantResponse response = mStub.cancelQuietParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                if(isSleep){
                    Thread.sleep(2000);
                }
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }


    @Override
    public String connect(String id, String[] terIds, boolean isSleep) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            ConnectParticipantRequest request = new ConnectParticipantRequest();
            request.setConferenceIdentifier(id);
            if(null != terIds && terIds.length > 0){
                request.setTerminalIdentifier(terIds);
            }else {
                request.setTerminalIdentifier(new String[0]);
            }
            ConnectParticipantResponse response = mStub.connectParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                if(isSleep){
                    Thread.sleep(3000);
                }
                return "1";
            }else {
                return response.getResult();
            }

        }catch (Exception e){
            e.printStackTrace();

        }
        return "0";
    }

    @Override
    public String disconnect(String id, String[] terIds) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            DisconnectParticipantRequest request = new DisconnectParticipantRequest();
            request.setConferenceIdentifier(id);
//            request.setTerminalIdentifier(terIds);
            if(null != terIds && terIds.length > 0){
                request.setTerminalIdentifier(terIds);
            }else {
                request.setTerminalIdentifier(new String[0]);
            }
            DisconnectParticipantResponse response = mStub.disconnectParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                Thread.sleep(3000);
                return "1";
            }else {
                return response.getResult();
            }

        }catch (Exception e){
            e.printStackTrace();

        }
        return "0";
    }

    @Override
    public ParticipantStatusV2[] participantStatusV2(String id) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetParticipantStatusV2Request request = new GetParticipantStatusV2Request();
            request.setConferenceIdentifier(id);
            GetParticipantStatusV2Response response = mStub.getParticipantStatusV2(request);
            if ("200".equals(response.getResult())){
                return response.getParticipantStatusV2();
            }
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return null;
    }

    @Override
    public String inviteParticipant(String id, Participant participant) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            InviteParticipantRequest request = new InviteParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setParticipant(participant);
            InviteParticipantResponse response = mStub.inviteParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                Thread.sleep(3000);
                return "1";
            }else {
                return response.getResult();
            }

        }catch (Exception e){
            e.printStackTrace();

        }
        return "0";
    }

    @Override
    public String setChairman(String id, String placeId) {

        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            SetChairmanParticipantRequest request = new SetChairmanParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(placeId);
            SetChairmanParticipantResponse response = mStub.setChairmanParticipant(request);
            if ("200".equals(response.getResult())){
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";

    }

    @Override
    public String boardcastParticipant(String id, String placeId) {

        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            BoardcastParticipantRequest request = new BoardcastParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(placeId);
            BoardcastParticipantResponse response = mStub.boardcastParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠一下，防止设备状态未更新
                Thread.sleep(1000);
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public String browseParticipant(String id, String terminalIdentifier, Integer cmdType) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            BrowseParticipantRequest request = new BrowseParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setBrowseType(1);
            request.setCmdType(cmdType);
            request.setTimeInterval(6);
            if(StringUtil.isNotEmpty(terminalIdentifier)){
                request.setTerminalIdentifier(terminalIdentifier.split(","));
            }else {
                request.setTerminalIdentifier(new String[0]);
            }
            BrowseParticipantResponse response = mStub.browseParticipant(request);
            if ("200".equals(response.getResult())){
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public List<BizSiteParamExVO> getParticipantStatusV2(String meetingId, String[] terminalIdentifiers) throws Exception{
        List<BizSiteParamExVO> resultList = new ArrayList<>();
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetParticipantStatusV2Request request = new GetParticipantStatusV2Request();
            request.setConferenceIdentifier(meetingId);
            if(null != terminalIdentifiers && terminalIdentifiers.length > 0){
                request.setTerminalIdentifier(terminalIdentifiers);
            }else {
                request.setTerminalIdentifier(new String[0]);
            }
            GetParticipantStatusV2Response response = mStub.getParticipantStatusV2(request);
            if ("200".equals(response.getResult())){
                ParticipantStatusV2[] reList = response.getParticipantStatusV2();
                if(null != reList && reList.length > 0){
                    for (ParticipantStatusV2 info : reList){
                        BizSiteParamExVO bizSiteParamExVO = new BizSiteParamExVO();
                        // 会场表
                        BizSiteParamEx bizSiteParamEx = new BizSiteParamEx();
                        BeanUtils.copyProperties(info,bizSiteParamEx);
                        BeanUtils.copyProperties(bizSiteParamEx,bizSiteParamExVO);
                        QueryWrapper<BizSiteParamEx> bizSiteQueryWrapper = new QueryWrapper<>();
                        bizSiteQueryWrapper.eq("TERMINAL_ID_",info.getTerminalIdentifier());
                        List<BizSiteParamEx> bizSiteParamExList = bizSiteParamExManager.list(bizSiteQueryWrapper);
                        if(null != bizSiteParamExList && bizSiteParamExList.size() > 0){
                            bizSiteParamEx = bizSiteParamExList.get(0);
                        }
                        BeanUtils.copyProperties(info, bizSiteParamEx);

                        // 终端表
                        BizTerminal bizTerminal = new BizTerminal();
                        QueryWrapper<BizTerminal> terminalQueryWrapper = new QueryWrapper<>();
                        terminalQueryWrapper.eq("TERMINAL_ID_",info.getTerminalIdentifier());
                        List<BizTerminal> bizTerminalList = terminalManager.list(terminalQueryWrapper);
                        if(null != bizTerminalList && bizTerminalList.size() > 0){
                            bizTerminal = bizTerminalList.get(0);
                        }
                        BeanUtils.copyProperties(info, bizTerminal);
                        bizSiteParamExVO.setBizTerminal(bizTerminal);
                        resultList.add(bizSiteParamExVO);
                    }
                    // 按照会场在线状态进行排序
                    Comparator comparator = new Comparator<BizSiteParamExVO>() {
                        public int compare(BizSiteParamExVO conferenceStatus01, BizSiteParamExVO conferenceStatus02) {
                            return conferenceStatus01.getStatus().compareTo(conferenceStatus02.getStatus());
                        }
                    };
                    Collections.sort(resultList, comparator);
                }
            }else {
                throw new BaseException(ZTEErrorCode.getDescByCode(response.getResult()));
            }
        return resultList;
    }

    @Override
    public MeetingVO getConferenceStatus(String meetintId) throws Exception{
        MeetingVO meetingVO = meetingManager.findById(meetintId);
        return getConferenceStatus(meetingVO);
    }

    @Override
    public MeetingVO getConferenceStatus(MeetingVO meetingVO) throws Exception{
        if(null == meetingVO || StringUtil.isEmpty(meetingVO.getId())){
            return null;
        }
        String meetintId = meetingVO.getId();
        MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
        mLocator.setMultimediaConferenceEndpointAddress(url);
        MultimediaConferenceSoapBindingStub mStub =
                (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
        // 设置消息头字段
        SOAPHeaderElement header = new SOAPHeaderElement(new
                QName("AuthHeader"));
        MessageElement element = new MessageElement(new QName("Version"), "1");
        MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
        header.addChild(tokenElement);
        header.addChild(element);
        mStub.setHeader(header);
        GetConferenceStatusRequest request = new GetConferenceStatusRequest();
        request.setConferenceIdentifier(meetintId);
        GetConferenceStatusResponse response = mStub.getConferenceStatus(request);
        if ("200".equals(response.getResult())){
            ConferenceStatus conferenceInfo = response.getConferenceInfo();
            BeanUtils.copyProperties(conferenceInfo, meetingVO);
//            Calendar calendar = Calendar.getInstance();
//            meetingVO.setStartTime(LocalDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()));
            meetingVO.setId(conferenceInfo.getConferenceIdentifier());
            meetingVO.setDuration(conferenceInfo.getDuration());
            meetingVO.setPassword(conferenceInfo.getConferencePassword());
            meetingVO.setTheme(conferenceInfo.getConferenceName());
            meetingVO.setConferenceNumber(conferenceInfo.getConferenceNumber());
            meetingVO.setIfRecord(conferenceInfo.isIfRecord());
            meetingVO.setRecordState(conferenceInfo.getRecordState());
            meetingVO.setLockState(conferenceInfo.isLockState());
            meetingVO.setConfCtrlMode(conferenceInfo.getConfCtrlMode());
            meetingVO.setBoardcaster(conferenceInfo.getBoardcaster());
            meetingVO.setDualBoardcaster(conferenceInfo.getDualBoardcaster());
            meetingVO.setChairman(conferenceInfo.getChairman());
            meetingVO.setIfUpMode(conferenceInfo.getIfUpMode());
            meetingVO.setMultiPicCtrlMode(conferenceInfo.getMultiPicCtrlMode());
            meetingVO.setMaxPicNum(conferenceInfo.getMaxPicNum());
            meetingVO.setCurPicNum(conferenceInfo.getCurPicNum());
        }else {
            // 如果会议不存在就将现在的会议状态置为结束
            if(ZTEErrorCode.E15.getCode().equalsIgnoreCase(response.getResult()) || ZTEErrorCode.E116.getCode().equalsIgnoreCase(response.getResult())){
                meetingManager.updateStatus(meetintId, 3);
            }
            throw new BaseException(ZTEErrorCode.getDescByCode(response.getResult()));
        }
        return meetingVO;
    }

    @Override
    public String muteParticipant(String id, String terId, boolean isSleep) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            MuteParticipantRequest request = new MuteParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(terId);
            MuteParticipantResponse response = mStub.muteParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                if(isSleep){
                    Thread.sleep(2000);
                }
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public String cancelMuteParticipant(String id, String terId, boolean isSleep) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            CancelMuteParticipantRequest request = new CancelMuteParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(terId);
            CancelMuteParticipantResponse response = mStub.cancelMuteParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                if(isSleep){
                    Thread.sleep(2000);
                }
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }


    @Override
    public String cancelConferenceReserved(String meetingId) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            CancelConferenceReservedRequest request = new CancelConferenceReservedRequest();
            request.setConferenceIdentifier(meetingId);
            CancelConferenceReservedResponse response = mStub.cancelConferenceReserved(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                Thread.sleep(2000);
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public String deleteParticipant(String id, String placeId) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            DeleteParticipantRequest request = new DeleteParticipantRequest();
            request.setConferenceIdentifier(id);
            request.setTerminalIdentifier(placeId.split(","));
            DeleteParticipantResponse response = mStub.deleteParticipant(request);
            if ("200".equals(response.getResult())){
                // 睡眠两秒，防止终端设备状态还未更新
                Thread.sleep(1000);
                return "1";
            }else {
                return response.getResult();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0";
    }

    @Override
    public List<ConferenceStatus> getConferenceInfoList() {
        GetConferenceInfoListResponse response = null;
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetConferenceInfoListRequest request = new GetConferenceInfoListRequest();
            request.setAccount(userName);
            response = mStub.getConferenceInfoList(request);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(response == null){
            return null;
        }
        if ("200".equals(response.getResult())){
            ConferenceStatus[] data = response.getConferenceList();
            java.util.ArrayList<ConferenceStatus> conferenceInfoList = new ArrayList<>(data.length);
            Collections.addAll(conferenceInfoList, data);
            return conferenceInfoList;
        }else {
            throw new BaseException(ZTEErrorCode.getDescByCode(response.getResult()));
        }
    }

    @Override
    public List<ConferenceSimpleInfo> getConferenceReservedList() {
        GetConferenceReservedListResponse response = null;
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetConferenceReservedListRequest request = new GetConferenceReservedListRequest();
            request.setAccount(userName);
            response = mStub.getConferenceReservedList(request);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(response == null){
            return null;
        }
        if ("200".equals(response.getResult())){
            ConferenceSimpleInfo[] data = response.getConferenceList();
            java.util.ArrayList<ConferenceSimpleInfo> conferenceSimpleInfoList = new ArrayList<>(data.length);
            Collections.addAll(conferenceSimpleInfoList, data);
            return conferenceSimpleInfoList;
        }else {
            throw new BaseException(ZTEErrorCode.getDescByCode(response.getResult()));
        }
    }

    @Override
    public List<ConfNode> getConfNodeList(String conferenceIdentifier, int page, int numPerPage) {
        if(page == 0){
            page = 1;
        }
        if(page < -1){
            page = -1;
        }
        if(numPerPage < 10){
            numPerPage = 10;
        }
        if(numPerPage < -1){
            numPerPage = -1;
        }
        GetConfNodeListResponse response = null;
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetConfNodeListRequest request = new GetConfNodeListRequest();
            request.setConferenceIdentifier(conferenceIdentifier);
            request.setPage(page);
            request.setNumPerPage(numPerPage);
            response = mStub.getConfNodeList(request);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(response == null){
            return null;
        }
        if ("200".equals(response.getResult())){
            ConfNode[] data = response.getConfNodeList();
            java.util.ArrayList<ConfNode> ConfNodeList = new ArrayList<>(data.length);
            Collections.addAll(ConfNodeList, data);
            return ConfNodeList;
        }else {
            throw new BaseException(ZTEErrorCode.getDescByCode(response.getResult()));
        }
    }


    @Override
    public List<ConferenceStatus> getHistoryConferenceList(HistoryConferenceVO historyConferenceVO) {
        Integer page = historyConferenceVO.getPage();
        Integer numPerPage = historyConferenceVO.getNumPerPage();
        if(page == 0){
            page = 1;
        }
        if(page < -1){
            page = -1;
        }
        if(numPerPage < 10){
            numPerPage = 10;
        }
        if(numPerPage < -1){
            numPerPage = -1;
        }
        GetHistoryConferenceListResponse response = null;
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            GetHistoryConferenceListRequest request = new GetHistoryConferenceListRequest();
            request.setAccount(userName);
            request.setOption(historyConferenceVO.getOption());
            if(StringUtil.isNotEmpty(historyConferenceVO.getConferenceNumber())){
                request.setConferenceNumber(historyConferenceVO.getConferenceNumber());
            }
            if(StringUtil.isNotEmpty(historyConferenceVO.getConferenceName())){
                request.setConferenceName(historyConferenceVO.getConferenceName());
            }
            if(null != historyConferenceVO.getStartTime()){
                Calendar localDateTimeCalendar = GregorianCalendar.from(ZonedDateTime.of(historyConferenceVO.getStartTime(), ZoneId.systemDefault()));
                request.setStartTime(localDateTimeCalendar);
            }
            request.setPage(page);
            request.setNumPerPage(numPerPage);
            response = mStub.getHistoryConferenceList(request);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(response == null){
            return null;
        }
        if ("200".equals(response.getResult())){
            ConferenceStatus[] data = response.getConferenceList();
            java.util.ArrayList<ConferenceStatus> conferenceStatusList = new ArrayList<>(data.length);
            Collections.addAll(conferenceStatusList, data);
            return conferenceStatusList;
        }else {
            throw new BaseException(ZTEErrorCode.getDescByCode(response.getResult()));
        }
    }


    @Override
    public ProlongConferenceResponse prolongConference(String meetingId, int minutes) {
        try {
            MultimediaConferenceServiceLocator mLocator = new MultimediaConferenceServiceLocator();
            mLocator.setMultimediaConferenceEndpointAddress(url);
            MultimediaConferenceSoapBindingStub mStub =
                    (MultimediaConferenceSoapBindingStub) mLocator.getMultimediaConference();
            // 设置消息头字段
            SOAPHeaderElement header = new SOAPHeaderElement(new
                    QName("AuthHeader"));
            MessageElement element = new MessageElement(new QName("Version"), "1");
            MessageElement tokenElement = new MessageElement(new QName("Token"), this.getToken());
            header.addChild(tokenElement);
            header.addChild(element);
            mStub.setHeader(header);
            ProlongConferenceRequest request = new ProlongConferenceRequest();
            request.setConferenceIdentifier(meetingId);
            request.setProlongTime(minutes);
            ProlongConferenceResponse response = mStub.prolongConference(request);

            return response;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
