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.TextView;

import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.frame.base.view.StarBar;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.util.listener.TextChangedListener;
import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.ruiwenliu.wrapper.weight.TitleView;
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.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 com.rv.home.rv.module.ui.main.home.order.bean.OrderListBean;
import com.rv.home.rv.module.ui.main.home.order.bean.ScoreBean;
import com.yuyife.okgo.OkGoUtil;

import org.w3c.dom.Text;

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 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.et_evaluation_content)
    EditText etEvaluationContent;
    @BindView(R2.id.tv_count)
    TextView tvCount;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.starbar1)
    StarBar starbar1;
    @BindView(R2.id.starbar2)
    StarBar starbar2;
    @BindView(R2.id.starbar3)
    StarBar starbar3;
    @BindView(R2.id.tv_hint1)
    TextView tvHint1;
    @BindView(R2.id.tv_hint2)
    TextView tvHint2;
    @BindView(R2.id.tv_hint3)
    TextView tvHint3;

    private EvaluationAdapter mAdapter;
    private List<String> listImg;
    private OrderListBean.DataBeanX.DataBean dataBean;
    private String mark1;
    private String mark2;
    private String mark3;

    public static Intent getIntent(Context context, OrderListBean.DataBeanX.DataBean dataBean) {
        return new Intent(context, EvaluationActivity.class)
                .putExtra("dataBean", dataBean);

    }

    @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));
        dataBean = (OrderListBean.DataBeanX.DataBean) intent.getSerializableExtra("dataBean");

        if (dataBean != null) {
            tvName.setText(dataBean.getName());
            GlideManager.getInstance(mActivity).loadImage(dataBean.getIcon(), ivCar);
        }


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

                }
            }
        });


        starbar1.setIntegerMark(true);
        starbar1.setOnStarChangeListener(new StarBar.OnStarChangeListener() {
            @Override
            public void onStarChange(float mark) {
                mark1 = String.valueOf((int)(mark * 10));
                setHint(mark, tvHint1);
            }
        });

        starbar2.setIntegerMark(true);
        starbar2.setOnStarChangeListener(new StarBar.OnStarChangeListener() {
            @Override
            public void onStarChange(float mark) {
                mark2 = String.valueOf((int)(mark * 10));
                setHint(mark, tvHint2);
            }
        });

        starbar3.setIntegerMark(true);
        starbar3.setOnStarChangeListener(new StarBar.OnStarChangeListener() {
            @Override
            public void onStarChange(float mark) {
                mark3 = String.valueOf((int)(mark * 10));
                setHint(mark, tvHint3);
            }
        });
    }

    private void setHint(float mark, TextView textView) {
        if (1 == mark) {
            textView.setText("非常差");
        } else if (2 == mark) {
            textView.setText("差");
        } else if (3 == mark) {
            textView.setText("一般");
        } else if (4 == mark) {
            textView.setText("好");
        } else if (5 == mark) {
            textView.setText("非常好");
        }
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                showToast("评价成功！");
                finish();
                break;
        }
    }


    @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(View view) {
        int id = view.getId();
        if (id == R.id.tv_commit) {
            onCommit();
        }
//        getIntent().putExtra("content", "可以的");
//        setResult(RESULT_OK);
//        finish();
//        processUploadImage();
    }

    private void onCommit() {
        if (TextUtil.isEmpty(mark1)) {
            showToast("服务态度评分不能为空！");
            return;
        }

        if (TextUtil.isEmpty(mark2)) {
            showToast("司机态度评分不能为空！");
            return;
        }

        if (TextUtil.isEmpty(mark3)) {
            showToast("体验感受评分不能为空！");
            return;
        }

        ArrayList<ScoreBean> scores = new ArrayList<>();
        ScoreBean scoreBean = new ScoreBean();
        scoreBean.setScore(mark1);
        scoreBean.setVehicleScoreType("SERVICE");
        scores.add(scoreBean);

        ScoreBean scoreBean2 = new ScoreBean();
        scoreBean2.setScore(mark2);
        scoreBean2.setVehicleScoreType("DRIVER");
        scores.add(scoreBean2);

        ScoreBean scoreBean3 = new ScoreBean();
        scoreBean3.setScore(mark3);
        scoreBean3.setVehicleScoreType("EXPERIENCE");
        scores.add(scoreBean3);
        String id = null;
        if (1==dataBean.getType()){
            OrderListBean.DataBeanX.DataBean.OrderRentVehicleDetail orderRentVehicleDetail = dataBean.getOrderRentVehicleDetail();
            if (orderRentVehicleDetail!=null){
                id = String.valueOf(orderRentVehicleDetail.getId());
            }
        }else if (2 == dataBean.getType()){
            OrderListBean.DataBeanX.DataBean.OrderTourDetail orderTourDetail = dataBean.getOrderTourDetail();
            if (orderTourDetail!=null){
                id = orderTourDetail.getId();
            }
        }

        mPresenter.postBodyData(0, ApiConfig.HTTP_URL_SCORE, BaseBean.class, new Score(id,dataBean.getId(),scores), getHeadMap(), true);
    }


    private Map<String, Object> getHeadMap() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        return headMap;
    }

    /**
     * 初始化文本输入框
     */
    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);
    }

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


    private class Score {
        private String modelId;//":23,
        private int orderId;//"
        private List<ScoreBean> scoretype;//"

        public Score(String modelId, int orderId, List<ScoreBean> scoretype) {
            this.modelId = modelId;
            this.orderId = orderId;
            this.scoretype = scoretype;
        }

        public String getModelId() {
            return modelId;
        }

        public void setModelId(String modelId) {
            this.modelId = modelId;
        }

        public int getOrderId() {
            return orderId;
        }

        public void setOrderId(int orderId) {
            this.orderId = orderId;
        }

        public List<ScoreBean> getScoretype() {
            return scoretype;
        }

        public void setScoretype(List<ScoreBean> scoretype) {
            this.scoretype = scoretype;
        }
    }
}
