package com.usai.apex.mainframe;


import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.ListFragment;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.R;
import com.usai.apex.Result.PullRefreshListView;
import com.usai.util.commonUtil;

import org.apache.http.util.EncodingUtils;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class TrackingListFragment extends ListFragment {
    protected BaseAdapter adapter;
    boolean bdirty = false;
//    List<Map<String, Object>> list_data;
TrackingListSearchResult searchresult	= new TrackingListSearchResult();

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

        outState.putSerializable("searchresult",searchresult);
        outState.putBoolean("dirty",bdirty);

    }

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

    @Override
    public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
        super.onViewStateRestored(savedInstanceState);

        if (savedInstanceState != null)
        {
            searchresult = (TrackingListSearchResult) savedInstanceState
                    .getSerializable("searchresult");
            bdirty = savedInstanceState.getBoolean("dirty");
            if (searchresult.get_count() == 0 && isActive())
                requestData();
//            else
//                initTable();
        }
//        else
//            requestData();
    }

//    protected class TrackingListSearchResult implements Serializable
//    {
//        private static final long serialVersionUID = 335021506170621905L;
//        List<Map<String, Object>>	datalist	= new ArrayList<Map<String, Object>>();
//
//        public int get_count()
//        {
//            return datalist.size();
//        }
//
//        public void add_records(String source, int count)
//        {
//            JSONArray arrrecords=null;
//            try
//            {
//                arrrecords = new JSONArray(source);
//
//                for (int i=0;i<arrrecords.length();i++)
//                {
//                    JSONObject objrec =arrrecords.getJSONObject(i);
//
//
////                    String title = objrec.getString("title");
////                    String icon = objrec.getString("icon");
////                    String description = objrec.getString("description");
////                    String detail = objrec.getString("detail");
////                    String date = objrec.getString("date");
////                    String port = objrec.getString("port");
////
////                    int iconid = commonUtil.iconName2Rid(getContext(),icon);
////
////
//////                    lastid = id;
////                    Map<String, Object> map = new HashMap<String, Object>();
////                    map.put("title", title);
////                    map.put("icon", iconid);
////                    map.put("description", description);
////                    map.put("detail", detail);
////                    map.put("date", date);
////                    map.put("port", port);
//
//
//                    Map<String, Object> map = new HashMap<String, Object>();
//
//                    Iterator<String> keys = objrec.keys();
//                    while (keys.hasNext()) {
//                        String key = keys.next();
//                        Object value = objrec.get(key);
//
//                        if (key.equals("icon")) {
//                            int iconid = commonUtil.iconName2Rid(getContext(),(String)value);
//                            value = iconid;
//                        }
//                        map.put(key, value);
//
//                    }
//
//                    datalist.add(map);
//
//                }
//
////                for (int i = 0; i < count; i++)
////                {
////                    // offset++;
////                    JSONObject objrec = objrecords.getJSONObject("record" + i);
////                    String title = objrec.getString("title");
////                    String content = objrec.getString("content");
////                    String image = objrec.getString("image");
////                    String id = objrec.getString("id");
////                    String url = objrec.getString("url");
//////                    lastid = id;
////                    Map<String, Object> map = new HashMap<String, Object>();
////                    map.put("title", title);
////                    map.put("content", content);
////                    map.put("image", image);
////                    map.put("id", id);
////                    map.put("url", url);
////                    datalist.add(map);
////
////                    // Iterator<?> it = rec.keys();
////                    // HashMap<String, String> record = new HashMap<String,
////                    // String>();
////                    // while (it.hasNext()) // loop for each function
////                    // {
////                    // String field_name = (String) it.next();
////                    // String val = rec.getString(field_name)
////                    // .replace("\n", "");
////                    // record.put(field_name, val);
////                    // }
////                    // records.add(record);
////
////                }
//            }
//            catch (JSONException e)
//            {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }
//
//        }
//
//        public List<Map<String, Object>> getData()
//        {
//
//            return datalist;
//        }
//
//        public void clear() {
//            datalist.clear();
//        }
//    }
    private class TrackingAdapter extends BaseAdapter
    {
        private LayoutInflater mInflater;	// 动态布局映射
        private TrackingListSearchResult result;

        // private Context context;
        // private int i = 0;
        public TrackingAdapter(TrackingListSearchResult result, Context context)
        {
            this.result = result;
            // this.context = context;
            this.mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount()
        {
            // TODO Auto-generated method stub
            return result.get_count();
        }

        @Override
        public Object getItem(int position)
        {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position)
        {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        {
            // TODO Auto-generated method stub

            /*
                             String title = objrec.getString("title");
                    String icon = objrec.getString("icon");
                    String description = objrec.getString("description");
                    String detail = objrec.getString("detail");
                    String date = objrec.getString("date");
                    String port = objrec.getString("port");
             */

            if(convertView==null)
                convertView = mInflater.inflate(R.layout.tracking_list_cell, null);// 根据布局文件实例化view

            TextView title = (TextView) convertView.findViewById(R.id.tv_title);// 找某个控件
            title.setText(result.getData().get(position).get("title")
                    .toString());// 给该控件设置数据(数据从集合类中来)

            TextView date = (TextView) convertView
                    .findViewById(R.id.tv_time);
            date.setText(result.getData().get(position).get("date")
                    .toString());

            TextView description = (TextView) convertView
                    .findViewById(R.id.tv_description);
            description.setText(result.getData().get(position).get("description")
                    .toString());

            TextView detail = (TextView) convertView
                    .findViewById(R.id.tv_detail);
            detail.setText(result.getData().get(position).get("detail")
                    .toString());

            TextView port = (TextView) convertView
                    .findViewById(R.id.tv_port);
            port.setText(result.getData().get(position).get("port")
                    .toString());

            ImageView iv_status = (ImageView) convertView
                    .findViewById(R.id.iv_status);
            iv_status.setImageResource((int)result.getData().get(position).get("icon"));

            View v=(View) convertView
                    .findViewById(R.id.v_transport_stage);

            String sstransport_stage =result.getData().get(position).get("transport_stage").toString();

            if(TextUtils.isEmpty(sstransport_stage))
                sstransport_stage="0";
            int  transport_stage = Integer.valueOf(sstransport_stage).intValue();

             switch(transport_stage)
             {

                 case 0:


                     v.setBackground(ApexTrackingApplication.getInstance().getResources().getDrawable(R.drawable.list_corner_transport_stage_bg_0));
//                     v.setBackgroundColor(.getColor(R.color.transport_stage_0));
                     break;
                 case 1:
                     v.setBackground(ApexTrackingApplication.getInstance().getResources().getDrawable(R.drawable.list_corner_transport_stage_bg_1));
//                     v.setBackgroundColor(ApexTrackingApplication.getInstance().getResources().getColor(R.color.transport_stage_1));
                     break;
                 case 2:
                     v.setBackground(ApexTrackingApplication.getInstance().getResources().getDrawable(R.drawable.list_corner_transport_stage_bg_2));
//                     v.setBackgroundColor(ApexTrackingApplication.getInstance().getResources().getColor(R.color.transport_stage_2));
                     break;
                 case 3:
                     v.setBackground(ApexTrackingApplication.getInstance().getResources().getDrawable(R.drawable.list_corner_transport_stage_bg_3));
//                     v.setBackgroundColor(ApexTrackingApplication.getInstance().getResources().getColor(R.color.transport_stage_3));
                     break;
                 default:
                     v.setBackground(ApexTrackingApplication.getInstance().getResources().getDrawable(R.drawable.list_corner_transport_stage_bg_0));
                    // v.setBackgroundColor(ApexTrackingApplication.getInstance().getResources().getColor(R.color.transport_stage_0));
                     break;

             }
//            if (result.getData().get(position).get("image").toString().length() > 0)
//            {
//                byte[] gzipBuff = Base64.decode(result.getData().get(position)
//                        .get("image").toString(), 0);
//
//                ByteArrayInputStream memstream = new ByteArrayInputStream(
//                        gzipBuff, 0, gzipBuff.length);
//
//                ByteArrayOutputStream baos = new ByteArrayOutputStream(
//                        gzipBuff.length);
//                ImageView iv_thumb = (ImageView) convertView
//                        .findViewById(R.id.iv_thumb);
//                try
//                {
//                    baos.write(gzipBuff);
//
//                    Bitmap bmp = BitmapFactory.decodeStream(memstream);
//
//                    // ImageView image = new ImageView(this);
//
//                    iv_thumb.setImageBitmap(bmp);
//                }
//                catch (IOException e)
//                {
//                    // TODO Auto-generated catch block
//                    e.printStackTrace();
//                }
//            }
            // img.setBackgroundResource((Integer)jObject.get("img"));

            return convertView;
        }
    }
    public TrackingListFragment() {
        // Required empty public constructor
    }
    protected View initHeaderView()
    {

        return null;

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);
//
//        progressDialog = new ProgressDialog(mContext);
//        progressDialog.setCancelable(false);


        if (savedInstanceState != null)
        {
            searchresult = (TrackingListSearchResult) savedInstanceState
                    .getSerializable("searchresult");
            bdirty = savedInstanceState.getBoolean("dirty");
            if (searchresult.get_count() == 0 && isActive())
                requestData();
//            else
//                initTable();
        }
//        else
//            requestData();

        setupAdapter();
        customize_style();




        // this.getListView().setBackgroundColor(Color.WHITE);
//        requestdata();

    }

    protected  void setupAdapter()
    {
        adapter = new TrackingAdapter(searchresult, this.getActivity());

//        module_name = getIntent().getStringExtra("module_name");
//
//        setTitle(module_name);
//        view_page_footer = LayoutInflater.from(this).inflate(
//                R.layout.view_page_footer, null);
//        getListView().addFooterView(view_page_footer);// 添加底部视图
//        TextView text_page = (TextView) view_page_footer
//                .findViewById(R.id.text_page);
//        text_page.setOnClickListener(new View.OnClickListener()
//        {
//            // 点击按钮 追加数据 并通知适配器
//            @Override
//            public void onClick(View v)
//            {
//                // TODO Auto-generated method stub
//                // TextView tv = (TextView) v;
//                // tv.setText("Loading...");
//                requestdata();
//                // tv.setText("下一页");
//                // adapter.notifyDataSetChanged();
//            }
//        });

        View headerView = initHeaderView();
        if(headerView!=null)
            getListView().addHeaderView(headerView);
        setListAdapter(adapter);
    }

    protected void customize_style()
    {



//        this.getListView().setDivider(new ColorDrawable(Color.RED));
        this.getListView().setDivider(getResources().getDrawable(R.drawable.list_div));
//        this.getListView().setDividerHeight(20);

        int px=commonUtil.dp2px(getActivity(), 8.75f);
        this.getListView().setDividerHeight(px);

//        this.getListView().setBackground(getResources().getDrawable(R.drawable.list_corner_round_bg));
        this.getListView().setBackgroundColor(getResources().getColor(R.color.table_bg)  );
//        this.getListView().setSelector(R.drawable.list_corner_round);


    }

    protected JSONObject loadfakecontent(int rawid)
    {

        String jstring = "";
        try
        {
            InputStream in = getResources().openRawResource(rawid);
            // 获取文件的字节数
            int lenght = in.available();
            // 创建byte数组
            byte[] buffer = new byte[lenght];
            // 将文件中的数据读到byte数组中
            in.read(buffer);
            jstring = EncodingUtils.getString(buffer, "UTF-8");
            JSONObject jsobj = new JSONObject(jstring);
            return jsobj;
//            JSONObject objrecords = jsobj.getJSONObject("records");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;

    }

    protected List<Map<String, Object>> getData(JSONObject jsobj)
    {
        return null;
    }

//    ProgressDialog progressDialog;
    boolean isLoading = false;//表示是否正处于加载状态
    Context mContext;
    SwipeRefreshLayout mSwipeRefresh;
    private TrackingBroadcastReceiver mReceiver;

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

//    protected void showProgressDialog(String title, String msg) {
//        if (!getUserVisibleHint()) {
//            return;
//        }
//
//        progressDialog.setTitle(title);
//        progressDialog.setMessage(msg);
//        progressDialog.show();
//    }

    public void showAlert(String msg) {

        if (!getUserVisibleHint()) {
            return;
        }

        if (msg == null || msg.isEmpty()) {
            return;
        }

        new AlertDialog.Builder(mContext)
                .setMessage(msg)
                .show();
    }

    static final int INTERNAL_EMPTY_ID = 0x00ff0001;
    static final int INTERNAL_PROGRESS_CONTAINER_ID = 0x00ff0002;
    static final int INTERNAL_LIST_CONTAINER_ID = 0x00ff0003;

    protected PullRefreshListView mPullRefreshListView;
    protected View refresh_footer;
    private ProgressBar mProgressLayout;

    public void showProgress(boolean show) {
        if (show) {
            mProgressLayout.setVisibility(View.VISIBLE);
        } else {
            mProgressLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final Context context = getContext();

        FrameLayout root = new FrameLayout(context);

        // ------------------------------------------------------------------

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


        // ------------------------------------------------------------------

        FrameLayout lframe = new FrameLayout(context);
        lframe.setId(INTERNAL_LIST_CONTAINER_ID);

        TextView tv = new TextView(context);
        tv.setId(INTERNAL_EMPTY_ID);
        tv.setGravity(Gravity.CENTER);
        lframe.addView(tv, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));


        // Swipe
        SwipeRefreshLayout swipeRefreshLayout = new SwipeRefreshLayout(context);
        mSwipeRefresh = swipeRefreshLayout;
        mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData();
            }
        });

        PullRefreshListView lv = new PullRefreshListView(context);
        mPullRefreshListView = lv;
        lv.setId(android.R.id.list);
        lv.setDrawSelectorOnTop(false);

        swipeRefreshLayout.addView(lv, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        lframe.addView(swipeRefreshLayout, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        root.addView(lframe, new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        // ------------------------------------------------------------------

        root.setLayoutParams(new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        ProgressBar progress = new ProgressBar(context, null, android.R.attr.progressBarStyleLarge);
        progress.setVisibility(View.GONE);
        FrameLayout.LayoutParams layoutParams =  new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        root.addView(progress, layoutParams);

        mProgressLayout = progress;

        return root;
    }

    @Override
    public void onDestroy() {

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

        super.onDestroy();
    }

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

        if (isVisibleToUser) {

        } else {

        }
    }

    public void checkDirty()
    {
        if(bdirty)
            requestData();
    }
    protected boolean isActive()
    {
        return false;
    }

    protected void requestData() {


    }

    class TrackingBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (searchresult.get_count() > 0) {
                mPullRefreshListView.setSelection(0);
            }

            bdirty = true;

            if(isActive())
            {
                requestData();
            }
//            checkDirty();
//
        }
    }

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