package com.xxfc.discovery.other;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.baidu.mapapi.model.LatLng;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.http.ProgressRequestBody;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.ProgressBarDialog;
import com.rv.component.utils.DateUtils;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryIMTokenBean;
import com.xxfc.discovery.bean.ImageSources;
import com.xxfc.discovery.bean.UpdateVideoFile;
import com.xxrv.video.bean.circle.VideoFile;
import com.xxfc.discovery.event.PostVideoEvent;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.xxrv.video.activity.SelectVideoActivity;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.AppSettingsDialog;

/**
 * 发短视频
 */
@Route(path = Constance.ACTIVITY_URL_SENDVIDEO)
public class SendVideoActivity extends BaseStatusActivity<DiscoveryPresenter> {

    @BindView(R2.id.et_video_content)
    EditText etVideoContent;
    @BindView(R2.id.iv_video_hint)
    ImageView ivVideoHint;
    @BindView(R2.id.tv_video_address)
    TextView tvPatAddress;
    @BindView(R2.id.iv_item_delete)
    ImageView ivItemDelete;

    private LocationManager locationManager;
    private double latLatitude = 0;
    private double lonLongitude;
    private LatLng mLatLng;//当前城市经纬度
    private String addrStr;
    private String address;
    private String name;
    private UpdateVideoFile videoBean;
    private UpdateVideoFile imageBean;
    private ArrayList<ImageSources> sourcesList;
    private ArrayList<ImageSources> sourcesList2;

    @Autowired()
    String mVideoFilePath;
    @Autowired()
    long mTimeLen;
    @Autowired()
    String mThumbPath;
    @Autowired()
    String mCurrBgmId;


    @Override
    protected int setLayout() {
        return R.layout.activity_send_video;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("发布视频");

        GlideManager.getInstance(mActivity).loadImage(mThumbPath, ivVideoHint);
        permissionProcess();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                videoBean = (UpdateVideoFile) result;
                uploadFile2(new File(mThumbPath), "Image");
                break;
            case 3:
                imageBean = (UpdateVideoFile) result;
                upData();
                break;
            case 1:
                DiscoveryIMTokenBean intokenBean = (DiscoveryIMTokenBean) result;
                setData(intokenBean);
                break;
            case 2:
                RxBus.post(new PostVideoEvent());
                showToast("发布成功！");
                finish();
                break;
        }
    }

    private void setData(DiscoveryIMTokenBean intokenBean) {
        if (intokenBean == null) {
            return;
        }

        if (videoBean == null) {
            showToast("请选择视频");
            return;
        }

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("access_token", intokenBean.getData());
        map.put("type", "4");
        map.put("flag", "3");
        map.put("visible", "1");
        map.put("text", etVideoContent.getText().toString());

        sourcesList = new ArrayList<>();
        ImageSources sources = new ImageSources();
        sources.setoUrl(videoBean.getData());
        sources.settUrl(videoBean.getData());
        sourcesList.add(sources);
        map.put("videos", JSON.toJSONString(sourcesList));

        sourcesList2 = new ArrayList<>();
        ImageSources sources2 = new ImageSources();
        sources2.setoUrl(imageBean.getData());
        sources2.settUrl(imageBean.getData());
        sourcesList2.add(sources2);
        map.put("images", JSON.toJSONString(sourcesList2));

        if (!TextUtils.isEmpty(address)) {
            addrStr = address;
            // 纬度
            map.put("latitude", String.valueOf(latLatitude));
            // 经度
            map.put("longitude", String.valueOf(lonLongitude));
            // 位置
            map.put("location", address);
        }
        if (!TextUtil.isEmpty(mCurrBgmId)) {
            map.put("musicId", mCurrBgmId);
        }
        map.put("cityId", "0");
        map.put("source", "2");
        map.put("time", DateUtils.getCurTimeMillis());
        mPresenter.postData(2, DiscoveryApi.DISCOVERY_MSG_ADD, BaseBean.class, map, true);
    }


    @OnClick({R2.id.rl_item_select_video, R2.id.ll_item_select_address, R2.id.tv_video_ok, R2.id.iv_item_delete})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_item_select_video) {
            startActivityForResult(SelectVideoActivity.getIntent(mActivity), 109);

        } else if (id == R.id.ll_item_select_address) {
            ARouter.getInstance()
                    .build(Constance.ACTIVITY_URL_MAPLOCATION)
                    .withDouble("latLatitude", latLatitude)
                    .withDouble("lonLongitude", lonLongitude)
                    .withString("name", name)
                    .withString("addrStr", addrStr)
                    .navigation(this, 211);
        } else if (id == R.id.tv_video_ok) {

            uploadFile(new File(mVideoFilePath), "video");
        } else if (id == R.id.iv_item_delete) {
            tvPatAddress.setText("");
            latLatitude = 0;
            lonLongitude = 0;
            address = "";
            ivItemDelete.setVisibility(View.GONE);
        }
    }

    private void upData() {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.postData(RvFrameConfig.HOST, 1, DiscoveryApi.DISCOVERY_IM_LOGIN, DiscoveryIMTokenBean.class, headMap, headMap, true);
        }
    }


    /**
     * 上传文件
     *
     * @param file
     */
    private void uploadFile(File file, String fileName) {
//        RequestBody requestFile =
//                RequestBody.create(MediaType.parse("application/otcet-stream"), file);

        ProgressBarDialog progressBarDialog = new ProgressBarDialog(mActivity);
        //设置点击屏幕不消失
        progressBarDialog.setCanceledOnTouchOutside(false);
        //设置点击返回键不消失
        progressBarDialog.setCancelable(false);
        progressBarDialog.show();

        //实现上传进度监听
        ProgressRequestBody requestFile = new ProgressRequestBody(file, "video/*", new ProgressRequestBody.UploadCallbacks() {
            @Override
            public void onProgressUpdate(int percentage) {
                Log.i("SendVideoActivity", "run:++ " + percentage);
                progressBarDialog.setContent(percentage);
                if (percentage == 100 && progressBarDialog != null) {
                    progressBarDialog.dismiss();
                }
            }
        });

        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RequestBody description =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), fileName);

        mPresenter.getUploadFile(RvFrameConfig.VEHICLE_UPLOAD, 0, DiscoveryApi.HTTP_URL_FILE_UPLOAD_VIDEO, UpdateVideoFile.class, description, body, false);
    }


    /**
     * 上传文件
     *
     * @param file
     */
    private void uploadFile2(File file, String fileName) {

        RequestBody requestFile =
                RequestBody.create(MediaType.parse("application/otcet-stream"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        RequestBody description =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), fileName);
        mPresenter.getUploadFile(RvFrameConfig.VEHICLE_UPLOAD, 3, DiscoveryApi.HTTP_URL_FILE_UPLOAD, UpdateVideoFile.class, description, body, false);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 109 && resultCode == 201) {
            VideoFile videofile = (VideoFile) data.getSerializableExtra("videofile");

//            uploadFile(new File(videofile.getFilePath()), "video");
        } else if (requestCode == 211 && resultCode == Activity.RESULT_OK) {
            ivItemDelete.setVisibility(View.VISIBLE);
            latLatitude = data.getDoubleExtra("latitude", 0);
            lonLongitude = data.getDoubleExtra("longitude", 0);
            address = data.getStringExtra("location");
            tvPatAddress.setText(data.getStringExtra("location"));
        }
    }


    /**
     * 定位权限处理
     */
    private void permissionProcess() {

        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(this).request(
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION
            ).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        initGps();
                    } else {
                        new AppSettingsDialog.Builder(SendVideoActivity.this).
                                setTitle("需要定位权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                }
            });
        } else {
            initGps();
        }
    }

    /**
     * 初始化定位
     */
    public void initGps() {
        locationManager = new LocationManager(this);
        locationManager.getLocationDetail(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation location) {
                //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
                //以下只列举部分获取经纬度相关（常用）的结果信息
                //更多结果信息获取说明，请参照类参考中BDLocation类中的说明

                //获取定位精度，默认值为0.0f
                float radius = location.getRadius();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准
                String coorType = location.getCoorType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
                int errorCode = location.getLocType();
//                setGpsContent("count=:",String.valueOf(count));
//                setGpsContent("latitude:",String.valueOf(location.getLatitude()));
//                setGpsContent("longitude:",String.valueOf(location.getLongitude()));
//                setGpsContent("城市:",location.getCity());
//                setGpsContent("街道:",location.getAddrStr());
//                setGpsContent("当前位置:",location.getLocationDescribe());
                addrStr = location.getAddrStr();
                latLatitude = location.getLatitude();
                lonLongitude = location.getLongitude();
                List<Poi> poiList = location.getPoiList();
                if (poiList != null && poiList.size() > 0) {
                    name = poiList.get(0).getName();
                }
                mLatLng = new LatLng(location.getLatitude(), location.getLongitude());
                locationManager.stopLocation();
            }
        });
    }

}
