package com.ycgis.macall.personalcenter.v.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.JsonObject;
import com.rs.macall.androidx.basemodel.base.BaseViewBindActivity;

import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.callback.PermissionListener;
import com.rs.macall.androidx.basemodel.request.RequestCode;
import com.rs.macall.androidx.basemodel.utils.BitMapUtils;
import com.rs.macall.androidx.basemodel.utils.DimensionConvert;
import com.rs.macall.androidx.basemodel.utils.LogUtils;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.rs.macall.androidx.basemodel.utils.TypConversion;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.ActivityMyDetailsBinding;
import com.ycgis.macall.personalcenter.m.adapterbean.BaseBean;
import com.ycgis.macall.personalcenter.p.app.RuanseeApplication;
import com.ycgis.macall.personalcenter.p.app.UserData;
import com.ycgis.macall.personalcenter.p.callback.BaseRequestCallback;
import com.ycgis.macall.personalcenter.p.callback.ImageCallBack;
import com.ycgis.macall.personalcenter.p.callback.UploadProgressListener;
import com.ycgis.macall.personalcenter.p.request.ApiModel;
import com.ycgis.macall.personalcenter.p.request.LoadPhotoImage;
import com.ycgis.macall.personalcenter.p.request.MediaTypeUtils;
import com.ycgis.macall.personalcenter.p.request.RetrofitService;
import com.ycgis.macall.personalcenter.p.request.UploadProgressResponsBody;
import com.ycgis.macall.personalcenter.util.FileUtils;
import com.ycgis.macall.personalcenter.util.PhoneValidateUtils;
import com.ycgis.macall.personalcenter.util.ReadDeviceInfo;
import com.ycgis.macall.personalcenter.util.UriUtils;
import com.ycgis.macall.personalcenter.v.custom.InputDialog;
import com.ycgis.macall.personalcenter.v.viewmodel.MyDetailsViewModel;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.File;
import java.util.List;

import io.reactivex.observers.TestObserver;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import top.zibin.luban.OnCompressListener;

public class MyDetailsActivity extends BaseViewBindActivity<ActivityMyDetailsBinding> implements PermissionListener {
    private InputDialog inputDialog;
    private MyDetailsViewModel viewModel;
    private String imei = "", imsi = "";
    private File photoFile;

    private boolean isUpdate = false;
    public static final int UPDATE_INFO = 3365;

    //检测组件 下载组件地址 ；http://20.90.1.135/download/tyfwzjV1.0.3.apk
    private LoadPhotoImage loadPhotoImage;

    @Override
    protected ActivityMyDetailsBinding getViewBinding() {
        return ActivityMyDetailsBinding.inflate(getLayoutInflater());
    }

    @Override
    protected boolean isImmersiveStatusBar() {
        return true;
    }

    /**
     * 返回上级页面
     */
    private void returnPreviousPage() {
        if (isUpdate) {
            setResult(UPDATE_INFO);
        }
        finish();
    }

    @Override
    protected void init() {
        viewModel = ViewModelProviders.of(this).get(MyDetailsViewModel.class);
        //9500 - 2422 - 1000 -3000
        viewModel.addUpdateLiveDataObserve(this, new Observer<BaseBean>() {
            @Override
            public void onChanged(BaseBean baseBean) {
                baseDismissDialog();
                if (baseBean.getBaseType() == -1) {
                    ToastUtil.centered(getContext(), baseBean.getBaseMessage());
                    return;
                }
                isUpdate = true;
                if (baseBean.getBaseType() == 1) {
                    RuanseeApplication.getUserData().setPhone1(baseBean.getBaseMessage());
                    viewBinding.myDetailsTvPhone1.setText(baseBean.getBaseMessage());
                }
                if (baseBean.getBaseType() == 2) {
                    RuanseeApplication.getUserData().setPhone2(baseBean.getBaseMessage());
                    viewBinding.myDetailsTvPhone2.setText(baseBean.getBaseMessage());
                }
            }
        });
    }

    @Override
    protected void readInstanceState(Bundle savedInstanceState) {

    }

    @Override
    protected void start() {
        viewBinding.myDetailsTitle.leftImage.setImageDrawable(getDrawables(R.drawable.back_cliener));
        viewBinding.myDetailsTitle.contentTitle.setText("个人信息");
        UserData userData = RuanseeApplication.getUserData();
        viewBinding.myDetailsTvCode.setText(userData.getUserCode());
        viewBinding.myDetailsTvDept.setText(userData.getDeptName());
        viewBinding.myDetailsTvName.setText(userData.getUserName());
        viewBinding.myDetailsTvIdcard.setText(userData.getIdCardNum());
        viewBinding.myDetailsTvPosition.setText(userData.getPolice_post());
        viewBinding.myDetailsTvPhone1.setText(userData.getPhone1());
        viewBinding.myDetailsTvPhone2.setText(userData.getPhone2());
        setViewOnClickListener(viewBinding.myDetailsIvPhoto);
        setViewOnClickListener(viewBinding.myDetailsTvPhone1);
        setViewOnClickListener(viewBinding.myDetailsTvPhone2);
        setViewOnClickListener(viewBinding.myDetailsTvDept);
        setViewOnClickListener(viewBinding.myDetailsTitle.titleleft);
        String[] needPermissions = {Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(needPermissions, this);
        } else {
            getImei();
            getPhotoImage();
        }
    }

    private void getPhotoImage() {
        if (loadPhotoImage == null) {
            loadPhotoImage = new LoadPhotoImage();
        }
        Bitmap bitmap = loadPhotoImage.loadPhotoImage(RuanseeApplication.getUserData().getPhoto(), viewBinding.myDetailsIvPhoto, new ImageCallBack() {
            @Override
            public void imageLoad(ImageView imageView, Bitmap bitmap) {
                if (getActivity().isDestroyed())return;
                Glide.with(getContext())
                        .load(bitmap)
                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))
                        .into(viewBinding.myDetailsIvPhoto);
            }

            @Override
            public void imageLoadError(ImageView imageView, String message) {
//                ToastUtil.centered(getContext(),message);
                viewBinding.myDetailsIvPhoto.setImageDrawable(getDrawables(RuanseeApplication.getUserData().getErrorPhotoByIdCardNum()));
            }
        });

        if (bitmap != null) {
            Glide.with(getContext())
                    .load(bitmap)
                    .apply(RequestOptions.bitmapTransform(new RoundedCorners(20)))
                    .into(viewBinding.myDetailsIvPhoto);
        }
    }


    @SuppressLint({"MissingPermission", "HardwareIds"})
    private void getImei() {
        imei = RuanseeApplication.getAppCache().getImei();
        if (StringUtil.isNullOrEmpty(imei)) {
            imei = ReadDeviceInfo.getDeviceId(getContext());
            if (StringUtil.isNullOrEmpty(imei)) {
                imei = ReadDeviceInfo.getIMEI1(getContext());
            }
            RuanseeApplication.getAppCache().setImei(imei);
        }
        imsi = RuanseeApplication.getAppCache().getImsi();
        if (StringUtil.isNullOrEmpty(imsi)) {
            imsi = ReadDeviceInfo.getIMSI(getContext(), 0);
            if (StringUtil.isNullOrEmpty(imsi)) {
                imsi = ReadDeviceInfo.getIMSI(getContext(), 1);
            }
            RuanseeApplication.getAppCache().setImsi(imsi);
        }
    }
    @Override
    protected void bindViewClick(View v) {
        if (v.getId() == R.id.titleleft) {
            returnPreviousPage();
        } else if (v.getId() == R.id.my_details_iv_photo) {
            updatePhotoDialog("选择头像");
        } else if (v.getId() == R.id.my_details_tv_dept) {
            ToastUtil.centered(getContext(), "正在紧急对接中");
            Intent intent = new Intent(getContext(), UpdateDeptActivity.class);
            intent.putExtra("imei", imei);
            intent.putExtra("imsi", imsi);
            startActivity(intent);
        } else if (v.getId() == R.id.my_details_tv_phone1) {
            upDate(1, "修改移动警务号码", viewBinding.myDetailsTvPhone1);
        } else if (v.getId() == R.id.my_details_tv_phone2) {
            upDate(2, "修改手机号码", viewBinding.myDetailsTvPhone2);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RequestCode.REQUEST_PHOTO) {                 //现场照片回调
                processingPictures(true);
                return;
            }
            if (requestCode == RequestCode.REQUEST_PHOTO_ALBUM) {
                if (data == null) {
                    ToastUtil.centered(this, "选择照片失败！");
                    return;
                }
                String ss = UriUtils.getRealPathFromUri(this, data.getData());
                photoFile = new File(ss);
                if (photoFile.length() > 307200) {
                    processingPictures(false);
                    return;
                }
                uploadPhoto();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 压缩图片
     *
     * @param isDel 是否删除原图片
     */
    private void processingPictures(final boolean isDel) {
        if (photoFile != null) {
            BitMapUtils.lubanCompress(getContext(), photoFile, FileUtils.IMAGE_DIR, new OnCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(File file) {
                    if (isDel) {
                        if (photoFile != null && !photoFile.getName().equals(file.getName())) {
                            photoFile.delete();
                            photoFile = null;
                        }
                    }
                    int pp = FileUtils.readPictureDegree(file.getAbsolutePath());
                    if (pp != 0) {
                        Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                        bitmap = FileUtils.rotateImage(pp, bitmap);
                        photoFile = BitMapUtils.saveBitmap(FileUtils.IMAGE_DIR, file.getName(), bitmap);
                    } else {
                        photoFile = file;
                    }
                    uploadPhoto();
                }

                @Override
                public void onError(Throwable e) {
                    photoFile.delete();
                    photoFile = null;
                    ToastUtil.centered(getContext(), e.getMessage());
//                    Message message = myHandler.obtainMessage(-500, "图片压缩失败，请重新拍摄！");
//                    myHandler.sendMessage(message);
                }
            });
        }
    }


    /**
     * 头像选择框
     *
     * @param title 提示信息
     */
    private void updatePhotoDialog(String title) {
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_select_photo, null, false);
        final Dialog dialog = new AlertDialog.Builder(this, R.style.MyDialogTheme)
                .setView(view)
                .create();
        Window dialogWindow = dialog.getWindow();
        // 设置 dialog 显示的位置
        dialogWindow.setGravity(Gravity.BOTTOM);
        int ss = DimensionConvert.dip2px(this, 10);
        // 设置 dialog 的边距
        dialogWindow.getDecorView().setPadding(ss, 0, ss, ss);
        // 设置 标题
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 获取 LayoutParams
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        // 设置 dialog 宽度高度
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        dialogWindow.setAttributes(lp);
        dialog.show();
        TextView tv = dialog.findViewById(R.id.tv_dialog_title);
        tv.setText(title);
        //相机
        view.findViewById(R.id.btn_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 拍照
                photoFile = new File(FileUtils.IMAGE_DIR, FileUtils.getPhotoName());
                Intent intent = UriUtils.getPhotoIntent(getContext(), photoFile);
                startActivityForResult(intent, RequestCode.REQUEST_PHOTO);
                dialog.dismiss();
            }
        });
        //相册
        view.findViewById(R.id.btn_album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openSysAlbum();
                dialog.dismiss();
            }
        });

    }

    /**
     * 打开系统相册
     */
    private void openSysAlbum() {
        Intent albumIntent = new Intent(Intent.ACTION_PICK);
        albumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(albumIntent, RequestCode.REQUEST_PHOTO_ALBUM);
    }

    private void upDate(int mun, String title, TextView tv) {
        if (inputDialog == null) {
            inputDialog = new InputDialog(getContext());
        }
        inputDialog.show();
        inputDialog.setInputTitle(title);
        String textString = getTextString(tv);
        String s = "暂无".equals(textString) ? "" : textString;
        inputDialog.setInputEdit(s);
        inputDialog.setInputType(InputType.TYPE_CLASS_PHONE);
        inputDialog.setSubmitListener(new CustomClickListener() {
            @Override
            public void onSingleClick(View v) {
                String inputEditText = inputDialog.getInputEditText();
                if (StringUtil.isNullOrEmpty(inputEditText)) {
                    ToastUtil.centered(getContext(), "请输入内容！");
                    return;
                }
                if (!PhoneValidateUtils.isLegitimatePhoneNum(inputEditText)) {
                    ToastUtil.centered(getContext(), "请输入正确的电话号码！");
                    return;
                }
                inputDialog.dismiss();
                baseShowDialog("正在提交请稍后...");
                viewModel.sendUpdate(mun, inputDialog.getInputEditText(), imsi, imei);
            }
        });
        inputDialog.create();
    }

    /**
     * 上传用户头像
     */
    public void uploadPhoto() {
        String fileName = photoFile.getName();
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("token", RuanseeApplication.getAppCache().getToken())
                .addFormDataPart("clientType", "MOBILE")
                .addFormDataPart("imsi1", imsi)
                .addFormDataPart("deviceFlags", imei)
                .addFormDataPart("sysCode", RuanseeApplication.getAppCache().getSysmCode())
                .addFormDataPart("file", fileName,
                        UploadProgressResponsBody.createCustomRequestBody(MediaTypeUtils.getMediaType(fileName), photoFile, new UploadProgressListener() {
                            @Override
                            public void onUploadProgress(long totalBytes, long remainingBytes, boolean done) {
                                LogUtils.w(TAG, "上传中 ========== 总长度:" + totalBytes + "  == 当前进度:" + remainingBytes);
                            }

                            @Override
                            public void onUploadDone(long totalSize) {
                                LogUtils.w(TAG, "上传完成========== 总长度:" + totalSize);
                            }
                        })).build();
        baseShowDialog("正在上传，请稍后...");
        //20.90.2.2/UniAuth/
        ApiModel.request(RetrofitService.getBaseInstance().saveAppOperationLog("http://20.90.2.2/UniAuth/api/sso/v1/uploadPhoto", requestBody),
                new BaseRequestCallback<JsonObject>() {
                    @Override
                    public void onRequestFailure(String msg) {
                        baseDismissDialog();
                        ToastUtil.centered(getContext(), msg);
                    }

                    @Override
                    public void onRequestSuccess(JsonObject result) {
                        baseDismissDialog();
                        ApiModel.uploadOperationLog("3","3","用户修改统一用户头像");
                        try {
                            JSONObject object = new JSONObject(result.toString());
                            String code = TypConversion.getJsonStr(object, "code");
                            if (!code.equals("200")) {
                                ToastUtil.centered(getContext(), TypConversion.getJsonStr(object, "content"));
                                return;
                            }
                            String data = TypConversion.getJsonStr(object, "data");
                            JSONObject object1 = new JSONObject(data);
                            String id = TypConversion.getJsonStr(object1, "id");
                            RuanseeApplication.getUserData().setPhoto(id);
                            if (photoFile != null) {
                                photoFile.delete();
                            }
                            isUpdate = true;
                            getPhotoImage();
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ToastUtil.centered(getContext(), e.getMessage());
                        }
                    }
                });
//        BaseRequest.uploadFile("http://20.90.1.126:7321/api/sso/v1/uploadPhoto", requestBody, myHandler);
    }


    @Override
    public void onGranted() {
        getImei();
        getPhotoImage();
    }

    @Override
    public void onDenied(List<String> deniDPermission) {
        showMissingPermissionDialog();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            returnPreviousPage();
        }
        return super.onKeyDown(keyCode, event);
    }
}