package com.danding.yang800;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
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.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.danding.yang800.Adapter.AbstractWheelTextAdapter;
import com.danding.yang800.Adapter.ArrayWheelAdapter;
import com.danding.yang800.Entity.AddressInfo;
import com.danding.yang800.General.PayResult;
import com.danding.yang800.Presenter.OrderPayActivityPresenter;
import com.danding.yang800.Util.LogUtil;
import com.danding.yang800.Util.StatusColorUtil;
import com.danding.yang800.Util.StringUtil;
import com.danding.yang800.Util.ToastUtil;
import com.danding.yang800.View.AuthCodeCountDown;
import com.danding.yang800.View.WheelView;
import com.danding.yang800.listener.OnWheelChangedListener;
import com.yanzhenjie.sofia.Sofia;

import java.util.ArrayList;
import java.util.Map;

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

public class OrderPayActivity extends BaseActivity implements
        OnWheelChangedListener {
    @BindView(R.id.orderPay_backTv)
    TextView orderPay_backTv;
    @BindView(R.id.orderPay_payTv)
    TextView orderPay_payTv;
    @BindView(R.id.orderPay_inputNameEdit)
    EditText orderPay_inputNameEdit;
    @BindView(R.id.orderPay_NameEdit)
    EditText orderPay_NameEdit;
    @BindView(R.id.orderPay_inputNumberEdit)
    EditText orderPay_inputNumberEdit;
    @BindView(R.id.orderPay_numberEdit)
    EditText orderPay_numberEdit;
    @BindView(R.id.orderPay_NameLayout)
    LinearLayout orderPay_NameLayout;
    //    @BindView(R.id.orderPay_codeTv)
//    TextView orderPay_codeTv;
    @BindView(R.id.orderPay_addressLayout)
    RelativeLayout orderPay_addressLayout;
    @BindView(R.id.orderPay_addressTv)
    TextView orderPay_addressTv;
    InputMethodManager imm;
    OrderPayActivityPresenter presenter;
    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 = "";
    String number = "";
    String storeSkuSn;
    @BindView(R.id.orderPay_addressEdit)
    EditText orderPay_addressEdit;
    private static final int SDK_PAY_FLAG = 111;
    String orderInfo = "";

    @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_order_pay);
        Sofia.with(this).statusBarDarkFont().statusBarBackground(ContextCompat.getColor(this, R.color.white));
        ButterKnife.bind(this);
        Intent intent = getIntent();
        storeSkuSn = intent.getStringExtra("storeSkuSn");
        if (savedInstanceState != null) {
            storeSkuSn = savedInstanceState.getString("storeSkuSn");
        }
        listenerEdit();
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        presenter = new OrderPayActivityPresenter(this);
        presenter.getInfo(storeSkuSn);

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        storeSkuSn = savedInstanceState.getString("storeSkuSn");
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putString("storeSkuSn", storeSkuSn);
    }

    private void listenerEdit() {
        orderPay_inputNameEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                orderPay_NameEdit.setText(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void initNumber(String result) {
        number = result;
        orderPay_inputNumberEdit.setText(result);
        orderPay_numberEdit.setText(result);
    }
//    public void sendSuccess() {
//        AuthCodeCountDown mAuthCodeDown = new AuthCodeCountDown(60 * 1000 + 1100, orderPay_codeTv);
//        mAuthCodeDown.start();
//        orderPay_codeTv.setEnabled(false);
//    }

    @OnClick({R.id.orderPay_backTv, R.id.orderPay_payTv, R.id.orderPay_addressLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.orderPay_backTv:
                finish();
                break;
            case R.id.orderPay_payTv:
                presenter.submit(storeSkuSn, province_name, city_name, region_name, orderPay_addressEdit.getText().toString().trim()
                        , orderPay_inputNameEdit.getText().toString().trim(), number);
//                startActivity(PayResultActivity.class);
                break;
//            case R.id.orderPay_codeTv:
//                sendSuccess();
//                break;
            case R.id.orderPay_addressLayout:
                hideKey();
                AbstractWheelTextAdapter.DEFAULT_TEXT_SIZE = 14;
                presenter.getAreaInfo("2");
                showWindow();
                break;
        }
    }

    public void hideKey() {
        imm.hideSoftInputFromWindow(orderPay_inputNameEdit.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 = "";
                }
                orderPay_addressTv.setText(province_name + city_name
                        + region_name);
                orderPay_addressTv.setTextColor(ContextCompat.getColor(OrderPayActivity.this, R.color.black));
                popupWindow.dismiss();
            }
        });
        setUpListener();
    }

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

    @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;
        }
    }

    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();
    }

    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<>(
                OrderPayActivity.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<String>(this, regionArray));
        mViewDistrict.setCurrentItem(0);
        region_id = region.get(0).getId();
        region_name = region.get(0).getName();
    }

    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<>(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);
    }

    Handler handler = new Handler() { // handle
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
//                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    LogUtil.d(resultStatus + "resultStatus");
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Intent intent = new Intent(OrderPayActivity.this, PayResultActivity.class);
                        intent.putExtra("result", "success");
                        intent.putExtra("orderInfo", orderInfo);
                        intent.putExtra("address", province_name + city_name + region_name + orderPay_addressEdit.getText().toString().trim());
                        intent.putExtra("name", orderPay_inputNameEdit.getText().toString().trim());
                        intent.putExtra("number", number);
                        startActivity(intent);
                    } else {
//                        orderPay_payTv.setText("继续支付");
//                        ToastUtil.show(OrderPayActivity.this, "支付失败");
                        Intent intent = new Intent(OrderPayActivity.this, PayResultActivity.class);
                        intent.putExtra("result", "fail");
                        intent.putExtra("orderInfo", orderInfo);
                        intent.putExtra("address", province_name + city_name + region_name + orderPay_addressEdit.getText().toString().trim());
                        intent.putExtra("name", orderPay_inputNameEdit.getText().toString().trim());
                        intent.putExtra("number", number);
                        startActivity(intent);
                    }
                    break;

            }
        }
    };

    public void aliPay(String result) {
        orderInfo = result;
        final String orderInfo;   // 订单信息
        try {
            byte[] b = result.getBytes("UTF-8");
            orderInfo = new String(StringUtil.base64Decrypt(b), "UTF-8");
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(OrderPayActivity.this);
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    handler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } catch (Exception e) {

        }
    }
}
