package com.xxfc.discovery.other;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

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.tools.android.IntentUtil;
import com.frame.base.bus.Observer;
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.browse.ActivityImageBrowseUrl;
import com.ruiwenliu.wrapper.browse.ActivityImageBrowseUrl2;
import com.ruiwenliu.wrapper.util.LocationManager;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.ButtonPromptDialog;
import com.rv.component.utils.DateUtils;
import com.rv.component.utils.Inc;
import com.xxfc.discovery.R;
import com.xxfc.discovery.R2;
import com.xxfc.discovery.adapter.DiscoveryPostPatAdapter;
import com.xxfc.discovery.api.DiscoveryApi;
import com.xxfc.discovery.bean.DiscoveryIMTokenBean;
import com.xxfc.discovery.bean.DiscoveryUploadImageBean;
import com.xxfc.discovery.bean.ImageSources;
import com.xxfc.discovery.event.PostPatEvent;
import com.xxfc.discovery.presenter.DiscoveryPresenter;
import com.xxfc.discovery.widget.MyCallBack;
import com.xxfc.discovery.widget.OnRecyclerItemClickListener;
import com.xxfc.imcamera.activity.EasyCameraActivity;
import com.xxfc.imcamera.event.MessageEventGpu;
import com.xxfc.imcamera.photopicker.PhotoPickerActivity;
import com.xxfc.imcamera.photopicker.SelectModel;
import com.xxfc.imcamera.photopicker.intent.PhotoPickerIntent;
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.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import pub.devrel.easypermissions.AppSettingsDialog;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 发布拍拍
 */
@Route(path = Constance.ACTIVITY_URL_POSTPAT)
public class PostPatActivity extends BaseStatusActivity<DiscoveryPresenter> {

    @BindView(R2.id.et_content)
    EditText etContent;
    @BindView(R2.id.tv_pat_address)
    TextView tvPatAddress;
    @BindView(R2.id.ll_item_select_address)
    LinearLayout llItemSelectAddress;
    @BindView(R2.id.tv_pat_ok)
    TextView tvPatOk;
    @BindView(R2.id.rv_icon)
    RecyclerView rvIcon;
    @BindView(R2.id.iv_item_delete)
    ImageView ivItemDelete;
    @BindView(R2.id.tv_delete)
    TextView tvDelete;
    @BindView(R2.id.iv_trash_can)
    ImageView ivTrashCan;
    @BindView(R2.id.ll_item_delete)
    LinearLayout llItemDelete;

    private static final int REQUEST_CODE_CAPTURE_PHOTO = 1;  // 拍照
    private static final int REQUEST_CODE_PICK_PHOTO = 2;     // 图库


    private DiscoveryPostPatAdapter mAdapter;
    private ArrayList<String> mPhotoList;
    private ArrayList<String> dragImages;//压缩长宽后图片
    // 拍照和图库，获得图片的Uri
    private Uri mNewPhotoUri;

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

    private String name;
    private ItemTouchHelper itemTouchHelper;

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("发布拍拍");
        initRxbus();
        permissionProcess();
        mPhotoList = new ArrayList<>();
        dragImages = new ArrayList<>();
        //添加按钮图片资源
        String plusPath = getString(R.string.glide_plus_icon_string) + getPackageName() + "/drawable/" + R.drawable.icon_circle_image;
        mPhotoList.add(plusPath);

        mAdapter = new DiscoveryPostPatAdapter(mActivity, mPhotoList);
        rvIcon.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        rvIcon.setAdapter(mAdapter);
        refreshLayout();

        MyCallBack myCallBack = new MyCallBack(mActivity, mAdapter, mPhotoList, mPhotoList);
        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(rvIcon);//绑定RecyclerView


        //事件监听
        rvIcon.addOnItemTouchListener(new OnRecyclerItemClickListener(rvIcon) {

            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                if (mPhotoList.get(vh.getAdapterPosition()).contains(getString(R.string.glide_plus_icon_string))) {//打开相册
                    showSelectPictureDialog();
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt(ActivityImageBrowseUrl.KEY_BACKGROUND, R.color.colorPrimary);
                    bundle.putInt(ActivityImageBrowseUrl.KEY_SELECTPOSITION, vh.getAdapterPosition());
                    bundle.putStringArrayList(ActivityImageBrowseUrl.KEY_IMAGE, mPhotoList);
                    IntentUtil.startActivity(mActivity, ActivityImageBrowseUrl.class, bundle);
                }
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                //如果item不是最后一个，则执行拖拽
                if (vh.getLayoutPosition() != mPhotoList.size() - 1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });


        myCallBack.setDragListener(new MyCallBack.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    llItemDelete.setBackgroundResource(R.color.gray_ffcc0000);
                    tvDelete.setText("松手即可删除");
                    ivTrashCan.setImageResource(R.drawable.icon_discover_pat_trash_can2);
                } else {
                    tvDelete.setText("拖动到此处删除");
                    llItemDelete.setBackgroundResource(R.color.gray_ffff4444);
                    ivTrashCan.setImageResource(R.drawable.icon_discover_pat_trash_can);
                }
            }

            @Override
            public void dragState(boolean start) {
                if (start) {
                    llItemDelete.setVisibility(View.VISIBLE);
                } else {
                    llItemDelete.setVisibility(View.GONE);
                }
            }

            @Override
            public void clearView() {
                refreshLayout();
            }
        });

    }

    /**
     * 刷新地理位置等布局
     */
    private void refreshLayout() {
        //判断提醒谁布局看是否需要下移
        int row = mAdapter.getItemCount() / 3;
        row = 0 == mAdapter.getItemCount() % 3 ? row : row + 1;
        row = 4 == row ? 3 : row;//row最多为三行
        int marginTop = (getResources().getDimensionPixelSize(R.dimen.size_10)
                + getResources().getDimensionPixelSize(R.dimen.size_100))
                * row
                + getResources().getDimensionPixelSize(R.dimen.size_100)
                + 10;
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) llItemSelectAddress.getLayoutParams();
        params.setMargins(getResources().getDimensionPixelSize(R.dimen.size_15), marginTop, 0, 0);
        llItemSelectAddress.setLayoutParams(params);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                DiscoveryUploadImageBean bean = (DiscoveryUploadImageBean) result;
                upData(bean.getData());
                break;
            case 1:
                DiscoveryIMTokenBean intokenBean = (DiscoveryIMTokenBean) result;
                setData(intokenBean);
                break;
            case 2:
                RxBus.post(new PostPatEvent());
                showToast("发布成功！");
                finish();
                break;
        }
    }


    private void setData(DiscoveryIMTokenBean intokenBean) {
        if (intokenBean == null) {
            return;
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("access_token", intokenBean.getData());
        map.put("type", "2");
        map.put("flag", "3");
        map.put("visible", "1");
        map.put("text", etContent.getText().toString());
        map.put("images", JSON.toJSONString(sourcesList));

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

    private void upData(List<DiscoveryUploadImageBean.DataBean> data) {
        sourcesList = new ArrayList<>();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                ImageSources sources = new ImageSources();
                sources.setoFileName(data.get(i).getFileName());
                sources.setoUrl(data.get(i).getImgUrl());
                sources.settUrl(data.get(i).getImgUrl());
                sourcesList.add(sources);
            }
        }

        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);
        }
    }


    @OnClick({R2.id.ll_item_select_address, R2.id.tv_pat_ok, R2.id.iv_item_delete})
    public void onViewClicked(View view) {
        int id = view.getId();
        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, 210);
        } else if (id == R.id.tv_pat_ok) {
            if (TextUtils.isEmpty(etContent.getText().toString())) {
                showToast("亲，请说点什么吧！");
                return;
            }

            if (mPhotoList.size() <= 1) {
                showToast("请选择需要上传的图片！");
                return;
            }

            if (mPhotoList.size() <= 0) {
                // 发布文字
//                sendShuoshuo();
            } else {
                // 发布图片+文字
                upIcon();
            }
        } else if (id == R.id.iv_item_delete) {
            tvPatAddress.setText("");
            latLatitude = 0;
            lonLongitude = 0;
            address = "";
            ivItemDelete.setVisibility(View.GONE);
        }
    }

    private void upIcon() {
        ArrayList<Imag> imags = new ArrayList<>();
        for (int i = 0; i < mPhotoList.size(); i++) {
            if (mPhotoList.get(i).contains(getString(R.string.glide_plus_icon_string))) {//说明是添加图片按钮
                continue;
            }
            File file = new File(mPhotoList.get(i));
            Imag imag = new Imag();
            imag.setFileName(file.getName());
            imag.setImgFile(Inc.imageToBase64(mPhotoList.get(i)));
            imags.add(imag);
        }
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_UPLOAD, 0, DiscoveryApi.HTTP_URL_FILE_UPLOADS, DiscoveryUploadImageBean.class, new Image("app", imags), true);
    }


    private void showSelectPictureDialog() {
        new ButtonPromptDialog(mActivity) {
            @Override
            public void helper(ViewHolder helper) {
                super.helper(helper);
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.tv1) {
                            processPicker(1);
                            dismiss();
                        } else if (i == R.id.tv2) {
                            processPicker(2);
                            dismiss();
                        }

                    }
                }, R.id.tv1, R.id.tv2);
            }
        }.show();
    }

    // 拍照
    private void takePhoto() {
        Intent intent = new Intent(this, EasyCameraActivity.class);
        startActivity(intent);
    }

    private void initRxbus() {
        RxBus.tObservable(MessageEventGpu.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<MessageEventGpu>(disposable) {
                    @Override
                    public void onNext(MessageEventGpu event) {
                        photograph(new File(event.getEvent()));
                    }
                });
    }

    /**
     * 相册
     * 可以多选的图片选择器
     */
    private void selectPhoto() {
        ArrayList<String> imagePaths = new ArrayList<>();
        PhotoPickerIntent intent = new PhotoPickerIntent(this);
        intent.setSelectModel(SelectModel.MULTI);
        // 是否显示拍照， 默认false
        intent.setShowCarema(false);
        // 最多选择照片数量，默认为9
        intent.setMaxTotal(10 - mPhotoList.size());
        // 已选中的照片地址， 用于回显选中状态
        intent.setSelectedPaths(imagePaths);
        // intent.setImageConfig(config);
        startActivityForResult(intent, REQUEST_CODE_PICK_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_CAPTURE_PHOTO) {
            // 拍照返回 Todo 已更换拍照方式
            if (resultCode == Activity.RESULT_OK) {
                if (mNewPhotoUri != null) {
                    photograph(new File(mNewPhotoUri.getPath()));
                } else {
                    showToast("拍照失败");
                }
            }
        } else if (requestCode == REQUEST_CODE_PICK_PHOTO) {
            // 选择图片返回
            if (resultCode == Activity.RESULT_OK) {
                if (data != null) {
                    boolean isOriginal = data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
                    album(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), isOriginal);
                } else {
                    showToast("选择失败");
                }
            }
        } else if (requestCode == 210 && 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 album(ArrayList<String> stringArrayListExtra, boolean isOriginal) {
//        if (isOriginal) {// 原图发送，不压缩
//            Log.e("zq", "原图上传，不压缩，选择原文件路径");
//            for (int i = 0; i < stringArrayListExtra.size(); i++) {
//                mPhotoList.add(stringArrayListExtra.get(i));
//                mAdapter.notifyDataSetInvalidated();
//            }
//            return;
//        }

//        List<File> fileList = new ArrayList<>();
//        for (int i = 0; i < stringArrayListExtra.size(); i++) {
//            // Luban只处理特定后缀的图片，不满足的不处理也不走回调，
//            // 只能挑出来不压缩，
//            List<String> lubanSupportFormatList = Arrays.asList("jpg", "jpeg", "png", "webp", "gif");
//            boolean support = false;
//            for (int j = 0; j < lubanSupportFormatList.size(); j++) {
//                if (stringArrayListExtra.get(i).endsWith(lubanSupportFormatList.get(j))) {
//                    support = true;
//                    break;
//                }
//            }
//            if (!support) {
//                fileList.add(new File(stringArrayListExtra.get(i)));
//                stringArrayListExtra.remove(i);
//            }
//        }
//
//        if (fileList.size() > 0) {
//            for (File file : fileList) {// 不压缩的部分，直接发送
//                mPhotoList.add(file.getPath());
//                mAdapter.notifyDataSetInvalidated();
//            }
//        }

        Luban.with(this)
                .load(stringArrayListExtra)
                .ignoreBy(70)// 原图小于70kb 不压缩
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        Log.e("zq", "压缩成功，压缩后图片位置:" + file.getPath() + "压缩后图片大小:" + file.length() / 1024 + "KB");
                        mPhotoList.add(mPhotoList.size() - 1, file.getPath());
                        mAdapter.notifyDataSetChanged();
                        refreshLayout();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();// 启动压缩
    }


    // 单张图片压缩 拍照
    private void photograph(final File file) {
        Log.e("zq", "压缩前图片路径:" + file.getPath() + "压缩前图片大小:" + file.length() / 1024 + "KB");
        // 拍照出来的图片Luban一定支持，
        Luban.with(this)
                .load(file)
                .ignoreBy(70)     // 原图小于70kb 不压缩
                // .putGear(2)     // 设定压缩档次，默认三挡
                // .setTargetDir() // 指定压缩后的图片路径
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        Log.e("zq", "开始压缩");
                    }

                    @Override
                    public void onSuccess(File file) {
                        Log.e("zq", "压缩成功，压缩后图片位置:" + file.getPath() + "压缩后图片大小:" + file.length() / 1024 + "KB");
                        mPhotoList.add(mPhotoList.size() - 1, file.getPath());
                        mAdapter.notifyDataSetChanged();
                        refreshLayout();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("zq", "压缩失败,原图上传");
                        mPhotoList.add(mPhotoList.size() - 1, file.getPath());
                        mAdapter.notifyDataSetChanged();
                        refreshLayout();
                    }
                }).launch();// 启动压缩
    }


    /**
     * 打开相机和相册
     *
     * @param type 1、相机2、相册
     */
    private void processPicker(final int type) {
        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission(mActivity).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA).subscribe(new Consumer<Boolean>() {
                @Override
                public void accept(Boolean aBoolean) throws Exception {
                    if (aBoolean == true) {
                        switch (type) {
                            case 1:
                                takePhoto();
                                break;
                            case 2:
                                selectPhoto();
                                break;
                        }
                    } else {
                        new AppSettingsDialog.Builder(PostPatActivity.this).
                                setTitle("需要获取相机权限、存储权限")
                                .setRationale("如果没有此权限，此应用程序可能无法正常工作,是否打开设置修改该应用权限")
                                .build().show();
                    }
                }
            });
        } else {
            switch (type) {
                case 1:
                    takePhoto();
                    break;
                case 2:
                    selectPhoto();
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    /**
     * 定位权限处理
     */
    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(PostPatActivity.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();
            }
        });
    }


    private class Image {
        private String prefix;
        private List<Imag> imgs;

        public Image(String prefix, List<Imag> imgs) {
            this.prefix = prefix;
            this.imgs = imgs;
        }

        public String getPrefix() {
            return prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public List<Imag> getImgs() {
            return imgs;
        }

        public void setImgs(List<Imag> imgs) {
            this.imgs = imgs;
        }

    }

    private class Imag {
        private String imgFile;
        private String fileName;

        public String getImgFile() {
            return imgFile;
        }

        public void setImgFile(String imgFile) {
            this.imgFile = imgFile;
        }

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }
    }
}
