package com.ruoyi.system.service.impl.Conversion;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ruoyi.system.domain.ActReadHistoryModel;
import com.ruoyi.system.domain.ActReadHistoryRuleModel;
import com.ruoyi.system.domain.ActSuppliesImportCleaningAcc;
import com.ruoyi.system.mapper.ActReadDataMapper;
import com.ruoyi.system.service.impl.ActReadDataServiceImpl;
import com.ruoyi.system.utils.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.IntStream;

/**
 * 2024/3/27
 */
@Service
public class OtherMethod implements MineConversion {
    private final ActReadDataMapper actReadDataMapper;

    public OtherMethod(ActReadDataMapper actReadDataMapper) {
        this.actReadDataMapper = actReadDataMapper;
    }

    @Override
    @Transactional
    public void conversion(ActReadHistoryModel actReadHistoryModel, Object obj) {
        String sskId = actReadHistoryModel.getSskId();
        String hdate = actReadHistoryModel.getHdate();
        String hId = actReadHistoryModel.gethId();
        String yyUuid = actReadHistoryModel.getYyUuid();
        List<ActSuppliesImportCleaningAcc> accList = new ArrayList<>();
        Gson gson = new Gson();
        JSONArray jsonArray1 = gson.fromJson(actReadHistoryModel.getHistoryRole(), JSONArray.class);
        ActReadHistoryRuleModel[] ruleJson = gson.fromJson(actReadHistoryModel.getRule(), ActReadHistoryRuleModel[].class);
        ActReadHistoryRuleModel rule = ruleJson[0];
        int headerRow;
        int codeColumn;
        int dateColumn;
        int nameColumn;
        int moneyColumn;
        int numberColumn;
        int departmentColumn;
        int unit;
        int model;
        int money;
        headerRow = rule.getHeaderRow() != null && !"".equals(rule.getHeaderRow()) ? Integer.parseInt(rule.getHeaderRow()) - 1 : -1;
        codeColumn = rule.getCodeColumn() != null && !"".equals(rule.getCodeColumn()) ? Integer.parseInt(rule.getCodeColumn()) - 1 : -1;
        dateColumn = rule.getDateColumn() != null && !"".equals(rule.getDateColumn()) ? Integer.parseInt(rule.getDateColumn()) - 1 : -1;
        nameColumn = rule.getNameColumn() != null && !"".equals(rule.getNameColumn()) ? Integer.parseInt(rule.getNameColumn()) - 1 : -1;
        moneyColumn = rule.getMoneyColumn() != null && !"".equals(rule.getMoneyColumn()) ? Integer.parseInt(rule.getMoneyColumn()) - 1 : -1;
        numberColumn = rule.getNumberColumn() != null && !"".equals(rule.getNumberColumn()) ? Integer.parseInt(rule.getNumberColumn()) - 1 : -1;
        departmentColumn = rule.getDepartmentColumn() != null && !"".equals(rule.getDepartmentColumn()) ? Integer.parseInt(rule.getDepartmentColumn()) - 1 : -1;
        unit = rule.getUnit() != null && !"".equals(rule.getUnit()) ? Integer.parseInt(rule.getUnit()) - 1 : -1;
        model = rule.getModel() != null && !"".equals(rule.getModel()) ? Integer.parseInt(rule.getModel()) - 1 : -1;
        money = rule.getMoney() != null && !"".equals(rule.getMoney()) ? Integer.parseInt(rule.getMoney()) - 1 : -1;
        List<Integer> cList = Arrays.asList(dateColumn, departmentColumn, unit, model, codeColumn, nameColumn, moneyColumn, numberColumn, money);
        Optional<Integer> max = cList.parallelStream().max(Comparator.comparingInt(a -> a));
        JSONArray jsonArray = gson.fromJson(actReadHistoryModel.getData(), JSONArray.class);
        JSONArray cellData = jsonArray.getJSONObject(0).getJSONArray("celldata");
        ActSuppliesImportCleaningAcc acc = new ActSuppliesImportCleaningAcc();
        for (int i = 0; i < cellData.size(); i++) {
            JSONObject object = cellData.getJSONObject(i);
            int c = object.getInteger("c");
            if (cList.contains(c)) {
                int row = object.getInteger("r");
                if (row < headerRow && headerRow != -1) {
                    continue;
                }
                    if (row >= headerRow && object.getJSONObject("v") != null
                            && object.getJSONObject("v").getString("v") != null) {
                        String string = object.getJSONObject("v").getString("v");
                        if (c == codeColumn) {
                            acc.setCodeColumn(string);
                        } else if (c == dateColumn) {
                            if (string != null && ActReadDataServiceImpl.PATTERN.matcher(string).matches()) {
                                acc.setDateColumn(DateUtil.excelDateConversion(string));
                            } else {
                                acc.setDateColumn(string);
                            }
                        } else if (c == nameColumn) {
                            acc.setNameColumn(string);
                        } else if (c == moneyColumn) {
                            acc.setMoneyColumn(string);
                        } else if (c == numberColumn) {
                            acc.setNumberColumn(string);
                        } else if (c == departmentColumn) {
                            acc.setDepartmentColumn(string);
                        } else if (c == unit) {
                            acc.setUnit(string);
                        } else if (c == model) {
                            acc.setModel(string);
                        } else if (c == money) {
                            acc.setMoney(string);
                        }
                    }
                if (max.get() == c) {
                    Optional<String> first = IntStream.range(0, jsonArray1.size())
                            .mapToObj(jsonArray1::getJSONObject)
                            .filter(v -> row == Integer.parseInt(v.getString("key")))
                            .map(v -> v.getString("value"))
                            .findFirst();
                    if (first.isPresent()) {
                        String[] split = first.get().split(",");
                        acc.setKmCode(split[0]);
                        acc.setsOfExpenses(split[1]);
                    }
                    acc.setSskId(sskId);
                    acc.setHdate(hdate);
                    acc.sethId(Long.valueOf(hId));
                    acc.setYyUuid(yyUuid);
                    Map<String, String> map = (Map<String, String>) obj;
                    String kmCode = StringUtils.substring(acc.getCodeColumn(), 0, 6);
                    if (map.containsKey(kmCode)) {
                        acc.setCategories(map.get(kmCode));
                    } else {
                        kmCode = StringUtils.substring(kmCode, 0, 4);
                        if (map.containsKey(kmCode)) {
                            acc.setCategories(map.get(kmCode));
                        } else {
                            kmCode = StringUtils.substring(kmCode, 0, 2);
                            acc.setCategories(map.getOrDefault(kmCode, "10"));
                        }
                    }
                    acc.setId(StringUtils.remove(String.valueOf(UUID.randomUUID()), "-"));
                    if (acc.getNumberColumn() != null && !"".equals(acc.getNumberColumn()) && acc.getMoneyColumn() != null && !"".equals(acc.getMoneyColumn())) {
                        BigDecimal num1 = new BigDecimal(acc.getNumberColumn());
                        if (acc.getMoneyColumn().equals("#DIV/0!")) continue;
                        BigDecimal money1 = new BigDecimal(acc.getMoneyColumn());
                        acc.setMoneyColumns(num1.multiply(money1) + "");
                    }
                    accList.add(acc);
                    acc = new ActSuppliesImportCleaningAcc();
                }
            }
        }
        if (accList.size() != 0) {
            actReadDataMapper.insertDateToAnalysisAfter(accList);
            actReadDataMapper.updateState(accList.get(0).getYyUuid());
        }






//        String sskId = actReadHistoryModel.getSskId();
//        String hdate = actReadHistoryModel.getHdate();
//        String hId = actReadHistoryModel.gethId();
//        String yyUuid = actReadHistoryModel.getYyUuid();
//        List<ActSuppliesImportCleaningAcc> accList = new ArrayList<>();
//        Gson gson = new Gson();
//        JSONArray jsonArray1 = gson.fromJson(actReadHistoryModel.getHistoryRole(), JSONArray.class);
//        ActReadHistoryRuleModel[] ruleJson = gson.fromJson(actReadHistoryModel.getRule(), ActReadHistoryRuleModel[].class);
//        ActReadHistoryRuleModel rule = ruleJson[0];
//        int headerRow;
//        int codeColumn;
//        int dateColumn;
//        int nameColumn;
//        int moneyColumn;
//        int numberColumn;
//        int departmentColumn;
//        int unit;
//        int model;
//        int money;
//        headerRow = rule.getHeaderRow() != null && !"".equals(rule.getHeaderRow()) ? Integer.parseInt(rule.getHeaderRow()) - 1 : -1;
//        codeColumn = rule.getCodeColumn() != null && !"".equals(rule.getCodeColumn()) ? Integer.parseInt(rule.getCodeColumn()) - 1 : -1;
//        dateColumn = rule.getDateColumn() != null && !"".equals(rule.getDateColumn()) ? Integer.parseInt(rule.getDateColumn()) - 1 : -1;
//        nameColumn = rule.getNameColumn() != null && !"".equals(rule.getNameColumn()) ? Integer.parseInt(rule.getNameColumn()) - 1 : -1;
//        moneyColumn = rule.getMoneyColumn() != null && !"".equals(rule.getMoneyColumn()) ? Integer.parseInt(rule.getMoneyColumn()) - 1 : -1;
//        numberColumn = rule.getNumberColumn() != null && !"".equals(rule.getNumberColumn()) ? Integer.parseInt(rule.getNumberColumn()) - 1 : -1;
//        departmentColumn = rule.getDepartmentColumn() != null && !"".equals(rule.getDepartmentColumn()) ? Integer.parseInt(rule.getDepartmentColumn()) - 1 : -1;
//        unit = rule.getUnit() != null && !"".equals(rule.getUnit()) ? Integer.parseInt(rule.getUnit()) - 1 : -1;
//        model = rule.getModel() != null && !"".equals(rule.getModel()) ? Integer.parseInt(rule.getModel()) - 1 : -1;
//        money = rule.getMoney() != null && !"".equals(rule.getMoney()) ? Integer.parseInt(rule.getMoney()) - 1 : -1;
//        List<Integer> cList = Arrays.asList(dateColumn, departmentColumn, unit, model, codeColumn, nameColumn, moneyColumn, numberColumn, money);
//        JSONArray jsonArray = gson.fromJson(actReadHistoryModel.getData(), JSONArray.class);
//        JSONArray cellData = jsonArray.getJSONObject(0).getJSONArray("celldata");
//        int r = Integer.MIN_VALUE;
//        ActSuppliesImportCleaningAcc acc = null;
//        for (int i = 0; i < cellData.size(); i++) {
//            JSONObject object = cellData.getJSONObject(i);
//            int row = object.getInteger("r");
//            if (row < headerRow && headerRow != -1) {
//                continue;
//            }
//            if (r != row) {
//                acc = new ActSuppliesImportCleaningAcc();
//                acc.setSskId(sskId);
//                acc.setHdate(hdate);
//                acc.sethId(Long.valueOf(hId));
//                acc.setYyUuid(yyUuid);
//                Optional<String> first = IntStream.range(0, jsonArray1.size())
//                        .mapToObj(jsonArray1::getJSONObject)
//                        .filter(v -> row == Integer.parseInt(v.getString("key")))
//                        .map(v -> v.getString("value"))
//                        .findFirst();
//                if (first.isPresent()) {
//                    String[] split = first.get().split(",");
//                    acc.setKmCode(split[0]);
//                    acc.setsOfExpenses(split[1]);
//                }
//                r = row;
//            }
//            int c = object.getInteger("c");
//            if (row >= headerRow && cList.contains(c) && object.getJSONObject("v") != null
//                    && object.getJSONObject("v").getString("v") != null) {
//                String string = object.getJSONObject("v").getString("v");
//                if (c == codeColumn) {
//                    assert acc != null;
//                    acc.setCodeColumn(string);
//                } else if (c == dateColumn) {
//                    assert acc != null;
//                    if (string != null && ActReadDataServiceImpl.PATTERN.matcher(object.getJSONObject("v").getString("v")).matches()) {
//                        acc.setDateColumn(DateUtil.excelDateConversion(string));
//                    } else {
//                        acc.setDateColumn(string);
//                    }
//                } else if (c == nameColumn) {
//                    assert acc != null;
//                    acc.setNameColumn(string);
//                } else if (c == moneyColumn) {
//                    assert acc != null;
//                    acc.setMoneyColumn(string);
//                } else if (c == numberColumn) {
//                    assert acc != null;
//                    acc.setNumberColumn(string);
//                } else if (c == departmentColumn) {
//                    assert acc != null;
//                    acc.setDepartmentColumn(string);
//                } else if (c == unit) {
//                    assert acc != null;
//                    acc.setUnit(string);
//                } else if (c == model) {
//                    assert acc != null;
//                    acc.setModel(string);
//                } else if (c == money) {
//                    assert acc != null;
//                    acc.setMoney(string);
//                }
//            }
//            JSONObject objectNext = null;
//            if (i != cellData.size() - 1) {
//                objectNext = cellData.getJSONObject(i + 1);
//            }
//            if (objectNext == null || objectNext.getInteger("r") != r) {
//                assert acc != null;
//                Map<String, String> map = (Map<String, String>) obj;
//                String kmCode = StringUtils.substring(acc.getCodeColumn(), 0, 6);
//                if (map.containsKey(kmCode)) {
//                    acc.setCategories(map.get(kmCode));
//                } else {
//                    kmCode = StringUtils.substring(kmCode, 0, 4);
//                    if (map.containsKey(kmCode)) {
//                        acc.setCategories(map.get(kmCode));
//                    } else {
//                        kmCode = StringUtils.substring(kmCode, 0, 2);
//                        acc.setCategories(map.getOrDefault(kmCode, "10"));
//                    }
//                }
//                acc.setId(StringUtils.remove(String.valueOf(UUID.randomUUID()), "-"));
//                if (acc.getNumberColumn() != null && !"".equals(acc.getNumberColumn()) && acc.getMoneyColumn() != null && !"".equals(acc.getMoneyColumn())) {
//                    BigDecimal num1 = new BigDecimal(acc.getNumberColumn());
//                    BigDecimal money1 = new BigDecimal(acc.getMoneyColumn());
//                    acc.setMoneyColumns(num1.multiply(money1) + "");
//                }
//                accList.add(acc);
//            }
//        }
//        if (accList.size() != 0) {
//            actReadDataMapper.insertDateToAnalysisAfter(accList);
//            actReadDataMapper.updateState(accList.get(0).getYyUuid());
//            System.err.println("共处理了：" + accList.size() + "条数据");
//        }
    }
}
