package com.navinfo.outdoor.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.kongzue.dialog.interfaces.OnDialogButtonClickListener;
import com.kongzue.dialog.util.BaseDialog;
import com.kongzue.dialog.util.DialogSettings;
import com.kongzue.dialog.v3.MessageDialog;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.navinfo.outdoor.R;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseFragment;
import com.navinfo.outdoor.bean.NameAuthenticationBean;
import com.navinfo.outdoor.http.Callback;
import com.navinfo.outdoor.http.DialogCallback;
import com.navinfo.outdoor.http.HttpInterface;
import com.navinfo.outdoor.http.OkGoBuilder;
import com.navinfo.outdoor.util.Geohash;
import com.navinfo.outdoor.util.PhotoPathUtil;
import com.navinfo.outdoor.util.PhotoUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.app.Activity.RESULT_OK;

/**
 * 实名认证
 */
public class UserAttestationFragment extends BaseFragment implements View.OnClickListener {

    private ImageView ivAttestation2;
    private ImageView ivAttestation1;
    private ImageView ivAttestation;
    private Button btnAttestation;
    private ArrayList<NameAuthenticationBean> authenticationBeans;
    private EditText etAttestationName;
    private EditText etNamePhone;
    private ImageView ivAttestation3;
    private ImageView ivHera1;
    private TextView tvCard1;
    private ImageView ivHera2;
    private TextView tvCard2;
    private ImageView ivHera3;
    private TextView tvCard3;
    private File file;
    private LinearLayout linearHint;
    private TextView tvTitle;
    private LinearLayout linearLayout;
    private View userAttestView;


    public static UserAttestationFragment newInstance(Bundle bundle) {
        UserAttestationFragment fragment = new UserAttestationFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.user_attestation_fragment;
    }


    @Override
    protected void initData() {
        super.initData();
        authenticationBeans = new ArrayList<>();


    }

    @Override
    protected void initView() {
        super.initView();
        ivAttestation = findViewById(R.id.iv_attestation);
        ivAttestation.setOnClickListener(this);
        ivAttestation1 = findViewById(R.id.iv_attestation1);
        ivAttestation1.setOnClickListener(this);
        ivAttestation2 = findViewById(R.id.iv_attestation2);
        ivAttestation2.setOnClickListener(this);
        ivAttestation3 = findViewById(R.id.iv_attestation3);
        ivAttestation3.setOnClickListener(this);
        btnAttestation = (Button) findViewById(R.id.btn_attestation);
        btnAttestation.setOnClickListener(this::onClick);
        linearHint = findViewById(R.id.linear_hint);
        etAttestationName = (EditText) findViewById(R.id.et_attestationName);
        etNamePhone = (EditText) findViewById(R.id.et_namePhone);
        ivHera1 = (ImageView) findViewById(R.id.iv_hera1);
        tvCard1 = (TextView) findViewById(R.id.tv_card1);
        ivHera2 = (ImageView) findViewById(R.id.iv_hera2);
        tvCard2 = (TextView) findViewById(R.id.tv_card2);
        ivHera3 = (ImageView) findViewById(R.id.iv_hera3);
        tvCard3 = (TextView) findViewById(R.id.tv_card3);
        tvTitle = findViewById(R.id.tv_title);
        userAttestView = findViewById(R.id.user_attestation_view);
        linearLayout = findViewById(R.id.ll_pic);//身份证照片

        if (Constant.AUDITSTATUS==-1){//审核中
            if (Constant.NAME!=null&&Constant.ID_NUM!=null){
                tvTitle.setText("1.审核中");
                linearHint.setVisibility(View.VISIBLE);
                etAttestationName.setText(Constant.NAME);
                etNamePhone.setText(Constant.ID_NUM);
                etAttestationName.setEnabled(false);
                etNamePhone.setEnabled(false);
                btnAttestation.setEnabled(false);
            }else {
                linearHint.setVisibility(View.GONE);
                etAttestationName.setEnabled(true);
                etNamePhone.setEnabled(true);
                btnAttestation.setEnabled(true);
            }
        }else if (Constant.AUDITSTATUS==0){//不通过
            linearHint.setVisibility(View.GONE);
            etAttestationName.setText(Constant.NAME);
            etNamePhone.setText(Constant.ID_NUM);
            etAttestationName.setEnabled(true);
            etNamePhone.setEnabled(true);
            btnAttestation.setEnabled(true);
        }else if (Constant.AUDITSTATUS==1){//通过
            tvTitle.setText("1.审核通过");
            linearHint.setVisibility(View.VISIBLE);
            etAttestationName.setText(Constant.NAME);
            etNamePhone.setText(Constant.ID_NUM);
            linearLayout.setVisibility(View.GONE);
            userAttestView.setVisibility(View.GONE);
            etAttestationName.setEnabled(false);
            etNamePhone.setEnabled(false);
            btnAttestation.setEnabled(false);
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_attestation:
                getActivity().finish();
                break;
            case R.id.iv_attestation1:
                Intent ivAttestationIntent1 = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("a", null);
                ivAttestationIntent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(ivAttestationIntent1, 121);
                break;
            case R.id.iv_attestation2:
                Intent ivAttestationIntent2 = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("b", null);
                ivAttestationIntent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(ivAttestationIntent2, 122);
                break;
            case R.id.iv_attestation3:
                Intent ivAttestationIntent3 = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("c", null);
                ivAttestationIntent3.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(ivAttestationIntent3, 123);
                break;
            case R.id.btn_attestation:
                if (etAttestationName.getText().toString() == null || etAttestationName.getText().toString().equals("")) {
                    Toast.makeText(getActivity(), "姓名不能为空，请输入姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!chineseNameTest(etAttestationName.getText().toString())) {
                    Toast.makeText(getActivity(), "请输入中文名字", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!checkNum(etNamePhone.getText().toString().trim())) {
                    Toast.makeText(getActivity(), "身份证号错误，请重新输入", Toast.LENGTH_SHORT).show();
                    return;
                }
                nameAuthentication();
                break;
        }
    }

    /***
     *
     */
    public boolean checkNum(String text) {
        Pattern patternSfzhm1 = Pattern
                .compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$");
        Pattern patternSfzhm2 = Pattern
                .compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
        Matcher matcherSfzhm1 = patternSfzhm1.matcher(text);
        Matcher matcherSfzhm2 = patternSfzhm2.matcher(text);
        if (!matcherSfzhm1.find() && !matcherSfzhm2.find())
            return false;
        else return true;

    }

    /**
     * 中文姓名效验
     */
    static boolean chineseNameTest(String name) {
        if (!name.matches("[\u4e00-\u9fa5]{2,4}")) {
            System.out.println("只能输入2到4个汉字");
            return false;
        } else return true;
    }

    private void nameAuthentication() {
        if (etAttestationName.getText().toString() == null || etAttestationName.getText().toString().equals("")) {
            Toast.makeText(getActivity(), "姓名不能为空，请输入姓名", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!checkNum(etNamePhone.getText().toString().trim())) {
            Toast.makeText(getActivity(), "身份证错误，请重新输入", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tvCard1.getTag() == null) {
            Toast.makeText(getActivity(), "请拍照  身份证人像面", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tvCard2.getTag() == null) {
            Toast.makeText(getActivity(), "请拍照  身份证国徽面", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tvCard3.getTag() == null) {
            Toast.makeText(getActivity(), "请拍照  手持身份证", Toast.LENGTH_SHORT).show();
            return;
        }

        ArrayList<File> takePhoneList = new ArrayList<>();
        String takePhotoPath1 = (String) tvCard1.getTag();
        takePhoneList.add(new File(takePhotoPath1));
        String takePhotoPath2 = (String) tvCard2.getTag();
        takePhoneList.add(new File(takePhotoPath2));
        String takePhotoPath3 = (String) tvCard3.getTag();
        takePhoneList.add(new File(takePhotoPath3));
        String attestationName = etAttestationName.getText().toString().trim();
        String namePhone = etNamePhone.getText().toString().trim();
        showLoadingDialog();
        setLoadingDialogText("实名认证中...");
        HttpParams httpParams = new HttpParams();
        httpParams.put("userid", Constant.USERID);
        httpParams.put("name", attestationName);
        httpParams.put("idnum", namePhone);
        OkGoBuilder.getInstance().Builder(getActivity())
                .url(HttpInterface.USER_AUTH_ADD)
                .cls(NameAuthenticationBean.class)
                .token(Constant.ACCESS_TOKEN)
                .params(httpParams)
                .fileList(takePhoneList)
                .postFileAsynchronous(new Callback<NameAuthenticationBean>() {
                    @Override
                    public void onSuccess(NameAuthenticationBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode()==200){
                            DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                            MessageDialog.show((AppCompatActivity) getActivity(), "提示", "提交成功", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    Constant.NAME=attestationName;
                                    Constant.ID_NUM=namePhone;
                                    Constant.AUDITSTATUS=-1;
                                   getActivity().finish();
                                    return false;
                                }
                            });
                        }else {
                            DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
                            MessageDialog.show((AppCompatActivity) getActivity(), "提示", "提交失败", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    Toast.makeText(getActivity(), response.getMessage()+"", Toast.LENGTH_SHORT).show();
                                    return false;
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Throwable e, int id) {
                        dismissLoadingDialog();
                        Log.d("TAG", "onSuccess: sss********sssssssssssss 失败" + e.getMessage() + "");
                    }
                });
        dismissDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 121 && resultCode == RESULT_OK) {
            if (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "没有拍摄照片", Toast.LENGTH_SHORT).show();
                return;

            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivAttestation1);
                tvCard1.setTag(s);
            }
            file = null;
            ivHera1.setVisibility(View.GONE);
            tvCard1.setVisibility(View.GONE);
//            int height = bitmap.getHeight();
//            int width = bitmap.getWidth();
//            if (height > width) {
//                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
//                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
//                    @Override
//                    public boolean onClick(BaseDialog baseDialog, View v) {
//                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
//                        startActivityForResult(intentPanorama, 100);
//                        return false;
//                    }
//                });
//            }
        } else if (requestCode == 122 && resultCode == RESULT_OK) {
            if (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "没有拍摄照片", Toast.LENGTH_SHORT).show();
                return;

            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivAttestation2);
                tvCard2.setTag(s);
            }
            file = null;
            ivHera2.setVisibility(View.GONE);
            tvCard2.setVisibility(View.GONE);
//            int height = bitmap.getHeight();
//            int width = bitmap.getWidth();
//            if (height > width) {
//                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
//                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
//                    @Override
//                    public boolean onClick(BaseDialog baseDialog, View v) {
//                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
//                        startActivityForResult(intentPanorama, 200);
//                        return false;
//                    }
//                });
//            }
        } else if (requestCode == 123 && resultCode == RESULT_OK) {
            if (file == null || !file.exists()) {
                Toast.makeText(getActivity(), "没有拍摄照片", Toast.LENGTH_SHORT).show();
                return;

            } else {
                String s = PhotoUtils.showPhotoAndGetPath(file, ivAttestation3);
                tvCard3.setTag(s);
            }
            file = null;
            ivHera3.setVisibility(View.GONE);
            tvCard3.setVisibility(View.GONE);
//            int height = bitmap.getHeight();
//            int width = bitmap.getWidth();
//            if (height > width) {
//                DialogSettings.style = DialogSettings.STYLE.STYLE_KONGZUE;
//                MessageDialog.show((AppCompatActivity) getContext(), "提示", "请重新拍照，要求横屏拍照", "确定").setOkButton(new OnDialogButtonClickListener() {
//                    @Override
//                    public boolean onClick(BaseDialog baseDialog, View v) {
//                        Intent intentPanorama = new Intent("android.media.action.IMAGE_CAPTURE");
//                        startActivityForResult(intentPanorama, 300);
//                        return false;
//                    }
//                });
//            } else {
//
//            }
        }
    }
}
