package com.rv.home.rv.module.ui.main.home.order;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.util.listener.TextChangedListener;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.home.rv.module.basic.dialog.PickerDialog;
import com.rv.home.rv.module.basic.presenter.PickerPresenter;
import com.rv.home.rv.module.ui.main.home.bean.ImageUploadBean;
import com.rv.home.rv.module.ui.main.home.order.adapter.EvaluationAdapter;

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;

/**
 * Created :Auser
 * Date: 2019/5/29.
 * Desc:评价
 */
public class EvaluationActivity extends BaseStatusActivity<PickerPresenter> {

    @BindView(R2.id.iv_car)
    ImageView ivCar;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_content)
    TextView tvContent;
    @BindView(R2.id.rating_serve_bar)
    RatingBar ratingServeBar;
    @BindView(R2.id.rating_driving_bar)
    RatingBar ratingDrivingBar;
    @BindView(R2.id.rating_bar)
    RatingBar ratingBar;
    @BindView(R2.id.et_evaluation_content)
    EditText etEvaluationContent;
    @BindView(R2.id.tv_count)
    TextView tvCount;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;

    private EvaluationAdapter mAdapter;
    private List<String> listImg;

    public static Intent getIntent(Context context) {
        return new Intent(context, EvaluationActivity.class);

    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {

    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(mActivity.getString(R.string.rv_to_appointment_evaluation));
        intiEt();
        listImg = new ArrayList<>();
        mAdapter = new EvaluationAdapter();
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 4));
        recyclerView.setAdapter(mAdapter);
        recyclerView.setNestedScrollingEnabled(false);
        listImg.add("");
        mAdapter.setNewData(listImg);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                int i = view.getId();
                if (i == R.id.iv_evaluation) {
                    if (TextUtils.isEmpty(mAdapter.getItem(position))) {
                        showPickerDialog();
                    }

                } else if (i == R.id.iv_delete) {
                    mAdapter.removeItem(position);

                }
            }
        });

    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPresenter.TYPE_ALBUM_CODE) {
            if (data != null && data.getData() != null && listImg != null) {

                String url = String.format("%1$s%2$s", "file://", mPresenter.getRealFilePath(data.getData()));
//                uploadImage(new File(mPresenter.getRealFilePath(data.getData())));
                mAdapter.addItem(url);
            }
            return;
        }
        if (requestCode == mPresenter.TYPE_CAMERA_CODE && listImg != null) {
            String url = String.format("%1$s%2$s", "file://", mPresenter.gerCameraStoreUrl());
//            uploadImage(new File(mPresenter.gerCameraStoreUrl()));
            mAdapter.addItem(url);
        }
    }

    @OnClick(R2.id.tv_commit)
    public void onViewClicked() {
//        getIntent().putExtra("content", "可以的");
//        setResult(RESULT_OK);
//        finish();
//        processUploadImage();

        processUploadImage();

    }

    /**
     * 初始化文本输入框
     */
    private void intiEt() {
        etEvaluationContent.addTextChangedListener(new TextChangedListener() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                tvCount.setText(String.format("%1$s%2$s", s.length(), "/200"));
            }
        });
    }

    /**
     * 显示相机弹窗
     */
    private void showPickerDialog() {

        new PickerDialog(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.btn_camera) {
                            processPicker(mPresenter.TYPE_CAMERA_CODE);
                            dismiss();

                        } else if (i == R.id.btn_album) {
                            processPicker(mPresenter.TYPE_ALBUM_CODE);
                            dismiss();

                        } else if (i == R.id.btn_cancel) {
                            dismiss();

                        }

                    }
                }, R.id.btn_camera, R.id.btn_album, R.id.btn_cancel);
            }
        }.show();
    }

    /**
     * 打开相机和相册
     *
     * @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 1001:
                                mPresenter.openCamera(false);
                                break;
                            case 1002:
                                mPresenter.openAlbum(false);
                                break;
                        }

                    }
                }
            });
        } else {
            switch (type) {
                case 1001:
                    mPresenter.openCamera(false);
                    break;
                case 1002:
                    mPresenter.openAlbum(false);
                    break;
            }
        }
    }

    private void uploadImage(File file){
        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"), file.getName());

//        // 创建 RequestBody，用于封装构建RequestBody
//        RequestBody requestFile =
//                RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        MultipartBody.Part body =
//                MultipartBody.Part.createFormData("file", file.getName(), requestFile);
        mPresenter.getUploadFile(RvFrameConfig.VEHICLE_UPLOAD, 0, ApiConfig.HTTP_URL_FILE_UPLOAD, ImageUploadBean.class, description, body, true);
    }



    /**
     *
     */
    private void processUploadImage(){


        Map<String,RequestBody> map=new LinkedHashMap<>();
        for(String url:mAdapter.getData()){
            if(TextUtils.isEmpty(url)){
                continue;
            }
            url=url.substring(7,url.length());
            File file=new File(url);
            map.put(file.getName(),getPart(file));
        }
        uploadImages(map);
    }

    private void uploadImages(Map<String,RequestBody> map){
        RequestBody description =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), "flie");
        mPresenter.getUploadFiles(RvFrameConfig.VEHICLE_UPLOAD, 0, ApiConfig.HTTP_URL_FILE_UPLOADS, BaseBean.class,description, map, true);
    }



    private RequestBody getPart(File file){
        return   RequestBody.create(MediaType.parse("application/otcet-stream"), file);
    }
}
