package com.stm.asset.page;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.room.Room;

import com.stm.asset.R;
import com.stm.asset.adapter.TaskAdapter;
import com.stm.asset.base.BaseFragment;
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.http.HttpException;
import com.stm.asset.http.RequestCallback;
import com.stm.asset.json.CommonStringJson;
import com.stm.asset.model.InventoryInfo;
import com.stm.asset.utils.FileUtils;
import com.stm.asset.utils.StringUtils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 类名称：TaskFragment
 * 类描述：盘点任务Fragment，包括未盘点和已完成
 * 创建人：story
 * 创建时间：2021-12-07 14:43
 */
public class TaskFragment extends BaseFragment implements View.OnClickListener {

    private RelativeLayout noneLayout;

    private TaskAdapter taskAdapter;
    private List<InventoryInfo> inventoryInfoList;
    private String type; // 类型：A:未盘点 B:已完成
    private InventoryInfoDao inventoryInfoDao;
    private CheckTaskActivity checkTaskActivity;
    private int excelNumberIndex = -1; // 盘点任务文件编号位置
    private int excelNameIndex = -1; // 盘点任务文件编号位置
    private int excelCountIndex = -1; // 盘点任务文件数量位置
    private String excelPath = null;
    private String exportPath = null;
    private String exportMessage = null;

    private TaskFragment(CheckTaskActivity checkTaskActivity, String type) {
        this.checkTaskActivity = checkTaskActivity;
        this.type = type;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_task, null);
        ListView listView = view.findViewById(R.id.fgm_task_list);
        noneLayout = view.findViewById(R.id.fgm_task_none_layout);
        taskAdapter = new TaskAdapter(getActivity());
        listView.setAdapter(taskAdapter);
        Button testBtn = view.findViewById(R.id.task_test_btn);
        Button saveBtn = view.findViewById(R.id.task_upload_btn);
        Button exportBtn = view.findViewById(R.id.task_export_btn);
        Button cleanBtn = view.findViewById(R.id.task_clean_btn);
        saveBtn.setOnClickListener(this);
        exportBtn.setOnClickListener(this);
        cleanBtn.setOnClickListener(this);
        testBtn.setOnClickListener(this);
        if ("B".equals(type)) {
            saveBtn.setVisibility(View.GONE);
            exportBtn.setVisibility(View.GONE);
        }

        InventoryInfoDatabase database = Room.databaseBuilder(checkTaskActivity, InventoryInfoDatabase.class, "inventoryInfoDemo").build();
        inventoryInfoDao = database.inventoryInfoDao();
        loadData();

        return view;
    }

    public void loadData() {
        StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
            @Override
            public void run() {
                if (inventoryInfoDao != null) {
                    if ("A".equals(type)) {
                        inventoryInfoList = inventoryInfoDao.getUndoInventoryList();
                    } else if ("B".equals(type)) {
                        inventoryInfoList = inventoryInfoDao.getDoneInventoryList();
                    }
                    StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                        @Override
                        public void run() {
                            taskAdapter.setData(inventoryInfoList);
                            if (checkTaskActivity != null) {
                                if ("A".equals(type)) {
                                    checkTaskActivity.setUnfinishedNum(inventoryInfoList.size());
                                } else if ("B".equals(type)) {
                                    checkTaskActivity.setFinishedNum(inventoryInfoList.size());
                                }
                            }
                            if (inventoryInfoList != null && inventoryInfoList.size() > 0) {
                                noneLayout.setVisibility(View.GONE);
                            } else {
                                noneLayout.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            }
        });
    }

    public static TaskFragment instance(CheckTaskActivity checkTaskActivity, String type) {
        return new TaskFragment(checkTaskActivity, type);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.task_upload_btn:
                // 直接修改状态
                int perRes = ActivityCompat.checkSelfPermission(checkTaskActivity, "android.permission.WRITE_EXTERNAL_STORAGE");
                int perRes2 = ActivityCompat.checkSelfPermission(checkTaskActivity, "android.permission.READ_EXTERNAL_STORAGE");
                if (perRes == PackageManager.PERMISSION_DENIED || perRes2 == PackageManager.PERMISSION_DENIED) {
                    ActivityCompat.requestPermissions(checkTaskActivity, new String[] {"android.permission.WRITE_EXTERNAL_STORAGE", "android.permission.READ_EXTERNAL_STORAGE"}, ConfigKey.PERMISSION_REQUEST_EXTERNAL_STORAGE);
                } else {
                    selectTaskFile();
                }
                break;
            case R.id.task_export_btn:
                if (inventoryInfoList != null) {
                    StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                        @Override
                        public void run() {
                            inventoryInfoDao.insertInventoryList(inventoryInfoList);
                            writeDateToExcel();
                        }
                    });
                }
                break;
            case R.id.task_clean_btn:
                if (inventoryInfoList != null) {
                    StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                        @Override
                        public void run() {
                            inventoryInfoDao.deleteInventoryList(inventoryInfoList);
                            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                                @Override
                                public void run() {
                                    StmApplication.getInstance().showToastShort("清空成功");
                                    inventoryInfoList.clear();
                                    taskAdapter.setData(inventoryInfoList);
                                    if ("A".equals(type)) {
                                        checkTaskActivity.setUnfinishedNum(inventoryInfoList.size());
                                    } else if ("B".equals(type)) {
                                        checkTaskActivity.setFinishedNum(inventoryInfoList.size());
                                    }
                                    noneLayout.setVisibility(View.VISIBLE);
                                }
                            });
                        }
                    });
                }
                break;
            case R.id.task_test_btn:
                String str = "0300261,0300462,0300313,0300260,030495,0300204,0300182,030731,010301686,010301109,030496,0300107,0300160,031083,030732,030840,0300320,0300409,0300331";
                String[] strArr = str.split(",");
                if (strArr.length > 0) {
                    StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                        @Override
                        public void run() {
                            List<InventoryInfo> list = new ArrayList<>();
                            for (int i=0;i<strArr.length;i++) {
                                InventoryInfo info = new InventoryInfo();
                                info.setNumber(strArr[i]);
                                info.setStatus("0");
                                info.setUserName(StmApplication.getInstance().getUserInfo().getUsername());
                                list.add(info);
                            }
                            inventoryInfoDao.insertInventoryList(list);
                            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                                @Override
                                public void run() {
                                    checkTaskActivity.refreshData();
                                }
                            });
                        }
                    });
                }
                break;
        }
    }

    public void selectTaskFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setType("application/*");
        String[] mimeTypes = {"application/vnd.ms-excel", "application/x-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        startActivityForResult(intent, ConfigKey.ACTIVITY_REQUEST_SELECT_TASK);
    }

    private void checkDataByExcel(Uri uri) {
        String filePath = getFilePath(uri);
        if (!StringUtils.isEmptyOrNull(filePath)) {
            List<InventoryInfo> excelDataList = readExcelData(filePath);
            if (excelDataList.size() > 0) {
                // 比较数据
                StmApplication.getInstance().showToastShort("读取到" + excelDataList.size() + "条数据");
                compareInventoryData(excelDataList);
            } else {
                StmApplication.getInstance().showToastShort("读取盘点任务文件为空");
            }
        } else {
            StmApplication.getInstance().showToastShort("读取盘点任务文件失败");
        }
    }

    private String getFilePath(Uri uri) {
        String filePath = "";
        if (DocumentsContract.isDocumentUri(checkTaskActivity, uri)) {
            if ("com.android.externalstorage.documents".equals(uri.getAuthority())) {
                String  docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    filePath = Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                String id = DocumentsContract.getDocumentId(uri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                filePath = getDataColumn(checkTaskActivity, contentUri, null, null);
            } else if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String docId = DocumentsContract.getDocumentId(uri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = "_id=?";
                String[] selectionArgs = new String[] {split[1]};
                filePath = getDataColumn(checkTaskActivity, contentUri, selection, selectionArgs);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            filePath = getDataColumn(checkTaskActivity, uri, null, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
        }
        return filePath;
    }

    private String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = "_data";
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

    private List<InventoryInfo> readExcelData(String filePath) {
        excelPath = filePath;
        InputStream ips = null;
        List<InventoryInfo> excelInventoryList = new ArrayList<>();
        try {
            ips = new FileInputStream(filePath);
            Workbook workbook = WorkbookFactory.create(ips);
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet != null) {
                Row titleRow = sheet.getRow(0);
                if (titleRow != null) {
                    // 获取表头得到需要字段的位置
                    excelNameIndex = -1;
                    excelNumberIndex = -1;
                    excelCountIndex = -1;
                    for (Cell cell : titleRow) {
                        String valueTemp = getCellValueStr(cell);
                        if ("资产名称".equals(valueTemp)) {
                            excelNameIndex = cell.getColumnIndex();
                        } else if ("资产编号".equals(valueTemp)) {
                            excelNumberIndex = cell.getColumnIndex();
                        } else if ("盘点数量".equals(valueTemp)) {
                            excelCountIndex = cell.getColumnIndex();
                        }
                    }
                    if (excelNameIndex != -1 && excelNumberIndex != -1 && excelCountIndex != -1) {
                        StmApplication.getInstance().showToastShort("filePath:" + filePath);
                        // 根据位置读取响应数据
                        boolean first = true;
                        for (Row row : sheet) {
                            if (first) {
                                first = false;
                            } else {
                                String assetNumber = getCellValueStr(row.getCell(excelNumberIndex)).trim();
                                String assetName = getCellValueStr(row.getCell(excelNameIndex));
                                if (StringUtils.isNumber(assetNumber) && assetNumber.length() % 4 == 0) {
                                    InventoryInfo tempInventory = new InventoryInfo();
                                    tempInventory.setNumber(assetNumber);
                                    tempInventory.setName(assetName);
                                    excelInventoryList.add(tempInventory);
                                }
                            }
                        }
                    } else {
                        StmApplication.getInstance().showToastShort("表头格式错误，请重新选择");
                    }
                } else {
                    StmApplication.getInstance().showToastShort("文件内容为空，请重新选择");
                }
            } else {
                StmApplication.getInstance().showToastShort("文件内容为空，请重新选择");
            }
            workbook.close();
        } catch (Exception e) {
            StmApplication.getInstance().showToastShort("文件读取异常");
            e.printStackTrace();
        } finally {
            if (ips != null) {
                try {
                    ips.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return excelInventoryList;
    }

    private String getCellValueStr(Cell cell) {
        String valueTemp = "";
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            if (cell.getColumnIndex() == excelNumberIndex) {
                valueTemp = new DecimalFormat("#").format(cell.getNumericCellValue());
            } else {
                valueTemp = String.valueOf(cell.getNumericCellValue());
            }
        } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            valueTemp = cell.getStringCellValue();
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            valueTemp = String.valueOf(cell.getBooleanCellValue());
        }
        return valueTemp;
    }

    private void compareInventoryData(List<InventoryInfo> excelDataList) {
        StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
            @Override
            public void run() {
                // 盘点前对数据处理，清理掉原来的盘点结果
                Iterator<InventoryInfo> infoIterator = inventoryInfoList.iterator();
                while (infoIterator.hasNext()) {
                    InventoryInfo info = infoIterator.next();
                    if ("2".equals(info.getItem01())) {
                        infoIterator.remove();
                    } else {
                        info.setItem01("0");
                    }
                }
                // 数据对比
                Map<String, List<InventoryInfo>> excelGroup = excelDataList.stream().collect(Collectors.groupingBy(InventoryInfo::getNumber));
                Set<String> assetNumberSet = new HashSet<>();
                for (InventoryInfo inventoryInfo : inventoryInfoList) {
                    assetNumberSet.add(inventoryInfo.getNumber());
                    if (excelGroup.containsKey(inventoryInfo.getNumber())) {
                        inventoryInfo.setItem01("1");
                        List<InventoryInfo> groupTemp = excelGroup.get(inventoryInfo.getNumber());
                        if (groupTemp != null && groupTemp.size() > 0) {
                            inventoryInfo.setName(groupTemp.get(0).getName());
                        }
                    } else {
                        inventoryInfo.setItem01("3");
                    }
                }
                // 处理盘亏数据
                for (String key : excelGroup.keySet()) {
                    if (!assetNumberSet.contains(key)) {
                        List<InventoryInfo> groupTemp = excelGroup.get(key);
                        if (groupTemp != null && groupTemp.size() > 0) {
                            InventoryInfo temp = groupTemp.get(0);
                            temp.setItem01("2");
                            temp.setStatus("0");
                            inventoryInfoList.add(temp);
                        }
                    }
                }
                StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                    @Override
                    public void run() {
                        taskAdapter.setData(inventoryInfoList);
                        StmApplication.getInstance().showToastShort("盘点完成");
                    }
                });
            }
        });

    }

    private void writeDateToExcel() {
        if (inventoryInfoList != null && inventoryInfoList.size() > 0) {
            Map<String, List<InventoryInfo>> inventoryGroupMap = inventoryInfoList.stream().collect(Collectors.groupingBy(InventoryInfo::getNumber));
            InputStream ips = null;
            OutputStream ops = null;
            exportMessage = "";
            try {
                ips = new FileInputStream(excelPath);
                Workbook workbook = WorkbookFactory.create(ips);
                Sheet sheet = workbook.getSheetAt(0);
                if (sheet != null) {
                    Row titleRow = sheet.getRow(0);
                    if (titleRow != null) {
                        // 获取表头得到需要字段的位置
                        excelNameIndex = -1;
                        excelNumberIndex = -1;
                        excelCountIndex = -1;
                        for (Cell cell : titleRow) {
                            String valueTemp = getCellValueStr(cell);
                            if ("资产名称".equals(valueTemp)) {
                                excelNameIndex = cell.getColumnIndex();
                            } else if ("资产编号".equals(valueTemp)) {
                                excelNumberIndex = cell.getColumnIndex();
                            } else if ("盘点数量".equals(valueTemp)) {
                                excelCountIndex = cell.getColumnIndex();
                            }
                        }
                        if (excelNameIndex != -1 && excelNumberIndex != -1 && excelCountIndex != -1) {
                            boolean first = true;
                            for (Row row : sheet) {
                                if (first) {
                                    first = false;
                                } else {
                                    String key = getCellValueStr(row.getCell(excelNumberIndex)).trim();
                                    if (inventoryGroupMap.containsKey(key)) {
                                        int count = 0;
                                        List<InventoryInfo> inList = inventoryGroupMap.get(key);
                                        if (inList != null && inList.size() > 0) {
                                            String item01 = inList.get(0).getItem01();
                                            if ("1".equals(item01)) {
                                                count = 1;
                                            }
                                        }
                                        Cell cell = row.getCell(excelCountIndex);
                                        if (cell == null) {
                                            cell = row.createCell(excelCountIndex);
                                        }
                                        cell.setCellType(Cell.CELL_TYPE_STRING);
                                        cell.setCellValue(String.valueOf(count));
                                    }
                                }
                            }
                        } else {
                            exportMessage = "导出盘点结果异常";
                        }
                    } else {
                        exportMessage = "导出盘点结果异常";
                    }
                } else {
                    exportMessage = "导出盘点结果异常";
                }
                // 获取一个新文件名
                exportPath = FileUtils.getNewPathWithStr(excelPath, "盘点结果");
                ops = new FileOutputStream(exportPath);
                workbook.write(ops);
                workbook.close();
                // 数据存储
                for (InventoryInfo info : inventoryInfoList) {
                    info.setStatus("2");
                }
                inventoryInfoDao.insertInventoryList(inventoryInfoList);
            } catch (Exception e) {
                exportMessage = "导出盘点结果异常";
                e.printStackTrace();
            } finally {
                if (ips != null) {
                    try {
                        ips.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                if (ops != null) {
                    try {
                        ops.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                @Override
                public void run() {
                    inventoryInfoList.clear();
                    taskAdapter.setData(inventoryInfoList);
                    noneLayout.setVisibility(View.VISIBLE);
                    checkTaskActivity.setUnfinishedNum(0);
                    if (StringUtils.isEmptyOrNull(exportMessage)) {
                        exportMessage = "导出成功到" + exportPath;
                    }
                    StmApplication.getInstance().showToastShort(exportMessage);
                }
            });
        }
    }

    @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) {
                checkDataByExcel(data.getData());
            }
        }
    }

    private RequestCallback<CommonStringJson> scan_cb = new RequestCallback<CommonStringJson>(CommonStringJson.class) {
        @Override
        public void onSuccess(CommonStringJson responseInfo) {
            checkTaskActivity.getLoadingDialog().dismiss();
            if (responseInfo.isSucess()) {
                StmApplication.getInstance().showToastShort("导出成功");
                // 处理盘点数据状态
                StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
                    @Override
                    public void run() {
                        if (inventoryInfoList != null && inventoryInfoList.size() > 0) {
                            for (InventoryInfo inventoryInfo : inventoryInfoList) {
                                inventoryInfo.setStatus("2");
                                inventoryInfoDao.updateInventory(inventoryInfo);
                            }
                            StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
                                @Override
                                public void run() {
                                    checkTaskActivity.refreshData();
                                }
                            });
                        }
                    }
                });
//                String str = responseInfo.getRspData();
//                Map<String, Object> failedMap = new Gson().fromJson(str, new TypeToken<Map<String, Object>>(){}.getType());
//                if (failedMap != null && failedMap.get("numList") != null) {
//                    List<String> numList = (List<String>) failedMap.get("numList");
//                    if (numList != null && numList.size() > 0) {
//                        StmApplication.getInstance().showToastShort(String.valueOf(failedMap.get("msg")));
//                        // 处理盘点失败数据
//                        StmApplication.getInstance().getAppExecutors().diskIO().execute(new Runnable() {
//                            @Override
//                            public void run() {
//                                if (inventoryInfoList != null && inventoryInfoList.size() > 0) {
//                                    for (InventoryInfo inventoryInfo : inventoryInfoList) {
//                                        boolean success = true;
//                                        for (String itemStr : numList) {
//                                            if (itemStr.equals(inventoryInfo.getNumber())) {
//                                                success = false;
//                                            }
//                                        }
//                                        if (success) {
//                                            inventoryInfo.setStatus("2");
//                                            inventoryInfoDao.updateInventory(inventoryInfo);
//                                        } else {
//                                            inventoryInfo.setStatus("1");
//                                            inventoryInfoDao.updateInventory(inventoryInfo);
//                                        }
//                                    }
//                                    StmApplication.getInstance().getAppExecutors().mainThread().execute(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            checkTaskActivity.refreshData();
//                                        }
//                                    });
//                                }
//                            }
//                        });
//                    } else {
//                        StmApplication.getInstance().showToastShort("导出成功");
//                    }
//                } else {
//                    StmApplication.getInstance().showToastShort("导出成功");
//                }
            } else {
                StmApplication.getInstance().showToastShort(responseInfo.getRspMsg());
            }
        }

        @Override
        public void onFailure(HttpException error, String msg) {
            checkTaskActivity.getLoadingDialog().dismiss();
            StmApplication.getInstance().showToastShort(msg);
        }
    };

}
