package com.yunbao.main.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;

import android.widget.FrameLayout;

import com.google.gson.Gson;
import com.yunbao.common.Constants;
import com.yunbao.common.activity.AbsActivity;
import com.yunbao.common.http.HttpCallback;
import com.yunbao.common.interfaces.CommonCallback;
import com.yunbao.common.interfaces.ImageResultCallback;
import com.yunbao.common.interfaces.VideoResultCallback;
import com.yunbao.common.upload.FileUploadManager;
import com.yunbao.common.upload.UploadBean;
import com.yunbao.common.upload.UploadCallback;
import com.yunbao.common.upload.UploadStrategy;
import com.yunbao.common.utils.BitmapList;
import com.yunbao.common.utils.DialogUitl;
import com.yunbao.common.utils.FileUtil;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.ProcessImageUtil;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.common.utils.WordUtil;
import com.yunbao.main.R;
import com.yunbao.main.adapter.AuthImageAdapter;
import com.yunbao.main.bean.AuthBean;
import com.yunbao.main.custom.UploadImageView;
import com.yunbao.main.custom.UploadImageView1;
import com.yunbao.main.http.MainHttpUtil;
import com.yunbao.one.http.OneHttpUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;

import butterknife.ButterKnife;

// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-03-22
// +———————————————————————————————————
public class AnchorAuthActivity extends AbsActivity implements View.OnClickListener {
    private static final String TAG = "AnchorAuthActivity";
    private ProcessImageUtil mImageUtil;
    private UploadImageView mCover;
    private UploadImageView1 mVideo;
    private int mTargetPositon;
    private RecyclerView mRecyclerView;
    private AuthImageAdapter mAdapter;
    private Dialog mChooseImageDialog;
    private Dialog mChooseVideoDialog;
    private FrameLayout mPlay;


    private UploadBean mCoverUploadBean;
    private UploadBean mVideoUploadBean;
    private UploadBean mVideoThumbBean;
    private List<UploadBean> mUploadList;
    private List<UploadBean> uploadList;
    private UploadStrategy mUploadStrategy;
    private Dialog mLoading;
    private String thumb,videoThumb;
    private String status,video,videoFormat;
    private List<String> backWall;
    private Button mSubmit;
    private File coverFile,videoFile;
    private List<File> backList;
    private UploadBean mUploadBean;



    public static void forward(Context context,String videoFormat,String video,String status) {
        Intent intent = new Intent(context, AnchorAuthActivity.class);
        intent.putExtra("videoFormat",videoFormat);
        intent.putExtra("video",video);
        intent.putExtra("status",status);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_author_auth;
    }

    @Override
    protected void main() {
        Intent intent=getIntent();
        status=intent.getStringExtra("status");
        videoFormat=intent.getStringExtra("videoFormat");
        video=intent.getStringExtra("video");

        mCover = findViewById(R.id.cover);
        mVideo = findViewById(R.id.video);
        mPlay = findViewById(R.id.play);
        mSubmit = findViewById(R.id.btn_submit);

        mImageUtil = new ProcessImageUtil(this);
        mImageUtil.setImageResultCallback(new ImageResultCallback() {
            @Override
            public void beforeCamera() {

            }

            @Override
            public void onSuccess(File file) {
                if (file == null) {
                    return;
                }
                if (mTargetPositon < 0) {
                    if (mCover != null) {
                        mCoverUploadBean.setOriginFile(file);
                        mCover.showImageData(mCoverUploadBean);
                    }
                } else {
                    if (mAdapter != null) {
                        mAdapter.updateItem(mTargetPositon, file);
                    }
                }
            }

            @Override
            public void onFailure() {
            }
        });

        mImageUtil.setVideosultCallback(new VideoResultCallback() {
            @Override
            public void onSuccess(File file) {
                mVideoUploadBean.setOriginFile(file);
                mVideo.showImageData(mVideoUploadBean);
                mPlay.setVisibility(View.VISIBLE);
                Bitmap bitmap= FileUtil.getVideoThumbnail(file.getAbsolutePath());
                mVideoThumbBean.setOriginFile(FileUtil.saveFile(bitmap));
            }

            @Override
            public void onFailure() {

            }
        });

        mCover.setActionListener(new UploadImageView.ActionListener() {
            @Override
            public void onAddClick(UploadImageView uploadImageView) {
                chooseImage(-1);
            }

            @Override
            public void onDelClick(UploadImageView uploadImageView) {
                if (mCoverUploadBean != null && mCover != null) {
                    mCoverUploadBean.setEmpty();
                    mCover.showImageData(mCoverUploadBean);
                    mSubmit.setText(R.string.title_010);
                }
            }
        });


        mVideo.setActionListener(new UploadImageView1.ActionListener() {
            @Override
            public void onAddClick(UploadImageView1 uploadImageView) {
                    chooseVideo();
            }

            @Override
            public void onClick(UploadImageView1 uploadImageView) {
                if (!TextUtils.isEmpty(videoFormat)){
                    String url = videoFormat;
                    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
                    String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
                    Intent mediaIntent = new Intent(Intent.ACTION_VIEW);
                    mediaIntent.setDataAndType(Uri.parse(url), mimeType);
                    startActivity(mediaIntent);
                }
            }

            @Override
            public void onDelClick(UploadImageView1 uploadImageView) {
                if (mVideoUploadBean != null && mVideo != null) {
                    mVideoUploadBean.setEmpty();
                    mVideoThumbBean.setEmpty();
                    mVideo.showImageData(mVideoUploadBean);
                    mPlay.setVisibility(View.GONE);
                    mSubmit.setText(R.string.title_010);
                }
            }
        });
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        mAdapter = new AuthImageAdapter(AnchorAuthActivity.this,status);
        mRecyclerView.setAdapter(mAdapter);
        mCoverUploadBean = new UploadBean();
        mVideoUploadBean = new UploadBean();
        mVideoThumbBean = new UploadBean();
        mUploadBean=new UploadBean();

        backList=new ArrayList<>();
        uploadList=new ArrayList<>();


        if (!"-1".equals(status)) {
            if (BitmapList.sBitmap!=null) {
                coverFile = FileUtil.saveFile(BitmapList.sBitmap);
                mCoverUploadBean.setOriginFile(coverFile);
                mCover.showImageData(mCoverUploadBean);
            }
            if (BitmapList.sBitmap1!=null) {
                videoFile = FileUtil.saveFile(BitmapList.sBitmap1);
                mVideoThumbBean.setOriginFile(videoFile);
                mVideo.showImageData(mVideoThumbBean);
            }

            if (BitmapList.list.size()>0) {
                for (int i = 0; i < BitmapList.list.size(); i++) {
                    File file = FileUtil.saveFile(BitmapList.list.get(i));
                    mUploadBean = new UploadBean();
                    mUploadBean.setOriginFile(file);
                    uploadList.add(mUploadBean);
                    backList.add(FileUtil.saveFile(BitmapList.list.get(i)));
                }
                if (mAdapter != null) {
                    if ("1".equals(status)||"0".equals(status)) {
                        mAdapter.setList1(uploadList);
                    }else{
                        mAdapter.setList(uploadList);
                    }
                }
            }
        }

        if ("0".equals(status)){
            mSubmit.setText(R.string.video_status_verify);
            mSubmit.setBackgroundResource(R.drawable.bg_main_me_false);
            mSubmit.setClickable(false);
            mCover.hideDelBtn();
            mVideo.hideDelBtn();
        }else if ("2".equals(status)){
            mSubmit.setText(R.string.check_fail);
        }else if ("1".equals(status)){
            mSubmit.setVisibility(View.GONE);
            mCover.hideDelBtn();
            mVideo.hideDelBtn();
        }else{
            mPlay.setVisibility(View.GONE);

        }
    }

    public void changeText(){
        mSubmit.setText(R.string.title_010);
    }
    /**
     * 选择图片
     */
    public void chooseImage(int targetPositon) {
        mTargetPositon = targetPositon;
        if (mChooseImageDialog == null) {
            mChooseImageDialog = DialogUitl.getStringArrayDialog(mContext, new Integer[]{
                    R.string.camera, R.string.alumb}, true, new DialogUitl.StringArrayDialogCallback() {
                @Override
                public void onItemClick(String text, int tag) {
                    if (tag == R.string.camera) {
                        mImageUtil.getImageByCamera(mTargetPositon < 0);
                    } else {
                        if (mTargetPositon < 0) {
                            mImageUtil.getImageByAlumb(true);
                        } else {
                            mImageUtil.getImageByAlumb(false);
                        }
                    }
                }
            });
        }
        mChooseImageDialog.show();
    }
    /**
     * 拍摄视频
     */
    public void chooseVideo() {
        if (mChooseVideoDialog == null) {
            mChooseVideoDialog = DialogUitl.getStringArrayDialog(mContext, new Integer[]{
                    R.string.title_014}, true, new DialogUitl.StringArrayDialogCallback() {
                @Override
                public void onItemClick(String text, int tag) {
                 mImageUtil.getVideoRecord();

                }
            });
        }
        mChooseVideoDialog.show();
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_submit) {
            submit();
        }
    }

    /**
     * 提交认证信息
     */
    private void submit() {
        mUploadList = new ArrayList<>();
        if (mCoverUploadBean.isEmpty()) {
            ToastUtil.show(R.string.auth_tip_32);
            return;
        }
        mUploadList.add(mCoverUploadBean);
        if (mAdapter.isEmpty()) {
            ToastUtil.show(R.string.auth_tip_33);
            return;
        }
        List<UploadBean> bgUploadList = mAdapter.getList();
        mUploadList.addAll(bgUploadList);

        if (TextUtils.isEmpty(videoFormat)) {
            if (mVideoUploadBean.isEmpty()) {
                ToastUtil.show(R.string.auth_tip_36);
                return;
            }
        }
        mUploadList.add(mVideoUploadBean);
        mUploadList.add(mVideoThumbBean);

        if (mLoading == null) {
            mLoading = DialogUitl.loadingDialog(mContext);
        }
        mLoading.show();
        uploadFile();
    }

    /**
     * 上传图片
     */
    private void uploadFile() {
        L.e(TAG, "上传图片开始--------->");
        FileUploadManager.getInstance().createUploadImpl(mContext, new CommonCallback<UploadStrategy>() {
            @Override
            public void callback(UploadStrategy strategy) {
                if (strategy == null) {
                    ToastUtil.show(WordUtil.getString(R.string.upload_type_error));
                    return;
                }
                mUploadStrategy = strategy;
                mUploadStrategy.upload(mUploadList, false, new UploadCallback() {
                    @Override
                    public void onFinish(List<UploadBean> list, boolean success) {
                        if (success) {
                            L.e(TAG, "上传图片完成---------> " + success);
                            if (list != null && list.size() > 1) {
                                String thumb = list.get(0).getRemoteFileName();
                                String videos = list.get(list.size()-2).getRemoteFileName();
                                String video_thumb = list.get(list.size()-1).getRemoteFileName();
                                StringBuilder sb = new StringBuilder();
                                if (!TextUtils.isEmpty(list.get(0).getRemoteAccessUrl())) {
                                    //如果有完整链接，则认为是之前发过的图片
                                    thumb = list.get(0).getRemoteAccessUrl();
                                }
                                if (!TextUtils.isEmpty(thumb)) {
                                    thumb = getPrefixUrl(thumb);
                                }
                                for (int i = 1, size = list.size(); i < size-2; i++) {
                                    String fileName = list.get(i).getRemoteFileName();
                                    if (!TextUtils.isEmpty(list.get(i).getRemoteAccessUrl())) {
                                        //如果有完整链接，则认为是之前发过的图片
                                        fileName = list.get(i).getRemoteAccessUrl();
                                    }
                                    if (!TextUtils.isEmpty(fileName)) {
                                        fileName = getPrefixUrl(fileName);
                                        sb.append(fileName);
                                        sb.append(",");
                                    }
                                }
                                if (!TextUtils.isEmpty(list.get(list.size()-2).getRemoteAccessUrl())) {
                                    //如果有完整链接，则认为是之前发过的视频
                                     videos= list.get(list.size()-2).getRemoteAccessUrl();
                                }
                                if (!TextUtils.isEmpty(videos)) {
                                    videos = getPrefixUrl(videos);
                                }

                                if (!TextUtils.isEmpty(list.get(list.size()-1).getRemoteAccessUrl())) {
                                    //如果有完整链接，则认为是之前发过的视频
                                    video_thumb= list.get(list.size()-1).getRemoteAccessUrl();
                                }
                                if (!TextUtils.isEmpty(video_thumb)) {
                                    video_thumb = getPrefixUrl(video_thumb);
                                }

                                String photos = sb.toString();
                                if (photos.length() > 1) {
                                    photos = photos.substring(0, photos.length() - 1);
                                }
                                if (TextUtils.isEmpty(videoFormat)) {
                                    doSubmit(thumb, photos, videos, video_thumb);
                                }else{
                                    doSubmit(thumb, photos, video, video_thumb);
                                }
                            }
                        }
                    }
                });

            }
        });
    }

    // TODO: 2021-01-05 如果服务端返回 完整的连接，替换前缀 保证服务端能判断旧图片存储方式
    private String getPrefixUrl(String completeUrl) {
        if (TextUtils.isEmpty(completeUrl)) {
            return "";
        }
        if (completeUrl.contains("http://") || completeUrl.contains("https://")) {
            String tempStr = completeUrl.substring(0, completeUrl.lastIndexOf(".") + 4);
            String lastName = tempStr.substring(tempStr.lastIndexOf("/") + 1);
            if (completeUrl.contains(Constants.UPLOAD_TYPE_AWS)) {
                completeUrl = Constants.UPLOAD_TYPE_PREFIX_AWS + lastName;
            } else if (completeUrl.contains(Constants.UPLOAD_TYPE_QINIU)) {
                completeUrl = Constants.UPLOAD_TYPE_PREFIX_QINIU + lastName;
            }
            L.e(TAG, "getPrefixUrl--->tempStr-->" + tempStr + " ---fileName--->" + completeUrl);
        }
        return completeUrl;
    }

    private void doSubmit(String thumb, String photos,String video,String video_thumb) {
        OneHttpUtil.setAuthorAuth(thumb, photos, video,video_thumb, new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String[] info) {
                        if (code == 0) {
                            finish();
                        }
                        ToastUtil.show(msg);
                    }

                    @Override
                    public void onFinish() {
                        if (mLoading != null) {
                            mLoading.dismiss();
                        }
                    }
                }
        );
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (coverFile != null && videoFile != null && backList.size() != 0) {
            coverFile.delete();
            videoFile.delete();
            for (int i = 0; i < backList.size(); i++) {
                File file = backList.get(i);
                file.delete();
            }
        }
    }
}
