package com.sheep.gamegroup.view.activity;

import android.support.annotation.IntDef;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.sheep.gamegroup.absBase.AbsObserver;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.IRefresh;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.CreateUserVideoReq;
import com.sheep.gamegroup.model.entity.InputAndUrlList;
import com.sheep.gamegroup.model.entity.Video;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ActionUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.QiNiuUploadUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.dialog.DialogProgress;
import com.sheep.gamegroup.view.fragment.FgtArticleVideo;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.Locale;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_IMAGE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_NONE;
import static android.provider.MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO;
import static com.sheep.gamegroup.util.QiNiuUploadUtil.UPLOAD_TYPE_FAIL;
import static com.sheep.gamegroup.util.QiNiuUploadUtil.UPLOAD_TYPE_NONE;
import static com.sheep.gamegroup.util.QiNiuUploadUtil.UPLOAD_TYPE_START;
import static com.sheep.gamegroup.util.QiNiuUploadUtil.UPLOAD_TYPE_SUCCESS;

/**
 * Created by realicing on 2018/11/26.
 * realicing@sina.com
 * 小绵羊3.4.5新增--发布发现内容
 */
public class ActPublishArticle extends BaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.act_publish_article;
    }

    @BindView(R.id.act_publish_article_et)
    EditText editText;
    @BindView(R.id.act_publish_article_cv)
    RecyclerView recyclerView;

    private InputAndUrlList inputAndUrlList = new InputAndUrlList();

    @Override
    public void initView() {
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitleFinish(this)
                .setTitle(this, "")
                .setRightBtn(this, "发布", 0, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onClickCommit(view);
                    }
                });
        inputAndUrlList.getList().add(null);
        recyclerView.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance(), LinearLayoutManager.HORIZONTAL, false));
        recyclerView.setAdapter(new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_image_view, inputAndUrlList.getList()) {
            @Override
            protected void convert(BaseViewHolder helper, final String item) {
                ImageView imageView = helper.getView(R.id.img_detail);
                if (item == null) {
                    ViewUtil.setImage(imageView, ViewUtil.getNetImgByName("add_img"));
                    helper.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            addVideo();
                        }
                    });
                } else {
                    Glide.with(SheepApp.getInstance())
                            .load(new File(item))
                            .into(imageView);
                    helper.itemView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            addVideo();
                        }
                    });
                }
            }
        });
//        Integer type = DataUtil.getObject(getIntent(), Integer.class);
//        if(type != null){
//            switch (type){
//                case MEDIA_TYPE_IMAGE:
//                case MEDIA_TYPE_VIDEO:
//                    break;
//                case MEDIA_TYPE_NONE:
//                default:
//                    break;
//            }
//        }
    }

    private void addVideo() {
        Jump2View.getInstance().gotoActMediaChoose(MEDIA_TYPE_NONE);
    }

    private int uploadType = UPLOAD_TYPE_NONE;

    //点击确定按钮
    public void onClickCommit(View view) {
        String input = editText.getText().toString();
        if (TextUtils.isEmpty(input)) {
            G.showToast(getString(R.string.x_cant_is_null, "内容不能为空"));
            return;
        }
//        if (inputAndUrlList.getList().isEmpty()) {
//            G.showToast(R.string.nedd_picker_img);
//            return;
//        }
        if (isErrorVideo()) {
            G.showToast(R.string.need_picker_video);
            return;
        }
        jsonObject.put("resource_type", CreateUserVideoReq.TYPE_VIDEO);
        jsonObject.put("title", input);
        jsonObject.put("duration", video.getDuration() / 1000);
        jsonObject.put("topic_id", video.getTopicId());
        inputAndUrlList.setInput(input);
        switch (uploadType) {
            case UPLOAD_TYPE_NONE:
                G.showToast("开始上传视频");
                uploadFile();
                break;
            case UPLOAD_TYPE_START:
                G.showToast("正在上传视频");
                break;
            case UPLOAD_TYPE_SUCCESS:
                break;
            case UPLOAD_TYPE_FAIL:
                G.showToast("重新上传视频");
                uploadFile();
                break;
        }
    }

    //
    private boolean isErrorVideo() {
        return video == null || video.getFilePath() == null || !new File(video.getFilePath()).exists();
    }

    private void uploadFile() {
        final DialogProgress dialogProgress = DialogProgress.showDialog(this);
        uploadType = UPLOAD_TYPE_START;
        QiNiuUploadUtil.getInstance().uploadFile(video.getFilePath()/*, QiNiuUploadUtil.TAG_VIDEO*/, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo info, JSONObject response) {
                LogUtil.println("qiniu", key, info, response);
                if (info == null) {
                    ViewUtil.setText(dialogProgress.getTextView(), "上传失败");
                    ViewUtil.dismiss(dialogProgress, 1);
                    uploadType = UPLOAD_TYPE_FAIL;
                    return;
                }
                //res包含hash、key等信息，具体字段取决于上传策略的设置
                if (info.isOK()) {
                    ViewUtil.setText(dialogProgress.getTextView(), "上传成功");
                    uploadType = UPLOAD_TYPE_SUCCESS;
                    String url = null;
                    try {
                        url = QiNiuUploadUtil.BASE_URL + response.getString("key");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    jsonObject.put("resource", url);
                    jsonObject.put("cover", String.format(Locale.CHINA, "%s?vframe/jpg/offset/0&w=%d&h=%d", url, video.getWidth(), video.getHeight()));
                    publishArticle(dialogProgress);
                } else {
                    ViewUtil.setText(dialogProgress.getTextView(), "上传失败");
                    ViewUtil.dismiss(dialogProgress, 1);
                    uploadType = UPLOAD_TYPE_FAIL;
                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                }
                LogUtil.println("qiniu", key + ",\r\n " + info + ",\r\n " + response);
            }
        }, new UpProgressHandler() {
            public void progress(String key, double percent) {
                LogUtil.println("qiniu", key + ": " + percent);
                ViewUtil.setText(dialogProgress.getTextView(), String.format(Locale.CHINA, "%d%%", (int) (percent * 100)));
            }
        });
    }

    private com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();

    private void publishArticle(final DialogProgress dialogProgress) {
        SheepApp.getInstance().getNetComponent().getApiService().postVideo(jsonObject)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        ViewUtil.setText(dialogProgress.getTextView(), "发布成功");
                        ViewUtil.dismiss(dialogProgress, 1);
                        ViewUtil.delay(new AbsObserver<Integer>() {
                            @Override
                            public void onNext(Integer integer) {
                                ActionUtil.getInstance().addNextAction(FgtArticleVideo.class.getSimpleName(), IRefresh.class.getSimpleName());
                                ActPublishArticle.this.finish();
                            }
                        },1);
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                        ViewUtil.setText(dialogProgress.getTextView(), baseMessage.getErrorMsg());
                        ViewUtil.dismiss(dialogProgress, 1);
                    }
                });
    }

    @IntDef({MEDIA_TYPE_IMAGE, MEDIA_TYPE_VIDEO, MEDIA_TYPE_NONE})
    public @interface Type {
    }

    @Override
    protected boolean needRegisterEventBus() {
        return true;
    }
    private Video video;
    @Subscribe
    public void onEventMainThread(Video data) {
        this.video = data;
        ListUtil.removeNull(inputAndUrlList.getList());
        inputAndUrlList.getList().add(video.getFilePath());
        ViewUtil.notifyDataSetChanged(recyclerView);
    }
}
