package com.xxfc.discovery.other;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
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.Address;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.Poi;
import com.baidu.mapapi.model.LatLng;
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.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.control.MyGridView;
import com.rv.component.control.SquareCenterImageView;
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.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.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.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
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.ll_item_select_icon)
    LinearLayout llItemSelectIcon;
    @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)
    MyGridView rvIcon;

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

    private GridViewAdapter mAdapter;
    private ArrayList<String> mPhotoList;
    // 拍照和图库，获得图片的Uri
    private Uri mNewPhotoUri;

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

    private  String name;

    @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<>();
        mAdapter = new GridViewAdapter();
        rvIcon.setAdapter(mAdapter);

        rvIcon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int viewType = mAdapter.getItemViewType(position);
                if (viewType == 1) {
                    showSelectPictureDialog();
                } else {
//                    showPictureActionDialog(position);
                }
            }
        });
    }


    @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());
                 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(addrStr)) {
            // 纬度
            map.put("latitude", String.valueOf(latLatitude));
            // 经度
            map.put("longitude", String.valueOf(lonLongitude));
            // 位置
            map.put("location", addrStr);
        }
        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_icon, R2.id.ll_item_select_address, R2.id.tv_pat_ok})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_select_icon) {

        } 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,210);
        } else if (id == R.id.tv_pat_ok) {
            if (TextUtils.isEmpty(etContent.getText().toString())){
                showToast("亲，请说点什么吧！");
                return;
            }

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

            if (mPhotoList.size() <= 0) {
                // 发布文字
//                sendShuoshuo();
            } else {
                // 发布图片+文字
                upIcon();
            }
        }
    }

    private void upIcon() {
        ArrayList<Imag> imags = new ArrayList<>();
        for (int i = 0; i <mPhotoList.size() ; i++) {
            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() {
        String[] items = new String[]{"拍照", "相片"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            processPicker(1);
                        } else {
                            processPicker(2);
                        }
                        dialog.dismiss();
                    }
                });
        builder.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(9 - 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){
            latLatitude = data.getDoubleExtra("latitude",0);
            lonLongitude = data.getDoubleExtra("longitude",0);
            addrStr = 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(100)// 原图小于100kb 不压缩
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        mPhotoList.add(file.getPath());
                        mAdapter.notifyDataSetInvalidated();
                    }

                    @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(100)     // 原图小于100kb 不压缩
                // .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(file.getPath());
                        mAdapter.notifyDataSetInvalidated();
                    }

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



    /**
     * 打开相机和相册
     *
     * @param type 1、相机2、相册
     */
    private void processPicker(final int type) {
        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            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 {
            switch (type) {
                case 1:
                    takePhoto();
                    break;
                case 2:
                    selectPhoto();
                    break;
            }
        }
    }



    private class GridViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mPhotoList.size() >= 9) {
                return 9;
            }
            return mPhotoList.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        @Override
        public int getItemViewType(int position) {
            if (mPhotoList.size() == 0) {
                // View Type 1代表添加更多的视图
                return 1;
            } else if (mPhotoList.size() < 9) {
                if (position < mPhotoList.size()) {
                    // View Type 0代表普通的ImageView视图
                    return 0;
                } else {
                    return 1;
                }
            } else {
                return 0;
            }
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(PostPatActivity.this).inflate(R.layout.rv_item_discovery_post_pat, parent, false);
            SquareCenterImageView iv = (SquareCenterImageView) view.findViewById(R.id.iv_icon);
            if (getItemViewType(position) == 0) { // 普通的视图
                GlideManager.getInstance(mActivity).loadImage(mPhotoList.get(position), iv);
            } else {
                iv.setImageResource(R.drawable.icon_circle_image);
            }
            return view;
        }
    }


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

        /**
         * 6.0以上手机做权限处理
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            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 {
                        finish();
                    }
                }
            });
        } 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;
        }
    }
}
