package com.meeting.demo.view.sdkconfig;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.huawei.hwmbiz.contact.api.impl.DepartmentInfoImpl;
import com.huawei.hwmbiz.contact.cache.DepartmentTreeInfoCache;
import com.huawei.hwmbiz.contact.cache.model.CorporateContactInfoModel;
import com.huawei.hwmconf.presentation.ConfUI;
import com.huawei.hwmconf.presentation.view.component.CustomLayoutManager;
import com.huawei.hwmconf.sdk.model.conf.entity.AttendeeModel;
import com.meeting.demo.R;
import com.meeting.demo.adapter.PeopleListItemAdapter;
import com.meeting.demo.utils.DemoUtil;
import com.huawei.hwmfoundation.HwmContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 自定义加人
 *
 * 注意：此实例中获取当前登录账号所在的部门编码：（DepartmentTreeInfoCache.getInstance().getMyDepartmentCode()，
 *      获取部门下所有成员列表（包含子部门）：DepartmentInfoImpl.getInstance().downloadDepartmentContactInfo），
 *      不属于开发API，仅作为与会者界面自定义加人示例演示，后期会不定期变更，请勿直接调用。
 */

public class AddPeopleActivity extends Activity {
    public final static String TAG = AddPeopleActivity.class.getSimpleName();
    private RecyclerView mPeopleListRecyclerView;
    private PeopleListItemAdapter peopleListItemAdapter;
    private TextView titleText;
    private LinearLayout backView;
    private Button demoCustomizeConfBtn;
    private static final int REQUEST_CODE = 5001;
    private final List<AttendeeModel> attendeeModels = new ArrayList<>();

    @SuppressLint("CheckResult")
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customize_add_people);
        /**
         *
         * ----------------------------该API仅供参考使用，开发过程中请勿使用此API------------------------------------
         * DepartmentTreeInfoCache.getInstance(DemoUtil.getApplication()).getMyDepartmentCode()，获取当前登录账号所在的部门编码
         *
         */
        DepartmentTreeInfoCache.getInstance(DemoUtil.getApplication()).getMyDepartmentCode()

                /**
                 *
                 * ----------------------------该API仅供参考使用，开发过程中请勿使用此API------------------------------------
                 * epartmentInfoImpl.getInstance(DemoUtil.getApplication()).downloadDepartmentContactInfo,获取部门下所有成员列表（包含子部门）
                 *
                 */
                .subscribe(departmentCode -> DepartmentInfoImpl.getInstance(DemoUtil.getApplication()).downloadDepartmentContactInfo(departmentCode,1)
                        .subscribe(departmentContactInfoModel -> {
                            List<CorporateContactInfoModel> allLevelTotalList = departmentContactInfoModel.getAllLevelTotalList();
                            for (int i = 0; i < allLevelTotalList.size(); i++) {
                                AttendeeModel attendeeModel = new AttendeeModel();
                                attendeeModel.setName(allLevelTotalList.get(i).getName());
                                attendeeModel.setEmail(allLevelTotalList.get(i).getEmail());
                                attendeeModel.setAccountId(allLevelTotalList.get(i).getAccount());
                                attendeeModel.setNumber(allLevelTotalList.get(i).getBindNum());
                                attendeeModels.add(attendeeModel);
                            }
                            updateMeetingList(attendeeModels);
                        }));


        mPeopleListRecyclerView = findViewById(R.id.demo_customize_list_recyclerview);
        demoCustomizeConfBtn = findViewById(R.id.demo_customize_conf_btn);
        titleText = findViewById(R.id.conf_title_text);
        backView = findViewById(R.id.conf_title_back_view);
        titleText.setText("自定义选人");
        initAddBtn();

        peopleListItemAdapter = new PeopleListItemAdapter();
        if (mPeopleListRecyclerView != null) {
            mPeopleListRecyclerView.setAdapter(peopleListItemAdapter);
            CustomLayoutManager customLayoutManager = new CustomLayoutManager(getApplicationContext());
            customLayoutManager.setSpeedRatio(0.5);
            mPeopleListRecyclerView.setLayoutManager(customLayoutManager);
        }

        //设置RecyclerView点击事件
        peopleListItemAdapter.setOnItemClickListener((view, position) -> peopleListItemAdapter.setSelectItem(position));

        //设置创建会议点击事件
        demoCustomizeConfBtn.setOnClickListener(v -> {
            Intent intent = new Intent();
            setResult(1,intent);
            List<AttendeeModel> members = new ArrayList<>();
            Map<Integer, Boolean> map = peopleListItemAdapter.getMap();
            for (int i = 0; i < map.size(); i++) {
                if (map.get(i).booleanValue()) {
                    members.add(attendeeModels.get(i));
                }
            }
            DemoUtil.selectModels = members;
            ConfUI.getAddAttendees().onActivityResult(5000, RESULT_OK, new Intent());
            finish();
        });

        backView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initAddBtn() {
        Button demoCustomizeAddBtn = findViewById(R.id.demo_customize_add_attendee_btn);
        demoCustomizeAddBtn.setVisibility(View.VISIBLE);
        demoCustomizeAddBtn.setOnClickListener(v -> {
            // 跳转AppId邀人界面
            Intent intent = new Intent(AddPeopleActivity.this, AddPeopleByAppidAuthActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        });
    }

    public void updateMeetingList(List<AttendeeModel> ckConfListInfos) {
        if (peopleListItemAdapter != null) {
            HwmContext.getInstance().runOnMainThread(() -> peopleListItemAdapter.updateConfList(ckConfListInfos));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            String json = data.getStringExtra("attendeeModel");
            AttendeeModel attendeeModel = new Gson().fromJson(json, AttendeeModel.class);
            attendeeModels.add(0, attendeeModel);
            updateMeetingList(attendeeModels);
        }
    }
}

