package com.danding.yang800;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.danding.yang800.Adapter.AbstractWheelTextAdapter;
import com.danding.yang800.Adapter.ArrayWheelAdapter;
import com.danding.yang800.Entity.AddressInfo;
import com.danding.yang800.Entity.BankInfo;
import com.danding.yang800.Presenter.BankInfoActivityPresenter;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.NetworkProgressDialog;
import com.danding.yang800.View.WheelView;
import com.danding.yang800.listener.OnWheelChangedListener;
import com.yanzhenjie.sofia.Sofia;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BankInfoActivity extends BaseActivity implements
        OnWheelChangedListener {
    @BindView(R.id.bankinfo_backTv)
    TextView bankinfo_backTv;
    @BindView(R.id.bankinfo_saveTv)
    TextView bankinfo_saveTv;
    @BindView(R.id.bankInfo_addressLayout)
    RelativeLayout bankInfo_addressLayout;
    @BindView(R.id.bankInfo_backLayout)
    RelativeLayout bankInfo_backLayout;
    @BindView(R.id.bankInfo_bankNameTv)
    TextView bankInfo_bankNameTv;
    @BindView(R.id.bankInfo_addressTv)
    TextView bankInfo_addressTv;
    @BindView(R.id.bankInfo_userNameEdit)
    EditText bankInfo_userNameEdit;
    @BindView(R.id.bankInfo_branchEdit)
    EditText bankInfo_branchEdit;
    @BindView(R.id.bankInfo_bankNumberEdit)
    EditText bankInfo_bankNumberEdit;
    @BindView(R.id.bankInfo_idCardEdit)
    EditText bankInfo_idCardEdit;
    @BindView(R.id.bankInfo_wxNumberEdit)
    EditText bankInfo_wxNumberEdit;
    private PopupWindow popupWindow;
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private TextView choiceaddress_tvsure;
    ArrayList<AddressInfo> province = new ArrayList<>();
    ArrayList<AddressInfo> arraycityList = new ArrayList<>();
    ArrayList<AddressInfo> region = new ArrayList<>();
    String province_name = "";
    String city_name = "";
    String region_name = "";
    String province_id = "";
    String city_id = "";
    String region_id = "";
    BankInfoActivityPresenter presenter;
    ArrayList<BankInfo> bankList = new ArrayList<BankInfo>();
    String bank[];
    private PopupWindow popupWindowBank;
    private WheelView bankWindow_Item;
    private int pCurrent;
    String bankName;
    private NetworkProgressDialog pd;
    String storeId = "";
    private String bankCode;
    String accountInfo;
    SharedPreferences sp;
    InputMethodManager imm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        int type = StatusColorUtil.StatusBarLightMode(this);
//        if (type > 0) {
//            StatusColorUtil.setStatusBarColor(this, R.color.white);
//            StatusColorUtil.StatusBarLightMode(this, type);
//        }
        setContentView(R.layout.activity_bank_info);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        sp = getSharedPreferences("variable", Context.MODE_PRIVATE);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        String name = intent.getStringExtra("name");
        bankInfo_userNameEdit.setText(name);
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        storeId = sp.getString("storeId", "");
        presenter = new BankInfoActivityPresenter(this);
        presenter.getInfo(storeId);
    }

    @OnClick({R.id.bankinfo_backTv, R.id.bankinfo_saveTv, R.id.bankInfo_addressLayout,
            R.id.bankInfo_backLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bankinfo_backTv:
                finish();
                break;
            case R.id.bankinfo_saveTv:
//                startActivity(TakeToBankActivity.class);
                // presenter.editInfo(storeId,);
                String userName = bankInfo_userNameEdit.getText().toString().trim();
                String subBranch = bankInfo_branchEdit.getText().toString().trim();
                String bankCardNum = bankInfo_bankNumberEdit.getText().toString().trim();
                String identity = bankInfo_idCardEdit.getText().toString().trim();
                String bankName = bankInfo_bankNameTv.getText().toString().trim();
                String address = bankInfo_addressTv.getText().toString().trim();
                if (userName.equals("")) {
                    ToastUtil.show(this, "持卡人姓名不能为空！");
                    return;
                }
                if (address.equals("")) {
                    ToastUtil.show(this, "省市区不能为空！");
                    return;
                }
                if (bankName.equals("")) {
                    ToastUtil.show(this, "银行信息不能为空！");
                    return;
                }
                if (subBranch.equals("")) {
                    ToastUtil.show(this, "支行信息不能为空！");
                    return;
                }
                if (bankCardNum.equals("")) {
                    ToastUtil.show(this, "银行卡号不能为空！");
                    return;
                }
                if (identity.equals("")) {
                    ToastUtil.show(this, "身份证号不能为空！");
                    return;
                }
                accountInfo = getJson(bankInfo_userNameEdit.getText().toString().trim(),
                        bankInfo_branchEdit.getText().toString().trim(),
                        bankInfo_bankNumberEdit.getText().toString().trim(),
                        bankInfo_idCardEdit.getText().toString().trim(),
                        bankInfo_wxNumberEdit.getText().toString().trim()).toString();
                presenter.editInfo(storeId, accountInfo);
                break;
            case R.id.bankInfo_addressLayout:
                hideKey();
                AbstractWheelTextAdapter.DEFAULT_TEXT_SIZE = 14;
                presenter.getAreaInfo("2");
                showWindow();
                break;
            case R.id.bankInfo_backLayout:
                hideKey();
                AbstractWheelTextAdapter.DEFAULT_TEXT_SIZE = 20;
                if (bankList.size() > 0) {
                    showBankWindow();
                } else {
                    presenter.getBank();
                }
                break;
        }
    }

    public void hideKey() {
        imm.hideSoftInputFromWindow(bankInfo_userNameEdit.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(bankInfo_branchEdit.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(bankInfo_bankNumberEdit.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(bankInfo_idCardEdit.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(bankInfo_wxNumberEdit.getWindowToken(), 0);
    }

    private void showWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.popupwindows_address, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        mViewProvince = (WheelView) contentView.findViewById(R.id.id_province);
        mViewCity = (WheelView) contentView.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) contentView.findViewById(R.id.id_district);
        choiceaddress_tvsure = (TextView) contentView
                .findViewById(R.id.choiceaddress_tvsure);
        TextView choiceaddress_tv = (TextView) contentView
                .findViewById(R.id.choiceaddress_tv);
        choiceaddress_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        choiceaddress_tvsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (region.size() == 0) {
                    region_name = "";
                    region_id = "";
                }
                bankInfo_addressTv.setText(province_name + city_name
                        + region_name);
                bankInfo_addressTv.setTextColor(ContextCompat.getColor(BankInfoActivity.this, R.color.black));
//                Toast.makeText(EditAddressActivity.this, ":" + provinceidMap.get(mCurrentProviceName) + "市," + cityidMap.get(mCurrentCityName) + "区," +
//                        mCurrentId, Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });
        setUpListener();
    }

    private void showBankWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.popupwindows_bank, null);
        popupWindowBank = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        popupWindowBank.setFocusable(true);
        popupWindowBank.setOutsideTouchable(true);
        popupWindowBank.setBackgroundDrawable(new BitmapDrawable());
        popupWindowBank.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
        TextView bankWindow_cancelTv = (TextView) contentView.findViewById(R.id.bankWindow_cancelTv);
        bankWindow_cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowBank.dismiss();
            }
        });
        TextView bankWindow_sureTv = (TextView) contentView.findViewById(R.id.bankWindow_sureTv);
        bankWindow_sureTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bankInfo_bankNameTv.setTextColor(ContextCompat.getColor(BankInfoActivity.this, R.color.black));
                bankInfo_bankNameTv.setText(bankName);
                popupWindowBank.dismiss();
            }
        });
        bankWindow_Item = (WheelView) contentView.findViewById(R.id.bankWindow_Item);
        bankWindow_Item.addChangingListener(this);
        bankWindow_Item.setViewAdapter(new ArrayWheelAdapter<String>(
                BankInfoActivity.this, bank));
        bankWindow_Item.setVisibleItems(7);
        // mViewCity.setVisibleItems(7);
        // mViewDistrict.setVisibleItems(7);

    }

    private void updateBank() {
        pCurrent = bankWindow_Item.getCurrentItem();
        bankName = bank[pCurrent];
        bankCode = bankList.get(pCurrent).getCode();
    }

    private void setUpListener() {
        mViewProvince.addChangingListener(this);
        mViewCity.addChangingListener(this);
        mViewDistrict.addChangingListener(this);
    }

    private void setUpData() {
        String provinceArray[] = new String[province.size()];
        for (int i = 0; i < province.size(); i++) {
            provinceArray[i] = province.get(i).getName();
        }
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(
                BankInfoActivity.this, provinceArray));
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        String parentId = province.get(0).getId();
        province_name = province.get(0).getName();
        province_id = province.get(0).getId();
        presenter.getChildren(parentId);
    }


    private void updateAreas() {

        String regionArray[] = new String[region.size()];

        for (int i = 0; i < region.size(); i++) {
            regionArray[i] = region.get(i).getName();
        }
        mViewDistrict
                .setViewAdapter(new ArrayWheelAdapter<>(this, regionArray));
        mViewDistrict.setCurrentItem(0);
        region_id = region.get(0).getId();
        region_name = region.get(0).getName();
//        mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[0];
//        mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
//        mCurrentId =
//                mregionidDatasMap.get(mCurrentCityName)[0];
//        city = mCurrentCityName;
//        city_id = cityidMap.get(mCurrentCityName);
//        region = mCurrentDistrictName;
//        region_id = mCurrentId;
    }

    private void updateCities() {
        String cityArray[] = new String[arraycityList.size()];
        for (int i = 0; i < arraycityList.size(); i++) {
            cityArray[i] = arraycityList.get(i).getName();
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cityArray));
        mViewCity.setCurrentItem(0);
        int pCurrent = mViewCity.getCurrentItem();
        String parentId = arraycityList.get(pCurrent).getId();
        city_name = arraycityList.get(0).getName();
        city_id = parentId;
        presenter.getRegionChildren(parentId);
        //  updateAreas();
//        province = mCurrentProviceName;
//        province_id = provinceidMap.get(mCurrentProviceName);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == mViewProvince) {
            int pCurrent = mViewProvince.getCurrentItem();
            String parentId = province.get(pCurrent).getId();
            province_name = province.get(pCurrent).getName();
            province_id = parentId;
            presenter.getChildren(parentId);
        } else if (wheel == mViewCity) {
            //  ToastUtil.show(this, arraycityList.size() + "s");
            int pCurrent = mViewCity.getCurrentItem();
            String parentId = arraycityList.get(pCurrent).getId();
            city_name = arraycityList.get(pCurrent).getName();
            city_id = parentId;
            presenter.getRegionChildren(parentId);
        } else if (wheel == mViewDistrict) {
            int pCurrent = mViewDistrict.getCurrentItem();
            region_id = region.get(pCurrent).getId();
            region_name = region.get(pCurrent).getName();
//            mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
//            mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
//            mCurrentId =
//                    mregionidDatasMap.get(mCurrentCityName)[newValue];
//            region = mCurrentDistrictName;
//            region_id = mCurrentId;
        } else if (wheel == bankWindow_Item) {
            updateBank();
        }
    }


    public void initDialog() {
        if (pd == null) {
            pd = NetworkProgressDialog.createDialog(this);
            if (!pd.isShowing()) {
                pd.show();
            }
        }
    }

    public void dismissDialog() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
            NetworkProgressDialog.clear();
        }
    }

    public void initBank(ArrayList<BankInfo> bankInfoArrayList) {
        bankList = bankInfoArrayList;
        if (bankList.size() > 0) {
            bank = new String[bankList.size()];
            for (int i = 0; i < bankList.size(); i++) {
                bank[i] = bankList.get(i).getName();
            }
            bankName = bank[0];
            bankCode = bankList.get(0).getCode();
            showBankWindow();
        }
    }

    //    {userName:"",address{provice:{id:"",name:""},city:{id:"",name:""},district:{id:"",name:""}},bank:{code:"",name:""},subBranch:"",bankCardNum:"",
//            identity:"",weChat:""}
    public JSONObject getJson(String userName, String subBranch, String bankCardNum, String identity, String weChat) {
        JSONObject object = new JSONObject();
        try {
            object.put("userName", userName);
            object.put("subBranch", subBranch);
            object.put("bankCardNum", bankCardNum);
            object.put("identity", identity);
            object.put("weChat", weChat);
            JSONObject addressObj = new JSONObject();
            JSONObject proviceObj = new JSONObject();
            proviceObj.put("id", province_id);
            proviceObj.put("name", province_name);
            JSONObject cityObj = new JSONObject();
            cityObj.put("id", city_id);
            cityObj.put("name", city_name);
            JSONObject districtObj = new JSONObject();
            districtObj.put("id", region_id);
            districtObj.put("name", region_name);
            addressObj.put("provice", proviceObj);
            addressObj.put("city", cityObj);
            addressObj.put("district", districtObj);
            object.put("address", addressObj);
            JSONObject bankObj = new JSONObject();
            bankObj.put("code", bankCode);
            bankObj.put("name", bankName);
            object.put("bank", bankObj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return object;
    }

    public void editSuccess() {
        Intent intent = new Intent(BankInfoActivity.this, TakeToBankActivity.class);
        intent.putExtra("accountInfo", accountInfo);
        startActivity(intent);
    }

    public void initData(String userName, String subBranch, String bankCardNum, String identity,
                         String weChat, String provinceId, String provinceName, String cityId, String cityName,
                         String districtId, String districtName, String bank_Code, String bank_Name) {
        bankInfo_userNameEdit.setText(userName);
        bankInfo_branchEdit.setText(subBranch);
        bankInfo_bankNumberEdit.setText(bankCardNum);
        bankInfo_idCardEdit.setText(identity);
        bankInfo_wxNumberEdit.setText(weChat);
        province_id = provinceId;
        city_id = cityId;
        region_id = districtId;
        bankCode = bank_Code;
        bankName = bank_Name;
        province_name = provinceName;
        city_name = cityName;
        region_name = districtName;
        bankInfo_addressTv.setText(provinceName + cityName + districtName);
        bankInfo_bankNameTv.setText(bankName);
        bankInfo_addressTv.setTextColor(ContextCompat.getColor(this, R.color.black));
        bankInfo_bankNameTv.setTextColor(ContextCompat.getColor(this, R.color.black));
    }

    public void updateProvince(ArrayList<AddressInfo> provinceList) {
        province = provinceList;
        if (province.size() > 0) {
            setUpData();
        }
    }

    public void updateCity(ArrayList<AddressInfo> cityList) {
        arraycityList = cityList;
        if (cityList.size() > 0) {
            updateCities();
        }
    }

    public void updateRegion(ArrayList<AddressInfo> regionList) {
        region = regionList;
        updateAreas();
    }
}
