package com.cooleshow.teacher.ui.minestyle;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

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

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.ui.activity.BaseMVPActivity;
import com.cooleshow.base.ui.video.VideoPlayActivity;
import com.cooleshow.base.utils.ActivityUtils;
import com.cooleshow.base.utils.FileUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.utils.ToastUtils;
import com.cooleshow.teacher.R;
import com.cooleshow.teacher.adapter.MineStyleVideoAdapter;
import com.cooleshow.teacher.adapter.TeachableSelectAdapter;
import com.cooleshow.teacher.bean.TeachableInstrumentBean;
import com.cooleshow.teacher.bean.TeacherSelfStyleInfoBean;
import com.cooleshow.teacher.contract.MineStylePageContract;
import com.cooleshow.teacher.databinding.ActivityMineStylePageBinding;
import com.cooleshow.teacher.presenter.minestyle.MineStylePagePresenter;
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.Gson;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.rong.imkit.utils.StatusBarUtil;

/**
 * 创建日期：2022/5/13 14:02
 *
 * @author Ryan
 * 类说明：
 */
@Route(path = RouterPath.MineCenter.MINE_STYLE_PAGE)
public class MineStylePageActivity extends BaseMVPActivity<ActivityMineStylePageBinding, MineStylePagePresenter> implements MineStylePageContract.MineStylePageView, View.OnClickListener {
    private final int SELECT_RESULT = 1001;
    private final int CHOOSE_VIDEO = 1002;
    private EditText etSelfIntroduction;
    private RecyclerView videoList;
    private MineStyleVideoAdapter mMineStyleVideoListAdapter;
    private RecyclerView rvTopSelect;
    private TeachableSelectAdapter teachableSelectAdapter;
    private TeacherSelfStyleInfoBean myStyleInfoBean = null;
    private List<TeachableInstrumentBean> selectTeachableInstrument = new ArrayList<>();

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_select_fans:
                Bundle bundle=new Bundle();
                bundle.putSerializable("selectTeachableInstrument", (Serializable) selectTeachableInstrument);
                ARouter.getInstance().build(RouterPath.MineCenter.MINE_TEACHABLE_INSTRUMENT)
                        .withBundle("bundle",bundle)
                        .navigation(this, SELECT_RESULT);
                break;
            case R.id.tv_save:
                Gson gson = new Gson();
                myStyleInfoBean.styleVideo.clear();
                for (TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean : videoBeanList) {
                    if (styleVideoBean.type!=1){
                        myStyleInfoBean.styleVideo.add(styleVideoBean);
                    }
                }
                myStyleInfoBean.introduction=etSelfIntroduction.getText().toString().trim();
                String subjectIdStr="";
                String subjectNameStr="";
                for (TeachableInstrumentBean teachableInstrumentBean : selectTeachableInstrument) {
                    subjectIdStr+=","+teachableInstrumentBean.id;
                    subjectNameStr+=","+teachableInstrumentBean.name;
                }
                if (subjectIdStr.startsWith(",")){
                    subjectIdStr=   subjectIdStr.replaceFirst(",","");
                }
                if (subjectNameStr.startsWith(",")){
                    subjectNameStr=   subjectNameStr.replaceFirst(",","");
                }
                myStyleInfoBean.subjectId=subjectIdStr;
                myStyleInfoBean.subjectName=subjectNameStr;
                presenter.saveTeacherStyle(gson.toJson(myStyleInfoBean));
                break;
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
        StatusBarUtil.setStatusBarDarkTheme(this, true);
    }

    @Override
    public void initData() {
        super.initData();
        presenter.getTeacherSelfStyle();
    }

    private List<TeacherSelfStyleInfoBean.StyleVideoBean> videoBeanList = new ArrayList<>();

    @SuppressLint("NotifyDataSetChanged")
    @Override
    protected void initView() {
        initMidTitleToolBar(viewBinding.toolbarInclude.toolbar, "个人风采");
        etSelfIntroduction = viewBinding.etSelfIntroduction;
        videoList = viewBinding.rvTeacherStyleVideo;
        viewBinding.tvSelectFans.setOnClickListener(this);
        viewBinding.tvSave.setOnClickListener(this);
        GridLayoutManager manager = new GridLayoutManager(this, 2);
        videoList.setLayoutManager(manager);
        addEmptyVideoBean();
        mMineStyleVideoListAdapter = new MineStyleVideoAdapter(videoBeanList);
        videoList.setAdapter(mMineStyleVideoListAdapter);
        mMineStyleVideoListAdapter.setItemAddClickAction(new MineStyleVideoAdapter.ItemAddClickAction() {
            @Override
            public void add() {
                getVideoPermission();
            }

            @Override
            public void play(String videoUrl) {
                VideoPlayActivity.start(MineStylePageActivity.this, videoUrl);
            }

            @Override
            public void delete(String url) {
                for (TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean : videoBeanList) {
                    if (styleVideoBean.type == 0 && styleVideoBean.videoUrl.equals(url)) {
                        videoBeanList.remove(styleVideoBean);
                        break;
                    }
                }
                mMineStyleVideoListAdapter.notifyDataSetChanged();
            }
        });
        rvTopSelect = viewBinding.rvTopSelect;
        //设置LayoutManager
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(this);
        //主轴为水平方向，起点在左端
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);
        //按正常方向换行
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);
        //定义项目在副轴轴上如何对齐
        flexboxLayoutManager.setAlignItems(AlignItems.CENTER);
        //多个轴对齐方式
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);
        rvTopSelect.setLayoutManager(flexboxLayoutManager);
        teachableSelectAdapter = new TeachableSelectAdapter(selectTeachableInstrument);
        rvTopSelect.setAdapter(teachableSelectAdapter);
        teachableSelectAdapter.setOnItemClickListener((adapter, view, position) -> {
            selectTeachableInstrument.remove(position);
            teachableSelectAdapter.notifyDataSetChanged();
        });
        addETListener();
    }

    private void addETListener() {
        etSelfIntroduction.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String trim = etSelfIntroduction.getText().toString();
                viewBinding.tvNumHint.setText(trim.length() + "/200");
            }
        });
    }

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

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

    @Override
    public void getSelfStyleSuccess(TeacherSelfStyleInfoBean styleInfoBean) {
        myStyleInfoBean = styleInfoBean;
        //个人介绍
        viewBinding.etSelfIntroduction.setText(styleInfoBean.introduction);
        //视频信息
        if (mMineStyleVideoListAdapter != null) {
            videoBeanList.clear();
            videoBeanList.addAll(styleInfoBean.styleVideo);
            addEmptyVideoBean();
            mMineStyleVideoListAdapter.notifyDataSetChanged();
        }
        if (!TextUtils.isEmpty(styleInfoBean.subjectId)){
            if (styleInfoBean.subjectId.contains(",")){
                String[] splitId = styleInfoBean.subjectId.split(",");
                String[] splitName = styleInfoBean.subjectName.split(",");
                for (int i = 0; i < splitId.length; i++) {
                    TeachableInstrumentBean instrumentBean=new TeachableInstrumentBean();
                    instrumentBean.id=Integer.parseInt(splitId[i]);
                    instrumentBean.name=splitName[i];
                    selectTeachableInstrument.add(instrumentBean);
                }
            }else{
                TeachableInstrumentBean instrumentBean=new TeachableInstrumentBean();
                instrumentBean.id=Integer.parseInt(styleInfoBean.subjectId);
                instrumentBean.name=styleInfoBean.subjectName;
                selectTeachableInstrument.add(instrumentBean);
            }
            teachableSelectAdapter.notifyDataSetChanged();

        }
    }


    @Override
    public void saveTeacherStyleSuccess(TeacherSelfStyleInfoBean styleInfoBean) {
        ToastUtil.getInstance().showShort("保存成功");
        finish();
    }

    @Override
    public void upLoadVideoSuccess(TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean) {
        videoBeanList.add(0, styleVideoBean);
        mMineStyleVideoListAdapter.notifyDataSetChanged();

    }

    @Override
    public void upLoadVideoFailure() {
    }

    private void addEmptyVideoBean() {
        TeacherSelfStyleInfoBean.StyleVideoBean styleVideoBean = new TeacherSelfStyleInfoBean.StyleVideoBean();
        styleVideoBean.type = 1;
        videoBeanList.add(styleVideoBean);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_RESULT) {
                List<TeachableInstrumentBean> dataSerializableExtra = (List<TeachableInstrumentBean>) data.getSerializableExtra("selectTeachableInstrument");
                selectTeachableInstrument.clear();
                selectTeachableInstrument.addAll(dataSerializableExtra);
                teachableSelectAdapter.notifyDataSetChanged();
            } else if (requestCode == CHOOSE_VIDEO) {
                Uri uri = data.getData();
                String v_path = FileUtils.getFilePathForN(uri, MineStylePageActivity.this);
                presenter.upLoadVideo(MineStylePageActivity.this, v_path);
            }
        }
    }


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

    private void chooseVideo() {
        Intent intent = new Intent();
        intent.setType("video/*"); //选择视频 (mp4 3gp 是android支持的视频格式)
        intent.setAction(Intent.ACTION_GET_CONTENT);
        /* 取得相片后返回本画面 */
        ActivityUtils.startActivityForResult(this, intent, CHOOSE_VIDEO);

    }
}
