package com.usai.apex.mainframe;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.KPI.KPICell;
import com.usai.apex.KPI.KPIViewPager;
import com.usai.apex.KPI.PieChartView;
import com.usai.apex.R;
import com.usai.apex.Result.AMResultActivity;
import com.usai.apex.ResultActivity;
import com.usai.util.Network;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 */
public class KPIFragment extends Fragment implements KPICell.KPIListener {

    boolean bdirty = false;


    protected boolean isActive()
    {
        return ApexTrackingApplication.getInstance().homeactive&& !ApexTrackingApplication.get_instance().recentactive;
    }
//    private static final long serialVersionUID = 2873400198824958986L;
public void checkDirty()
{

    if(bdirty) {
        loadKPIData();

    }
}
    public static class KPIModel implements Serializable,Parcelable {

        private static final long serialVersionUID = -6280156291692980527L;
        public ArrayList<PieChartView.ChartItem> items;
        public String name;
        public String module_name;
        public int total;


        public KPIModel() {

        }

        protected KPIModel(Parcel in) {
            name = in.readString();
            module_name = in.readString();
            total = in.readInt();
        }

        public static final Creator<KPIModel> CREATOR = new Creator<KPIModel>() {
            @Override
            public KPIModel createFromParcel(Parcel in) {
                return new KPIModel(in);
            }

            @Override
            public KPIModel[] newArray(int size) {
                return new KPIModel[size];
            }
        };

        @Override
        public int describeContents() {
            return 0;
        }

        @Override
        public void writeToParcel(Parcel dest, int flags) {
            dest.writeString(name);
            dest.writeString(module_name);
            dest.writeInt(total);
        }
    }

    private static class Month implements Serializable {

        private static final long serialVersionUID = -1567922292260033377L;
        String shipVal;
        int shipColor = Color.WHITE;

        void setShipColor(String color) {
            if (color == null) {
                return;
            }
            shipColor = Color.parseColor(color.replace("0x","#"));
        }

        String containerVal;
        int containerColor = Color.WHITE;

        void setContainerColor(String color) {
            if (color == null) {
                return;
            }
            containerColor = Color.parseColor(color.replace("0x","#"));
        }

        String teuVal;
        int teuColor = Color.WHITE;

        void setTeuColor(String color) {
            if (color == null) {
                return;
            }
            teuColor = Color.parseColor(color.replace("0x","#"));
        }
    }

    public interface KPIPagerScrollListener {
        /*
         * 解决Home.KPI --> My --> History显示KPI Title
         * isHidden()、getUserHint()取得的值不正确
         * */
        void KPIPagerDidScrollToPage(int position);
    }
    private KPIPagerScrollListener mScrollListener;

    public void setKPIScrollListener(KPIPagerScrollListener mScrollListener) {
        this.mScrollListener = mScrollListener;
    }

    Context mContext;
    KPIViewPager mKPIPager;
    KPIPagerAdapter mAdapter;
    JSONObject mData;
    ArrayList<KPIModel> mKPIArr = new ArrayList<>();
    Month mMonthModel;
    SwipeRefreshLayout mSwipeRefresh;
    ProgressBar mLoadIndicator;
    private KPIFragment self;

    private int currentKPI = 1, totalKPI = 0;

    private KPIBroadcastReceiver mReceiver;

    public KPIFragment() {
        // Required empty public constructor
    }

    @Override
    public void onDestroyView() {

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getContext());
        localBroadcastManager.unregisterReceiver(mReceiver);

        super.onDestroyView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_kpi, container, false);

        mContext = getContext();
        self = this;

        if (savedInstanceState != null) {
            bdirty = savedInstanceState.getBoolean("dirty");
            currentKPI = savedInstanceState.getInt("currentKPI");
            mKPIArr = (ArrayList<KPIModel>) savedInstanceState.getSerializable("KPIData");
            mMonthModel = (Month) savedInstanceState.getSerializable("KPIMonth");
            if (mKPIArr != null) {
                totalKPI = mKPIArr.size();
            }
        }

        LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(getContext());
        IntentFilter intentFilter = new IntentFilter("com.apex.broadcast.person_mode");
        mReceiver = new KPIBroadcastReceiver();
        localBroadcastManager.registerReceiver(mReceiver,intentFilter);

        mLoadIndicator = root.findViewById(R.id.loadKPI_indicator);
        mSwipeRefresh = root.findViewById(R.id.kpi_swipe_refresh);
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loadKPIData();
            }
        });

        mKPIPager = mSwipeRefresh.findViewById(R.id.kpi_pager);
//        mKPIPager = root.findViewById(R.id.kpi_pager);
        mAdapter = new KPIPagerAdapter();
        mKPIPager.setAdapter(mAdapter);
        mKPIPager.setScrollEnable(true);
        mKPIPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                Log.d("KPI", "onPageScrolled: " + position);
            }

            @Override
            public void onPageSelected(int position) {

                currentKPI = position;
                int display_index = currentKPI;
                Log.d("KPI", "onPageSelected: " + position);
                if (position == 0) {
                    display_index = totalKPI;
//                    mKPIPager.setCurrentItem(currentKPI,false);
                } else if (position == totalKPI + 1) {
                    display_index = 1;
//                    mKPIPager.setCurrentItem(currentKPI,false);
                } else
                    {
                        display_index = position;
                }
                if (mScrollListener != null) {
                    mScrollListener.KPIPagerDidScrollToPage(display_index);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                Log.d("KPI", "onPageScrollStateChanged: " + state);

                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    if (currentKPI == mKPIPager.getAdapter().getCount() - 1) {
                        mKPIPager.setCurrentItem(1, false);
                    }
                    else if (currentKPI == 0) {
                        mKPIPager.setCurrentItem(mKPIPager.getAdapter().getCount() - 2, false);
                    }
                }
                }
        });

        mSwipeRefresh.setEnabled(true);

//        if (savedInstanceState != null) {
//            String kpiString = savedInstanceState.getString("KPIData");
//            if (kpiString != null) {
//                try {
//                    mData = new JSONObject(kpiString);
//                    prepareData();
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//

        if (mKPIArr != null && mKPIArr.size() > 0) {
            int display_index = currentKPI;
            mKPIPager.setCurrentItem(display_index,false);
        }
        if (mKPIArr == null || mKPIArr.size() == 0) {
            loadKPIData();
        }

        return root;
    }

//    @Override
//    public void setUserVisibleHint(boolean isVisibleToUser) {
//        super.setUserVisibleHint(isVisibleToUser);
//        showTitle(isVisibleToUser);
//    }
//
//    @Override
//    public void onHiddenChanged(boolean hidden) {
//        super.onHiddenChanged(hidden);
//        showTitle(!hidden);
//    }

    public void showTitle(Context ctx,boolean show) {
        if (ctx == null) {
            return;
        }
        android.support.v7.app.ActionBar bar = ((RootActivity)ctx).getSupportActionBar();
        if (bar == null) {
            return;
        }
        if (show) {
//            bar.setDisplayShowTitleEnabled(true);
            if (totalKPI > 0) {
                int display_index = currentKPI % mKPIArr.size()==0?mKPIArr.size():currentKPI % mKPIArr.size();
                ((Activity)ctx).setTitle(display_index + "/" + totalKPI);
            } else {
                ((Activity)ctx).setTitle(null);
            }
        } else {
//            bar.setDisplayShowTitleEnabled(false);
            ((Activity)ctx).setTitle(null);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        if (mKPIArr != null) {
            outState.putSerializable("KPIData",mKPIArr);
        }
        if (mMonthModel != null) {
            outState.putSerializable("KPIMonth",mMonthModel);
        }
        outState.putInt("currentKPI",currentKPI);
        outState.putBoolean("dirty",bdirty);


//        mKPIArr.clear();
//        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);
        if (savedInstanceState != null) {

            bdirty = savedInstanceState.getBoolean("dirty");
//            currentKPI = savedInstanceState.getInt("currentKPI");
//            mKPIArr = (ArrayList<KPIModel>) savedInstanceState.getSerializable("KPIData");
//            mMonthModel = (Month) savedInstanceState.getSerializable("KPIMonth");
//        }
//
//        if (mKPIArr == null || mKPIArr.size() == 0) {
//            loadKPIData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
    }


    private ProgressDialog mProgressDialog;

    public void showProgressDialog() {

        if (mProgressDialog == null) {
            if (getContext() == null) {
                return;
            }
            mProgressDialog = new ProgressDialog(getContext());
            mProgressDialog.setCancelable(false);
            mProgressDialog.setMessage("Loading...");
        }
        mProgressDialog.show();
    }

    public void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private boolean loading = false;
    private void loadKPIData() {

        if (loading) {
            return;
        }

        loading = true;
//        mLoadIndicator.setVisibility(View.VISIBLE);

        showProgressDialog();

        new Thread(new Runnable() {
            @Override
            public void run() {

                mData = Network.request_KPI();

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mLoadIndicator.getVisibility() == View.VISIBLE) {
                            mLoadIndicator.setVisibility(View.GONE);
                        }
                        if (mSwipeRefresh.isRefreshing()) {
                            mSwipeRefresh.setRefreshing(false);
                        }
                        dismissProgressDialog();
                        prepareData();
//                        if (mKPIArr != null && mKPIArr.size() > 0) {
//                            mKPIPager.setCurrentItem(currentKPI,false);
//                        }
                        loading = false;
                        bdirty = false;
                    }
                });
            }
        }).start();

    }

    private void prepareData() {

        if (mData == null) {
            return;
        }

        JSONArray monthArray = mData.optJSONArray("month");
        if (monthArray != null) {

            Month monthModel = new Month();
            for (int i = 0; i < monthArray.length(); i++) {
                JSONObject month = monthArray.optJSONObject(i);
                if (month != null) {
                    String key = month.optString("key");
                    String val = month.optString("val");
                    String color = month.optString("color");
                    if (key != null) {
                        if (key.equals("Shipment")) {

                            monthModel.shipVal = val;
                            monthModel.setShipColor(color);

                        } else if (key.equals("Container")) {

                            monthModel.containerVal = val;
                            monthModel.setContainerColor(color);

                        } else if (key.equals("TEU")) {

                            monthModel.teuVal = val;
                            monthModel.setTeuColor(color);
                        }
                    }
                }
            }
            mMonthModel = monthModel;

        }

        JSONArray kpiArray = mData.optJSONArray("KPI");

        if (kpiArray != null) {
            if (mKPIArr == null) {
                mKPIArr = new ArrayList<>();
            }
            mKPIArr.clear();
//            currentKPI = 1;
            for (int i = 0; i < kpiArray.length(); i++) {

                JSONObject kpi = kpiArray.optJSONObject(i);
                if (kpi != null) {

                    KPIModel model = new KPIModel();

                    ArrayList<PieChartView.ChartItem> items = new ArrayList<>();

                    JSONArray jsonArr = kpi.optJSONArray("arr_val");
                    if (jsonArr != null) {

                        for (int j = 0; j < jsonArr.length(); j++) {
                            JSONObject item = jsonArr.optJSONObject(j);
                            if (item != null) {
                                PieChartView.ChartItem itm = new PieChartView.ChartItem();
                                itm.value = Integer.valueOf(item.optString("A_val"));
                                itm.title = item.optString("full_title");
                                String color_str = item.optString("color");
                                if (color_str != null) {
                                    color_str = color_str.replace("0x","#");
                                    itm.color = Color.parseColor(color_str);
                                }
                                itm.display = item.optBoolean("display");
                                itm.shortTitle = item.optString("title");

                                items.add(itm);
                            }
                        }

                    }
                    model.name = kpi.optString("name");
                    model.total = kpi.optInt("total");
                    model.module_name = kpi.optString("module_name");
                    model.items = items;

                    mKPIArr.add(model);
                }

            }
            totalKPI = mKPIArr.size();
        }
        mAdapter.notifyDataSetChanged();
        if (mKPIArr != null && mKPIArr.size() > 0) {
            int display_index = currentKPI;
            mKPIPager.setCurrentItem(display_index,false);
        }
    }

    @Override
    public void KPIPieChartClickedItem(KPICell cell, PieChartView.ChartItem item) {

        String selection = null;
        if (item != null) {
            selection = String.format("%s %d %.2f%%",item.title, (int)item.value, item.getPercentage() * 100);
        }
        cell.setSelection(selection);
    }

    @Override
    public void KPIPieChartClickedTitle(KPICell cell) {
        Log.d("KPICell", "pieChartCenterClicked: ");
    }

//    @Override
//    public void KPIPreviousButtonClicked(KPICell cell) {
//        int index = mKPIPager.getCurrentItem();
//        if (index == 0) {
//            mKPIPager.setCurrentItem(mKPIArr.size() - 1,false);
//        } else {
//            mKPIPager.setCurrentItem(index - 1,false);
//        }
//    }
//
//    @Override
//    public void KPINextButtonClicked(KPICell cell) {
//        int index = mKPIPager.getCurrentItem();
//        if (index == mKPIArr.size() - 1) {
//            mKPIPager.setCurrentItem(0,false);
//        } else {
//            mKPIPager.setCurrentItem(index + 1,false);
//        }
//    }


    @Override
    public void KPIPieChartDidBeginClicked() {
        mSwipeRefresh.setEnabled(false);
        mKPIPager.setScrollEnable(false);
    }

    @Override
    public void KPIPieChartDidEndClicked() {
        mSwipeRefresh.setEnabled(true);
        mKPIPager.setScrollEnable(true);
    }

    @Override
    public void KPIListTouched(boolean touch) {
        mSwipeRefresh.setEnabled(!touch);
    }

    @Override
    public void KPICellDidDoubleClickItem(KPICell cell, int index, KPIModel model) {

        if (model == null) {
            return;
        }

        PieChartView.ChartItem legend = model.items.get(index);
        String kpi_name = model.name;
        String sector = legend.title;
        String module_name = model.module_name;
        if (kpi_name == null) {
            kpi_name = "";
        }
        if (sector == null) {
            sector = "";
        }
        if (module_name == null) {
            module_name = "";
        }

        Bundle params = new Bundle();
        params.putBoolean("is_kpi",true);
        params.putString("name",kpi_name);
        params.putString("sector",sector);
        params.putString("module_name",module_name);

        Intent intent = new Intent(getContext(), AMResultActivity.class);
        intent.putExtra("query_params",params);
        startActivity(intent);
    }

    public class KPIPagerAdapter extends PagerAdapter {

        ArrayList<KPICell> mReusePool = new ArrayList<>();

        @Override
        public int getCount() {
            if (mKPIArr == null || mKPIArr.size() == 0) {
                return 0;
            }
            return mKPIArr.size() + 2;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public int getItemPosition(Object object) {
//            return super.getItemPosition(object);
            return POSITION_NONE;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

            KPICell cell = (KPICell)object;
            cell.setListener(null);
            container.removeView(cell);
            mReusePool.add(cell);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {

            KPICell cell = null;
            if (mReusePool.isEmpty()) {
                cell = (KPICell) LayoutInflater.from(mContext).inflate(R.layout.kpi_cell,null);
                cell.init();
            } else {
                cell = mReusePool.get(0);
                mReusePool.remove(cell);
            }



            int index = position;
            if (position == 0) {
                index = mKPIArr.size() - 1;
            } else if (position == mKPIArr.size() + 1) {
                index = 0;
            } else {
                index = position - 1;
            }

            KPIModel model = mKPIArr.get(index);
            Log.d("KPI Cell", "dequeue Cell " + index);
//            cell.setChartItems(model.items);
//            cell.setNameAndCount(model.name,model.total);
//            cell.randomColor();
            cell.setKPIModel(model);

            if (mMonthModel != null) {
                cell.setMonthShipment(mMonthModel.shipVal,mMonthModel.shipColor);
                cell.setMonthContainer(mMonthModel.containerVal,mMonthModel.containerColor);
                cell.setMonthTeu(mMonthModel.teuVal,mMonthModel.teuColor);
            }

            container.addView(cell);
            cell.setListener(self);

            return cell;
        }
    }


    class KPIBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals("com.apex.broadcast.person_mode")) {

//                loadKPIData();
                bdirty = true;

                if(isActive())
                {
                    loadKPIData();
                }
            }
//            else if (intent.getAction().equals("com.usai.apex.push.cancel")) {
//                mData = null;
//                mKPIArr.clear();
//                mAdapter.notifyDataSetChanged();
//            }
        }
    }

}
