aboutsummaryrefslogtreecommitdiff
path: root/RhSolutions.AddIn/Services/GuessReader.cs
blob: 86e7d27f6956f4bd066fb303219441047beb5759 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
using System.IO;

namespace RhSolutions.Services;

public class GuessReader : IReader
{
    private readonly Application _application;
    private ProgressBar _progressBar;

    public GuessReader(Application application)
    {
        _application = application;
    }

    public Dictionary<Product, double> ReadProducts(Range range)
    {
        _progressBar = new("Ищу колонку с артикулами...", range.Columns.Count);
        int? productColumnIndex = null;

        for (int column = 1; column < range.Columns.Count + 1; column++)
        {
            _progressBar.Update();
            if (IsProductColumn(range.Columns[column]))
            {
                productColumnIndex = column;
                break;
            }
        }

        if (productColumnIndex == null)
        {
            throw new ArgumentException("Колонка с артикулом не определена");
        }

        int? amountColumnIndex = null;
        int currentIndex = productColumnIndex.Value + 1;
        _progressBar = new("Ищу колонку с количеством...", range.Columns.Count);

        while (currentIndex > 0)
        {
            _progressBar.Update();
            if (currentIndex > range.Columns.Count + 1)
            {
                currentIndex = productColumnIndex.Value - 1;
                continue;
            }
            if (currentIndex > productColumnIndex)
            {
                if (IsAmountColumn(range.Columns[currentIndex]))
                {
                    amountColumnIndex = currentIndex;
                    break;
                }
                else currentIndex++;
            }
            else
            {
                if (IsAmountColumn(range.Columns[currentIndex]))
                {
                    amountColumnIndex = currentIndex;
                    break;
                }
                else currentIndex--;
            }
        }

        if (amountColumnIndex == null)
        {
            throw new ArgumentException("Колонка с количеством не определена");
        }

        else
        {
            return GetDictionaryFromColumns(range.Columns[productColumnIndex],
                range.Columns[amountColumnIndex]);
        }
    }

    private bool IsProductColumn(Range column)
    {
        int successCounter = 0;
        var cells = column.Value2;

        if (cells == null)
        {
            return false;
        }

        for (int row = 1; row < column.Rows.Count + 1; row++)
        {            
            object currentCell = column.Rows.Count == 1 ? cells : cells[row, 1];
            if (currentCell == null)
            {
                continue;
            }

            if (ProductSku.TryParse(currentCell.ToString(), out _))
            {
                successCounter++;
            }

            if (successCounter > 2)
            {
                return true;
            }
        }

        return successCounter > 0;
    }

    private bool IsAmountColumn(Range column)
    {
        int successCounter = 0;
        var cells = column.Value2;
        double maxValue = 30000;

        if (cells == null)
        {
            return false;
        }

        if (column.Rows.Count == 1)
        {
            double? value = cells as double?;

            return value != null
                && value != 0
                && value < maxValue;
        }

        else
        {
            for (int row = 1; row < column.Rows.Count + 1; row++)
            {
                object currentCell = cells[row, 1];
                double? value = currentCell as double?;

                if (value == null 
                    || value == 0 
                    || value > maxValue)
                {
                    continue;
                }

                if (++successCounter > 3)
                {
                    return true;
                }
            }
        }
        return successCounter > 1;
    }

    private Dictionary<Product, double> GetDictionaryFromColumns(Range productColumn, Range amountColumn)
    {
        Dictionary<Product, double> result = new();
        var firstRowIndex = 1;
        var lastRowIndex = amountColumn.Worksheet
            .Cells[amountColumn.Worksheet.Rows.Count, amountColumn.Column]
            .End[XlDirection.xlUp].Row; 
        _progressBar = new("Заполняю словарь значений...", lastRowIndex);
        Worksheet worksheet = amountColumn.Worksheet;

        for (int row = firstRowIndex; row < lastRowIndex + 1; row++)
        {
            _progressBar.Update();
            object currentAmountCell = worksheet.Cells[row, amountColumn.Column].Value2;
            object currentProductCell = worksheet.Cells[row, productColumn.Column].Value2;
            double? amountValue = currentAmountCell as double?;

            if (amountValue == null || amountValue == 0 || currentProductCell == null)
            {
                continue;
            }

            if (ProductSku.TryParse(currentProductCell.ToString(), out IEnumerable<ProductSku> skus))
            {
                Product p = new(skus.First())
                {
                    Name = "Распознанный артикул"
                };
                if (result.ContainsKey(p))
                {
                    result[p] += amountValue.Value;
                }
                else
                {
                    result.Add(p, amountValue.Value);
                }
            }
        }
        return result;
    }

    public List<(string, Dictionary<Product, double>)> ReadProducts(IEnumerable<Worksheet> worksheets)
    {
        List<(string, Dictionary<Product, double>)> result = new();
        foreach (Worksheet worksheet in worksheets)
        {
            string wbName = Path.GetFileNameWithoutExtension(
                worksheet.Parent.Name);
            Range range = worksheet.UsedRange;
            var productsDict = ReadProducts(range);
            result.Add((wbName, productsDict));
        }
        return result;
    }

    public List<(string, Dictionary<Product, double>)> ReadProducts(string[] files)
    {
        _progressBar = new("Открываю исходные файлы...", files.Length);
        List<Worksheet> worksheets = new();

        _application.ScreenUpdating = false;
        foreach (string file in files)
        {
            Workbook wb = _application.Workbooks.Open(file);
            worksheets.Add(wb.ActiveSheet);
            _progressBar.Update();
        }
        _application.ScreenUpdating = true;
        var result = ReadProducts(worksheets);
        foreach (var ws in worksheets)
        {
            ws.Parent.Close();
        }
        return result;
    }

    public void Dispose()
    {
        _progressBar?.Dispose();
    }
}