package com.stm.asset.page;

import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;

import com.stm.asset.R;
import com.stm.asset.adapter.AdvantageAdapter;
import com.stm.asset.base.BaseActivity;
import com.stm.asset.base.ConfigKey;
import com.stm.asset.base.StmApplication;
import com.stm.asset.dao.InventoryInfoDao;
import com.stm.asset.database.InventoryInfoDatabase;
import com.stm.asset.model.InventoryInfo;
import com.stm.asset.utils.FileUtils;
import com.stm.asset.utils.StringUtils;
import com.stm.asset.utils.TimeUtil;
import com.stm.asset.utils.ViewUtil;
import com.stm.asset.view.CommonAlertDialog;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 待确认盘盈 页面
 */
public class AdvantageListActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout noneLayout;
    private AdvantageAdapter advantageAdapter;

    private InventoryInfoDao inventoryInfoDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_advantage_list);
        initView();
        try {
            InventoryInfoDatabase database = Room.databaseBuilder(this, InventoryInfoDatabase.class, "inventoryInfoDemo").build();
            inventoryInfoDao = database.inventoryInfoDao();

            loadData();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initView() {
        initTitle();
        titleTxt.setText("待确认盘盈");
        findViewById(R.id.common_title_back_layout).setOnClickListener(this);
        RecyclerView recyclerView = findViewById(R.id.advantage_data_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        advantageAdapter = new AdvantageAdapter(this);
        recyclerView.setAdapter(advantageAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, RecyclerView.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        noneLayout = findViewById(R.id.advantage_data_none_layout);
        Button saveBtn = findViewById(R.id.advantage_save_btn);
        saveBtn.setOnClickListener(this);
    }

    public void loadData() {
        StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
            @Override
            public void run() {
                if (inventoryInfoDao != null) {
                    List<InventoryInfo> inventoryInfoList = inventoryInfoDao.getUndoInventoryList();
                    StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                        @Override
                        public void run() {
                            advantageAdapter.setData(inventoryInfoList);
                            if (inventoryInfoList != null && inventoryInfoList.size() > 0) {
                                noneLayout.setVisibility(View.GONE);
                            } else {
                                noneLayout.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            }
        });
    }

    private void exportAdvantageData() {
        List<InventoryInfo> dataList = advantageAdapter.queryData();
        if (dataList != null && dataList.size() > 0) {
            StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                @Override
                public void run() {
                    String msg = "";
                    String filePath = FileUtils.getDateFilePath("盘盈数据" + TimeUtil.getCurrentDate() + ".txt");
                    if (!StringUtils.isEmptyOrNull(filePath)) {
                        OutputStream ops = null;
                        OutputStreamWriter outputStreamWriter = null;
                        BufferedWriter bufferedWriter = null;
                        try {
                            ops = new FileOutputStream(filePath);
                            outputStreamWriter = new OutputStreamWriter(ops, StandardCharsets.UTF_8);
                            bufferedWriter = new BufferedWriter(outputStreamWriter);
                            for (InventoryInfo info : dataList) {
                                bufferedWriter.write(info.getNumber() + "\r\n");
                                bufferedWriter.flush();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            msg = "导出异常";
                        } finally {
                            if (bufferedWriter != null) {
                                try {
                                    bufferedWriter.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (outputStreamWriter != null) {
                                try {
                                    outputStreamWriter.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                            if (ops != null) {
                                try {
                                    ops.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else {
                        msg = "导出异常：读取文件失败";
                    }
                    if (StringUtils.isEmptyOrNull(msg)) {
                        inventoryInfoDao.deleteInventoryList(dataList);
                        msg = "盘盈数据成功导出到" + filePath;
                    }
                    String finalMsg = msg;
                    StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                        @Override
                        public void run() {
                            if (finalMsg.startsWith("盘盈数据成功导出到")) {
                                advantageAdapter.setData(null);
                                noneLayout.setVisibility(View.VISIBLE);
                                showExportDialog(finalMsg);
                            } else {
                                StmApplication.getInstance().showToastShort(finalMsg);
                            }
                        }
                    });
                }
            });
        }
    }

    private void showExportDialog(String content) {
        int dialog_width = (int) (ViewUtil.getScreenWidth(this) * 4 / 5.0);
        final CommonAlertDialog dialog = new CommonAlertDialog(AdvantageListActivity.this);
        dialog.setViewParams(new LinearLayout.LayoutParams(dialog_width, -2));
        dialog.show();
        dialog.hideCancelBtn();
        dialog.setText("提示", content, "确定");
        dialog.setSureListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                sApp.setShowBackground(false);
                AdvantageListActivity.this.finish();
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back_layout:
                finish();
                break;
            case R.id.advantage_save_btn:
                int perRes = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
                int perRes2 = ActivityCompat.checkSelfPermission(this, "android.permission.READ_EXTERNAL_STORAGE");
                if (perRes == PackageManager.PERMISSION_DENIED || perRes2 == PackageManager.PERMISSION_DENIED) {
                    ActivityCompat.requestPermissions(this, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"}, ConfigKey.PERMISSION_REQUEST_EXTERNAL_STORAGE);
                } else {
                    exportAdvantageData();
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == ConfigKey.PERMISSION_REQUEST_EXTERNAL_STORAGE) {
            boolean sp = true;
            for (int grantResult : grantResults) {
                if (grantResult == PackageManager.PERMISSION_DENIED) {
                    sp = false;
                    break;
                }
            }
            if (sp) {
                exportAdvantageData();
            } else {
                StmApplication.getInstance().showToastShort("导出盘盈数据需要访问手机存储权限");
            }
        }
    }
}
