package com.wisewoods.eduandroid.ui;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;

import androidx.recyclerview.widget.GridLayoutManager;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.Target;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.app.PictureAppMaster;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.entity.MediaExtraInfo;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.MediaUtils;
import com.luck.picture.lib.tools.ScreenUtils;
import com.wisewoods.base.app.UserManager;
import com.wisewoods.base.bean.BankCardBean;
import com.wisewoods.base.bean.IDCardBean;
import com.wisewoods.base.bean.NationBean;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.bean.TeacherInfo;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.utils.$;
import com.wisewoods.base.utils.GlideEngine;
import com.wisewoods.base.utils.ImgUtils;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.app.BasePhotoActivity;
import com.wisewoods.eduandroid.app.ImgManager;
import com.wisewoods.eduandroid.area.AreaView;
import com.wisewoods.eduandroid.databinding.ActivityTeacherInfoBinding;
import com.wisewoods.eduandroid.oss.ICloundOS;
import com.wisewoods.eduandroid.oss.OSSManager;
import com.wisewoods.eduandroid.ui.adapter.photo.FullyGridLayoutManager;
import com.wisewoods.eduandroid.ui.adapter.photo.GridImageAdapter;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Response;

public class TeacherInfoActivity extends BasePhotoActivity<ActivityTeacherInfoBinding> {


    private GridImageAdapter mAdapter;
    private TeacherInfo.DataBean data;
    private String sexId;
    private String nationId;
    private String avater;
    private String card1;
    private String card2;
    private String bank1;
    private String bank2;
    private List<NationBean.ListBean> nations;
    private List<String> ids;
    private AreaView dialog;

    @Override
    protected void initData(Bundle savedInstanceState) {
        showBarBack(binding.bar.tvTitle, "师资信息", binding.bar.ivBack);

//        binding.lv.setLocationSelectListener((location, ids) -> {
//            this.ids = ids;
//        });
        dialog = new AreaView(activity);
        dialog.setListener((code, area) -> {
            binding.tvArea.setText(area);
            if (code != null) {
                this.ids = Arrays.asList(code.split(",").clone());
            }
        });
        binding.tvArea.setOnClickListener(v -> {
            if (dialog != null && !dialog.isShowing()) {
                dialog.show();
            }
        });

        binding.ivPhoto.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            OSSManager.getInstance().selectAvater(this, OSSManager.OSSPATH, (code, msg) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    ImgUtils.load(activity, msg, binding.ivPhoto);
                    avater = msg;
                } else {
                    $.toast(msg);
                }
                hideLoading();
            });
        });

        binding.ivCard1.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            selectBase64((code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    ImgUtils.load(activity, msg, binding.ivCard1);
                    card1 = msg;

                    File file = FileUtils.getFileByPath(msg);
                    String type = FileUtils.getFileExtension(msg);
                    RequestBody fileRQ = RequestBody.create(MediaType.parse("image/"+type), file);
                    MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), fileRQ);

                    App.api.idCardOCR(part).enqueue(new JCallback<IDCardBean>() {
                        @Override
                        public void onS(Response<IDCardBean> response, IDCardBean idCardBean) {
                            binding.etIdcard.setText(idCardBean.data.IdNum);
                        }
                    });
                } else {
                    $.toast(msg);
                }
                hideLoading();
            });
        });

        binding.ivCard2.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            selectBase64((code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    ImgUtils.load(activity, msg, binding.ivCard2);
                    card2 = msg;
                } else {
                    $.toast(msg);
                }
                hideLoading();
            });
        });

        binding.ivBank1.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            selectBase64((code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    ImgUtils.load(activity, msg, binding.ivBank1);
                    bank1 = msg;
                    File file = FileUtils.getFileByPath(msg);
                    String type = FileUtils.getFileExtension(msg);
                    RequestBody fileRQ = RequestBody.create(MediaType.parse("image/"+type), file);
                    MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), fileRQ);
                    App.api.bankCardOCR(part).enqueue(new JCallback<BankCardBean>() {
                        @Override
                        public void onS(Response<BankCardBean> response, BankCardBean bankCardBean) {
                            binding.etBankNum.setText(bankCardBean.data.CardNo);
                        }
                    });
                } else {
                    $.toast(msg);
                }
                hideLoading();
            });
        });

        binding.ivBank2.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            selectBase64((code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    ImgUtils.load(activity, msg, binding.ivBank2);
                    bank2 = msg;
                } else {
                    $.toast(msg);
                }
                hideLoading();
            });
        });


        binding.tvSex.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            OptionsPickerView pvOptions = new OptionsPickerBuilder(activity, (options1, option2, options3, v1) -> {
                //返回的分别是三个级别的选中位置
                String tx = ImgManager.getSexList().get(options1).name;
                sexId = ImgManager.getSexList().get(options1).id;
                binding.tvSex.setText(tx);
            }).build();
            pvOptions.setPicker(ImgManager.getSexList());
            pvOptions.show();
        });
        binding.tvNation.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            if (nations == null) {
                $.toast("请等待数据加载或者稍后重试");
                getNation();
            } else {
                OptionsPickerView pvOptions = new OptionsPickerBuilder(activity, (options1, option2, options3, v1) -> {
                    //返回的分别是三个级别的选中位置
                    String tx = nations.get(options1).dictLabel;
                    binding.tvNation.setText(tx);
                    nationId = nations.get(options1).dictValue;
                }).build();
                pvOptions.setPicker(nations);
                pvOptions.show();
            }

        });

        binding.tvChangeInfo.setOnClickListener(v -> {
            if (isFastClick()) {
                changeInfo();
            }
        });

        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                3, GridLayoutManager.VERTICAL, false);
        binding.rvPhoto.setLayoutManager(manager);
        binding.rvPhoto.addItemDecoration(new GridSpacingItemDecoration(3,
                ScreenUtils.dip2px(this, 8), false));
        mAdapter = new GridImageAdapter(this, R.drawable.ic_photo_add, () -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            OSSManager.getInstance().selectImage(this, OSSManager.OSSPATH, (code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    mAdapter.getData().add(localMedia);
                    mAdapter.notifyDataSetChanged();
                }
                hideLoading();
            });
        });
        mAdapter.setOnItemClickListener(listener);
        binding.rvPhoto.setAdapter(mAdapter);

        getData();

        getNation();

    }

    private void getNation() {
        App.api.getDict("sys_nation")
                .enqueue(new JCallback<NationBean>() {
                    @Override
                    public void onS(Response<NationBean> response, NationBean nationBean) {
                        nations = nationBean.data;
                        changeNation();
                    }
                });
    }

    private void changeNation() {
        if (nations != null && data != null) {
            for (NationBean.ListBean nation : nations) {
                if (nation.dictValue.equals(data.nation)) {
                    binding.tvNation.setText(nation.dictLabel);
                }
            }
        }
    }


    private void changeInfo() {
        if (TextUtils.isEmpty(avater)) {
            $.toast("请上传照片");
            return;
        }
        String name = binding.etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            $.toast("请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(sexId)) {
            $.toast("请选择性别");
            return;
        }
        if (TextUtils.isEmpty(nationId)) {
            $.toast("请选择民族");
            return;
        }

        String idCard = binding.etIdcard.getText().toString().trim();
        if (TextUtils.isEmpty(idCard)) {
            $.toast("请输入身份证号");
            return;
        }

        if (!RegexUtils.isIDCard18Exact(idCard)) {
            $.toast("请输入正确的身份证号");
            return;
        }

        String unit = binding.etUnit.getText().toString().trim();
        if (TextUtils.isEmpty(unit)) {
            $.toast("请输入单位");
            return;
        }
        if (ids == null || ids.size() == 0) {
            $.toast("基地地点不能为空");
            return;
        }

        String address = binding.etAddress.getText().toString().trim();
        if (TextUtils.isEmpty(idCard)) {
            $.toast("请输入居住地");
            return;
        }
        String bankNum = binding.etBankNum.getText().toString().trim();
        if (TextUtils.isEmpty(bankNum)) {
            $.toast("请输入银行卡号");
            return;
        }
        if (!ImgManager.checkBankCard(bankNum)) {
            $.toast("请输入正确的银行卡号");
            return;
        }

        String bank = binding.etBank.getText().toString().trim();
        if (TextUtils.isEmpty(bank)) {
            $.toast("请输入银行开户行");
            return;
        }
        String phone = binding.etPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            $.toast("请输入联系电话");
            return;
        }

        if (!RegexUtils.isMobileSimple(phone)) {
            $.toast("请输入正确的联系电话");
            return;
        }

        String des = binding.etDes.getText().toString().trim();
        if (TextUtils.isEmpty(des)) {
            $.toast("请输入教师简介");
            return;
        }
        String title = binding.etTitle.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            $.toast("请输入荣誉称号");
            return;
        }


        if (TextUtils.isEmpty(card1)) {
            $.toast("请上传身份证照片正面");
            return;
        }

        if (TextUtils.isEmpty(card2)) {
            $.toast("请上传身份证照片反面");
            return;
        }
        if (TextUtils.isEmpty(bank1)) {
            $.toast("请上传银行卡照片正面");
            return;
        }
        if (TextUtils.isEmpty(bank2)) {
            $.toast("请上传银行卡照片反面");
            return;
        }

        if (mAdapter.getData().size() == 0) {
            $.toast("请上传证书照片");
            return;
        }

        ArrayList<String> imgDatas = new ArrayList<>();
        for (LocalMedia localMedia : mAdapter.getData()) {
            imgDatas.add(localMedia.getCompressPath());
        }


        File card1File = FileUtils.getFileByPath(card1);
        RequestBody fileRQ1 = RequestBody.create(MediaType.parse("image/*"), card1File);

        File card2File = FileUtils.getFileByPath(card2);
        RequestBody fileRQ2 = RequestBody.create(MediaType.parse("image/*"), card2File);

        File card3File = FileUtils.getFileByPath(bank1);
        RequestBody fileRQ3 = RequestBody.create(MediaType.parse("image/*"), card3File);

        File card4File = FileUtils.getFileByPath(bank2);
        RequestBody fileRQ4 = RequestBody.create(MediaType.parse("image/*"), card4File);

//        RequestBody fileRQ = RequestBody.create(MediaType.parse("multipart/form-data"), file);

        RequestBody body = new MultipartBody.Builder()
                .addFormDataPart("id", data.id + "")
                .addFormDataPart("teacherName", name)
                .addFormDataPart("photoUrl", avater)
                .addFormDataPart("sex", sexId)
                .addFormDataPart("nation", nationId)
                .addFormDataPart("idCard", idCard)
                .addFormDataPart("unit", unit)
                .addFormDataPart("address", address)
                .addFormDataPart("region", GsonUtils.toJson(ids))
                .addFormDataPart("cardNumber", bankNum)
                .addFormDataPart("bankDeposit", bank)
                .addFormDataPart("telephone", phone)
                .addFormDataPart("teacherProfile", des)
                .addFormDataPart("honoraryTitle", title)
                .addFormDataPart("idCardFront", card1)
                .addFormDataPart("idCardSide", card2)
                .addFormDataPart("bankCardFront", bank1)
                .addFormDataPart("bankCardSide", bank2)
                .addFormDataPart("certificate", GsonUtils.toJson(imgDatas))
                .addFormDataPart("idCardFrontImg", card1File.getName(), fileRQ1)
                .addFormDataPart("idCardSideImg", card2File.getName(), fileRQ2)
                .addFormDataPart("bankCardFrontImg", card3File.getName(), fileRQ3)
                .addFormDataPart("bankCardSideImg", card4File.getName(), fileRQ4)
                .build();


        App.api.putTeacher(body)
                .enqueue(new JDCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        $.toast("提交成功");
                        finish();
                    }
                });
    }

    private void getData() {
        App.api.getTeacher(UserManager.getUid())
                .enqueue(new JDCallback<TeacherInfo>() {
                    @Override
                    public void onS(Response<TeacherInfo> response, TeacherInfo teacherInfo) {
                        if (teacherInfo.data == null) {
                            return;
                        }
                        data = teacherInfo.data;
                        avater = data.photoUrl;
                        sexId = data.sex;
                        nationId = data.nation;
                        ImgUtils.load(activity, data.photoUrl, binding.ivPhoto);
                        binding.etName.setText(teacherInfo.data.teacherName);
                        binding.tvSex.setText(ImgManager.getSex(teacherInfo.data.sex));
                        binding.etIdcard.setText(teacherInfo.data.idCard);
                        binding.etAddress.setText(teacherInfo.data.address);
                        binding.etUnit.setText(teacherInfo.data.unit);
                        binding.etBankNum.setText(teacherInfo.data.cardNumber);
                        binding.etBank.setText(teacherInfo.data.bankDeposit);
                        binding.etPhone.setText(teacherInfo.data.telephone);
                        binding.etDes.setText(teacherInfo.data.teacherProfile);
                        binding.etTitle.setText(teacherInfo.data.honoraryTitle);
                        changeNation();
//                        card1 = teacherInfo.data.idCardFrontBase64;
//                        card2 = teacherInfo.data.idCardSideBase64;
//                        bank1 = teacherInfo.data.bankCardFrontBase64;
//                        bank2 = teacherInfo.data.bankCardSideBase64;
                        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/img";
                        boolean b1 = FileIOUtils.writeFileFromBytesByStream(dir+"/card1.jpg",
                                EncodeUtils.base64Decode(teacherInfo.data.idCardFrontBase64));
                        if (b1){
                            card1 =dir+"/card1.jpg";
                        }
                        boolean b2 = FileIOUtils.writeFileFromBytesByStream(dir+"/card2.jpg",
                                EncodeUtils.base64Decode(teacherInfo.data.idCardSideBase64));
                        if (b2){
                            card2 =dir+"/card2.jpg";
                        }
                        boolean b3 = FileIOUtils.writeFileFromBytesByStream(dir+"/bank1.jpg",
                                EncodeUtils.base64Decode(teacherInfo.data.bankCardFrontBase64));
                        if (b3){
                            bank1 =dir+"/bank1.jpg";
                        }
                        boolean b4 = FileIOUtils.writeFileFromBytesByStream(dir+"/bank2.jpg",
                                EncodeUtils.base64Decode(teacherInfo.data.bankCardSideBase64));
                        if (b4){
                            bank2 =dir+"/bank2.jpg";
                        }

                        ImgUtils.load(activity, card1, R.drawable.ic_photo1, binding.ivCard1);
                        ImgUtils.load(activity, card2, R.drawable.ic_photo2, binding.ivCard2);
                        ImgUtils.load(activity, bank1, R.drawable.ic_photo1, binding.ivBank1);
                        ImgUtils.load(activity, bank2, R.drawable.ic_photo2, binding.ivBank2);

                        ArrayList<LocalMedia> imgs = new ArrayList<>();
                        for (String url : teacherInfo.data.certificateList) {
                            LocalMedia localMedia = new LocalMedia();
                            localMedia.setCompressed(true);
                            localMedia.setCompressPath(url);
                            imgs.add(localMedia);
                        }
                        mAdapter.setList(imgs);
                        mAdapter.notifyDataSetChanged();
                        ids = teacherInfo.data.regionList;

                        dialog.setData(teacherInfo.data.getBaseRegion());
//                        binding.lv.setData(teacherInfo.data.regionList, teacherInfo.data.getRegionName());
                    }


                });
    }


    private void selectBase64(OSSManager.PictureSelectorCallback callback) {
        PictureSelector.create(activity)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .selectionMode(PictureConfig.SINGLE)
                .imageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .isCompress(true)// 是否压缩
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        for (LocalMedia media : result) {
                            if (media.getWidth() == 0 || media.getHeight() == 0) {
                                if (PictureMimeType.isHasImage(media.getMimeType())) {
                                    MediaExtraInfo imageExtraInfo = MediaUtils.getImageSize(media.getPath());
                                    media.setWidth(imageExtraInfo.getWidth());
                                    media.setHeight(imageExtraInfo.getHeight());
                                }
                            }
                        }

                        String mCoverImagePath = "";
                        if (result.get(0).isCompressed()) {
                            mCoverImagePath = result.get(0).getCompressPath();
                        } else {
                            mCoverImagePath = result.get(0).getRealPath();
                        }
                        if (callback != null) {
                            callback.call(ICloundOS.CODE_SUCCESS, mCoverImagePath, null);
                        }
                    }

                    @Override
                    public void onCancel() {
                        if (callback != null) {
                            callback.call(ICloundOS.CODE_ERROR, "取消选择", null);
                        }
                    }
                });
    }





}
