package com.tofly.ghrq_route.common.ui.activity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.widget.ListPopupWindow;

import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.view.DateTimePicker.CustomDatePicker;
import com.tofly.ghrq_route.module.deviceInfo.domain.DeviceInfoBean;
import com.tofly.ghrq_route.module.gps.domain.GPSDataBean;
import com.tofly.ghrq_route.module.gps.domain.LocationGPSDataBean;
import com.tofly.ghrq_route.module.plan.domain.OfflinePathBean;
import com.tofly.ghrq_route.module.sqlite.DBToExcelTool;
import com.tofly.ghrq_route.module.systemConfig.SystemConfigTool;
import com.tofly.ghrq_route.module.systemConfig.controller.ServerSysConfigCallBack;
import com.tofly.ghrq_route.module.user.domain.UserBean;
import com.tofly.ghrq_route.common.util.date.DateUtils;
import com.tofly.ghrq_route.common.util.file.FileSizeUtil;
import com.tofly.ghrq_route.common.util.file.IntentBuilder;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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

/**
 * Created by Amu on 2018/4/24.
 */

public class UiDatabaseExport extends BaseUi {
    @BindView(R.id.text_select_table)
    TextView textSelectState;
    @BindView(R.id.text_date_start)
    TextView textDateStart;
    @BindView(R.id.text_date_end)
    TextView textDateEnd;
    @BindView(R.id.layout_date_picker)
    LinearLayout layoutDatePicker;
    @BindView(R.id.btn_query_data)
    Button btnQueryData;
    @BindView(R.id.text_result)
    TextView textResult;
    @BindView(R.id.btn_export)
    TextView btnExport;
    @BindView(R.id.layout_export_file)
    LinearLayout layoutExportFile;
    @BindView(R.id.text_log_name)
    TextView textLogName;
    @BindView(R.id.text_log_date)
    TextView textLogDate;
    @BindView(R.id.text_log_size)
    TextView textLogSize;
    @BindView(R.id.btn_upload)
    TextView btnUpload;

    private int mTableIndex = 0;

    private static String[] tableNames = {"离线轨迹表", "本地轨迹表", "设备信息表", "离线巡检点表"};

    private CustomDatePicker datePickerStart, datePickerEnd;

    private DBToExcelTool dbToExcelTool;

    private ArrayList<ArrayList<String>> mQueryDatas;

    private static final Map<String, Class> tableClassMap = new HashMap<>();

    static {
        tableClassMap.put(tableNames[0], GPSDataBean.class);
        tableClassMap.put(tableNames[1], LocationGPSDataBean.class);
        tableClassMap.put(tableNames[2], DeviceInfoBean.class);
        tableClassMap.put(tableNames[3], OfflinePathBean.class);
    }

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

        setContentView(R.layout.ui_database_export);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    private void initView() {
        /*设置初始化第一个选中的表*/
        textSelectState.setText(tableNames[mTableIndex]);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR, -BaseApp.LOG_SAVED_DAY_MAX + 1);
        String minDate = sdf.format(instance.getTime());

        String now = sdf.format(new Date());
        datePickerStart = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                textDateStart.setText(time);
            }
        }, getResources().getString(R.string.database_export_dialog_start_title), minDate, now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        datePickerStart.showSpecificTime(true); // 显示时和分
        datePickerStart.setIsLoop(true); // 允许循环滚动

        instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_YEAR, -1);
        String oneDayAgo = sdf.format(instance.getTime());
        textDateStart.setText(oneDayAgo);

        textDateEnd.setText(now);

        datePickerEnd = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                textDateEnd.setText(time);
            }
        }, getResources().getString(R.string.database_export_dialog_end_title), minDate, now); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        datePickerEnd.showSpecificTime(true); // 显示时和分
        datePickerEnd.setIsLoop(true); // 允许循环滚动
    }

    private void initData() {
        dbToExcelTool = DBToExcelTool.getInstance();
    }

    private void initListener() {

    }

    private void startQueryData(){
        String strStart = textDateStart.getText().toString();
        String strEnd = textDateEnd.getText().toString();
        if (strStart == null || strStart.length() == 0) {
            toast("请选择开始时间");
            return;
        }
        if (strEnd == null || strEnd.length() == 0) {
            toast("请选择结束时间");
            return;
        }

        queryData(strStart, strEnd);
    }

    private void queryData(final String startTime, final String endTime){
        AsyncTask asyncTask = new AsyncTask() {
            @Override
            protected void onPreExecute() {
                String strUploading = getResources().getString(R.string.database_export_querying);
                ProgressManager.getInstance().showProgress(UiDatabaseExport.this, null, strUploading, false);
            }

            @Override
            protected Object doInBackground(Object[] params) {
                long result = -1;
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                if (userBean != null) {
                    String talbeName = tableNames[mTableIndex];
                    Class aclass = tableClassMap.get(talbeName);
                    if (aclass != null){
                        mQueryDatas = dbToExcelTool.getBillData(aclass, userBean.getUserid(), startTime, endTime);
                    }
                    result = 0;
                }
                return result;
            }

            @Override
            protected void onPostExecute(Object obj) {
                ProgressManager.getInstance().cancelProgress();

                long result = (long) obj;
                if (result == 0) {
                    if (mQueryDatas != null & mQueryDatas.size() > 0){
                        String strRes = String.format("查询结果：%d条数据", mQueryDatas.size());
                        textResult.setText(strRes);
                        btnExport.setVisibility(View.VISIBLE);
                    }else {
                        textResult.setText(getResources().getText(R.string.no_data));
                        btnExport.setVisibility(View.GONE);
                    }
                }else {
                    textResult.setText(getResources().getText(R.string.no_data));
                    btnExport.setVisibility(View.GONE);
                }
            }
        };
        asyncTask.execute();
    }

    private void showTableSelectPopupWindow(){
        final ListPopupWindow listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setAdapter(new ArrayAdapter<String>(this, R.layout.popup_content_item, tableNames));
        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mTableIndex = position;
                textSelectState.setText(tableNames[mTableIndex]);
                listPopupWindow.dismiss();
            }
        });
        listPopupWindow.setAnchorView(textSelectState);
        listPopupWindow.setVerticalOffset(5);
        listPopupWindow.setModal(true);
        listPopupWindow.show();
    }

    private boolean isValid() {
        boolean hasFile = false;

        if (mQueryDatas != null && mQueryDatas.size() > 0) {
            hasFile = true;
        }

        if (!hasFile) {
            toast("没有可以导出的数据文件！");
            return false;
        }
        return true;
    }

/*    private void showAlertDialog() {
        String title = "数据导出";
        String content = "是否导出数据库文件?";
        showAlertDialog(title, content, (dialog, which) -> exportDatabaseFile());
    }*/

    private String mDatabaseFile = null;
    private void exportDatabaseFile() {
        AsyncTask asyncTask = new AsyncTask() {
            @Override
            protected void onPreExecute() {
                String strUploading = getResources().getString(R.string.database_export_exporting);
                ProgressManager.getInstance().showProgress(UiDatabaseExport.this, null, strUploading, false);
            }

            @Override
            protected Object doInBackground(Object[] params) {
                long result = -1;
                UserBean userBean = BaseApp.getInstance().getLoginUser();
                if (userBean != null) {
                    final String userid = userBean.getUserid();
                    String strStart = textDateStart.getText().toString();
                    String strEnd = textDateEnd.getText().toString();
                    String talbeName = tableNames[mTableIndex];
                    Class aclass = tableClassMap.get(talbeName);
                    if (aclass != null){
                        mDatabaseFile = dbToExcelTool.createExcelFile(UiDatabaseExport.this, aclass, talbeName, userid, strStart, strEnd);
                        result = 0;
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(Object obj) {
                ProgressManager.getInstance().cancelProgress();

                long result = (long) obj;
                if (result == 0) {
                    showLogFile();
                    toast("导出成功，请在Route/log目录查看相关文件。");
                }else {
                    textResult.setText(getResources().getText(R.string.no_data));
                    layoutExportFile.setVisibility(View.GONE);
                    toast("导出失败。");
                }
            }
        };
        asyncTask.execute();
    }

    private void showLogFile() {
        if (mDatabaseFile != null && !mDatabaseFile.isEmpty()) {
            File file = new File(mDatabaseFile);
            if (file != null) {
                layoutExportFile.setVisibility(View.VISIBLE);

                /*文件名*/
                String fileName = file.getName();
                textLogName.setText(fileName);

                /*修改日期*/
                String date = DateUtils.getHMS(file.lastModified());
                textLogDate.setText(date);

                /*文件大小*/
                try {
                    long size = FileSizeUtil.getFileSize(file);
                    String fileSize = FileSizeUtil.FormetFileSize(size);
                    if (fileSize != null)
                        textLogSize.setText(fileSize);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                textLogName.setOnClickListener(v -> IntentBuilder.viewFile(this, mDatabaseFile));
            }
        }
    }

/*    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        MenuItem menuItem = menu.findItem(R.id.action_commit);
        menuItem.setTitle(getResources().getString(R.string.export));
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_commit) {
            if (isValid()) {
                showAlertDialog();
            }
        }
        return super.onOptionsItemSelected(item);
    }*/

    @OnClick({R.id.text_date_start, R.id.text_date_end, R.id.text_select_table, R.id.btn_query_data,
            R.id.btn_export, R.id.btn_upload})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_date_start: {
                // 日期格式为yyyy-MM-dd HH:mm
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                datePickerStart.show(now);
            }
            break;
            case R.id.text_date_end:{
                // 日期格式为yyyy-MM-dd HH:mm
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
                String now = sdf.format(new Date());
                datePickerEnd.show(now);
            }
            break;
            case R.id.text_select_table:{
                showTableSelectPopupWindow();
            }
            break;
            case R.id.btn_query_data:{
                startQueryData();
                layoutExportFile.setVisibility(View.GONE);
                mDatabaseFile = null;
            }
            break;
            case R.id.btn_export: {
                if (isValid()) {
                    exportDatabaseFile();
                }
            }
            break;
            case R.id.btn_upload: {
                showUploadAlertDialog();
            }
            break;
        }
    }

    private void uploadLogFiles(){
        String msg = getResources().getString(R.string.log_upload_uploading);
        ProgressManager.getInstance().showProgress(this, null, msg, false);

        List<String> files = new ArrayList<>();
        files.add(mDatabaseFile);

        SystemConfigTool systemConfigTool = SystemConfigTool.getInstance();
        systemConfigTool.uploadLocalSystemLogFiles(this, files, new ServerSysConfigCallBack() {
            @Override
            public void onUploadLocalSystemLogFiles(boolean isSuccess, int errorCode, String errMsg) {
                super.onUploadLocalSystemLogFiles(isSuccess, errorCode, errMsg);

                ProgressManager.getInstance().cancelProgress();
            }
        });
    }

    private void showUploadAlertDialog() {
        String title = "日志上传";
        String content = "是否上传日志文件?";
        showAlertDialog(title, content, (dialog, which) -> uploadLogFiles());
    }
}
