package com.navinfo.outdoor.fragment;

import android.app.Dialog;
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.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
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.adapter.BankAdapter;
import com.navinfo.outdoor.api.Constant;
import com.navinfo.outdoor.base.BaseFragment;
import com.navinfo.outdoor.bean.BankPathBean;
import com.navinfo.outdoor.bean.BankPhoneBean;
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.GetJsonDataUtil;
import com.navinfo.outdoor.util.PhotoPathUtil;
import com.navinfo.outdoor.util.PhotoUtils;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;

import static android.app.Activity.RESULT_OK;

/**
 * 收款信息
 */
public class GatheringFragment extends BaseFragment implements View.OnClickListener {

    private ImageView ivGathering, imageBank;
    private Button btnBank;
    private TextView tvBank;
    private TextView tvName;
    private EditText etBankNum;
    private ImageView gatheringCamera;

    private ArrayList<BankPathBean> jsonBean;
    private String value;
    private File file;


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

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

    }

    @Override
    protected void initView() {
        super.initView();
        ivGathering = findViewById(R.id.iv_gathering);
        ivGathering.setOnClickListener(this::onClick);
        imageBank = findViewById(R.id.iv_bank);
        imageBank.setOnClickListener(this::onClick);
        tvBank = findViewById(R.id.tv_bank);
        tvBank.setOnClickListener(this::onClick);
        btnBank = findViewById(R.id.btn_bank);
        btnBank.setOnClickListener(this::onClick);
        tvName = (TextView) findViewById(R.id.tv_name);
        etBankNum = (EditText) findViewById(R.id.et_bank_num);
        gatheringCamera = (ImageView) findViewById(R.id.gathering_camera);
        gatheringCamera.setOnClickListener(this::onClick);
        if (Constant.NAME!=null){
            tvName.setText(Constant.NAME);
        }
        if (Constant.ID_NUMBER!=null){
            etBankNum.setText(Constant.ID_NUMBER);
            btnBank.setText("已绑定");
        }
    }

    @Override
    protected void initData() {
        super.initData();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_gathering:
                getActivity().finish();
                break;
            case R.id.et_bank_num:

                break;
            case R.id.iv_bank:
                String bankJson = new GetJsonDataUtil().getJson(getContext(), "bank.json");//获取assets目录下的json文件数据
                //用Gson 转成实体
                jsonBean = parseData(bankJson);
                Dialog dialog = new Dialog(getContext());
                //弹窗点击周围空白处弹出层自动消失弹窗消失(false时为点击周围空白处弹出层不自动消失)
                dialog.setCanceledOnTouchOutside(true);
                //将布局设置给Dialog
                dialog.setContentView(R.layout.bank_item);
                RecyclerView rlvBank = dialog.findViewById(R.id.rlv_bank);
                rlvBank.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
                rlvBank.setLayoutManager(new LinearLayoutManager(getContext()));
                BankAdapter bankAdapter = new BankAdapter(jsonBean, getContext());
                rlvBank.setAdapter(bankAdapter);
                bankAdapter.setOnBankClick(new BankAdapter.OnBankClick() {
                    @Override
                    public void onClick(int pos) {

                        tvBank.setText(jsonBean.get(pos).getLabel());
                        value = jsonBean.get(pos).getValue();
                        bankAdapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                });
                Window window = dialog.getWindow();
                WindowManager.LayoutParams wlp = window.getAttributes();
                wlp.gravity = Gravity.BOTTOM;
                wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
                wlp.height = 1000;
                window.setAttributes(wlp);
                dialog.show();
                break;
            case R.id.btn_bank:
                if (etBankNum.getText().toString() == null && etBankNum.getText().toString().equals("")) {
                    Toast.makeText(getActivity(), "银行卡号不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                gatheringNetWork();
                break;
            case R.id.gathering_camera:
                Intent gatheringNumberIntent = new Intent("android.media.action.IMAGE_CAPTURE");
                file = PhotoUtils.showPhotoFile("a", null);
                gatheringNumberIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(gatheringNumberIntent, 131);
                break;
        }
    }

    private void gatheringNetWork() {
        ArrayList<File> gatheringList = new ArrayList<>();
        if (gatheringCamera.getTag() == null) {
            Toast.makeText(getActivity(), "请先拍银行卡", Toast.LENGTH_SHORT).show();
            return;
        }
        String gatheringCameraTag = (String) gatheringCamera.getTag();
        gatheringList.add(new File(gatheringCameraTag));
        String etBankAccount = etBankNum.getText().toString().trim();
        if (etBankAccount == null || etBankAccount.equals("")) {
            if (!etBankAccount.matches("^\\\\d{19}$\"")) {
                Toast.makeText(getActivity(), "银行卡号不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        showLoadingDialog();

        HttpParams httpParams = new HttpParams();

        httpParams.put("userid", Constant.USERID);
        httpParams.put("bankAccount", value);//银行id
        httpParams.put("idNumber", etBankAccount);//银行卡号
        OkGoBuilder.getInstance().Builder(getActivity())
                .url(HttpInterface.USER_BANKCARD_UP_DATA)
                .cls(BankPhoneBean.class)
                .token(Constant.ACCESS_TOKEN)
                .params(httpParams)
                .fileList(gatheringList)
                .postFileAsynchronous(new Callback<BankPhoneBean>() {
                    @Override
                    public void onSuccess(BankPhoneBean response, int id) {
                        dismissLoadingDialog();
                        if (response.getCode() == 200) {
                            MessageDialog.show((AppCompatActivity) getActivity(), "提示", "绑定成功", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    Constant.BANKACCOUNT=value;
                                    Constant.ID_NUMBER=etBankAccount;
                                    getActivity().finish();
                                    return false;
                                }
                            });
                        } else {
                            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();
                        Toast.makeText(getActivity(), e.getMessage()+"", Toast.LENGTH_SHORT).show();
                    }
                });
        /*OkGo
                // 请求方式和请求url
                .<BankPhoneBean>post(HttpInterface.USER_BANKCARD_UP_DATA)
                // 请求的 tag, 主要用于取消对应的请求
                .params("userid", "1")
                .params("bankAccount", value)//银行id
                .params("idNumber", etBankAccount)//银行卡号
                .addFileParams("file", gatheringList)//银行卡拍照
                .tag(this)
                .execute(new DialogCallback<BankPhoneBean>(BankPhoneBean.class) {
                    @Override
                    public void onSuccess(Response<BankPhoneBean> response) {
                        dismissLoadingDialog();
                        Log.d("TAG", "onSuccess: " + response.toString() + "sssssssssssss");
                        if (response.code() == 200) {
                            MessageDialog.show((AppCompatActivity) getActivity(), "绑定成功", "确定", "确定", "取消").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    navInfoEditor.putString("bankAccount", value);
                                    navInfoEditor.commit();
                                    return false;
                                }
                            });
                        } else {
                            MessageDialog.show((AppCompatActivity) getActivity(), "绑定失败", "取消", "取消", "确定").setOkButton(new OnDialogButtonClickListener() {
                                @Override
                                public boolean onClick(BaseDialog baseDialog, View v) {
                                    // Toast.makeText(getContext(), "点击了确定", Toast.LENGTH_SHORT).show();
                                    return false;
                                }
                            });
                        }
                    }

                    @Override
                    public void onError(Response<BankPhoneBean> response) {
                        super.onError(response);
                        dismissLoadingDialog();
                        Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                        Log.d("TAG", "onError: " + response.message());
                    }
                });*/
        dismissDialog();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 131 && resultCode == RESULT_OK) {
            if (file == null && !file.exists()) {
                Toast.makeText(getActivity(), "请先拍照", Toast.LENGTH_SHORT).show();
                return;
            }
            gatheringCamera.setTag(file.getAbsolutePath());
//            gatheringPath = PhotoPathUtil.getTakePhotoPath(data, "", "");
        }
    }

    //所属银行解析
    public ArrayList<BankPathBean> parseData(String result) {//Gson 解析
        ArrayList<BankPathBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                BankPathBean bankPath = gson.fromJson(data.optJSONObject(i).toString(), BankPathBean.class);
                detail.add(bankPath);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

}
