package com.usai.apex.Result;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.Layout;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.HorizontalScrollView;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.R;
import com.usai.util.Network;
import com.usai.util.RAUtil;

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

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

//import com.usai.redant.Detail.KVDetailActivity;
//import com.usai.redant.Detail.OrderDetailActivity;
//import com.usai.apex.redantmobile.BuildConfig;

//import static com.usai.redant.CommonEditor.CommonEditorActivity.URL_REMOTE;


public class SearchResultActivity extends AppCompatActivity {

    public static SearchResultActivity instance = null;
    protected Bundle mParams;
    protected JSONObject resultData = new JSONObject();

    protected Context mContext;
    protected PullRefreshListView resultListView;
    protected ResultAdapter adapter;
    protected SwipeRefreshLayout resultSwipe;
    protected View list_footer;
    protected View refresh_footer;

    private View clickedView;
    private View.OnTouchListener resultRowClickListener;
    private GestureDetector detector;

    protected int footer_height;
    protected int header_height;

    ProgressDialog progressDialog;
    public boolean isLoading = false;//表示是否正处于加载状态


    public void cellDoubleTapAction(int position) {

//        try {
//
//            JSONArray row_action = resultData.optJSONArray("row_action");
//            if (row_action != null) {
//
//                if (row_action.length() == 1) {
//
//                    JSONObject action = row_action.getJSONObject(0);
//                    String module = action.getString("module");
//
//                    if (module.equals("quick_look")) {
//                        JSONObject param = action.getJSONObject("params");
//                        String url = action.getString("url");
//                        showQuickLook(param,url);
//                    } else if (module.equals("kv_detail")) {
//                        JSONObject params = new JSONObject();
//                        params.put("query_id",mParams.get("query_id"));
//
//                        JSONObject criteria = new JSONObject();
//                        JSONObject action_params = action.getJSONObject("params");
//                        Iterator<String> iterator = action_params.keys();
//                        while (iterator.hasNext()) {
//                            String key = iterator.next();
//                            JSONArray item = contentData().getJSONArray("item_" + position);
//                            int idx = action_params.getInt(key);
//                            criteria.put(key,item.get(idx));
//                        }
//
//                        params.put("criteria",criteria.toString());
//                        showKVDetail(params);
//
//                    } else if (module.equals("order_detail")) {
//
//                        showOrderDetail();
//
//                    }
//
//
//                } else if (row_action.length() > 1) {
//
//                    ArrayList<String> titleList = new ArrayList<>();
//
//                    for (int i = 0; i < row_action.length(); i++) {
//                        JSONObject json = row_action.getJSONObject(i);
//                        String title = json.getString("title");
//                        titleList.add(title);
//                    }
//
//                    new AlertDialog.Builder(mContext)
//                            .setSingleChoiceItems((String[])titleList.toArray(new String[titleList.size()]), -1, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                    try {
//                                        JSONArray content_action = resultData.getJSONArray("row_action");
//                                        JSONObject json = content_action.getJSONObject(which);
//                                        String module = json.getString("module");
//                                        JSONObject add_params = json.getJSONObject("params");
//
//                                        if (module.equals("quick_look")) {
//                                            JSONObject param = json.getJSONObject("params");
//                                            String url = json.getString("url");
//                                            showQuickLook(param,url);
//                                        } else if (module.equals("kv_detail")) {
//
//                                            JSONObject params = json.getJSONObject("params");
//                                            showKVDetail(params);
//
//                                        } else if (module.equals("order_detail")) {
//
//                                            showOrderDetail();
//
//                                        }
//
//
//                                    } catch (JSONException exception) {
//                                        Log.d("Result", "onClick: ",exception);
//                                    }
//                                    dialog.dismiss();
//
//                                }
//                            })
//                            .show();
//
//                }
//
//            }
//
//        } catch (JSONException exception) {
//            Log.e("Result", "onDoubleTapEvent: ",exception);
//        }
    }

    void setMargin(View view,int l,int t,int r,int b) {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(view.getLayoutParams());
        lp.setMargins(l, t, r, b);
        view.setLayoutParams(lp);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (progressDialog != null) {
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);

        instance = this;
        mContext = this;
        footer_height = dp2px(this,30);
        header_height = dp2px(this,60);

        resultListView = (PullRefreshListView) findViewById(R.id.result_table_list);
        resultSwipe = findViewById(R.id.result_swipe);

        progressDialog = new ProgressDialog(mContext);
        progressDialog.setCancelable(false);

        initClickListener();


        adapter = new ResultAdapter(mContext);
        resultListView.setAdapter(adapter);
        resultListView.setDividerHeight(0);

        // refresh header & footer
        list_footer = View.inflate(this, R.layout.refresh_footer, null);
        resultListView.setRefreshFooter(list_footer);

        refresh_footer = findViewById(R.id.result_refresh_footer);
        refresh_footer.bringToFront();

        resultListView.setOnRefreshListener(new PullRefreshListView.OnRefreshListener() {
            @Override
            public void onHeaderStateChange(int state, int offset) {
                Log.d("Pull Down", "onHeaderStateChange: " + offset);
//                setMargin(refresh_header,0,offset,0,0);
//                if (state == PullRefreshListView.REFRESHING) {
//                   loadData();
//                }
            }

            @Override
            public void onFooterStateChange(int state, int offset) {

                setMargin(refresh_footer,0,resultListView.getHeight() - offset,0,0);
                if (state == PullRefreshListView.REFRESHING) {
                    if (!isLoading) {
                        loadMore();
                    }
                }
            }

            @Override
            public void shouldPullDownToRefresh(boolean should) {
                resultSwipe.setEnabled(should);
            }
        });

        resultSwipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (isLoading) {
                    resultSwipe.setRefreshing(false);
                } else {
                    loadData();
                }
            }
        });



        if (savedInstanceState != null) {
            mParams = savedInstanceState.getBundle("query_params");
        } else {
            mParams = getIntent().getBundleExtra("query_params");
        }

        if (mParams == null) {
            mParams = new Bundle();
        }

        String title = mParams.getString("title");
        setTitle(title);

        loadData();

    }

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

        outState.putBundle("query_params",mParams);
    }

    // 动态修改Menu
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.clear();


//        if (resultData != null) {
//            try {
//                JSONArray menu_json = resultData.getJSONArray("menu");
//
//                if (menu_json != null && menu_json.length() > 0) {
//
//                    for (int i = 0; i < menu_json.length(); i++) {
//                        JSONObject json = menu_json.getJSONObject(i);
//                        String title = json.getString("title");
//                        menu.add(0, i, 0, title);
//                    }
//                }
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//        }

        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {


//        int which = item.getItemId();
//        try {
//            JSONArray menu = resultData.getJSONArray("menu");
//            JSONObject json = menu.getJSONObject(which);
//
//            String actionType = json.getString("action");
//            String url = json.optString("url");
//
//            if (actionType.equals("download")) {
//                export(url);
//            } else if (actionType.equals("save")) {
//                if(BuildConfig.DEBUG && true){
//                    //do something for assert aim
//                    Log.e("Result", "onOptionsItemSelected DialogClick: not implement");
//                }
//            }
//
//        } catch (JSONException exception) {
//            Log.d("Result", "onClick: ",exception);
//        }

        return true;
    }


//    public int last_index;
//    public int total_index;
//
//    @Override
//    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
//        last_index = firstVisibleItem+visibleItemCount;
//        total_index = totalItemCount;
//    }
//
//    @Override
//    public void onScrollStateChanged(AbsListView view, int scrollState) {
//        if(last_index == total_index && (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE))
//        {
//            // 表示此时需要显示刷新视图界面进行新数据的加载(要等滑动停止)
//            if(!isLoading)
//            {
//                // 设置刷新界面可见
//                footer.setVisibility(View.VISIBLE);
//                loadMore();
//            }
//        }
//    }

    // 设置header 和 footer宽度，否则listView会显示默认宽度
    protected void setupUI() {
        try {
            if (resultData == null) {
                return;
            } else {
                int result = resultData.getInt("result");
                if (result != 2) {
                    return;
                }
            }
            JSONObject layout = resultData.getJSONObject("layout");

            JSONObject header = layout.getJSONObject("header");
            int width = header.getInt("width");
            width = convertDp2Px(width);

            AbsListView.LayoutParams footerLayoutParams = (AbsListView.LayoutParams)list_footer.getLayoutParams();
            if (footerLayoutParams == null) {
                footerLayoutParams = new AbsListView.LayoutParams(width,footer_height);
            }
            footerLayoutParams.height = footer_height;
            footerLayoutParams.width = width;
            list_footer.setLayoutParams(footerLayoutParams);


        } catch (JSONException e) {
            Log.e("Result", "setupUI: ", e);
        }

    }

    public void loadComplete() {

        setupUI();
        resultListView.completeRefresh();
        if (resultSwipe.isRefreshing()) {
            resultSwipe.setRefreshing(false);
        }
        resultListView.forceLayout();

        isLoading = false;//设置正在刷新标志位false
        invalidateOptionsMenu();

        String title = resultData.optString("table_title");
        setTitleColor(Color.BLACK);
        setTitle(title);

        progressDialog.dismiss();
    }


    protected void showProgressDialog(String title, String msg) {
        progressDialog.setTitle(title);
        progressDialog.setMessage(msg);
        progressDialog.show();
    }

    JSONObject readRawFile(int id)
    {
        String content;
        Resources resources=this.getResources();
        InputStream is=null;
        try{
            is=resources.openRawResource(id);
            byte buffer[]=new byte[is.available()];
            is.read(buffer);
            content=new String(buffer);
            JSONObject json = new JSONObject(content);
            return json;
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        finally
        {
            if(is!=null)
            {
                try{
                    is.close();
                }catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    protected void loadData() {

//        resultData = readRawFile(R.raw.predef_query);
//        if (1 == 1) {
//            return;
//        }

        if (isLoading) {
            return;
        }

        isLoading = true;

        showProgressDialog(null,"Loading");

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

                try {

                    mParams.putInt("offset",0);
                    mParams.putInt("limit",25);
                    JSONObject new_resultData = Network.query(mParams);

                    if (new_resultData != null) {
                        Iterator<String> iterator = new_resultData.keys();
                        while (iterator.hasNext()) {
                            String key = iterator.next();
                            Object value = new_resultData.get(key);
                            resultData.put(key,value);
                        }
                    }

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

                            loadComplete();
                            int result = resultData.optInt("result",0);
                            if (result == 2) {

                            } else {

                                String msg = resultData.optString("msg");
                                if (msg == null || msg.isEmpty()) {
                                    msg = "Sorry,some error occurred";
                                }

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

                            adapter.notifyDataSetChanged();
                        }
                    });

                } catch (Exception e) {
                    Log.e("Result", "onCreate: ",e);
                }




            }
        }).start();

    }

    protected void loadMore() {

        if (isLoading) {
            return;
        }

        isLoading = true;
        showProgressDialog(null,"Loading");

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

                try {

//                    Thread.sleep(2000);
//
//                    InputStream in = getResources().openRawResource( R.raw.result);
//                    int length = in.available();
//                    byte[] buffer = new byte[length];
//                    in.read(buffer);
//                    String res = new String(buffer,"utf8");
//                    in.close();
//
//                    JSONObject newJson = new JSONObject(res);

                    mParams.putInt("offset",adapter.getCount());
                    mParams.putInt("limit",25);
                    JSONObject newJson = Network.query(mParams);

                    if (newJson != null) {

                        int result = newJson.getInt("result");
                        if (result == 2) {
                            JSONObject newData = newJson.getJSONObject("data");
                            int add_count = newData.getInt("count");

                            JSONObject data = resultData.getJSONObject("data");
                            int count = data.getInt("count");

                            for (int i = 0; i < add_count; i++) {
                                JSONArray new_data_item = newData.getJSONArray("item_" + i);
                                if (new_data_item != null) {
                                    data.put("item_" + count++,new_data_item);
                                }
                            }
                            data.put("count",count);
                            resultData.put("data",data);

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

                                    loadComplete();
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        } else {
                            String msg = newJson.optString("msg");
                            if (msg == null || msg.isEmpty()) {
                                msg = "Some error occurred";
                            }
                            showAlert(msg);
                        }


                    }


                } catch (Exception e) {
                    Log.e("Result", "onCreate: ",e);
                    showAlert("Some error occurred");
                }




            }
        }).start();
    }

    protected JSONObject contentData() {
        try {
            return resultData.getJSONObject("data");
        } catch (JSONException e) {
            Log.e("Result", "contentData: ", e);
        }
        return null;
    }

    protected JSONArray contentMenu() {
        if (resultData != null) {
            try {
                JSONArray menu_json = resultData.getJSONArray("menu");
                return menu_json;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    protected JSONArray contentAction() {
        if (resultData != null) {
            try {
                JSONArray action_json = resultData.getJSONArray("row_action");
                return action_json;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    protected JSONObject contentLayout() {
        if (resultData != null) {
            try {
                JSONObject layout = resultData.getJSONObject("layout");
                return layout;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;

    }


    private class GestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {


            if (e.getAction() == MotionEvent.ACTION_UP) {

                TableRow cellRow = (TableRow)clickedView.getParent();
                RelativeLayout cell = (RelativeLayout)cellRow.getParent();

                int position = resultListView.getPositionForView(cell);
//                Log.d("Result", "onDoubleTapEvent: " + position);

                if (position == 0) {
                    return false;
                }

                cellDoubleTapAction(position);

            }

            return false;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if (clickedView instanceof TextView) {
                TextView tv = (TextView)clickedView;
                if (ellipsisTextView(tv)) {
                    showAlert(tv.getText().toString());
                }
            }
            return false;
        }
    }

    private int normalColor;
    private int touchColor = Color.GRAY;
    private void initClickListener() {

        // 需要作为成员变量
        detector = new GestureDetector(mContext, new GestureListener());

        resultRowClickListener = new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                TableRow cellRow = (TableRow)v.getParent();
                RelativeLayout cell = (RelativeLayout)cellRow.getParent();

                int position = resultListView.getPositionForView(cell);

                if (position == 0) {
                    return false;
                }


//                View cellRow = (View) v.getParent();
                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    if (clickedView != null) {
                        ((View)clickedView.getParent()).setBackgroundColor(normalColor);
                    }

                    normalColor = ((ColorDrawable)cellRow.getBackground()).getColor();
                    cellRow.setBackgroundColor(touchColor);

                } else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
//                    cell.setBackgroundColor(normalColor);
                }

                clickedView = v;

                detector.onTouchEvent(event);

                return true;
            }
        };

    }



    protected class ResultAdapter extends BaseAdapter {

        @Override
        public boolean areAllItemsEnabled() {
            return true;
        }

        @Override
        public boolean isEnabled(int position) {
            return true;
        }

        private class ResultHoder {
            public ResultHoder(View view) {
                row = (TableRow)view.findViewById(R.id.result_row);
                view.setTag(this);
            }
            TableRow row;
        }

        public ResultAdapter(Context ctx) {

        }

        @Override
        public void registerDataSetObserver(DataSetObserver observer) {
            super.registerDataSetObserver(observer);
        }

        @Override
        public void unregisterDataSetObserver(DataSetObserver observer) {
            super.unregisterDataSetObserver(observer);
        }

        @Override
        public int getCount() {
            if (resultData == null) {
                return 0;
            } else {
                int result = resultData.optInt("result");
                if (result != 2) {
                    return 0;
                }
            }
            try {
                JSONObject data = resultData.getJSONObject("data");
                int result_count = data.getInt("count");
                return result_count + 1; // header + data

            } catch (JSONException e) {
                Log.e("Result", "getCount: ", e);
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            try {
                if (position == 0) {
                    // header

                    JSONObject layout = resultData.getJSONObject("layout");
                    JSONObject header = layout.getJSONObject("header");
                    JSONArray col = header.getJSONArray("col");

                    return col;

                } else {
                    // result row

                    JSONObject data = resultData.getJSONObject("data");
                    JSONArray item = data.getJSONArray("item_" + (position - 1));

                    return item;
                }


            } catch (JSONException e) {
                Log.e("Result", "getItem: ", e);
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View cell;
            ResultHoder holder;
            if (convertView == null) {

                cell = LayoutInflater.from(mContext).inflate(R.layout.result_cell,null);
                holder = new ResultHoder(cell);


            } else {

                cell = convertView;
                holder = (ResultHoder)cell.getTag();

            }
//            holder.row.removeAllViews();

//            cell.setOnTouchListener(resultRowClickListener);

            holder.row.setBackgroundColor(Color.WHITE);
            // setup
           try {

               JSONObject layout = resultData.getJSONObject("layout");

               JSONObject header = layout.getJSONObject("header");
               int width = header.getInt("width");
               int height = header.getInt("height");
               int margin_t = header.getInt("margin_t");
               int margin_l = header.getInt("margin_l");
               int margin_b = header.getInt("margin_b");
               int margin_r = header.getInt("margin_r");

               width = convertDp2Px(width);
               height = convertDp2Px(height);
               margin_t = convertDp2Px(margin_t);
               margin_l = convertDp2Px(margin_l);
               margin_b = convertDp2Px(margin_b);
               margin_r = convertDp2Px(margin_r);


               HorizontalScrollView.LayoutParams listViewLayoutParams = (HorizontalScrollView.LayoutParams)resultListView.getLayoutParams();
               listViewLayoutParams.width = width;
               resultListView.setLayoutParams(listViewLayoutParams);



               JSONArray obj = (JSONArray)getItem(position);
               JSONArray arr_col = header.getJSONArray("col");

               if (position == 0) {

                   // header
                   String bg_color = header.getString("bg_color");
                   String f_color = header.getString("f_color");

                   if (!bg_color.contains("0x")) {
                       bg_color = "0x" + bg_color;
                   }
                   if (!f_color.contains("0x")) {
                       f_color = "0x" + f_color;
                   }
                   bg_color = bg_color.replace("0x","#");
                   f_color = f_color.replace("0x","#");

                   RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)holder.row.getLayoutParams();
                   layoutParams.height = height;
                   holder.row.setLayoutParams(layoutParams);

                   // 调整显示列后，需要删除多余的列
                   if (holder.row.getChildCount() > arr_col.length()) {
                       for (int i = arr_col.length(); i < holder.row.getChildCount(); i++) {
                           TextView tv = (TextView)holder.row.findViewById(i);
                           holder.row.removeView(tv);
                       }
                   }

                   // col
                   for (int i = 0; i < arr_col.length(); i++) {

                       JSONObject value = obj.getJSONObject(i);
                       int col_w = value.getInt("width");
                       col_w = convertDp2Px(col_w);

                       String h_align = value.getString("h_align");
                       String v_center = value.getString("v_center");
                       String col_bg_color = value.getString("bg_color");
                       String col_f_color = value.getString("f_color");
                       String name = value.getString("name");


                       bg_color = bg_color.replace("0x","#");
                       f_color = f_color.replace("0x","#");

                       TextView tv = (TextView)holder.row.findViewById(i);
                       if (tv == null) {
                           tv = new TextView(mContext);

                           tv.setGravity(convertGravity("h_align",h_align) | convertGravity("v_center",v_center));
                           tv.setSingleLine();
                           tv.setEllipsize(TextUtils.TruncateAt.END);
                           tv.setId(i);
                           tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.result_black_border));
                           tv.setOnTouchListener(resultRowClickListener);
                       } else {
                           holder.row.removeView(tv);
                       }

                       // layout
                       tv.setWidth(col_w);
                       tv.setHeight(height);
                       tv.setPadding(margin_l,margin_t,margin_r,margin_b);

                       TableRow.LayoutParams tvLayoutParams = new  TableRow.LayoutParams(col_w, height);

                       holder.row.addView(tv,i,tvLayoutParams);

                       // content
                       tv.setTextColor(Color.parseColor(f_color));
                       tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,14);
                       tv.getPaint().setFakeBoldText(true);

                       if (name.contains("</")) {
                           tv.setText(Html.fromHtml(name));
                       } else {
                           tv.setText(name);
                       }

                   }
                   holder.row.setBackgroundColor(Color.parseColor(bg_color));

               } else {

                   // row
                   JSONObject row = layout.getJSONObject("row");
                   String f_color = row.getString("f_color");
                   String color_0 = row.getString("color_0");
                   String color_1 = row.getString("color_1");

                   if (!f_color.contains("0x")) {
                       f_color = "0x" + f_color;
                   }
                   if (!color_0.contains("0x")) {
                       color_0 = "0x" + color_0;
                   }
                   if (!color_1.contains("0x")) {
                       color_1 = "0x" + color_1;
                   }


                   f_color = f_color.replace("0x","#");
                   color_0 = color_0.replace("0x","#");
                   color_1 = color_1.replace("0x","#");

                   int row_h = row.getInt("height");
                   row_h = convertDp2Px(row_h);

                   RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)holder.row.getLayoutParams();
                   layoutParams.height = row_h;
                   holder.row.setLayoutParams(layoutParams);

                   // 调整显示列后，需要删除多余的列
                   if (holder.row.getChildCount() > arr_col.length()) {
                       for (int i = arr_col.length(); i < holder.row.getChildCount(); i++) {
                           TextView tv = (TextView)holder.row.findViewById(i);
                           holder.row.removeView(tv);
                       }
                   }

                   // col
                   for (int i = 0; i < arr_col.length(); i++) {

                       JSONArray col_layout = row.getJSONArray("val");
                       JSONObject layout_val = col_layout.getJSONObject(i);

                       String type = layout_val.getString("type");
                       String h_align = layout_val.getString("h_align");
                       String v_center = layout_val.getString("v_center");
                       String col_bg_color = layout_val.getString("bg_color");
                       String col_f_color = layout_val.getString("f_color");

                       col_bg_color = col_bg_color.replace("0x","#");
                       col_f_color = col_f_color.replace("0x","#");

                       String value = obj.getString(i);


                       JSONObject size = ((JSONArray)getItem(0)).getJSONObject(i);
                       int col_w = size.getInt("width");
                       int col_h = row.getInt("height");

                       col_w = convertDp2Px(col_w);
                       col_h = convertDp2Px(col_h);

                       TextView tv = (TextView) holder.row.findViewById(i);
                       if (tv == null) {
                           tv = new TextView(mContext);

                           tv.setGravity(convertGravity("h_align",h_align) | convertGravity("v_center",v_center));
                           tv.setSingleLine();
                           tv.setEllipsize(TextUtils.TruncateAt.END);
                           tv.setId(i);
                           tv.setOnTouchListener(resultRowClickListener);
                           tv.setBackgroundDrawable(getResources().getDrawable(R.drawable.result_black_border));
                       } else {
                           holder.row.removeView(tv);
                       }

                       // layout
                       tv.setWidth(col_w);
                       tv.setHeight(col_h);
                       tv.setPadding(margin_l,margin_t,margin_r,margin_b);

                       TableRow.LayoutParams tvLayoutParams = new  TableRow.LayoutParams(col_w, col_h);
                       holder.row.addView(tv,i,tvLayoutParams);

                       // content

                       tv.setTextColor(Color.parseColor(f_color));
                       tv.setTextSize(TypedValue.COMPLEX_UNIT_SP,12);
                       tv.getPaint().setFakeBoldText(false);
                       tv.setText(Html.fromHtml(value));
//                       if (value.contains("</")) {
//                           tv.setText(Html.fromHtml(value));
//                       } else {
//                           tv.setText(value);
//                       }


                   }

                   if ((position - 1) % 2 == 0) {
                       holder.row.setBackgroundColor(Color.parseColor(color_0));
                   } else {
                       holder.row.setBackgroundColor(Color.parseColor(color_1));

                   }
               }

           } catch (JSONException e) {
               Log.e("Result", "getView: ", e);
           }

            return cell;
        }

        private int convertGravity(String key, String align) {

            if (key.equals("h_align")) {
                if (align.equals("center")) {
                    return Gravity.CENTER_HORIZONTAL;
                } else if (align.equals("left")) {
                    return Gravity.LEFT;
                } else if (align.equals("right")) {
                    return Gravity.RIGHT;
                }

            }

            if (key.equals("v_center")) {

                if (align.equals("center")) {
                    return Gravity.CENTER_VERTICAL;
                } else if (align.equals("top")) {
                    return Gravity.TOP;
                } else if (align.equals("bottom")) {
                    return Gravity.BOTTOM;
                }
            }
            return Gravity.CENTER;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public boolean isEmpty() {
            return false;
        }
    }


    public boolean ellipsisTextView(TextView tv) {
        Layout l = tv.getLayout();
        if ( l != null){
            int lines = l.getLineCount();
            if ( lines > 0) {
                if (l.getEllipsisCount(lines - 1) > 0) {
                    return true;
                }
            }
        }
        return false;
    }

    public int convertDp2Px(int dp) {
        return dp2px(mContext,dp);
    }

    public int px2dp(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public int dp2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public int px2sp(Context context, float pxValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    public int sp2px(Context context, float spValue) {
        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    protected String documentPath;
    protected String download_query;
    protected void export(final String download_url) {

        if (download_query != null) {
            documentPath = download_query;
            openFile(new File(download_query));
            return;
        }

        showProgressDialog(null,"Please wait");
        new Thread(new Runnable() {
            @Override
            public void run() {

                String cacheDir = ApexTrackingApplication.getInstance().getDocumentDir();
                // download & get path
                final File downloadFile = Network.download_query(download_url,cacheDir);
                final String path = downloadFile != null && downloadFile.exists() ? downloadFile.getPath() : null;



                documentPath = path;
                download_query = path;


                if (path != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.dismiss();
                            openFile(downloadFile);
                        }
                    });
                }

            }
        }).start();

    }

    public void showAlert(final String msg) {
        if (msg == null || msg.isEmpty()) {
            return;
        }

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(mContext)
                        .setMessage(msg)
                        .show();
            }
        });
    }

    public void showOrderDetail() {
//        Intent intent = OrderDetailActivity.build(mContext,OrderDetailActivity.class,null,URL_REMOTE,null,new Bundle());
//
//        startActivity(intent);
    }

    public void showKVDetail(final JSONObject param) {
//        showProgressDialog("Please wait","Loading...");
//
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                final JSONObject json = Network.kv_detail(RAUtil.Json2Bundle(param));
////                final JSONObject json = readRawFile(R.raw.kv);
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        progressDialog.dismiss();
//
//                        int result = 0;
//                        if (json != null) {
//                            result = json.optInt("result",0);
//                        }
//                        if (result == 2) {
//
//                            Intent intent = KVDetailActivity.build(mContext,json.toString());
//
//                            startActivity(intent);
//
//                        } else {
//                            String msg = json.optString("msg");
//                            if (msg == null) {
//                                msg = "Sorry,some error occurred";
//                            }
//                            showAlert(msg);
//                        }
//
//                    }
//                });
//
//            }
//        }).start();

    }

    public void showQuickLook(final JSONObject param, final String url) {

        showProgressDialog("Please wait","Downloading...");
        new Thread(new Runnable() {
            @Override
            public void run() {

                String cacheDir = ApexTrackingApplication.getInstance().getDocumentDir();
                // 下载文件
                final File downloadFile = Network.downloadFile(RAUtil.Json2Bundle(param),url,cacheDir);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        if (downloadFile != null && downloadFile.exists()) {
//                            try {
//                                //此处需要新增保存文档的本地表
//                                param;
////                                String email=param.getString("email");
////                                String email_subject=param.getString("email_subject");
////                                String email_content=param.getString("email_content");
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
                            openFile(downloadFile);
                        } else {
                            showAlert("Sorry,there is a wrong.");
                        }
                    }
                });

            }
        }).start();


    }

    protected void openFile(File file) {

        if (file == null || !file.exists()) {
            return;
        }

        Uri uri = null;
        String type = RAUtil.getMimeType(file.getPath());

        // type "application/pdf"
        Intent intent = new Intent(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            // "com.usai.apex.fileprovider"即是在Manifest文件中配置的authorities
            uri = FileProvider.getUriForFile(mContext, "com.usai.apex.fileprovider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }

        intent.setDataAndType(uri, type);

        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            // someone knows how to handle this mime type with this scheme, don't download.
            try {
                startActivity(intent);
                return;
            } catch (Exception ex) {
                Log.d("Open File", "activity not found for " + type + " over " + uri, ex);
            }

        } else {
            Log.d("Open File", "openFileAtPath: " + "No App " + uri);
            try {
                shareFile(uri,type);
            } catch (Exception e) {
                Log.e("Show Dialog Error", "openFileAtPath: ", e);
            }
        }

    }

    protected void shareFile(Uri uri, String type) {

        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.setType(type);
        startActivity(Intent.createChooser(shareIntent, "Share"));
    }


}
