
package com.meeting.demo.view.sdkconfig;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
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.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.huawei.cloudlink.openapi.HWMSdk;
import com.huawei.cloudlink.openapi.api.param.JoinConfParam;
import com.huawei.cloudlink.openapi.api.param.PasswordJoinConfParam;
import com.huawei.hwmbiz.HWMBizSdk;
import com.huawei.hwmcommonui.utils.DateUtil;
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.ConfDetailModel;
import com.huawei.hwmconf.sdk.model.conf.entity.EditConfParam;
import com.huawei.hwmconf.sdk.model.conf.entity.EditCycleConfParam;
import com.huawei.hwmconf.sdk.model.conf.entity.JoinConfPermissionType;
import com.huawei.hwmconf.sdk.model.conf.entity.MeetingType;
import com.huawei.hwmconf.sdk.model.conf.entity.VmrIdType;
import com.huawei.hwmconf.sdk.util.BaseDateUtil;
import com.huawei.hwmconf.sdk.util.Utils;
import com.huawei.hwmconf.sdk.util.timezone.TimeZoneUtil;
import com.meeting.demo.R;
import com.meeting.demo.adapter.ConfListItemAdapter;
import com.meeting.demo.dependency.NeedCustomType;
import com.meeting.demo.model.ConfItemModel;
import com.meeting.demo.utils.DemoUtil;
import com.meeting.demo.view.BaseActivity;
import com.meeting.demo.view.DemoActivity;
import com.meeting.demo.view.sdk.AttendeeListInfosFragment;
import com.meeting.demo.view.sdk.CustomLayoutManager;
import com.meeting.demo.view.sdk.EditSubConfFragment;
import com.huawei.hwmfoundation.HwmContext;
import com.huawei.hwmfoundation.callback.HwmCallback;
import com.huawei.hwmfoundation.callback.HwmCancelableCallBack;
import com.huawei.hwmfoundation.utils.LanguageUtil;
import com.huawei.hwmfoundation.utils.route.HCActivityManager;
import com.huawei.hwmlogger.HCLog;
import com.huawei.hwmsdk.common.SdkCallback;
import com.huawei.hwmsdk.enums.AutoMuteType;
import com.huawei.hwmsdk.enums.ConfAllowJoinUserType;
import com.huawei.hwmsdk.enums.ConfMediaType;
import com.huawei.hwmsdk.enums.ConfPromptLanguageType;
import com.huawei.hwmsdk.enums.ConfRecordMode;
import com.huawei.hwmsdk.enums.CycleType;
import com.huawei.hwmsdk.enums.SDKERR;
import com.huawei.hwmsdk.enums.SummaryState;
import com.huawei.hwmsdk.model.param.CancelSubCycleConfParam;
import com.huawei.hwmsdk.model.param.ConfCommonParam;
import com.huawei.hwmsdk.model.param.CycleConfParam;
import com.huawei.hwmsdk.model.param.ModifyVmrParam;
import com.huawei.hwmsdk.model.param.SubCycleConfParam;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

@SuppressWarnings("checkstyle:ClassFanOutComplexity")
public class ConfDetailActivity extends BaseActivity
    implements View.OnClickListener, ConfListItemAdapter.Listener, EditSubConfFragment.Listener {
    private static final String TAG = ConfDetailActivity.class.getSimpleName();

    private AlertDialog alertLoadingDialog;

    // 会议主题
    private EditText subjectText;

    // 开始时间
    private EditText startTimeText;

    // 时区
    private EditText timezomeText;

    // 会议时长
    private EditText timeDuartionText;

    // 来宾密码
    private EditText guestPwd;

    // 周期间隔
    private EditText cycleIntervalText;

    // 周期子会议时间点
    private EditText cycleSubDatesText;

    // 周期结束日期
    private EditText cycleEndDateText;

    // 周期会议提前通知天数
    private EditText cyclePreMindDaysText;

    // 音频按钮
    private RadioButton audioBtn;

    // 视频按钮
    private RadioButton videoBtn;

    private Switch recordSwitch;

    private Switch isAutoStartRecordSwitch;

    private Switch summarySwitch;

    private Switch autoPublishSummarySwitch;

    private Switch sendEmailSwitch;

    private Switch sendSmsSwitch;

    private Switch sendEmailCalendarSwitch;

    private Switch needWithMemberSwitch;

    private Switch confDetailSwitch;

    private Switch cycleConfSwitch;

    private Switch subCycleConfSwitch;

    // 允许来宾提前入会
    private Switch allowGuestStartConfSwitch;

    private Switch openWaitingRoomSwitch;

    private Switch openForbiddenScreenShots;

    private Switch openWatermark;

    // 允许来宾提前入会时间
    private EditText guestStartConfTimeText;

    private View confDetailView;

    private TextView confIdTv;

    private TextView hostPwdTv;

    private TextView hostLinkTv;

    private TextView guestPwdTv;

    private TextView shareLinkTv;

    private Button editConfbtn;

    private Button joinConfbtn;

    private RadioGroup modeGroup;

    private JoinConfPermissionType joinConfPermissionType = JoinConfPermissionType.PERMIT_EVERYONE;

    private Spinner cycleTypeSpinner;

    private LinearLayout cycleSettingsView;

    private CycleType mSelectedCycleType;

    private boolean mIsCycleConf;

    private ConfAllowJoinUserType mConfAllowJoinUserType;

    private RecyclerView subCycleConfList;

    private ConfListItemAdapter confListAdapter;

    private String cycleConfId;

    private EditConfParam editConfParam;

    private EditCycleConfParam editCycleConfParam;

    private EditText customMsg;

    private EditText maxNumber;

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

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

    private List<AttendeeModel> attendeeList;

    public void setConfDetailModel(ConfDetailModel confDetailModel) {
        this.confDetailModel = confDetailModel;
    }

    public void setJoinConfPermissionType(JoinConfPermissionType joinConfPermissionType) {
        this.joinConfPermissionType = joinConfPermissionType;
        if (JoinConfPermissionType.PERMIT_EVERYONE == joinConfPermissionType) {
            ((RadioButton) findViewById(R.id.allow_mode_everyone)).setChecked(true);
        } else if (JoinConfPermissionType.PERMIT_ENTERPRISE_USER == joinConfPermissionType) {
            ((RadioButton) findViewById(R.id.allow_mode_enterprise)).setChecked(true);
        } else {
            ((RadioButton) findViewById(R.id.allow_mode_invite)).setChecked(true);
        }
    }

    private ConfDetailModel confDetailModel;

    private static final int HANDLE_MESSAGE_GET_CONF_DETAIL_SUCCESS = 10001;

    private static final int SHOW_SELECTED_SUB_CONF_PAGE = 10002;

    private Handler confDetailPageHandler = new ConfDetailHandler(this);

    @Override
    public void onItemClicked(ConfItemModel item) {
        HCLog.i("TAG：", "跳转会议详情：" + item.getConfSubject());
        Activity currentActivity = HCActivityManager.getInstance().getCurActivity();
        if (item.isSubCycleConf()) {
            Message message = Message.obtain(confDetailPageHandler);
            message.what = SHOW_SELECTED_SUB_CONF_PAGE;
            message.obj = item;
            message.sendToTarget();
            return;
        }
        if (null != currentActivity) {
            Intent intent = new Intent(currentActivity, ConfDetailActivity.class);
            intent.putExtra("confid", item.getConfId());
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            currentActivity.startActivity(intent);
        }
    }

    @Override
    public void onCancelConfBtnClicked(ConfItemModel item) {
        CancelSubCycleConfParam cancelSubCycleConfParam = new CancelSubCycleConfParam();
        cancelSubCycleConfParam.setConfId(cycleConfId);
        cancelSubCycleConfParam.setSubConfID(item.getConfId());
        cancelSubCycleConfParam.setEndOnlineConf(true);
        HWMBizSdk.getBizOpenApi().cancelSubCycleConf(cycleConfId, item.getConfId(), new SdkCallback<Void>() {
            @Override
            public void onFailed(SDKERR retCode) {
                HCLog.i(TAG, "cancel sub cycle conf onFailed " + retCode);
                String err = ErrorMessageFactory.create(retCode);
                if (TextUtils.isEmpty(err)) {
                    err = DemoUtil.getResContext().getString(R.string.hwmconf_cancel_fail_tip);
                }
                DemoUtil.showToast("cancel sub cycle conf failed: " + err);
                confListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onSuccess(Void aVoid) {
                DemoUtil.showToast("cancel sub cycle conf success");
                updateConfDetail(cycleConfId);
            }
        });
    }

    @Override
    public void onEditSubCycleConfSuccess() {
        updateConfDetail(cycleConfId);
    }

    private void updateConfDetail(String cycleConfId) {
        HWMBizSdk.getBizOpenApi().getConfDetail(cycleConfId, new HwmCallback<ConfDetailModel>() {
            @Override
            public void onSuccess(ConfDetailModel confDetailModel) {
                DemoUtil.showToast("获取会议详情成功");
                Message message = Message.obtain(confDetailPageHandler);
                message.what = HANDLE_MESSAGE_GET_CONF_DETAIL_SUCCESS;
                message.obj = confDetailModel;
                message.sendToTarget();
            }

            @Override
            public void onFailed(int retCode, String desc) {
                String err = ErrorMessageFactory.create(retCode);
                if (!TextUtils.isEmpty(err)) {
                    desc = err;
                }
                HCLog.i(TAG, "get conf detail onFailed " + retCode + " desc " + desc);
                DemoUtil.showToastDialog("获取会议详情", retCode, desc);
            }
        });
    }

    static class ConfDetailHandler extends Handler {

        private WeakReference<ConfDetailActivity> mOuter;

        public ConfDetailHandler(ConfDetailActivity activity) {
            mOuter = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            ConfDetailActivity outer = mOuter.get();
            if ((null != outer) && msg.what == HANDLE_MESSAGE_GET_CONF_DETAIL_SUCCESS) {
                HCLog.i(TAG, "get conf detail success.");
                outer.setConfDetailModel((ConfDetailModel) msg.obj);
                outer.subjectText.setText(outer.confDetailModel.getConfSubject());
                int position = TimeZoneUtil.getInstance().getTimeZonePosById(String.valueOf(outer.confDetailModel.getTimeZone()));
                String startTime = DateUtil.convertDateToString(new Date(outer.confDetailModel.getStartTimeStamp() * 1000), DateUtil.FMT_YMDHMS, TimeZoneUtil.getInstance()
                        .getTimeZoneByPosition(position));
                handleConfDetail(outer, startTime);
                DemoUtil.addConsoleLog("ConfDetailModel startTimeStamp: " + outer.confDetailModel.getStartTimeStamp());
                DemoUtil.addConsoleLog("ConfDetailModel endTimeStamp: " + outer.confDetailModel.getEndTimeStamp());
                handleCycleConfInfo(outer);
            } else if ((outer != null) && msg.what == SHOW_SELECTED_SUB_CONF_PAGE) {
                List<SubCycleConfParam> subCycleConfParams = outer.confDetailModel.getSubCycleConfList();
                ConfItemModel confItemModel = (ConfItemModel) msg.obj;
                SubCycleConfParam subCycleConf = null;
                for (SubCycleConfParam subCycleConfParam : subCycleConfParams) {
                    if (subCycleConfParam.getSubConfID().equals(confItemModel.getConfId())) {
                        subCycleConf = subCycleConfParam;
                        DemoUtil.addConsoleLog("SubCycleConfParam startTimeStamp: " + subCycleConfParam.getStartTimeStamp());
                        DemoUtil.addConsoleLog("SubCycleConfParam endTimeStamp: " + subCycleConfParam.getEndTimeStamp());
                    }
                }
                if (subCycleConf != null) {
                    EditSubConfFragment fragment = new EditSubConfFragment();
                    fragment.show(outer.getSupportFragmentManager(), null);
                    fragment.init(subCycleConf, outer.confDetailModel);
                    fragment.setListener(outer);
                }
            } else {
                HCLog.e(TAG, "Invalid msg");
            }
            super.handleMessage(msg);
        }
    }

    private static void handleConfDetail(ConfDetailActivity outer, String startTime) {
        outer.startTimeText.setText(startTime);
        outer.timezomeText.setText(String.valueOf(outer.confDetailModel.getTimeZone()));
        outer.timeDuartionText.setText(String.valueOf(outer.confDetailModel.getMinutes()));
        if (outer.confDetailModel.isVideo()) {
            outer.audioBtn.setChecked(false);
            outer.videoBtn.setChecked(true);
        } else {
            outer.audioBtn.setChecked(true);
            outer.videoBtn.setChecked(false);
        }

        JoinConfPermissionType type = outer.confDetailModel.getCallInRestrictionType();
        outer.setJoinConfPermissionType(type);
        switch (type) {
            case PERMIT_EVERYONE:
                outer.mConfAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_ANYONE;
                break;
            case PERMIT_ENTERPRISE_USER:
                outer.mConfAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_IN_COMPANY_USER;
                break;
            case PERMIT_INVITED_USER:
                outer.mConfAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_INVITED_USER;
                break;
            default:
                break;
        }
        outer.recordSwitch.setChecked(outer.confDetailModel.isRecordOn());
        outer.isAutoStartRecordSwitch.setChecked(outer.confDetailModel.isAutoRecord());
        outer.summarySwitch.setChecked(outer.confDetailModel.getDefaultSummaryState() == SummaryState.SUMMARY_STATE_OPEN);
        outer.autoPublishSummarySwitch.setChecked(outer.confDetailModel.isAutoPublishSummary());
        outer.sendEmailSwitch.setChecked(outer.confDetailModel.getIsMailOn());
        outer.sendSmsSwitch.setChecked(outer.confDetailModel.getIsSmsOn());
        outer.sendEmailCalendarSwitch.setChecked(outer.confDetailModel.getIsEmailCalenderOn());
        outer.allowGuestStartConfSwitch.setChecked(outer.confDetailModel.isAllowGuestStartConf());
        outer.openWaitingRoomSwitch.setChecked(outer.confDetailModel.isOpenWaitingRoom());
        outer.guestStartConfTimeText.setText(String.valueOf(outer.confDetailModel.getAllowGuestStartConfTime()));
        outer.openForbiddenScreenShots.setChecked(outer.confDetailModel.isForbiddenScreenShots());
        outer.openWatermark.setChecked(outer.confDetailModel.isOpenWatermark());

        String confId;
        if (outer.confDetailModel.getVmrFlag() == 1
            && !TextUtils.isEmpty(outer.confDetailModel.getVmrConferenceId())) {
            confId = outer.confDetailModel.getVmrConferenceId();
        } else {
            confId = outer.confDetailModel.getConfId();
        }
        outer.confIdTv.setText(confId);
        outer.hostPwdTv.setText(outer.confDetailModel.getChairmanPwd());
        outer.hostLinkTv.setText(outer.confDetailModel.getChairJoinUri());
        outer.guestPwdTv.setText(outer.confDetailModel.getGuestPwd());
        outer.shareLinkTv.setText(outer.confDetailModel.getGuestJoinUri());

        outer.editConfbtn.setEnabled(true);
        outer.joinConfbtn.setEnabled(true);
        if (outer.guestPwd != null) {
            outer.guestPwd.setText(outer.confDetailModel.getGuestPwd());
        }
        outer.customMsg.setText(outer.confDetailModel.getCustomInfo());
        outer.maxNumber.setText(String.valueOf(outer.confDetailModel.getConcurrentParticipants()));
        handleConfDetailAutoMute(outer);
    }

    private static void handleCycleConfInfo(ConfDetailActivity outer) {
        outer.cycleConfId = outer.confDetailModel.getConfId();
        outer.mIsCycleConf = outer.confDetailModel.isCycleConf();
        outer.subCycleConfList.setVisibility(outer.mIsCycleConf ? View.VISIBLE : View.GONE);
        outer.cycleConfSwitch.setChecked(outer.mIsCycleConf);
        outer.subCycleConfSwitch.setChecked(outer.mIsCycleConf);
        outer.cycleSettingsView.setVisibility(outer.mIsCycleConf ? View.VISIBLE : View.GONE);
        outer.cycleConfSwitch.setEnabled(false);

        if (outer.mIsCycleConf) {
            CycleConfParam cycleConfParam = outer.confDetailModel.getCycleConfParam();
            outer.cycleIntervalText.setText(String.valueOf(cycleConfParam.getInterval()));
            outer.cycleSubDatesText.setText(cycleConfParam.getListPoints());
            outer.cyclePreMindDaysText.setText(String.valueOf(cycleConfParam.getPreRemindDays()));
            Calendar endDate = Calendar.getInstance();
            endDate.setTimeInMillis(cycleConfParam.getEndTimeStamp() * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
            outer.cycleEndDateText.setText(sdf.format(endDate.getTime()));
            outer.cycleTypeSpinner.setSelection(cycleConfParam.getCycleType().getValue());

            outer.subCycleConfSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    outer.subCycleConfList.setVisibility(isChecked ? View.VISIBLE : View.GONE);
                }
            });
            outer.updateMeetingList(outer.confDetailModel.getSubCycleConfList());
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.conf_detail_activity);
        initView();
        initData();
    }

    private void initView() {
        subjectText = findViewById(R.id.edit_subject);
        startTimeText = findViewById(R.id.edit_start_time);
        timezomeText = findViewById(R.id.edit_time_zone);
        timeDuartionText = findViewById(R.id.edit_duration);
        guestPwd = findViewById(R.id.edit_guest_pwd);
        audioBtn = findViewById(R.id.edit_radio_audio);
        videoBtn = findViewById(R.id.edit_radio_video);
        recordSwitch = findViewById(R.id.edit_switch_record_conf);
        isAutoStartRecordSwitch = findViewById(R.id.edit_switch_record_is_auto_start);
        summarySwitch = findViewById(R.id.edit_switch_summary);
        autoPublishSummarySwitch = findViewById(R.id.edit_switch_auto_publish_summary);
        sendEmailSwitch = findViewById(R.id.edit_switch_send_email);
        sendSmsSwitch = findViewById(R.id.edit_switch_send_sms);
        sendEmailCalendarSwitch = findViewById(R.id.edit_switch_send_email_calandar);
        guestStartConfTimeText = findViewById(R.id.edit_allow_guest_start_conf_time);
        openWaitingRoomSwitch = findViewById(R.id.edit_switch_open_waiting_room);
        openForbiddenScreenShots = findViewById(R.id.forbidden_screen_shots_switch);
        openWatermark = findViewById(R.id.open_watermark_switch);

        allowGuestStartConfSwitch = findViewById(R.id.edit_switch_allow_guest_start_conf);
        customMsg = findViewById(R.id.custom_message);
        maxNumber = findViewById(R.id.max_num_edit);
        allowGuestStartConfSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                guestStartConfTimeText.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });
        needWithMemberSwitch = findViewById(R.id.edit_switch_with_attend);
        needWithMemberSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showChooseAttend();
            }
        });
        View attendView = findViewById(R.id.edit_attend_view);
        attendView.setVisibility(needWithMemberSwitch.isChecked() ? View.VISIBLE : View.GONE);
        editConfbtn = findViewById(R.id.edit_conf_btn);
        editConfbtn.setOnClickListener(this);
        editConfbtn.setEnabled(false);

        joinConfbtn = findViewById(R.id.join_conf_btn);
        joinConfbtn.setOnClickListener(this);
        joinConfbtn.setEnabled(false);

        confDetailView = findViewById(R.id.conf_detail_view);
        confDetailSwitch = findViewById(R.id.conf_detail_switch);
        confDetailSwitch.setOnClickListener(v -> {
            if (confDetailSwitch.isChecked()) {
                confDetailView.setVisibility(View.VISIBLE);
            } else {
                confDetailView.setVisibility(View.GONE);
            }
        });
        hostPwdTv = findViewById(R.id.conf_detail_host_pwd);
        hostLinkTv = findViewById(R.id.conf_detail_host_link);
        guestPwdTv = findViewById(R.id.conf_detail_guest_pwd);
        shareLinkTv = findViewById(R.id.conf_detail_share_link);
        confIdTv = findViewById(R.id.conf_detail_conf_id);

        modeGroup = findViewById(R.id.allow_group);
        ((RadioButton) 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;
                    mConfAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_ANYONE;
                } else if (id == R.id.allow_mode_enterprise) {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_ENTERPRISE_USER;
                    mConfAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_IN_COMPANY_USER;
                } else {
                    joinConfPermissionType = JoinConfPermissionType.PERMIT_INVITED_USER;
                    mConfAllowJoinUserType = ConfAllowJoinUserType.CONF_ALLOW_JOIN_INVITED_USER;
                }
            }
        });
        handleCycleConf();
        handleAttendeeInfos();
        handleAutoMute();
    }

    private void handleCycleConf() {
        cycleSettingsView = findViewById(R.id.cycle_conf_setting_edit);
        cycleConfSwitch = findViewById(R.id.switch_is_open_cycle_conf_edit);
        cycleTypeSpinner = findViewById(R.id.cycle_type_spinner_edit);
        cycleIntervalText = findViewById(R.id.cycle_interval_input_edit);
        cycleSubDatesText = findViewById(R.id.cycle_sub_dates_input_edit);
        cycleEndDateText = findViewById(R.id.cycle_end_date_input_edit);
        cyclePreMindDaysText = findViewById(R.id.cycle_premind_days_input_edit);
        subCycleConfSwitch = findViewById(R.id.cycle_sub_conf_list_switch);
        subCycleConfList = findViewById(R.id.cycle_sub_conf_list);
        confListAdapter = new ConfListItemAdapter(this);
        if (subCycleConfList != null) {
            subCycleConfList.setAdapter(confListAdapter);
            CustomLayoutManager customLayoutManager = new CustomLayoutManager(this);
            customLayoutManager.setSpeedRatio(0.5);
            subCycleConfList.setLayoutManager(customLayoutManager);
        }

        List<String> cycleTypeList = new ArrayList<>();
        cycleTypeList.add("按日");
        cycleTypeList.add("按周");
        cycleTypeList.add("按月");
        ArrayAdapter<String> typeAdapter =
            new ArrayAdapter<>(getApplicationContext(), R.layout.main_spinner_item, cycleTypeList);
        typeAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        cycleTypeSpinner.setAdapter(typeAdapter);
        cycleTypeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mSelectedCycleType = CycleType.CYCLE_TYPE_DAY;
                } else if (position == 1) {
                    mSelectedCycleType = CycleType.CYCLE_TYPE_WEEK;
                } else if (position == 2) {
                    mSelectedCycleType = CycleType.CYCLE_TYPE_MONTH;
                }
            }

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

    private void handleAttendeeInfos() {
        TextView attendeeListInfos = findViewById(R.id.attendee_list_infos_tv);
        attendeeListInfos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AttendeeListInfosFragment attendeeListInfosFragment = new AttendeeListInfosFragment();
                if (confDetailModel != null) {
                    attendeeListInfosFragment.init(confDetailModel.getAttendeeModels());
                }
                attendeeListInfosFragment.show(getSupportFragmentManager(), null);
            }
        });
    }

    private void initData() {
        Intent intent = getIntent();
        Bundle bundle = null;
        if (intent != null) {
            bundle = intent.getExtras();
        }
        if (null != bundle) {
            String confid = bundle.getString("confid");
            updateConfDetail(confid);
        }
        getFragmentManager();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.edit_conf_btn) {
            getEditConfParam();
        } else if (v.getId() == R.id.join_conf_btn) {
            joinConf(null);
        } else if (v.getId() == R.id.join_conf_btn_with_demo_activity) {
            joinConf(DemoActivity.getInstance());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private void getEditConfParam() {
        // 会议主题
        String subject = subjectText.getText().toString();
        if (TextUtils.isEmpty(subject)) {
            subject = subjectText.getHint().toString();
        }

        // 会议开始时间、时区、会议时长
        String startTimeLocal = startTimeText.getText().toString();
        long startTimeStamp = BaseDateUtil.dateToTimeStamp(startTimeLocal, BaseDateUtil.FMT_YMDHMS);
        String timeZomeStr = timezomeText.getText().toString();
        if (TextUtils.isEmpty(timeZomeStr)) {
            DemoUtil.showToast("请填写时区！");
            return;
        }
        String timedurStr = timeDuartionText.getText().toString();
        if (TextUtils.isEmpty(timedurStr)) {
            DemoUtil.showToast("请填写会议时长！");
            return;
        }
        int timeZone = Integer.parseInt(timeZomeStr);
        int timeDuration = Integer.parseInt(timedurStr);

        List<AttendeeModel> attendeeInfos = confDetailModel.getAttendeeModels();
        boolean needWithMember = needWithMemberSwitch.isChecked();
        if (needWithMember && attendeeList != null && !attendeeList.isEmpty()) {
            attendeeInfos.addAll(attendeeList);
        }

        showGlobalLoading();

        editConf(subject, startTimeStamp, timeZone, timeDuration, joinConfPermissionType, attendeeInfos);
    }

    private void handleAutoMute() {
        RadioGroup autoMutePersonGroup = findViewById(R.id.auto_mute_person_group);
        ((RadioButton)findViewById(R.id.auto_mute_person_mute)).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 = findViewById(R.id.auto_mute_room_group);
        ((RadioButton)findViewById(R.id.auto_mute_room_unmute)).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;
                }
            }
        });
    }

    private static void handleConfDetailAutoMute(ConfDetailActivity outer) {
        if (outer == null) {
            return;
        }
        ConfDetailModel confDetailModel = outer.confDetailModel;
        if (confDetailModel == null) {
            return;
        }
        outer.autoMuteMode = confDetailModel.getAutoMuteMode();
        switch (outer.autoMuteMode) {
            case AUTO_MUTE_TYPE_MUTE:
                ((RadioButton) outer.findViewById(R.id.auto_mute_person_mute)).setChecked(true);
                break;
            case AUTO_MUTE_TYPE_UNMUTE:
                ((RadioButton) outer.findViewById(R.id.auto_mute_person_unmute)).setChecked(true);
                break;
            case AUTO_MUTE_TYPE_DEFAULT:
            default:
                ((RadioButton) outer.findViewById(R.id.auto_mute_person_default)).setChecked(true);
                break;
        }


        outer.hardTerminalAutoMuteMode = confDetailModel.getHardTerminalAutoMuteMode();
        switch (outer.hardTerminalAutoMuteMode) {
            case AUTO_MUTE_TYPE_MUTE:
                ((RadioButton) outer.findViewById(R.id.auto_mute_room_mute)).setChecked(true);
                break;
            case AUTO_MUTE_TYPE_UNMUTE:
                ((RadioButton) outer.findViewById(R.id.auto_mute_room_unmute)).setChecked(true);
                break;
            case AUTO_MUTE_TYPE_DEFAULT:
            default:
                ((RadioButton) outer.findViewById(R.id.auto_mute_person_default)).setChecked(true);
                break;
        }
    }

    private void editConf(String subject, long startTimeStamp, int timeZone, int timeDuration,
        JoinConfPermissionType permissionType, List<AttendeeModel> attendeeInfos) {
        boolean needRecord = recordSwitch.isChecked();
        boolean isAutoStartRecord = isAutoStartRecordSwitch.isChecked();
        boolean needSummary = summarySwitch.isChecked();
        boolean autoPublishSummary = autoPublishSummarySwitch.isChecked();
        boolean needEmail = sendEmailSwitch.isChecked();
        boolean needSms = sendSmsSwitch.isChecked();
        boolean needEmailCalendar = sendEmailCalendarSwitch.isChecked();
        MeetingType confType = audioBtn.isChecked() ? MeetingType.CONF_AUDIO : MeetingType.CONF_VIDEO;
        boolean allowGuestStartConf = allowGuestStartConfSwitch.isChecked();
        boolean isOpenWaitingRoom = openWaitingRoomSwitch.isChecked();
        boolean isForbiddenScreenShots = openForbiddenScreenShots.isChecked();
        boolean isOpenWatermark = openWatermark.isChecked();

        int allowGuestStartConfTime = 0;
        String guestStartConfTime = guestStartConfTimeText.getText().toString();
        if (!TextUtils.isEmpty(guestStartConfTime)) {
            try {
                allowGuestStartConfTime = Integer.parseInt(guestStartConfTime);
            } catch (NumberFormatException e) {
                HCLog.e(TAG, "transfer int exception.");
            }
        }

        int interval = getEditTextStr(cycleIntervalText);
        Calendar endTime = handleEndDate();
        int preMindDays = getEditTextStr(cyclePreMindDaysText);

        editConfParam = new EditConfParam().setConfId(confDetailModel.getConfId())
            .setVmrIdFlag(1 == confDetailModel.getVmrFlag())
            .setVmrId(confDetailModel.getVmrId())
            .setVmrConfIdType(TextUtils.isEmpty(confDetailModel.getVmrConferenceId()) ? VmrIdType.RANDOM_ID
                : VmrIdType.FIXED_ID)
            .setConfSubject(subject)
            .setStartTimeStamp(startTimeStamp)
            .setTimeZone(timeZone)
            .setDuration(timeDuration)
            .setConfType(confType)
            .setNeedConfPwd(!confDetailModel.getIsGuestFreePwd())
            .setJoinConfRestrictionType(permissionType)
            .setRecordOn(needRecord)
            .setAutoRecord(isAutoStartRecord)
            .setDefaultSummaryState(needSummary ? SummaryState.SUMMARY_STATE_OPEN : SummaryState.SUMMARY_STATE_CLOSE)
            .setAutoPublishSummary(autoPublishSummary)
            .setMailOn(needEmail)
            .setSmsOn(needSms)
            .setEmailCalenderOn(needEmailCalendar)
            .setAllowGuestStartConf(allowGuestStartConf)
            .setAllowGuestStartConfTime(allowGuestStartConfTime)
            .setAttendees(attendeeInfos)
            .setOpenWaitingRoom(isOpenWaitingRoom)
            .setForbiddenScreenShots(isForbiddenScreenShots)
            .setOpenWatermark(isOpenWatermark)
            .setGuestPwd(guestPwd == null ? confDetailModel.getGuestPwd() : guestPwd.getText().toString())
            .setCustomInfo(customMsg.getText().toString())
            .setConcurrentParticipants(confDetailModel.getConcurrentParticipants())
            .setAutoMuteMode(autoMuteMode)
            .setHardTerminalAutoMuteMode(hardTerminalAutoMuteMode);

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

        if (mIsCycleConf) {
            CycleConfParam cycleConfParam = new CycleConfParam();
            cycleConfParam.setCycleType(mSelectedCycleType);
            cycleConfParam.setInterval(interval);
            cycleConfParam.setListPoints(cycleSubDatesText.getText().toString());
            cycleConfParam.setStartTimeStamp(startTimeStamp);
            cycleConfParam.setEndTimeStamp(endTime.getTimeInMillis() / 1000);
            cycleConfParam.setPreRemindDays(preMindDays);

            editCycleConfParam = new EditCycleConfParam();
            editCycleConfParam.setEditConfParam(editConfParam);
            editCycleConfParam.setCycleConfParam(cycleConfParam);
        }
        doModifyVmrInfoAndEditConf(allowGuestStartConf);
    }

    private void doModifyVmrInfoAndEditConf(boolean allowGuestStartConf) {
        // 如果是编辑的是VMR固定会议ID，且需要修改 允许来宾提前启动会议 开关，则先调用changeVmrInfo接口
        if (editConfParam.isVmrIdFlag() && editConfParam.getVmrConfIdType() == VmrIdType.FIXED_ID && allowGuestStartConf != confDetailModel.isAllowGuestStartConf()) {
            ModifyVmrParam vmrParam = new ModifyVmrParam();
            vmrParam.setGuestPwd(confDetailModel.getGuestPwd());
            vmrParam.setHostPwd(confDetailModel.getChairmanPwd());
            vmrParam.setVmrId(confDetailModel.getVmrId());
            vmrParam.setAllowGuestStartConf(allowGuestStartConf);
            HWMBizSdk.getBizOpenApi().changeVmrInfo(vmrParam, new HwmCallback<Void>() {
                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG, "change vmr info onFailed " + retCode + " desc " + desc);
                    dismissGlobalLoading();
                    DemoUtil.showToastDialog("编辑VMR信息", retCode, desc);
                }

                @Override
                public void onSuccess(Void unused) {
                    doEditConf();
                }
            });
            return;
        }
        doEditConf();
    }

    @NotNull
    private Calendar handleEndDate() {
        String endDateTxt = cycleEndDateText.getText().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Calendar endTime = Calendar.getInstance();
        try {
            Date date = sdf.parse(endDateTxt);
            endTime.setTime(date != null ? date : new Date());
        } catch (ParseException e) {
            HCLog.e(TAG, "parse end date failed:" + endDateTxt);
        }
        return endTime;
    }

    private int getEditTextStr(EditText editText) {
        String cycleIntervalTxt = editText.getText().toString();
        int interval = 0;
        if (!TextUtils.isEmpty(cycleIntervalTxt) && TextUtils.isDigitsOnly(cycleIntervalTxt)) {
            interval = Integer.parseInt(cycleIntervalTxt);
        }
        return interval;
    }

    private void doEditConf() {
        if (mIsCycleConf) {
            HWMBizSdk.getBizOpenApi().editCycleConf(editCycleConfParam, new HwmCallback<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    dismissGlobalLoading();
                    DemoUtil.showToast("编辑周期会议成功：" + integer);
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG, "edit cycle conf " + retCode + " desc " + desc);
                    dismissGlobalLoading();
                    DemoUtil.showToastDialog("编辑周期会议", retCode, desc);
                }
            });
        } else {
            HWMBizSdk.getBizOpenApi().editConf(editConfParam, new HwmCallback<Integer>() {
                @Override
                public void onSuccess(Integer integer) {
                    dismissGlobalLoading();
                    DemoUtil.showToast("编辑会议成功：" + integer);
                }

                @Override
                public void onFailed(int retCode, String desc) {
                    HCLog.i(TAG, "edit conf onFailed " + retCode + " desc " + desc);
                    dismissGlobalLoading();
                    DemoUtil.showToastDialog("编辑会议", retCode, desc);
                }
            });
        }
    }

    private void buildConfCommonParam(boolean needRecord, boolean isAutoStartRecord, ConfCommonParam confCommonParam) {
        confCommonParam.setConfAllowJoinUser(mConfAllowJoinUserType);
        confCommonParam.setConfMediaType(
            audioBtn.isChecked() ? ConfMediaType.CONF_MEDIA_AUDIO : ConfMediaType.CONF_MEDIA_VIDEO);
        confCommonParam
            .setRecordMode(needRecord ? ConfRecordMode.CONF_RECORD_RECORD : ConfRecordMode.CONF_RECORD_DISABLE);
        confCommonParam.setIsAutoRecord(isAutoStartRecord);
        confCommonParam.setIsGuestJoinConfWithoutPwd(confDetailModel.getIsGuestFreePwd());
        if (LanguageUtil.getLanguage(Utils.getApp()).toLowerCase().startsWith("zh")) {
            confCommonParam.setPromptLanguage(ConfPromptLanguageType.CONF_PROMPT_LANGUAGE_ZH_CN);
        } else {
            confCommonParam.setPromptLanguage(ConfPromptLanguageType.CONF_PROMPT_LANGUAGE_EN_US);
        }
        confCommonParam.setVmrId(confDetailModel.getVmrId());
        confCommonParam.setVmrFlag(1 == confDetailModel.getVmrFlag());
    }

    public void showChooseAttend() {
        if (needWithMemberSwitch.isChecked()) {
            List<AttendeeModel> selectedAccount = new ArrayList<>();
            if (confDetailModel != null) {
                selectedAccount = confDetailModel.getAttendeeModels();
            }
            ConfUI.getInstance().getAddAttendees().doAddAttendees(this, selectedAccount,
                    " ", 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;
                        }
                    });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public void showGlobalLoading() {
        if (alertLoadingDialog == null) {
            alertLoadingDialog = new AlertDialog.Builder(this).create();
            alertLoadingDialog.getWindow().setBackgroundDrawable(new ColorDrawable());
            alertLoadingDialog.setCancelable(false);
            alertLoadingDialog.setOnKeyListener(
                (dialog, keyCode, event) -> keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_BACK);
            alertLoadingDialog.setCanceledOnTouchOutside(false);

        }
        if (!isFinishing()) {
            alertLoadingDialog.show();
            alertLoadingDialog.setContentView(R.layout.loading_alert);
        }
    }

    public void dismissGlobalLoading() {
        if (null != alertLoadingDialog && alertLoadingDialog.isShowing()) {
            if (!isFinishing()) {
                alertLoadingDialog.dismiss();
            }
        }
    }

    private void joinConf(Activity activity) {

        showGlobalLoading();

        String code = TextUtils.isEmpty(confDetailModel.getChairmanPwd())
            ? confDetailModel.getGuestPwd()
            : confDetailModel.getChairmanPwd();

        JoinConfParam joinConfParam = new PasswordJoinConfParam()
            .setConfId(confDetailModel.getConfId())
            .setStopConflictConf(DemoUtil.needCustom(NeedCustomType.IS_STOP_CONFLICT_CONF))
            .setPassword(code);

        final HwmCancelableCallBack<Void> joinConfCallback = new HwmCancelableCallBack<Void>() {
            @Override
            public void onSuccess(Void ret) {
                dismissGlobalLoading();
            }

            @Override
            public void onFailed(int retCode, String desc) {
                HCLog.i(TAG, "join conf onFailed " + retCode + " desc " + desc);
                dismissGlobalLoading();
                DemoUtil.showToastDialog("加入会议", retCode, desc);
            }

            @Override
            public void onCancel() {
                dismissGlobalLoading();
            }
        };

        if (activity == null) {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).joinConf(joinConfParam, joinConfCallback);
        } else {
            HWMSdk.getOpenApi(DemoUtil.getApplication()).joinConf(activity, joinConfParam, joinConfCallback);
        }
    }

    public void updateMeetingList(List<SubCycleConfParam> subConfList) {
        List<ConfItemModel> confItemModels = DemoUtil.getInstance().transformSubCycleConfList(subConfList);
        if (subCycleConfSwitch != null) {
            String listTitle = "子会议列表 (" + confItemModels.size() + ")";
            subCycleConfSwitch.setText(listTitle);
        }
        if (confListAdapter != null) {
            HwmContext.getInstance().runOnMainThread(() -> confListAdapter.updateConfList(confItemModels));
        }
    }
}
