package com.daya.live_teaching.ui.fragmnet;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.core.LogisticsCenter;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.launcher.ARouter;
import com.cooleshow.base.router.RouterPath;
import com.cooleshow.base.utils.LogUtils;
import com.cooleshow.base.utils.ToastUtil;
import com.cooleshow.base.widgets.dialog.BaseDialogFragment;
import com.cooleshow.base.widgets.dialog.DialogFragmentViewHolder;
import com.daya.live_teaching.R;
import com.daya.live_teaching.common.ResultCallback;
import com.daya.live_teaching.ui.adapter.AddPhotoListAdapter;
import com.daya.live_teaching.utils.GlideEngine;
import com.daya.live_teaching.viewmodel.ClassViewModel;
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 java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ComplaintDialogFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ComplaintDialogFragment extends BaseDialogFragment {

    // TODO: Re     \name parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    // TODO: Rename and change types of parameters
    private String       mParam1;
    private String       mParam2;
    private TextView     tvTitle;
    private RecyclerView recyclerView;
    private EditText     etContent;
    private TextView     btnCancel;
    private TextView     btnCommit;
    private int          maxSelectNum = 3;
    private int          position     = 0;
    List<LocalMedia> selectList = new ArrayList<>();
    private       AddPhotoListAdapter addPhotoListAdapter;
    private final int                 SELECT_PHOTO_REQUEST_CODE = 10000;
    List<String> urlList = new ArrayList<>();
    private DialogFragment     dialogFragment;
    private ClassViewModel classViewModel;

    public ComplaintDialogFragment() {
    }

    public static ComplaintDialogFragment newInstance(String param1, String param2) {
        ComplaintDialogFragment fragment = new ComplaintDialogFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int intLayoutId() {
        return R.layout.fragment_complaint_dialog;
    }

    @Override
    public void convertView(DialogFragmentViewHolder holder, BaseDialogFragment dialog) {
        classViewModel = ViewModelProviders.of(getActivity()).get(ClassViewModel.class);
        tvTitle = holder.getView(R.id.tv_title);
        recyclerView = holder.getView(R.id.recyclerView);
        etContent = holder.getView(R.id.et_content);
        btnCancel = holder.getView(R.id.btn_cancel);
        btnCommit = holder.getView(R.id.btn_commit);
        ImageView ivClose = holder.getView(R.id.iv_close);
        ivClose.setOnClickListener(v -> dialog.dismiss());
        btnCancel.setOnClickListener(v -> dialog.dismiss());
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        recyclerView.setLayoutManager(gridLayoutManager);
        addPhotoListAdapter = new AddPhotoListAdapter(getContext(), maxSelectNum);
        recyclerView.setAdapter(addPhotoListAdapter);
        addPhotoListAdapter.setOnItemClickListener(position -> {
            if (selectList.size() == 0) {
                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.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .maxSelectNum(maxSelectNum)
                        .isCompress(true)// 是否压缩 true or false
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            } else {
                if (selectList.size() < maxSelectNum && position == selectList.size()) {
                    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.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                            .maxSelectNum(maxSelectNum - selectList.size())
                            .isCompress(true)// 是否压缩 true or false
                            .forResult(PictureConfig.CHOOSE_REQUEST);
                } else {
                    Postcard postcard = ARouter.getInstance().build(RouterPath.OnlineClassroom.ACTIVITY_PHOTO_PREVIEW)
                            .withParcelableArrayList("list", (ArrayList<? extends Parcelable>) selectList)
                            .withInt("position", position);
                    LogisticsCenter.completion(postcard);
                    Intent intent = new Intent(getActivity(), postcard.getDestination());
                    intent.putExtras(postcard.getExtras());
                    startActivityForResult(intent, SELECT_PHOTO_REQUEST_CODE);
                }
            }

        });

        btnCommit.setOnClickListener(v -> {
            if (null == selectList || selectList.size() <= 0) {
                ToastUtil.getInstance().show(getContext(), "请选择要上传照片");
                return;
            }
            String content = etContent.getText().toString();
            if (TextUtils.isEmpty(content)) {
                ToastUtil.getInstance().show(getContext(), "请填写课程情况说明");
                return;
            }
            showLoading();
            position = 0;
            String compressPath = selectList.get(position).getCompressPath();
            uploadFile(content, compressPath);
        });
    }


    private void uploadFile(String content, String compressPath) {
        LogUtils.i("白板问题==WhiteBoardInsertImage  = uploadFile==" + compressPath);
        if (!TextUtils.isEmpty(compressPath)) {
            classViewModel.uploadFile(compressPath, new ResultCallback<String>() {
                @Override
                public void onSuccess(String url) {
                    position += 1;
                    urlList.add(url);
                    if (urlList.size() == selectList.size()) {
                        String attachment = "";
                        for (int i = 0; i < urlList.size(); i++) {
                            attachment += ("," + urlList.get(i));
                        }
                        urlList.clear();
                        String attachments = attachment.substring(1);
                        classViewModel.addComplaints(classViewModel.getRoomId().getValue().substring(1), attachments, content, new ResultCallback<Boolean>() {
                            @Override
                            public void onSuccess(Boolean aBoolean) {
                                hideLoading();
                                ToastUtil.getInstance().show(getContext(), "提交成功");
                                VideoViewManager.getInstance().clear();
                                classViewModel.leaveRoom(classViewModel.getRoomId().getValue(), classViewModel.getUserInfo().getValue().getUserId());
                                classViewModel.quitRtcRoom(classViewModel.getRoomId().getValue());
                                getActivity().finish();
                            }

                            @Override
                            public void onFail(int errorCode, String errorStr) {
                                hideLoading();
                            }
                        });
                    } else {
                        String compressPath = selectList.get(position).getCompressPath();
                        uploadFile(content, compressPath);
                    }
                }

                @Override
                public void onFail(int errorCode, String errorStr) {
                }
            });
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> list = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(list);
                    addPhotoListAdapter.setData(selectList);

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //                    GlideImageLoaderUtils.getInstance().loadCircleImage(this,selectList.get(0).getCutPath(),ivPortrait);

                    break;
                case SELECT_PHOTO_REQUEST_CODE:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> list1 = data.getParcelableArrayListExtra("list");
                    selectList.clear();
                    selectList.addAll(list1);
                    addPhotoListAdapter.setData(selectList);
                    break;

            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    public void showLoading() {
    }

    public void hideLoading() {
        if (null != dialogFragment && null != dialogFragment.getDialog()) {
            dialogFragment.getDialog().dismiss();
            dialogFragment = null;
        }


    }

}