package com.huawei.hwmdemo.view.sdk;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmconf.presentation.ConfUI;
import com.huawei.hwmconf.presentation.error.ErrorMessageFactory;
import com.huawei.hwmconf.sdk.model.conf.entity.AttendeeModel;
import com.huawei.hwmconf.sdk.model.conf.entity.BookConfParam;
import com.huawei.hwmconf.sdk.model.conf.entity.ConfInfo;
import com.huawei.hwmconf.sdk.model.conf.entity.JoinConfPermissionType;
import com.huawei.hwmconf.sdk.model.conf.entity.MeetingIdType;
import com.huawei.hwmconf.sdk.model.conf.entity.MeetingType;
import com.huawei.hwmconf.sdk.model.conf.entity.VmrIdType;
import com.huawei.hwmconf.sdk.model.conf.entity.VmrInfoListModel;
import com.huawei.hwmconf.sdk.model.conf.entity.VmrInfoModel;
import com.huawei.hwmconf.sdk.util.BaseDateUtil;
import com.huawei.hwmconf.sdk.util.Utils;
import com.huawei.hwmdemo.R;
import com.huawei.hwmdemo.utils.DemoUtil;
import com.huawei.hwmdemo.view.base.BaseDialogFragment;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmfoundation.utils.LanguageUtil;
import com.huawei.hwmfoundation.utils.StringUtil;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.enums.AutoMuteType;
import com.huawei.hwmsdk.enums.ConfAllowJoinUserType;
import com.huawei.hwmsdk.enums.ConfResType;
import com.huawei.hwmsdk.enums.SDKERR;
import com.huawei.hwmsdk.enums.SummaryState;
import com.huawei.hwmsdk.model.param.ModifyVmrParam;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
public class BookMeetingFragment extends BaseDialogFragment {
    public final static String TAG = BookMeetingFragment.class.getSimpleName();

    private View rootView;

    private List<VmrInfoModel> vmrList = new ArrayList<>();

    private VmrInfoModel mVmrInfoModel = new VmrInfoModel();

    // 共享云会议室是否可用
    private boolean isEnableShareVmr = false;

    private RadioGroup modeGroup;

    private JoinConfPermissionType joinConfPermissionType = JoinConfPermissionType.PERMIT_EVERYONE;

    private Switch autoInviteSwitch;

    private RadioGroup vmrIdTypeGroup;

    private VmrIdType vmrConfIdType = VmrIdType.RANDOM_ID;

    private Switch personnalIDSwitch;

    private Switch needUseVmrConfSwitch;

    private Switch shareVmrSwitch;

    private boolean needUseVmrConf = false;

    private LinearLayout fixIdChosenArea;

    private String chosenVmrId;

    private Spinner fixVmrIdChosenSpinner;

    private Switch allowGuestStartConfSwitch;

    private EditText guestStartConfTimeText;

    private Switch needPasswordSwitch;

    private Switch needRecordSwitch;

    private Switch isAutoStartRecordSwitch;

    private Switch summarySwitch;

    private Switch autoPublishSummarySwitch;

    private Switch needEmailSwitch;

    private Switch needSmsSwitch;

    private Switch needEmailCalendarSwitch;

    private Switch needWithMemberSwitch;

    private Switch openWaitingRoomSwitch;

    private List<String> vmrConferenceIdList = new ArrayList<>();

    private LinearLayout guestPwdView;

    private EditText guestPwd;

    private RadioButton allowModeAnyone;

    private RadioButton allowModeEnterprise;

    private RadioButton allowModeInvite;

    private EditText customMsg;

    private EditText maxNumber;

    private EditText vmrIdText;

    // 来宾入会，软终端自动静音模式
    private AutoMuteType autoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_DEFAULT;

    // 来宾入会，硬终端自动静音模式
    private AutoMuteType hardTerminalAutoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_DEFAULT;

    private Switch forbiddenScreenShots;

    private Switch openWatermark;

    private List<AttendeeModel> attendeeList;

    // 与会者列表是否去掉预定者
    private Switch attendeesExcludeSelf;


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        rootView = inflater.inflate(R.layout.sdk_book_conf, container, false);

        Button createBtn = rootView.findViewById(R.id.book_conf);
        createBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bookConf();
            }
        });

        autoInviteSwitch = rootView.findViewById(R.id.switch_auto_invite);
        autoInviteSwitch.setChecked(true);

        if (HWMBizSdk.getBizOpenApi().hasBookConfSmsPermission()) {
            rootView.findViewById(R.id.switch_send_sms).setVisibility(View.VISIBLE);
        } else {
            rootView.findViewById(R.id.switch_send_sms).setVisibility(View.GONE);
        }

        TextView startTimeView = rootView.findViewById(R.id.book_start_time);
        Date startTimeDate = BaseDateUtil.getDefaultStartTime();
        String defaultTime = BaseDateUtil.convertDateToString(startTimeDate, BaseDateUtil.FMT_YMDHMS);
        startTimeView.setText(defaultTime);

        Timer timer = new Timer();
        timer.schedule(new MyTimerTask(), 50);
        vmrIdText = rootView.findViewById(R.id.book_vmrid);
        handleVmrConf();
        handleShareVmr();

        allowGuestStartConfSwitch = rootView.findViewById(R.id.book_switch_allow_guest_start_conf);
        guestStartConfTimeText = rootView.findViewById(R.id.book_allow_guest_start_conf_time);
        allowGuestStartConfSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                guestStartConfTimeText.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });

        needPasswordSwitch = rootView.findViewById(R.id.book_switch_need_password);
        needRecordSwitch = rootView.findViewById(R.id.switch_record_conf);
        isAutoStartRecordSwitch = rootView.findViewById(R.id.switch_record_is_auto_start);
        summarySwitch = rootView.findViewById(R.id.switch_summary);
        autoPublishSummarySwitch = rootView.findViewById(R.id.switch_auto_publish_summary);
        needEmailSwitch = rootView.findViewById(R.id.switch_send_email);
        needSmsSwitch = rootView.findViewById(R.id.switch_send_sms);
        needEmailCalendarSwitch = rootView.findViewById(R.id.switch_send_email_calandar);
        needWithMemberSwitch = rootView.findViewById(R.id.book_switch_with_attend);
        needWithMemberSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                showChooseAttend(isChecked);
            }
        });
        View attendView = rootView.findViewById(R.id.book_attend_view);
        attendView.setVisibility(needWithMemberSwitch.isChecked() ? View.VISIBLE : View.GONE);
        openWaitingRoomSwitch = rootView.findViewById(R.id.book_switch_open_waiting_room);
        forbiddenScreenShots = rootView.findViewById(R.id.forbidden_screen_shots_switch);
        forbiddenScreenShots.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (forbiddenScreenShots != null) {
                    forbiddenScreenShots.setChecked(b);
                }
            }
        });
        openWatermark = rootView.findViewById(R.id.open_watermark_switch);
        openWatermark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (openWatermark != null) {
                    openWatermark.setChecked(b);
                }
            }
        });
        guestPwdView = rootView.findViewById(R.id.guest_pwd_view);
        guestPwd = rootView.findViewById(R.id.guest_pwd);
        needPasswordSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (guestPwdView == null) {
                return;
            }
            if (isChecked) {
                guestPwdView.setVisibility(View.VISIBLE);
            } else {
                guestPwdView.setVisibility(View.GONE);
            }
        });
        customMsg = rootView.findViewById(R.id.custom_message);
        maxNumber = rootView.findViewById(R.id.max_num_edit);
        attendeesExcludeSelf = rootView.findViewById(R.id.attendees_exclude_self);
        handleAutoMute();
        return rootView;
    }

    private void handleShareVmr() {
        shareVmrSwitch = rootView.findViewById(R.id.switch_is_use_share_vmr);
        shareVmrSwitch.setEnabled(isEnableShareVmr);
        shareVmrSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                personnalIDSwitch.setEnabled(!isChecked);
                needUseVmrConfSwitch.setEnabled(!isChecked);
                // 共享云会议室仅支持随机会议ID
                vmrConfIdType = VmrIdType.RANDOM_ID;
                fixIdChosenArea.setVisibility(View.GONE);
                vmrIdText.setVisibility(View.GONE);
            }
        });
    }

    private void handleVmrConf() {
        fixIdChosenArea = rootView.findViewById(R.id.vmr_choose_fix_id_area);
        fixIdChosenArea.setVisibility(View.GONE);

        personnalIDSwitch = rootView.findViewById(R.id.switch_is_use_personnal_id);
        personnalIDSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                needUseVmrConfSwitch.setEnabled(!isChecked);
                shareVmrSwitch.setEnabled(!isChecked);
                if (isChecked) {
                    if (!vmrList.isEmpty()) {
                        mVmrInfoModel = vmrList.get(0);
                        vmrIdText.setText(mVmrInfoModel.getVmrConferenceId());
                        updateVmrJoinTypeAndWaitingRoomStatus(mVmrInfoModel);
                    }
                    vmrIdText.setVisibility(View.VISIBLE);
                } else {
                    vmrIdText.setVisibility(View.GONE);
                }
            }
        });

        modeGroup = rootView.findViewById(R.id.allow_group);
        ((RadioButton) rootView.findViewById(R.id.allow_mode_everyone)).setChecked(true);
        modeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int id) {
                if (id == R.id.allow_mode_everyone) {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_EVERYONE;
                } else if (id == R.id.allow_mode_enterprise) {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_ENTERPRISE_USER;
                } else {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_INVITED_USER;
                }
            }
        });

        handleCloudMeetingRoom();
    }

    private void updateVmrJoinTypeAndWaitingRoomStatus(VmrInfoModel model) {
        if (openWaitingRoomSwitch != null) {
            openWaitingRoomSwitch.setChecked(model.isOpenWaitingRoom());
        }
        int allowMode = model.getConfAllowJoinUserType().getValue();
        if (allowMode == ConfAllowJoinUserType.CONF_ALLOW_JOIN_ANYONE.getValue()) {
            if (allowModeAnyone != null) {
                allowModeAnyone.setChecked(true);
            }
        } else if (allowMode == ConfAllowJoinUserType.CONF_ALLOW_JOIN_IN_COMPANY_USER.getValue()) {
            if (allowModeEnterprise != null) {
                allowModeEnterprise.setChecked(true);
            }
        } else if (allowMode == ConfAllowJoinUserType.CONF_ALLOW_JOIN_INVITED_USER.getValue()) {
            if (allowModeInvite != null) {
                allowModeInvite.setChecked(true);
            }
        }
    }

    private void handleCloudMeetingRoom() {
        fixVmrIdChosenSpinner = rootView.findViewById(R.id.fix_vmr_id_spinner);
        fixVmrIdChosenSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position < 0 || position >= vmrList.size()) {
                    return;
                }
                chosenVmrId = findVmrIdByFromList(vmrConferenceIdList.get(position));
                updateVmrJoinTypeAndWaitingRoomStatus(findVmrInfoFormList(chosenVmrId));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        vmrIdTypeGroup = rootView.findViewById(R.id.vmr_id_group);
        allowModeAnyone = rootView.findViewById(R.id.allow_mode_everyone);
        allowModeEnterprise = rootView.findViewById(R.id.allow_mode_enterprise);
        allowModeInvite = rootView.findViewById(R.id.allow_mode_invite);

        allowModeAnyone.setChecked(true);
        vmrIdTypeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int id) {
                if (id == R.id.vmr_id_type_fixed) {
                    vmrConfIdType = VmrIdType.FIXED_ID;
                    fixIdChosenArea.setVisibility(View.VISIBLE);
                    setVmrSpinner();
                } else {
                    vmrConfIdType = VmrIdType.RANDOM_ID;
                    fixIdChosenArea.setVisibility(View.GONE);
                }
            }
        });

        needUseVmrConfSwitch = rootView.findViewById(R.id.switch_is_use_vmr_conf);
        LinearLayout vmrIdTypeArea = rootView.findViewById(R.id.vmr_id_type_area);
        needUseVmrConfSwitch.setChecked(false);
        vmrIdTypeArea.setVisibility(View.GONE);
        needUseVmrConfSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                personnalIDSwitch.setEnabled(!isChecked);
                shareVmrSwitch.setEnabled(!isChecked);
                needUseVmrConf = needUseVmrConfSwitch.isChecked();
                vmrIdTypeArea.setVisibility(needUseVmrConf ? View.VISIBLE : View.GONE);
                if (!needUseVmrConf) {
                    fixIdChosenArea.setVisibility(View.GONE);
                }
            }
        });
    }

    private void handleAutoMute() {
        RadioGroup autoMutePersonGroup = rootView.findViewById(R.id.auto_mute_person_group);
        ((RadioButton)rootView.findViewById(R.id.auto_mute_person_default)).setChecked(true);
        autoMutePersonGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int id) {
                if (id == R.id.auto_mute_person_mute) {
                    autoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_MUTE;
                } else if (id == R.id.auto_mute_person_unmute) {
                    autoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_UNMUTE;
                } else {
                    autoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_DEFAULT;
                }
            }
        });

        RadioGroup autoMuteRoomGroup = rootView.findViewById(R.id.auto_mute_room_group);
        ((RadioButton)rootView.findViewById(R.id.auto_mute_room_default)).setChecked(true);
        autoMuteRoomGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int id) {
                if (id == R.id.auto_mute_room_mute) {
                    hardTerminalAutoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_MUTE;
                } else if (id == R.id.auto_mute_room_unmute) {
                    hardTerminalAutoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_UNMUTE;
                } else {
                    hardTerminalAutoMuteMode = AutoMuteType.AUTO_MUTE_TYPE_DEFAULT;
                }
            }
        });
    }

    class MyTimerTask extends TimerTask {

        @Override
        public void run() {
            HWMBizSdk.getBizOpenApi().getVmrInfoList(new HwmCallback<VmrInfoListModel>() {
                @Override
                public void onSuccess(VmrInfoListModel vmrInfoListModel) {
                    vmrList = vmrInfoListModel.getVmrInfoList();
                    Log.i(TAG, "getVmrList: " + (vmrList.size()));
                    isEnableShareVmr = vmrInfoListModel.isEnableShareVmr();
                    if (shareVmrSwitch != null) {
                        if (shareVmrSwitch.isChecked()) {
                            shareVmrSwitch.setChecked(isEnableShareVmr);
                        }
                        shareVmrSwitch.setEnabled(isEnableShareVmr);
                    }
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG,"getVmrList onFailed" + retCode + " " + desc);
                }
            });
        }
    }

    private void setVmrSpinner() {
        vmrConferenceIdList.clear();
        for (VmrInfoModel vmrInfoModel : vmrList) {
            if (vmrInfoModel.getType() == MeetingIdType.CLOUD_MEETING_ROOM_ID) {
                vmrConferenceIdList.add(vmrInfoModel.getVmrConferenceId());
            }
        }
        ArrayAdapter<String> vmrIdAdapter =
            new ArrayAdapter<>(Utils.getApp().getApplicationContext(), R.layout.main_spinner_item,
                vmrConferenceIdList);
        vmrIdAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        fixVmrIdChosenSpinner.setAdapter(vmrIdAdapter);

        if (vmrConferenceIdList.size() > 0) {
            chosenVmrId = findVmrIdByFromList(vmrConferenceIdList.get(0));
            updateVmrJoinTypeAndWaitingRoomStatus(findVmrInfoFormList(chosenVmrId));
        }
    }

    private void bookConf() {
        // 会议主题
        TextView subjectView = rootView.findViewById(R.id.book_subject);
        String subject = subjectView.getText().toString();
        if (TextUtils.isEmpty(subject)) {
            subject = subjectView.getHint().toString();
        }

        // 会议开始时间、时区、会议时长
        TextView startTimeView = rootView.findViewById(R.id.book_start_time);
        TextView timeZomeView = rootView.findViewById(R.id.book_time_zone);
        TextView timeDurationView = rootView.findViewById(R.id.book_duration);
        String startTime = getStartTime(startTimeView.getText().toString());
        long startTimeStamp = BaseDateUtil.dateToTimeStamp(startTime, BaseDateUtil.FMT_YMDHMS);
        String timeZomeStr = timeZomeView.getText().toString();
        if (TextUtils.isEmpty(timeZomeStr)) {
            DemoUtil.showToast("请填写时区！");
            return;
        }

        int duration = 30;
        String timedurStr = timeDurationView.getText().toString();
        if (!TextUtils.isEmpty(timedurStr)) {
            duration = Integer.parseInt(timedurStr);
        }

        RadioButton audioBtn = rootView.findViewById(R.id.radio_audio);
        personnalIDSwitch = rootView.findViewById(R.id.switch_is_use_personnal_id);
        EditText vmrText = rootView.findViewById(R.id.book_vmrid);
        String vmrConferenceId = vmrText.getText().toString();
        boolean needUsePersonnalId = personnalIDSwitch.isChecked();
        if (needUsePersonnalId) {
            if (StringUtil.isEmpty(vmrConferenceId)) {
                DemoUtil.showToast("使用个人会议ID预约会议时，vmrid不能为空！");
                return;
            } else {
                chosenVmrId = findVmrIdByFromList(vmrConferenceId);
            }
        }

        boolean needPassword = needPasswordSwitch.isChecked();
        boolean needRecord = needRecordSwitch.isChecked();
        boolean isAutoStartRecord = isAutoStartRecordSwitch.isChecked();
        boolean needSummary = summarySwitch.isChecked();
        boolean autoPublishSummary = autoPublishSummarySwitch.isChecked();
        boolean needEmail = needEmailSwitch.isChecked();
        boolean needSms = needSmsSwitch.isChecked();
        boolean needEmailCalendar = needEmailCalendarSwitch.isChecked();
        boolean needWithMember = needWithMemberSwitch.isChecked();
        boolean isOpenWaitingRoom = openWaitingRoomSwitch.isChecked();
        boolean isForbiddenScreenShots = forbiddenScreenShots.isChecked();
        boolean isOpenWatermark = openWatermark.isChecked();
        boolean isAttendeesExcludeSelf = attendeesExcludeSelf.isChecked();


        List<AttendeeModel> attendeeInfos = new ArrayList<>();
        processWithAttendee(needWithMember, attendeeInfos);
        boolean allowGuestStartConf = allowGuestStartConfSwitch.isChecked();
        int allowGuestStartConfTime = 0;
        String guestStartConfTime = guestStartConfTimeText.getText().toString();
        if (!TextUtils.isEmpty(guestStartConfTime)) {
            allowGuestStartConfTime = Integer.parseInt(guestStartConfTime);
        }

        showLoading();

        BookConfParam bookConfParam = new BookConfParam()
            .setConfSubject(subject)
            .setStartTimeStamp(startTimeStamp)
            .setTimeZone(Integer.parseInt(timeZomeStr))
            .setDuration(duration)
            .setConfType(audioBtn.isChecked() ? MeetingType.CONF_AUDIO : MeetingType.CONF_VIDEO)
            .setVmrIdFlag(needUsePersonnalId || needUseVmrConf)
            .setVmrId(chosenVmrId)
            .setVmrIdType(vmrConfIdType)
            .setNeedConfPwd(needPassword)
            .setJoinConfRestrictionType(joinConfPermissionType)
            .setRecordOn(needRecord)
            .setAutoRecord(isAutoStartRecord)
            .setAutoPublishSummary(autoPublishSummary)
            .setDefaultSummaryState(getDefaultSummaryState(needSummary))
            .setMailOn(needEmail)
            .setSmsOn(needSms)
            .setEmailCalenderOn(needEmailCalendar)
            .setAttendees(attendeeInfos)
            .setAllowGuestStartConf(allowGuestStartConf)
            .setAllowGuestStartConfTime(allowGuestStartConfTime)
            .setOpenWaitingRoom(isOpenWaitingRoom)
            .setForbiddenScreenShots(isForbiddenScreenShots)
            .setOpenWatermark(isOpenWatermark)
            .setGuestPwd(guestPwd == null ? "" : guestPwd.getText().toString())
            .setCustomInfo(customMsg.getText().toString())
            .setAutoMuteMode(autoMuteMode)
            .setHardTerminalAutoMuteMode(hardTerminalAutoMuteMode)
            .setAttendeesExcludeSelf(isAttendeesExcludeSelf);
        if (shareVmrSwitch.isChecked()) {
            bookConfParam.setVmrIdFlag(false)
                    .setVmrIdType(VmrIdType.RANDOM_ID)
                    .setConfResType(ConfResType.CONF_RESTYPE_SHARE_VMR);
        }

        if (!TextUtils.isEmpty(maxNumber.getText().toString())) {
            int maxConcurrent;
            try {
                maxConcurrent = Integer.parseInt(maxNumber.getText().toString());
            } catch (NumberFormatException e) {
                DemoUtil.showToast("会议最大方数格式不正确");
                dismissLoading();
                return;
            }
            bookConfParam.setConcurrentParticipants(maxConcurrent);
        }

        // 如果是预约VMR固定会议ID，且需要修改 允许来宾提前启动会议 开关，则先调用changeVmrInfo接口
        if (bookConfParam.isVmrIdFlag() && bookConfParam.getVmrIdType() == VmrIdType.FIXED_ID) {
            doModifyVmrInfoAndBookConf(allowGuestStartConf, bookConfParam);
            return;
        }

        HWMBizSdk.getBizOpenApi().bookConf(bookConfParam, this.completeHandler);
    }

    private static SummaryState getDefaultSummaryState(boolean needSummary) {
        return needSummary ? SummaryState.SUMMARY_STATE_OPEN : SummaryState.SUMMARY_STATE_CLOSE;
    }

    private void doModifyVmrInfoAndBookConf(boolean allowGuestStartConf, BookConfParam bookConfParam) {
        ModifyVmrParam vmrParam = new ModifyVmrParam();
        VmrInfoModel vmrInfo = findVmrInfoFormList(chosenVmrId);
        vmrParam.setGuestPwd(vmrInfo.getGuestPwd());
        vmrParam.setHostPwd(vmrInfo.getChairmanPwd());
        vmrParam.setVmrId(vmrInfo.getVmrId());
        vmrParam.setSubject(vmrInfo.getName());
        vmrParam.setAllowGuestStartConf(allowGuestStartConf);
        HWMBizSdk.getBizOpenApi().changeVmrInfo(vmrParam, new HwmCallback<Void>() {
            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG,"changeVmrInfo onFailed" + retCode + " " + desc);
                doDismissDialogAndFragment();
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                DemoUtil.showToastDialog("changeVmrInfo", retCode, desc);
            }

            @Override
            public void onSuccess(Void unused) {
                HWMBizSdk.getBizOpenApi().bookConf(bookConfParam, new HwmCallback<ConfInfo>() {
                    @Override
                    public void onFailed(int retCode, String desc) {
                        HCLog.i(TAG,"bookConf onFailed" + retCode + " " + desc);
                        doDismissDialogAndFragment();
                        String err = ErrorMessageFactory.create(retCode);
                        if (!TextUtils.isEmpty(err)) {
                            desc = err;
                        }
                        DemoUtil.showToastDialog("预约会议", retCode, desc);
                    }

                    @Override
                    public void onSuccess(ConfInfo confInfo) {
                        doDismissDialogAndFragment();
                        DemoUtil.showToast("预约会议成功");
                    }
                });
            }
        });
    }

    private String getStartTime(String startTimeLocal) {
        String startTime = startTimeLocal;
        if (startTime.isEmpty()) {
            Date startTimeDate = BaseDateUtil.getDefaultStartTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(BaseDateUtil.FMT_YMDHMS, LanguageUtil.getSystemLocale(DemoUtil.getResContext()));
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
            startTime = simpleDateFormat.format(startTimeDate);
        }
        return startTime;
    }

    private void processWithAttendee(boolean needWithMember, List<AttendeeModel> attendeeInfos) {
        if (needWithMember) {
            attendeeInfos.addAll(attendeeList);
        }
    }

    private HwmCallback<ConfInfo> completeHandler = new HwmCallback<ConfInfo>() {
        @Override
        public void onSuccess(ConfInfo result) {
            doDismissDialogAndFragment();
            DemoUtil.showToast("预约会议成功");
        }

        @Override
        public void onFailed(int retCode, String desc) {
            HCLog.i(TAG,"bookConf onFailed" + retCode + " " + desc);
            doDismissDialogAndFragment();
            String err = ErrorMessageFactory.create(retCode);
            if (!TextUtils.isEmpty(err)) {
                desc = err;
            }
            DemoUtil.showToastDialog("预约会议", retCode, desc);
        }
    };

    public void showChooseAttend(boolean isChecked) {
        if (isChecked) {
            ConfUI.getInstance().getAddAttendees().doAddAttendees(getActivity(), new ArrayList<>(),
                    " ", false, new HwmCallback<List<AttendeeModel>>() {
                        @Override
                        public void onFailed(int retCode, String desc) {
                            if (SDKERR.SDKERR_SUCCESS.getValue() != retCode) {
                                DemoUtil.showToast("添加与会者失败：" + desc);
                            }
                        }

                        @Override
                        public void onSuccess(List<AttendeeModel> attendeeModels) {
                            attendeeList = attendeeModels;
                        }
                    });
        }
    }

    private String findVmrIdByFromList(String vmrConferenceId) {
        String vmrId = mVmrInfoModel.getVmrId();
        for (VmrInfoModel vmrInfoModel : vmrList) {
            if (vmrInfoModel.getVmrConferenceId().equals(vmrConferenceId)) {
                vmrId = vmrInfoModel.getVmrId();
            }
        }
        return vmrId;
    }

    private VmrInfoModel findVmrInfoFormList(String vmrId) {
        VmrInfoModel vmrInfo = mVmrInfoModel;
        for (VmrInfoModel vmrInfoModel : vmrList) {
            if (vmrInfoModel.getVmrId().equals(vmrId)) {
                vmrInfo = vmrInfoModel;
            }
        }
        return vmrInfo;
    }
}
