package com.cooleshow.teacher.ui.live;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.utils.GlideUtils;
import com.cooleshow.base.utils.MyFileUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.base.utils.helper.QMUIStatusBarHelper;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.contract.CreateLiveContract;
import com.cooleshow.teacher.databinding.ActivityCreateLiveBinding;
import com.cooleshow.teacher.presenter.live.CreateLivePresenter;
import com.daya.live_teaching.utils.GlideEngine;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import androidx.annotation.Nullable;

/**
 * 创建日期：2022/5/20 14:45
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.LiveCenter.TEACHER_MINE_CREATE_COURSE)
public class CreateLiveActivity extends BaseMVPActivity<ActivityCreateLiveBinding, CreateLivePresenter> implements CreateLiveContract.CreateLiveView, View.OnClickListener {
    public static final String[] LIVE_TIMES_LIMIT = new String[]{"30", "45", "60", "90"};
    private OptionsPickerView pvOptions;
    private List<String> mTimes;
    private String currentLimitTime = LIVE_TIMES_LIMIT[0];
    public final int REQUEST_CODE_LOCAL = 0x19;
    private String coverUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "创建直播");
        viewBinding.tvConfirm.setOnClickListener(this);
        viewBinding.csLiveDuration.setOnClickListener(this);
        viewBinding.flUploadCover.setOnClickListener(this);
    }

    @Override
    public void initData() {
        super.initData();
        mTimes = Arrays.asList(LIVE_TIMES_LIMIT);

    }

    @Override
    protected ActivityCreateLiveBinding getLayoutView() {
        return ActivityCreateLiveBinding.inflate(getLayoutInflater());
    }

    @Override
    protected CreateLivePresenter createPresenter() {
        return new CreateLivePresenter();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.tv_confirm) {
            //创建直播间
            String liveTitle = viewBinding.etTitle.getText().toString().trim();
            if (TextUtils.isEmpty(liveTitle)) {
                ToastUtil.getInstance().showShort("请输入直播间标题");
                return;
            }
            String liveContent = viewBinding.etContent.getText().toString().trim();
            if (TextUtils.isEmpty(liveContent)) {
                ToastUtil.getInstance().showShort("请输入直播间内容");
                return;
            }
            if (TextUtils.isEmpty(coverUrl)) {
                ToastUtil.getInstance().showShort("请上传直播封面");
                return;
            }
            presenter.createTempLive(liveContent, liveTitle, coverUrl, currentLimitTime);
            return;
        }

        if (view.getId() == R.id.fl_upload_cover) {
            //上传封面
            toAlbum();
        }

        if (view.getId() == R.id.cs_live_duration) {
            showTimeSelect();
            return;
        }
    }

    private void toAlbum() {
        new RxPermissions(this)
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        goAlbum();
                    } else {
                        ToastUtil.getInstance().show(this, "请选择存储和相机权限！");
                    }
                });
    }

    private void goAlbum() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(com.cooleshow.base.R.style.picture_daya_style)// 主题样式设置 具体参考 values/styles   用法：R .style.picture.white.style
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .enableCrop(true)// 是否裁剪 true or false
                .cutOutQuality(100)
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                .compress(true)// 是否压缩 true or false
                .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                .forResult(REQUEST_CODE_LOCAL);
    }


    private void showTimeSelect() {
        if (pvOptions == null) {
            pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                currentLimitTime = mTimes.get(options1);
                viewBinding.tvLiveTime.setText(currentLimitTime + "分钟");
                viewBinding.tvLiveTime.setTextColor(getResources().getColor(com.cooleshow.base.R.color.color_333333));
            }).setLayoutRes(R.layout.pickerview_live_time_layout, v -> {
                //自定义布局中的控件初始化及事件处理
                final TextView tvSubmit = (TextView) v.findViewById(com.cooleshow.base.R.id.tv_finish);
                TextView ivCancel = (TextView) v.findViewById(com.cooleshow.base.R.id.tv_cancel);
                tvSubmit.setOnClickListener(v12 -> {
                    pvOptions.returnData();
                    pvOptions.dismiss();
                });
                ivCancel.setOnClickListener(v1 -> pvOptions.dismiss());

            }).isDialog(false).build();
        }
        pvOptions.setPicker(mTimes);
        pvOptions.show();

    }

    /**
     * 创建直播间成功,返回直播间id
     *
     * @param roomId
     */
    @Override
    public void onCreateLiveSuccess(String roomId) {
        ToastUtil.getInstance().showShort("创建成功");
        TeacherLiveRoomActivity.start(this, roomId);
        finish();
    }

    @Override
    public void upLoadImageSuccess(String fileUrl) {
        if (isDestroyed() || isFinishing()) {
            return;
        }
        this.coverUrl = fileUrl;
        GlideUtils.INSTANCE.loadImage(this, fileUrl, viewBinding.ivCover, com.cooleshow.base.R.drawable.bg_video_placeholder);

    }

    @Override
    public void upLoadImageFailure() {
        ToastUtil.getInstance().showShort("封面上传失败,请重新选择");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_LOCAL) {
                //上传封面
                if (data != null) {
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    String v_path = null;
                    if (selectList != null && selectList.size() > 0) {
                        v_path = selectList.get(0).getCompressPath();
                    }
                    if (!TextUtils.isEmpty(v_path)) {
//                        String v_path = FileUtils.getFilePathForN(avatar, PersonalSettingActivity.this);
                        boolean isImg = MyFileUtils.isImg(v_path);
                        if (isImg) {
                            presenter.upLoadImage(CreateLiveActivity.this, v_path);
                        } else {
                            ToastUtil.getInstance().showShort("请选择图片类型文件");
                        }
                    }
                }
            }
        }
    }
}
