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

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.rv.home.R;
import com.rv.home.R2;
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.ApiConfig;
import com.rv.component.dialog.PickerDialog;
import com.ruiwenliu.wrapper.base.presenter.PickerPresenter;
import com.rv.home.rv.module.ui.main.home.bean.DrivingListBean;
import com.rv.home.rv.module.ui.main.home.bean.ImageUploadBean;
import com.yuyife.okgo.OkGoUtil;

import java.io.File;
import java.io.Serializable;
import java.util.LinkedHashMap;
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 top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class DrivingUploadActivity extends BaseStatusActivity<PickerPresenter> {


    @BindView(R2.id.et_name)
    EditText etName;
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.et_id_card)
    EditText etIdCard;
    @BindView(R2.id.iv_card)
    ImageView ivCard;
    @BindView(R2.id.iv_card_copy)
    ImageView ivCardCopy;
    @BindView(R2.id.tv_delete)
    TextView tvDelete;
    @BindView(R2.id.ll_card)
    LinearLayout llCard;
    @BindView(R2.id.ll_card_copy)
    LinearLayout llCardCopy;
    private int drivingId;
    private int cardType;
    private String strCard;
    private String strCardCopy;

    public static Intent getIntent(Context context, DrivingListBean.DataBeanX.DataBean bean) {
        return new Intent(context, DrivingUploadActivity.class).putExtra("bean", (Serializable) bean);
    }

    ;

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        DrivingListBean.DataBeanX.DataBean dataBean = (DrivingListBean.DataBeanX.DataBean) intent.getSerializableExtra("bean");
        if (dataBean != null) {
            drivingId = dataBean.getId();
            etName.setText(dataBean.getName());
            etIdCard.setText(dataBean.getIdCard());
            etPhone.setText(dataBean.getPhone());
            strCard = dataBean.getImg();
            strCardCopy = dataBean.getFimg();
            GlideManager.getInstance(mActivity).loadImage(dataBean.getImg(), ivCard);
            GlideManager.getInstance(mActivity).loadImage(dataBean.getFimg(), ivCardCopy);
            tvDelete.setVisibility(View.VISIBLE);
            llCardCopy.setVisibility(View.GONE);
            llCard.setVisibility(View.GONE);
            titleView.setTitle(mActivity.getString(R.string.rv_edit_driving_title));
        } else {
            tvDelete.setVisibility(View.GONE);
            titleView.setTitle(mActivity.getString(R.string.rv_add_driving_title));
        }

        titleView.setText(R.id.tv_title_right, mActivity.getString(R.string.rv_save));
        titleView.setChildClickListener(R.id.tv_title_right, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(getDrivingName())) {
                    showToast(mActivity.getString(R.string.rv_name_hint));
                    return;
                }
                if (TextUtils.isEmpty(getDrivingPhone())) {
                    showToast(mActivity.getString(R.string.rv_phone_hint));
                    return;
                }

                if (getDrivingPhone().length() != 11) {
                    showToast("请输入正确手机号");
                    return;
                }

                if (TextUtils.isEmpty(getDrivingIdCard())) {
                    showToast(mActivity.getString(R.string.rv_id_card_hint));
                    return;
                }

                if (getDrivingIdCard().length() != 18) {
                    showToast("请输入正确身份证号");
                    return;
                }

                if (TextUtils.isEmpty(strCard)) {
                    showToast(mActivity.getString(R.string.rv_upload_driving_toast));
                    return;
                }
//                if (TextUtils.isEmpty(strCardCopy)) {
//                    showToast(mActivity.getString(R.string.rv_upload_driving_copy_toast));
//                    return;
//                }

                processDriving();
            }
        });
    }

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

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                ImageUploadBean bean = (ImageUploadBean) result;
                if (cardType == 0) {
                    strCard = bean.getData();
                } else {
                    strCardCopy = bean.getData();
                }
                break;
            case 1:
            case 2:
                setResult(RESULT_OK);
                finish();
                break;
        }
    }


    @OnClick({R2.id.rl_card, R2.id.rl_card_copy, R2.id.tv_delete})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.rl_card) {
            showPickerDialog(0);

        } else if (i == R.id.rl_card_copy) {
            showPickerDialog(1);

        } else if (i == R.id.tv_delete) {
            deleteDriving(drivingId);

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == mPresenter.TYPE_ALBUM_CODE && resultCode == RESULT_OK) {
            if (data != null && data.getData() != null) {
                llCard.setVisibility(View.GONE);
                GlideManager.getInstance(mActivity).loadImage(mPresenter.getUriUrl(data.getData()), cardType == 0 ? ivCard : ivCardCopy);
                uploadFile(new File(mPresenter.getRealFilePath(data.getData())), "album");
            }
            return;
        }
        if (requestCode == mPresenter.TYPE_CAMERA_CODE && resultCode == RESULT_OK) {
            if (!TextUtils.isEmpty(mPresenter.gerCameraStoreUrl())) {
                llCard.setVisibility(View.GONE);
                String url = String.format("%1$s%2$s", "file://", mPresenter.gerCameraStoreUrl());
                GlideManager.getInstance(mActivity).loadImage(url, cardType == 0 ? ivCard : ivCardCopy);
                uploadFile(new File(mPresenter.gerCameraStoreUrl()), "camera");
            }
        }

    }


    /**
     * 显示相机弹窗
     */
    private void showPickerDialog(int type) {
        cardType = type;
        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.READ_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;
            }
        }
    }

    /**
     * 上传文件
     *
     * @param files
     */
    private void uploadFile(File files, final String fileName) {

        Luban.with(this)
                .load(files)                                   // 传人要压缩的图片列表
                .ignoreBy(100)                                  // 忽略不压缩图片的大小
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(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"), fileName);

//        // 创建 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);
                    }

                    @Override
                    public void onError(Throwable e) {

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


    }


    /**
     * 编辑或修改驾驶证信息
     */
    private void processDriving() {
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_CAR_POST, 1,
                ApiConfig.HTTP_URL_EDIT_DRIVING, BaseBean.class,
                new addDriving(drivingId == 0 ? null : drivingId, getDrivingPhone(), getDrivingIdCard(), getDrivingName(), strCard, strCardCopy),
                getHeadMap(), true);
    }


    /**
     * 删除驾驶员
     */
    private void deleteDriving(int id) {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("id", id);
        mPresenter.getData(RvFrameConfig.VEHICLE_CAR_POST, 2, ApiConfig.HTTP_URL_DELETE_DRIVING, BaseBean.class, map, getHeadMap(), true);
    }


    /**
     * 获取驾驶员名字
     *
     * @return
     */
    private String getDrivingName() {
        return etName.getText().toString().trim();
    }

    /**
     * 获取驾驶员手机号
     *
     * @return
     */
    private String getDrivingPhone() {
        return etPhone.getText().toString().trim();
    }

    /**
     * 获取驾驶员身份证号
     *
     * @return
     */
    private String getDrivingIdCard() {
        return etIdCard.getText().toString().trim();
    }


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

    private class addDriving {
        private Integer id;
        private String phone;
        private String idCard;
        private String name;
        private String img;
        private String fimg;

        public addDriving(Integer id, String phone, String idCard, String name, String img, String fimg) {
            this.id = id;
            this.phone = phone;
            this.idCard = idCard;
            this.name = name;
            this.img = img;
            this.fimg = fimg;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getIdCard() {
            return idCard;
        }

        public void setIdCard(String idCard) {
            this.idCard = idCard;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getImg() {
            return img;
        }

        public void setImg(String img) {
            this.img = img;
        }

        public String getFimg() {
            return fimg;
        }

        public void setFimg(String fimg) {
            this.fimg = fimg;
        }
    }

}
