package com.stm.asset.page;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
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.seuic.uhf.EPC;
import com.seuic.uhf.UHFService;
import com.stm.asset.R;
import com.stm.asset.adapter.TaskListAdapter;
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.ViewUtil;
import com.stm.asset.view.CommonAlertDialog;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class TaskListActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout noneLayout;
    private Button beginBtn;

    private TaskListAdapter taskListAdapter;
    private UHFService uhfService;
    private boolean isInventory;
    private Thread inventoryThread;
    private InventoryRunnable inventoryRunnable;
    private InventoryInfoDao inventoryInfoDao;
    private String filePath;
    private String exportPath;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_task_list);
        initView();
        inventoryRunnable = new InventoryRunnable();
        try {
            InventoryInfoDatabase database = Room.databaseBuilder(this, InventoryInfoDatabase.class, "inventoryInfoDemo").build();
            inventoryInfoDao = database.inventoryInfoDao();
            uhfService = UHFService.getInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        uhfService.open();
    }

    @Override
    protected void onPause() {
        super.onPause();
        uhfService.close();
        isInventory = false;
    }

    private void initView() {
        initTitle();
        titleTxt.setText("盘点方案");
        findViewById(R.id.common_title_back_layout).setOnClickListener(this);
        RecyclerView recyclerView = findViewById(R.id.task_data_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        taskListAdapter = new TaskListAdapter(this);
        recyclerView.setAdapter(taskListAdapter);
        recyclerView.addItemDecoration(new DividerItemDecoration(this, RecyclerView.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        noneLayout = findViewById(R.id.task_data_none_layout);
        noneLayout.setVisibility(View.VISIBLE);
        noneLayout.setOnClickListener(this);
        beginBtn = findViewById(R.id.task_inventory_begin_btn);
        beginBtn.setOnClickListener(this);
        Button finishBtn = findViewById(R.id.task_inventory_finish_btn);
        finishBtn.setOnClickListener(this);
        Button saveBtn = findViewById(R.id.task_inventory_save_btn);
        saveBtn.setOnClickListener(this);
    }

    private void selectTaskFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType("text/plain");
        startActivityForResult(intent, ConfigKey.ACTIVITY_REQUEST_SELECT_TASK);
    }

    private void readTxtByLine(Uri uri) {
        InputStream ips = null;
        filePath = getFilePath(uri);
        List<InventoryInfo> infoList = new ArrayList<>();
        if (!StringUtils.isEmptyOrNull(filePath)) {
            try {
                ips = new FileInputStream(filePath);
                InputStreamReader inputStreamReader = new InputStreamReader(ips);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (!StringUtils.isEmptyOrNull(line)) {
                        String[] strArray = line.split("\\|");
                        if (strArray.length >= 13 && !StringUtils.isEmptyOrNull(strArray[0]) && !StringUtils.isEmptyOrNull(strArray[5]) && !StringUtils.isEmptyOrNull(strArray[6]) && strArray[6].length() % 4 == 0) {
                            InventoryInfo info = new InventoryInfo(strArray[5], strArray[6], strArray[0]);
                            infoList.add(info);
                        } else {
                            StmApplication.getInstance().showToastShort("length:" + strArray.length + "  number:" + strArray[6]);
                        }
                    }
                }
//                StmApplication.getInstance().showToastShort("filePath:" + filePath);
            } catch (Exception e) {
                e.printStackTrace();
                StmApplication.getInstance().showToastShort("Exception:" + e.getMessage());
            } finally {
                if (ips != null) {
                    try {
                        ips.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            if (infoList.size() > 0) {
                taskListAdapter.setData(infoList);
                noneLayout.setVisibility(View.GONE);
            } else {
                noneLayout.setVisibility(View.VISIBLE);
                StmApplication.getInstance().showToastShort("未读取到有效数据");
            }
        } else {
            StmApplication.getInstance().showToastShort("读取盘点任务文件失败");
        }
    }

    private String getFilePath(Uri uri) {
        String filePath = "";
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            filePath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme()) && uri.getAuthority() != null) {
            String authority = uri.getAuthority();
            if (authority.startsWith("com.android.externalstorage") && uri.getPath() != null) {
                filePath = Environment.getExternalStorageDirectory() + "/" + uri.getPath().split(":")[1];
            } else {
                String idStr = "";
                if (authority.equals("media")) {
                    idStr = uri.toString().substring(uri.toString().lastIndexOf('/') + 1);
                } else if (authority.startsWith("com.android.providers")) {
//                    idStr = DocumentsContract.getDocumentId(uri).split(":")[1];
                    String documentId = DocumentsContract.getDocumentId(uri);
                    idStr = (!StringUtils.isEmptyOrNull(documentId) && documentId.split(":").length > 1) ? documentId.split(":")[1].trim() : documentId;
                }
                ContentResolver contentResolver = this.getContentResolver();
                Cursor cursor = contentResolver.query(MediaStore.Files.getContentUri("external"), new String[] {MediaStore.Files.FileColumns.DATA}, "_id=?", new String[] {idStr}, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    try {
                        int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
                        filePath = cursor.getString(idx);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        cursor.close();
                    }
                }
            }
        }

        return filePath;
    }

    private String writeResultToTxt(List<InventoryInfo> resultList) {
        String resMsg = "";
        if (!StringUtils.isEmptyOrNull(filePath) && resultList != null && resultList.size() > 0) {
            InputStream ips = null;
            OutputStream ops = null;
            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;
            OutputStreamWriter outputStreamWriter = null;
            BufferedWriter bufferedWriter = null;
            try {
                ips = new FileInputStream(filePath);
                inputStreamReader = new InputStreamReader(ips, StandardCharsets.UTF_8);
                bufferedReader = new BufferedReader(inputStreamReader);
                exportPath = FileUtils.getNewPathWithStr(filePath, "盘点结果");
                if (exportPath.startsWith("Exception:")) {
                    return exportPath;
                }
                ops = new FileOutputStream(exportPath);
                outputStreamWriter = new OutputStreamWriter(ops, StandardCharsets.UTF_8);
                bufferedWriter = new BufferedWriter(outputStreamWriter);
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (!StringUtils.isEmptyOrNull(line)) {
                        String[] strArray = line.split("\\|");
                        if (strArray.length >= 13 && !StringUtils.isEmptyOrNull(strArray[0]) && !StringUtils.isEmptyOrNull(strArray[5]) && !StringUtils.isEmptyOrNull(strArray[6]) && strArray[6].length() % 4 == 0) {
                            boolean write = false;
                            for (InventoryInfo info : resultList) {
                                if (strArray[6].equals(info.getNumber())) {
                                    strArray[9] = ("1".equals(info.getItem01())) ? "1" : "0";
                                    strArray[12] = ("1".equals(info.getItem01())) ? "相符" : "待确认";
                                    String resultLine = String.join("|", strArray);
                                    bufferedWriter.write(resultLine);
                                    bufferedWriter.newLine();
                                    bufferedWriter.flush();
                                    write = true;
                                    break;
                                }
                            }
                            if (!write) {
                                bufferedWriter.write(line);
                                bufferedWriter.newLine();
                                bufferedWriter.flush();
                            }
                        } else {
                            bufferedWriter.write(line);
                            bufferedWriter.newLine();
                            bufferedWriter.flush();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                resMsg = "写入盘点结果异常";
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (ips != null) {
                    try {
                        ips.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                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 {
            resMsg = "写入盘点任务文件失败";
        }
        return resMsg;
    }

    private void showExportDialog(String content) {
        int dialog_width = (int) (ViewUtil.getScreenWidth(this) * 4 / 5.0);
        final CommonAlertDialog dialog = new CommonAlertDialog(TaskListActivity.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);
                TaskListActivity.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.task_data_none_layout:
                // 选择盘点文件读取任务数据
                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 {
                    selectTaskFile();
                }
                break;
            case R.id.task_inventory_begin_btn:
                if (uhfService.inventoryStart()) {
                    beginBtn.setClickable(false);
                    beginBtn.setText(R.string.task_list_btn_inventory_doing);
                    isInventory = true;
                    inventoryThread = new Thread(inventoryRunnable);
                    inventoryThread.start();
                } else {
                    StmApplication.getInstance().showToastShort("开启盘询失败，请稍后操作");
                }
                break;
            case R.id.task_inventory_finish_btn:
                if (uhfService.inventoryStop()) {
                    isInventory = false;
                    if (inventoryThread != null) {
                        inventoryThread.interrupt();
                        inventoryThread = null;
                    }
                    beginBtn.setClickable(true);
                    beginBtn.setText(R.string.inventory_btn_begin);
                } else {
                    StmApplication.getInstance().showToastShort("关闭盘询失败，请稍后操作");
                }
                break;
            case R.id.task_inventory_save_btn:
                if (isInventory) {
                    StmApplication.getInstance().showToastShort("正在盘询，请稍后操作");
                } else {
                    List<InventoryInfo> resultList = taskListAdapter.queryResultData();
                    List<InventoryInfo> advantageList = taskListAdapter.queryAdvantageData();
                    StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                        @Override
                        public void run() {
                            String resMsg = null;
                            if (resultList != null && resultList.size() > 0) {
                                resMsg = writeResultToTxt(resultList);
                            }
                            if (advantageList != null && advantageList.size() > 0) {
                                inventoryInfoDao.insertInventoryList(advantageList);
                            }
                            String finalResMsg = resMsg;
                            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                                @Override
                                public void run() {
                                    if (StringUtils.isEmptyOrNull(finalResMsg)) {
                                        taskListAdapter.setData(null);
                                        noneLayout.setVisibility(View.VISIBLE);
                                        showExportDialog("导出成功到" + exportPath);
                                    } else {
                                        StmApplication.getInstance().showToastShort(finalResMsg);
                                    }
                                }
                            });
                        }
                    });
                }
                break;
            case R.id.task_inventory_clean_btn:
                if (isInventory) {
                    StmApplication.getInstance().showToastShort("正在盘询，请稍后操作");
                } else {
                    taskListAdapter.setData(null);
                    noneLayout.setVisibility(View.VISIBLE);
                }
                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) {
                selectTaskFile();
            } else {
                StmApplication.getInstance().showToastShort("读取盘点任务文件需要访问手机存储权限");
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ConfigKey.ACTIVITY_REQUEST_SELECT_TASK) {
            if (resultCode == Activity.RESULT_OK && data != null && data.getData()!= null) {
                readTxtByLine(data.getData());
            }
        }
    }

    private class InventoryRunnable implements Runnable {
        @Override
        public void run() {
            while (isInventory) {
                StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                    @Override
                    public void run() {
                        List<EPC> epcList = uhfService.getTagIDs();
                        if (epcList != null && epcList.size() > 0) {
                            taskListAdapter.updateStatus(epcList);
                        }
                    }
                });
                try {
                    Thread.sleep(500);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
