package com.usai.apex.Result;

import android.app.Dialog;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.CustomizeFieldsActivity;
import com.usai.apex.DetailActivity;
import com.usai.apex.R;
import com.usai.apex.pdf.PDFPreviewActivity;
import com.usai.util.Network;
import com.usai.util.RAUtil;
import com.usai.util.dbUtil;

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

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by macmini1 on 2018/2/23.
 */

public class AMResultActivity extends SearchResultActivity {
    TextView mtitleview;
    private static int REQUEST_FIELD_SETTING = 1000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setCustomActionBar();

    }
    private void setCustomActionBar() {
        ActionBar.LayoutParams lp =new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        View mActionBarView = LayoutInflater.from(this).inflate(R.layout.actionbar_customtitle, null);

        mtitleview= mActionBarView.findViewById(R.id.title);
        String title = mParams.getString("title");
        mtitleview.setText(title);
        setTitle(title);
//
//        mActionBarView.setBackgroundColor(Color.YELLOW);
//        titleview.setBackgroundColor(Color.BLUE);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setCustomView(mActionBarView, lp);
//        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);


//        actionBar.setIcon(getNumberDrawable());
//        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
    }
//    @Override
//    public void setTitle(CharSequence title) {
////        View mActionBarView = LayoutInflater.from(this).inflate(R.layout.actionbar_customtitle, null);
////
////        TextView mtitleviewtitleview = mActionBarView.findViewById(R.id.title);
//
//        if(title==null)
//            title="";
//        if(mtitleview!=null)
//            mtitleview.setText(title);
//    }
    @Override
    protected void loadData() {
        if (mParams.getString("columns") == null) {
            ArrayList<String> header_name = new ArrayList<String>();
            ArrayList<String> header_aname = new ArrayList<String>();
            getHeader(header_name, header_aname);
            String fields = "";
            Iterator<String> iterator = header_name.iterator();
            while (iterator.hasNext()) {
                String name = iterator.next();
                fields = fields + name + ",";
            }
            if (fields.length() > 0) {
                fields = fields.substring(0, fields.length() - 1);
            }
            mParams.putString("columns", fields);
        }
        super.loadData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

//        resultListView.setAdapter(adapter);
//
//        Iterator<String> keyIterator = resultData.keys();
//        ArrayList<String> keys = new ArrayList<>();
//        while (keyIterator.hasNext()) {
//            String key = keyIterator.next();
//            keys.add(key);
//        }
//        for (int i = 0; i < keys.size(); i++) {
//            String key = keys.get(i);
//            resultData.remove(key);
//        }
//
//        adapter.notifyDataSetChanged();

        if (requestCode == REQUEST_FIELD_SETTING) {

            ArrayList<String> header_name = new ArrayList<String>();
            ArrayList<String> header_aname = new ArrayList<String>();
            getHeader(header_name,header_aname);
            String fields = "";
            Iterator<String> iterator = header_name.iterator();
            while (iterator.hasNext()) {
                String name = iterator.next();
                fields = fields + name + ",";
            }
            fields = fields.substring(0,fields.length() - 1);
            mParams.putString("columns",fields);


            loadData();

        }

    }

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


        if (resultData != null && resultData.length() > 0) {
            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();

        switch (item.getItemId())
        {

            case android.R.id.home:
                finish();
                break;
            default:
            {
                try {
                    JSONArray menu = resultData.getJSONArray("menu");
                    JSONObject json = menu.getJSONObject(which);

                    String actionType = json.getString("action");
                    String url = json.optString("url");



                    if (actionType.equals("field_setting")) {

                        fieldSetting();
                    } else if (actionType.equals("save")) {

                        save();
                    } else if (actionType.equals("download")) {

                        export(url);
                    }

                } catch (JSONException exception) {
                    Log.d("Result", "onClick: ",exception);
                }
            }
        }



        return true;
    }


    @Override
    public void cellDoubleTapAction(final int position) {

        final JSONArray content_action = contentAction();
        if (content_action != null) {

            try {
                if (content_action.length() == 1) {

                    JSONObject action = content_action.getJSONObject(0);
                    String module = action.getString("module");

                    if (module.equals("quick_look")) {

                        showQuickLookForPosition(position,action);

                    } else if (module.equals("detail")) {

                        showDetailForPosition(position);
                    }


                } else if (content_action.length() > 1) {

                    ArrayList<String> titleList = new ArrayList<>();

                    for (int i = 0; i < content_action.length(); i++) {
                        JSONObject json = content_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 {

                                        JSONObject json = content_action.getJSONObject(which);
                                        String module = json.getString("module");

                                        if (module.equals("quick_look")) {

                                            showQuickLookForPosition(position,json);
                                        } else if (module.equals("detail")) {

                                            showDetailForPosition(position);
                                        }


                                    } catch (JSONException exception) {
                                        Log.d("Result", "onClick: ",exception);
                                    }
                                    dialog.dismiss();

                                }
                            })
                            .show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

    public void showDetailForPosition(final int position) {

        ArrayList<String> actions = getActions();
        if (actions.size() < 1) {
            return;
        }

        try {
            JSONArray arr_col = contentLayout().getJSONObject("header").getJSONArray("col");
            JSONArray item = contentData().getJSONArray("item_" + (position - 1));

            String module_name = mParams.getString("module_name");
            String detail_id = item.getString(arr_col.length());

            Intent intent = new Intent(mContext, DetailActivity.class);
            intent.putExtra("function_name", module_name);
            intent.putExtra("actions_count", actions.size());
            intent.putExtra("_id",detail_id);

            Iterator<String> iterator = actions.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                String name = iterator.next();
                intent.putExtra("action" + i++, name);
            }
            startActivity(intent);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    @Override
    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().getExternalCacheDir().getAbsolutePath();//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()) {
                            String email = null,email_subject = null,email_content = null;
                            try {
                                //此处需要新增保存文档的本地表

                                email=param.getString("email");
                                email_subject=param.getString("email_subject");
                                email_content=param.getString("email_content");

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            previewPDF(downloadFile.getAbsolutePath(),email,email_subject,email_content);
                        } else {
                            showAlert("Sorry,there is a wrong.");
                        }
                    }
                });

            }
        }).start();


    }
    public void showQuickLookForPosition(final int position,JSONObject action) {

        try {

            JSONObject params = new JSONObject();
            Iterator<String> iterator = action.getJSONObject("params").keys();
            while (iterator.hasNext()) {
                String key = iterator.next();
                JSONArray item = contentData().getJSONArray("item_" + (position - 1));
                int idx = action.getJSONObject("params").getInt(key);
                params.put(key,item.get(idx));
            }

            String url = action.getString("url");
//            String module_name = mParams.getString("module_name");

            showQuickLook(params,url);
//            downloaddoc(url);

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    protected void previewPDF(String file,String email,String subject,String content) {
        Intent myIntent = new Intent();
        myIntent = new Intent(AMResultActivity.this, PDFPreviewActivity.class);

        myIntent.putExtra("file",file);
        myIntent.putExtra("iscache",true);

        try {
            JSONObject json = new JSONObject();
//            email = "66666@qq.com";
//            subject = "test subject";
//            content = "test body";
            if (email != null) {
                json.put("email",email);
            }
            if (subject != null) {
                json.put("subject",subject);
            }
            if (content != null) {
                json.put("content",content);
            }
            myIntent.putExtra("email",json.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }


        startActivity(myIntent);
    }

    private void downloaddoc(String url)
    {

            // if (true)
            // return;
//            URLSpan span[] = ((TextView) v).getUrls();
//            if (span.length < 1)
//                return;
//            span[0].getURL();
//            Log.d("Text", span[0].getURL());
//
//            TextView tv = (TextView)v;

            final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

            Uri uri = Uri.parse(url);
            final DownloadManager.Request request = new DownloadManager.Request(uri);

            // 设置允许使用的网络类型，这里是移动网络和wifi都可以
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                    | DownloadManager.Request.NETWORK_WIFI);

            request.setDestinationInExternalPublicDir("Apex Mobile",url);

            // 禁止发出通知，既后台下载，如果要使用这一句必须声明一个权限：android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
            // request.setShowRunningNotification(false);

            // 不显示下载界面
            request.setVisibleInDownloadsUi(false);
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

							/*
							 * 设置下载后文件存放的位置,如果sdcard不可用，那么设置这个将报错，
							 * 因此最好不设置如果sdcard可用，下载后的文件 在/mnt/sdcard/Android/
							 * data/packageName/files目录下面
							 * ，如果sdcard不可用,设置了下面这个将报错，不设置，下载后的文件在/cache这个 目录下面
							 */
            // request.setDestinationInExternalFilesDir(this,
            // null, "tar.apk");

            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(
                    AMResultActivity.this);
            builder.setMessage(getString(R.string.str_downloadmessage));

            builder.setTitle(getString(R.string.str_confirmdownload));

            builder.setPositiveButton(
                    getString(R.string.str_download),
                    new Dialog.OnClickListener()
                    {

                        @Override
                        public void onClick(
                                DialogInterface dialog,
                                int which)
                        {
                            downloadManager.enqueue(request);
                            dialog.dismiss();

                        }
                    });

            builder.setNegativeButton(
                    getString(R.string.str_cancel),
                    new Dialog.OnClickListener()
                    {

                        @Override
                        public void onClick(
                                DialogInterface dialog,
                                int which)
                        {
                            dialog.dismiss();
                        }
                    });

            builder.create().show();


    }

    public void getHeader(ArrayList<String> header_name, ArrayList<String> header_aname) {

        String module_name = mParams.getString("module_name");
        String user = ApexTrackingApplication.get_user();

        SQLiteDatabase db = dbUtil.OpenDB(this, null, false);
        Cursor cursor = db.query("fields_info", new String[] { "aname", "name",
                "_id" }, "function_name='" + module_name + "' and user='"
                + user + "' and behavior=" + Network.BEHAVIOR_RESULT
                + " and show = 1", null, null, null, "priority , aname", null);
        while (cursor.moveToNext())
        {
            String aname = cursor.getString(0);
            String name = cursor.getString(1);

            header_name.add(name);
            header_aname.add(aname);
        }
        dbUtil.CloseCursor(cursor);
        dbUtil.CloseDB(db);
    }

    public ArrayList<String> getActions() {

        String module_name = mParams.getString("module_name");

        SQLiteDatabase db = dbUtil.OpenDB(this, null, false);
        Cursor cursor = db.query("actions_info",
                new String[] { "name" }, "function_name='"
                        + module_name + "' and user='" + ApexTrackingApplication.get_user() + "'", null,
                null, null, "priority", null);

        ArrayList<String> actions = new ArrayList<>();

        while (cursor.moveToNext())
        {
            String name = cursor.getString(0);
            actions.add(name);
        }
        dbUtil.CloseCursor(cursor);
        dbUtil.CloseDB(db);

        return actions;

    }

    public void save() {

        final View edit = new EditText(this);
        new android.app.AlertDialog.Builder(this)
                .setIconAttribute(android.R.attr.alertDialogIcon)
                .setTitle(R.string.str_createname)
                .setView(edit)
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog,
                                                int whichButton)
                            {
                                String name = ((EditText) edit)
                                        .getText().toString();

                                if(TextUtils.isEmpty(name))
                                {
                                    new android.app.AlertDialog.Builder(AMResultActivity.this)
                                            .setTitle("Warning")
                                            .setMessage("Name can not be empty.")

                                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {

                                                }
                                            })
                                            .show();
                                    return;
                                }

                                String param = getIntent().toUri(0);

                                JSONObject obj = new JSONObject();
                                Set<String> keys = mParams.keySet();
                                for (String key : keys)
                                {


                                    try
                                    {
                                        obj.put(key, mParams.get(key).toString());

                                    }
                                    catch (JSONException e)
                                    {
                                        // TODO Auto-generated catch block
                                        e.printStackTrace();
                                    }

                                }
                                obj.toString();

                                SQLiteDatabase db = dbUtil.OpenDB(
                                        ApexTrackingApplication.get_instance(), null, true);
                                db.execSQL("insert into history(params,name,criterion,module_name,user,create_time) values('"

                                        + param
                                        + "','"
                                        + name
                                        + "','"
                                        + obj.toString()
                                        + "','"
                                        + mParams.getString("module_name")
                                        + "','"
                                        + ApexTrackingApplication.get_user()
                                        + "',"
                                        + System.currentTimeMillis() + ")");
                                dbUtil.CloseDB(db);

										/* User clicked OK so do some stuff */
                            }
                        })
                .setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener()
                        {
                            public void onClick(DialogInterface dialog,
                                                int whichButton)
                            {

										/* User clicked cancel so do some stuff */
                            }
                        }).create().show();
    }

    public void fieldSetting() {

        Intent intent = new Intent();
        intent.setClass(this, CustomizeFieldsActivity.class);
        intent.putExtra("user", ApexTrackingApplication.get_user());
        intent.putExtra("function_name", mParams.getString("module_name"));
        intent.putExtra("behavior", Network.BEHAVIOR_RESULT);
        startActivityForResult(intent,REQUEST_FIELD_SETTING);

    }

}
