package com.wisewoods.eduandroid.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.tools.ScreenUtils;
import com.wisewoods.base.base.BaseActivity;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.bean.TencentHostInfo;
import com.wisewoods.base.bean.TreePeopleBean;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.utils.$;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.databinding.ActivityCreateMettingBinding;
import com.wisewoods.eduandroid.databinding.ViewOtherPeopleBinding;
import com.wisewoods.eduandroid.ui.adapter.MettingPeopleAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Response;

public class CreateMettingActivity extends BaseActivity<ActivityCreateMettingBinding> {
    private List<TencentHostInfo.ListBean> hostList;
    private List<String> types;
    private int meetingType = -1;
    private List<ViewOtherPeopleBinding> others;
    private List<HashMap<String, String>> othersData;
    private String userId = "";
    private String memberList = "[]";
    public static final int CODE_REQUEST_MEMBERS = 101;
    public static final int CODE_RESULT_MEMBERS = 701;
    private MettingPeopleAdapter mAdapter;

    @Override
    protected void initData(Bundle savedInstanceState) {
        showBarBack(binding.bar.tvTitle, "创建会议", binding.bar.ivBack);
        others = new ArrayList<>();
        types = new ArrayList<>();
        types.add("预约会议");
        types.add("快速会议");

        binding.tvCreate.setOnClickListener(v -> {
            if (isFastClick()) {
                createMetting();
            }
        });

        binding.tvMettingPeople.setOnClickListener(v -> {
            Intent intent = new Intent(this, MettingPeopleActivity.class);
            intent.putExtra("ids", getIds());
            ActivityUtils.startActivityForResult(this, intent, CODE_REQUEST_MEMBERS);
        });
        binding.tvHost.setOnClickListener(v -> {
            selectHost();
        });
        binding.tvType.setOnClickListener(v -> {
            selectType();
        });
        binding.tvStart.setOnClickListener(v -> {
            selectStart();
        });

        binding.tvEnd.setOnClickListener(v -> {
            selectEnd();
        });

        binding.tvAddOther.setOnClickListener(v -> {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            params.topMargin = SizeUtils.dp2px(8);
            binding.llOther.addView(createOther(), params);
        });

        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
        layoutManager.setFlexWrap(FlexWrap.WRAP);
        layoutManager.setFlexDirection(FlexDirection.ROW);
        layoutManager.setAlignItems(AlignItems.STRETCH);
        layoutManager.setJustifyContent(JustifyContent.FLEX_START);
        binding.rvMettingPeople.setLayoutManager(layoutManager);
        binding.rvMettingPeople.addItemDecoration(new GridSpacingItemDecoration(4,
                ScreenUtils.dip2px(this, 7), false));
        mAdapter = new MettingPeopleAdapter();
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            mAdapter.removeAt(position);
        });
        binding.rvMettingPeople.setAdapter(mAdapter);


        initHostData();

    }

    private String getIds() {
        List<Long> ids = new ArrayList<>();
        for (TreePeopleBean.DataBean data : mAdapter.getData()) {
            ids.add(data.userId);
        }
        return GsonUtils.toJson(ids);
    }

    private View createOther() {
        ViewOtherPeopleBinding otherPeopleBinding = ViewOtherPeopleBinding.inflate(getLayoutInflater());
        otherPeopleBinding.ivDel.setOnClickListener(v -> {
            binding.llOther.removeView(otherPeopleBinding.getRoot());
            others.remove(otherPeopleBinding);
        });
        others.add(otherPeopleBinding);
        return otherPeopleBinding.getRoot();
    }

    private void initHostData() {
        App.api.getTencentHost()
                .enqueue(new JCallback<TencentHostInfo>() {
                    @Override
                    public void onS(Response<TencentHostInfo> response, TencentHostInfo tencentHostInfo) {
                        hostList = tencentHostInfo.data;
                    }
                });
    }

    private void selectEnd() {
        KeyboardUtils.hideSoftInput(this);

        String startStr = binding.tvStart.getText().toString().trim();
        if (TextUtils.isEmpty(startStr)) {
            $.toast("请选择会议开始时间");
            return;
        }
        Calendar startDate = Calendar.getInstance();
        startDate.setTime(TimeUtils.string2Date(startStr));
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(TimeUtils.string2Date(startStr));
        endDate.add(Calendar.DATE, 1);

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v12) -> {//选中事件回调
            if (TimeUtils.getTimeSpan(TimeUtils.getNowDate(), date, TimeConstants.SEC) < 0) {
                if (TimeUtils.getTimeSpan(startDate.getTime(), date, TimeConstants.SEC) < 0) {
                    if (TimeUtils.getTimeSpan(startDate.getTime(), date, TimeConstants.SEC) >=
                            -24 * 60 * 60) {
                        binding.tvEnd.setText(TimeUtils.date2String(date));
                    } else {
                        $.toast("会议时间段必须在24小时内");
                    }
                } else {
                    $.toast("结束时间必须大于开始时间");
                }
            } else {
                $.toast("选择的时间不能小于当前时间");
            }

        })
                .setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .build();
        pvTime.show();
    }

    private void selectStart() {
        KeyboardUtils.hideSoftInput(this);

        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        endDate.add(Calendar.DATE, 1);

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v12) -> {//选中事件回调
            if (TimeUtils.getTimeSpan(TimeUtils.getNowDate(), date, TimeConstants.SEC) < 0) {
                binding.tvStart.setText(TimeUtils.date2String(date));
            } else {
                $.toast("选择的时间不能小于当前时间");
            }
        })
                .setType(new boolean[]{true, true, true, true, true, true})// 默认全部显示
                .setRangDate(startDate, null)//起始终止年月日设定
                .build();
        pvTime.show();
    }

    private void selectType() {
        KeyboardUtils.hideSoftInput(this);

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this,
                (options1, option2, options3, v1) -> {
                    //返回的分别是三个级别的选中位置
                    meetingType = options1;
                    binding.cardStartTime.setVisibility(options1 == 0 ? View.VISIBLE : View.GONE);
                    binding.cardEndTime.setVisibility(options1 == 0 ? View.VISIBLE : View.GONE);

                    String tx = types.get(options1);
                    binding.tvType.setText(tx);
                }).build();
        pvOptions.setPicker(types);
        pvOptions.show();
    }

    private void selectHost() {
        KeyboardUtils.hideSoftInput(this);

        if (hostList == null){
            $.toast("请等待数据加载或者稍后重试");
            initHostData();
        }else{
            OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v1) -> {
                //返回的分别是三个级别的选中位置
                String tx = hostList.get(options1).username;
                binding.tvHost.setText(tx);
                userId = hostList.get(options1).userId;

            }).build();
            pvOptions.setPicker(hostList);
            pvOptions.show();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_MEMBERS && resultCode == CODE_RESULT_MEMBERS) {
            memberList = data.getStringExtra("members");
            List<TreePeopleBean.DataBean> list = GsonUtils.fromJson(memberList, new TypeToken<List<TreePeopleBean.DataBean>>() {
            }.getType());
            mAdapter.setNewInstance(list);
        }
    }

    private void createMetting() {

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        HashMap<String, String> map = new HashMap<>();

        String subject = binding.etName.getText().toString().trim();
        if (TextUtils.isEmpty(subject)) {
            $.toast("会议主题不能为空");
            return;
        }
        if (TextUtils.isEmpty(userId)) {
            $.toast("会议主持人不能为空");
            return;
        }
        if (meetingType == -1) {
            $.toast("会议类型不能为空");
            return;
        }

        if (meetingType == 0) {
            String startTime = binding.tvStart.getText().toString().trim();
            if (TextUtils.isEmpty(startTime)) {
                $.toast("会议开始时间不能为空");
                return;
            }
            String endTime = binding.tvEnd.getText().toString().trim();
            if (TextUtils.isEmpty(endTime)) {
                $.toast("会议结束时间不能为空");
                return;
            }
            map.put("startTime", startTime);
            map.put("endTime", endTime);

        }

        String venue = binding.etAddress.getText().toString().trim();
        String pasword = binding.etPwd.getText().toString().trim();
        if (pasword.length() > 0 && pasword.length() < 4) {
            $.toast("会议密码必须是4-6位");
            return;
        }
        String muteStatus = binding.rgMute.getCheckedRadioButtonId() == R.id.rb_mute_true ? "true" : "false";


        othersData = new ArrayList<>();
        String phones = "[]";
        for (int i = 0; i < others.size(); i++) {
            ViewOtherPeopleBinding otherPeopleBinding = others.get(i);
            String name = otherPeopleBinding.etName.getText().toString().trim();
            String phone = otherPeopleBinding.etPhone.getText().toString().trim();

            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(phone)) {
                if (!RegexUtils.isMobileSimple(phone)) {
                    $.toast("第" + (i + 1) + "个其他参会人员的手机号有误");
                    return;
                }
                HashMap<String, String> others = new HashMap<>();
                others.put("phoneName", name);
                others.put("phone", phone);
                othersData.add(others);
            } else {
                $.toast("其他参会人员的姓名或者手机号不能为空");
                return;
            }
        }

        phones = GsonUtils.toJson(othersData);

        if (mAdapter.getData().size() == 0 && "[]".equals(phones)) {
            $.toast("请选择参会人员");
            return;
        }

        map.put("subject", subject);
        map.put("userId", userId);
        map.put("meetingType", meetingType + "");
        map.put("venue", venue);
        map.put("pasword", pasword);
        map.put("muteStatus", muteStatus);
        map.put("phones", phones);
        map.put("smsStatus", "true");
        map.put("members", getIds());

        LogUtils.e("提交数据", GsonUtils.toJson(map));

        RequestBody body = RequestBody.create(GsonUtils.toJson(map), JSON);
        App.api.addMeeting(body)
                .enqueue(new JDCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        $.toast("创建成功");
                        EventBus.getDefault().post(new BaseEvent.MeetingEvent());
                        finish();
                    }
                });

    }
}
