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

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.lcp.arecyclerview.widget.ARecycleView;
import com.mgq.base.utils.logger.LogRecorder;
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.adapter.LogFilesAdapter;
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.crashHandler.CrashHandler;
import com.tofly.ghrq_route.common.util.date.DateUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

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

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

public class UiLogUpload extends BaseUi {
    @BindView(R.id.text_date_selected)
    TextView textDateSelected;
    @BindView(R.id.layout_date_picker)
    LinearLayout layoutDatePicker;
    @BindView(R.id.recycler_view)
    ARecycleView recyclerView;

    private LogFilesAdapter logFilesAdapter;

    private String mDatePicked;

    private List<String> logFiles = null;

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

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

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

    private void initView(){

    }

    private void initData(){
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        /*获取今天所有的日志文件*/
        String today = DateUtils.getYMD();
        getLogFiles(today);
    }

    private void initListener(){

    }

    private void getLogFiles(String date){
        mDatePicked = date;
        textDateSelected.setText(date);

        if (logFiles == null)
            logFiles = new ArrayList<>();
        else
            logFiles.clear();

        UserBean userBean = BaseApp.getInstance().getLoginUser();
        if (userBean != null){
            String userid = userBean.getUserid();
            /*当天的轨迹日志路径*/
            String amapLogFile = LogRecorder.getAmapLogPath(this, userid, date);
            File file = new File(amapLogFile);
            if (file.exists())
                logFiles.add(amapLogFile);

            /*当天的轨迹日志路径*/
            String deviceLogFile = LogRecorder.getDeviceLogPath(this, userid, date);
            file = new File(deviceLogFile);
            if (file.exists())
                logFiles.add(deviceLogFile);

            /*当天的崩溃日志文件路径*/
            List<String> crashFiles = CrashHandler.getCrashLogByDay(userid, date);
            if (crashFiles != null && crashFiles.size() > 0){
                logFiles.addAll(crashFiles);
            }
        }

        setDateAdapter();
    }

    private void setDateAdapter(){
        if (logFiles != null){
            if (logFilesAdapter == null){
                logFilesAdapter = new LogFilesAdapter(this, logFiles);
                recyclerView.setAdapter(logFilesAdapter);
            }else {
                logFilesAdapter.setData(logFiles);
            }
            logFilesAdapter.allSelected();

        }
    }

    private void showDatePickerDialog() {
        String date = textDateSelected.getText().toString();
        if (!date.isEmpty()) {
            int[] dateArray = DateUtils.getYMDArray(date, "-");
            int year = dateArray[0];
            int month = dateArray[1];
            int day = dateArray[2];
            DatePickerDialog datePickerDialog = new DatePickerDialog(this, android.R.style.Widget_Material_DatePicker, (view, year1, monthOfYear, dayOfMonth) -> {
                GregorianCalendar dateSet = new GregorianCalendar(year1, monthOfYear, dayOfMonth);
                String ymd = DateUtils.getYMD(dateSet.getTime().getTime());
                if (!ymd.isEmpty() && !mDatePicked.equals(ymd)) {
                    getLogFiles(ymd);
                }
            }, year, month, day);
            DatePicker datePicker = datePickerDialog.getDatePicker();
            datePicker.setMaxDate(new Date().getTime());
            String strMinDate = DateUtils.getDaysAgoYMD(BaseApp.LOG_SAVED_DAY_MAX);
            long mindate = DateUtils.getTimeFromYMD(strMinDate);
            datePicker.setMinDate(mindate);
            datePickerDialog.show();
        }
    }

    private boolean isValid(){
        boolean hasFile = false;

        if (logFilesAdapter != null){
            int count = logFilesAdapter.getSelectedPositionSet().size();
            if (count > 0)
                hasFile = true;
        }

        if (!hasFile){
            toast("没有需要上传的日志文件！");
            return false;
        }
        return true;
    }

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

        List<String> files = logFilesAdapter.getSelectFiles();

        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 showAlertDialog() {
        String title = "日志上传";
        String content = "是否上传日志信息?";
        showAlertDialog(title, content, (dialog, which) -> uploadLogFiles());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_commit, menu);
        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.layout_date_picker})
    public void onClick(View view) {
        if (view.getId() == R.id.layout_date_picker) {
            showDatePickerDialog();
        }
    }

}
