'use strict';

/**
 *
 *
 * @author Mai
 * @date
 * @version
 */

$(document).ready(() => {
    const spreadNS = GC.Spread.Sheets;
    const spread = SpreadJsObj.createNewSpread($('.sjs-height-1')[0]);
    const sheet = spread.getActiveSheet();

    const hCenter = spreadNS.HorizontalAlign.center;
    const vCenter = spreadNS.VerticalAlign.center;

    const compareObj = {
        cacheList: [],
        sortNodeData: function (data) {
            data.sort(function (a, b) {
                if (a.code > b.code) {
                    return 1;
                } else if (a.code < b.code) {
                    return -1;
                } else {
                    return 0;
                }
            });
        },
        showCompareData: function () {
            const cols = compareObj.cols, colsName = compareObj.colsName;
            const colCount = colsName.length;
            function loadNode (node, row) {
                sheet.getCell(row, compareObj.cols.code).text(node.code).wordWrap(true).vAlign(vCenter);
                sheet.getCell(row, compareObj.cols.name).text(node.name).wordWrap(true).vAlign(vCenter);
                sheet.getRange(row, 0, 1, colCount).backColor('#dae5ee');
                sheet.autoFitRow(row);
            }
            function loadIndex(index, row) {
                for (const colName of colsName) {
                    if (colName === 'averageIndex') {
                        const aver = Number((index.sumValue / index.sumCount).toFixed(2));
                        sheet.getCell(row, cols[colName]).value(aver).wordWrap(true).vAlign(vCenter);
                    } else if (index[colName]) {
                        sheet.getCell(row, cols[colName]).value(index[colName]).wordWrap(true).vAlign(vCenter);
                    }
                }
                sheet.autoFitRow(row);
            }

            SpreadJsObj.beginMassOperationSheet(sheet);

            let iRow = 2;
            sheet.setRowCount(2);
            console.log(compareObj.showData);
            for (const sd of compareObj.showData) {
                sheet.addRows(iRow, 1);
                loadNode(sd, iRow);
                iRow += 1;
                for (const index of sd.children) {
                    sheet.addRows(iRow, 1);
                    loadIndex(index, iRow);
                    iRow += 1;
                }
            }

            SpreadJsObj.endMassOperationSheet(sheet);
        },
        initXMatchCompareHeader: function (data) {
            const cols = {}, colsName = [];
            const indexColCount = data.selects.length + 1;
            SpreadJsObj.beginMassOperationSheet(sheet);

            const spans = sheet.getSpans();
            for (const span of spans) {
                sheet.removeSpan(span.row, span.col);
            }
            sheet.setColumnCount(6 + indexColCount);
            sheet.setRowCount(2);
            sheet.frozenRowCount(2);

            colsName.push('code');
            cols.code = 0;
            sheet.getCell(0, cols.code).text('指标编号').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.code, 2, 1);
            sheet.setColumnWidth(cols.code, 80);

            colsName.push('name');
            cols.name = 1;
            sheet.getCell(0, cols.name).text('项目或费用名称').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.name, 2, 1);
            sheet.setColumnWidth(cols.name, 220);

            colsName.push('unit1');
            cols.unit1 = 2;
            colsName.push('unit2');
            cols.unit2 = 3;
            sheet.getCell(0, cols.unit1).text('指标单位').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.unit1, 2, 2);
            sheet.setColumnWidth(cols.unit1, 65);
            sheet.setColumnWidth(cols.unit2, 65);

            if (data.selects.length > 0) {
                sheet.getCell(0, cols.unit2+1).text('经济指标').hAlign(hCenter).vAlign(vCenter);
                sheet.addSpan(0, cols.unit2+1, 1, indexColCount - 1);

                for (let i = 0, iLen = indexColCount - 1; i < iLen; i++) {
                    const colName = 'bills_xid' + (data.selects[i].id > 0 ? '_' + data.selects[i].id : '');
                    colsName.push(colName);
                    cols[colName] = 4+i;
                    sheet.getCell(1, cols[colName]).text(data.selects[i].id > 0 ? data.selects[i].name : '其他')
                        .hAlign(hCenter).vAlign(vCenter).wordWrap(true);
                    sheet.setColumnWidth(cols[colName], 150);
                }

                colsName.push('averageIndex');
                cols.averageIndex = 4 + indexColCount - 1;
                sheet.getCell(0, cols.averageIndex).text('平均指标').hAlign(hCenter).vAlign(vCenter);
                sheet.addSpan(0, cols.averageIndex, 2, 1);
                sheet.setColumnWidth(cols.averageIndex, 100);
            }

            colsName.push('rule');
            cols.rule = 4 + indexColCount;
            sheet.getCell(0, cols.rule).text('计算规则').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.rule, 2, 1);
            sheet.setColumnWidth(cols.rule, 300);

            colsName.push('memo');
            cols.memo = 5 + indexColCount;
            sheet.getCell(0, cols.memo).text('备注').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.memo, 2, 1);
            sheet.setColumnWidth(cols.memo, 100);

            sheet.autoFitRow(0);
            sheet.autoFitRow(1);

            compareObj.colsName = colsName;
            compareObj.cols = cols;
            SpreadJsObj.endMassOperationSheet(sheet);
        },
        sortXMatchCompareData: function (data) {
            function findNode(data, src, xid) {
                for (const node of data) {
                    const field = xid > 0 ? 'bills_xid_' + xid : 'bills_xid';
                    if (node.code === src.code && node.name === src.name && node[field] === src[field]) {
                        return node;
                    }
                }
                return null;
            }
            function findIndex(data, src) {
                for (const index of data) {
                    if (index.code === src.code && index.name === src.name) {
                        return index;
                    }
                }
                return null;
            }
            const result = [];
            for (const select of compareObj.data.selects) {
                const searchData = data.filter(function (x) { return x.bills_xid === select.id});
                for (const sd of searchData) {
                    let sortNode = findNode(result, sd, select.id);
                    if (!sortNode) {
                        sortNode = {
                            code: sd.code,
                            name: sd.name,
                            children: [],
                        };
                        result.push(sortNode);
                    }
                    if (select.id > 0) {
                        sortNode['bills_xid_' + select.id] = sd.bills_xid;
                    } else {
                        sortNode['bills_xid'] = sd.bills_xid;
                    }
                    for (const index of sd.children) {
                        let sortIndex = findIndex(sortNode.children, index);
                        if (!sortIndex) {
                            sortIndex = {
                                code: index.code,
                                name: index.name,
                                unit1: index.unit1,
                                unit2: index.unit2,
                                sumValue: 0,
                                sumCount: 0,
                                rule: index.rule,
                                memo: index.memo,
                            };
                            sortNode.children.push(sortIndex)
                        }
                        if (select.id > 0) {
                            sortIndex['bills_xid_' + select.id] = index.value;
                        } else {
                            sortIndex['bills_xid'] = index.value;
                        }
                        sortIndex.sumValue += index.value;
                        sortIndex.sumCount += 1;
                    }
                }
            }
            compareObj.sortNodeData(result);
            return result;
        },
        loadXMatchCompareData(data) {
            compareObj.initXMatchCompareHeader(compareObj.data);
            compareObj.showData = compareObj.sortXMatchCompareData(data);
            compareObj.showCompareData();
        },
        initCommonCompareHeader: function () {
            const cols = {}, colsName = [];
            SpreadJsObj.beginMassOperationSheet(sheet);

            const spans = sheet.getSpans();
            for (const span of spans) {
                sheet.removeSpan(span.row, span.col);
            }
            sheet.setColumnCount(7);
            sheet.setRowCount(2);
            sheet.frozenRowCount(2);

            colsName.push('code');
            cols.code = 0;
            sheet.getCell(0, cols.code).text('指标编号').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.code, 2, 1);
            sheet.setColumnWidth(cols.code, 80);

            colsName.push('name');
            cols.name = 1;
            sheet.getCell(0, cols.name).text('项目或费用名称').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.name, 2, 1);
            sheet.setColumnWidth(cols.name, 220);

            colsName.push('unit1');
            cols.unit1 = 2;
            colsName.push('unit2');
            cols.unit2 = 3;
            sheet.getCell(0, cols.unit1).text('指标单位').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.unit1, 2, 2);
            sheet.setColumnWidth(cols.unit1, 65);
            sheet.setColumnWidth(cols.unit2, 65);

            colsName.push('value');
            cols.name = 4;
            sheet.getCell(0, cols.name).text('经济指标').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.name, 2, 1);
            sheet.setColumnWidth(cols.name, 220);

            colsName.push('rule');
            cols.rule = 5;
            sheet.getCell(0, cols.rule).text('计算规则').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.rule, 2, 1);
            sheet.setColumnWidth(cols.rule, 300);

            colsName.push('memo');
            cols.memo = 6;
            sheet.getCell(0, cols.memo).text('备注').hAlign(hCenter).vAlign(vCenter);
            sheet.addSpan(0, cols.memo, 2, 1);
            sheet.setColumnWidth(cols.memo, 100);

            compareObj.colsName = colsName;
            compareObj.cols = cols;
            SpreadJsObj.endMassOperationSheet(sheet);
        },
        loadCommonCompareData(data) {
            compareObj.initCommonCompareHeader();
            compareObj.sortNodeData(data);
            this.showData = data;
            compareObj.showCompareData();
        },
        loadCompareData: function (data) {
            compareObj.resultData = data;
            if (compareObj.data.xMatch) {
                compareObj.loadXMatchCompareData(data);
            } else {
                compareObj.loadCommonCompareData(data);
            }
        },
        load: function () {
            postData(window.location.pathname + '/search', compareObj.data, function (result) {
                compareObj.lastData = compareObj.data;
                $('#select-lib').text(compareObj.data.lib_name + ': ' + compareObj.data.name);
                compareObj.loadCompareData(result);
                if (compareObj.data.xMatch) {
                    $('#select-data').modal('hide');
                } else {
                    $('#generate-data').modal('hide');
                }
            });
        },
        generateXList: function (arr) {
            $('#select-title').text('选择对比项 —— ' + compareObj.data.lib_name + ': ' + compareObj.data.name);
            const html = [];
            for (const r of arr) {
                html.push('<tr>');
                html.push('<td class="text-center">', "<input x-data='" + JSON.stringify({id: r.bills_xid, name: r.name, code: r.code}) + "' type='checkbox'>", '</td>');
                html.push('<td>', r.code, '</td>');
                html.push('<td>', r.bills_xid === -1 ? '其他' : r.name, '</td>');
                html.push('<td class="text-center">', r.units, '</td>');
                html.push('<td class="text-right">', r.dgn_quantity1, '</td>');
                html.push('<td class="text-right">', r.dgn_quantity2, '</td>');
                html.push('<td class="text-right">', r.dgn_price, '</td>');
                html.push('<td class="text-right">', r.total_price, '</td>');
                html.push('</tr>');
            }
            $('#x-list').html(html.join(''));
            $('#select-data').modal('show');
            $('#generate-data').modal('hide');
        },
        loadParentNode: function () {
            const compareCode = function (str1, str2, symbol = '-') {
                if (!str1) {
                    return -1;
                } else if (!str2) {
                    return 1;
                }

                const path1 = str1.split(symbol);
                const path2 = str2.split(symbol);
                const reg = /^[0-9]*$/;
                for (let i = 0, iLen = Math.min(path1.length, path2.length); i < iLen; i++) {
                    if (reg.test(path1[i]) && reg.test(path2[i])) {
                        const num1 = parseInt(path1[i]);
                        const num2 = parseInt(path2[i]);
                        if (num1 !== num2)  {
                            return num1 - num2;
                        }
                    } else if (path1[i] < path2[i]) {
                        return -1;
                    } else if (path1[i] > path2[i]) {
                        return 1;
                    }
                }
                return path1.length - path2.length;
            };
            const history = compareObj.cacheList.find(function (l) {
                return l.lib_id === compareObj.data.lib_id && l.className === compareObj.data.className;
            });
            if (!history) {
                postData(window.location.pathname + '/parent', compareObj.data, function (result) {
                    result.sort(function (x, y) {
                        return compareCode(x.code, y.code);
                    });
                    compareObj.cacheList.push({lib_id: compareObj.data.lib_id, className: compareObj.data.className, xList: result});
                    compareObj.generateXList(result);
                });
            } else {
                compareObj.generateXList(history.xList);
            }
        },
    };
    compareObj.initCommonCompareHeader();
    $('#generate-data').modal('show');
    $('.dropdown-item').click(function () {
        $('#btnGroupDrop1').text($(this).text()).attr('data', $(this).attr('data'));
        if ($('#hint1').attr('hint-type') === 'dy') {
            $('#hint1').hide();
        }
    });
    $('input[type=radio]').bind('click', function () {
        $('input[type=radio]').parent().parent().addClass('table-secondary');
        if (this.checked) {
            $(this).parent().parent().removeClass('table-secondary');
        }
        if ($('#hint1').attr('hint-type') === 'bd') {
            $('#hint1').hide();
        }
    });
    $('#next').click(function () {
        const dy = $('#btnGroupDrop1').attr('data');
        if (!dy) {
            $('#hint1').attr('hint-type', 'dy').html('未选择单元指标类型').show();
            return;
        }
        const bd = $('input[type=radio]:checked')[0];
        if (!bd) {
            $('#hint1').attr('hint-type', 'bd').html('未选择造价文件').show();
            return;
        }
        compareObj.data = JSON.parse(dy);
        const lib_data = JSON.parse(bd.getAttribute('lib-data'));
        compareObj.data.lib_id = lib_data.id;
        compareObj.data.lib_name = lib_data.filename;
        if (compareObj.data.xMatch) {
            compareObj.loadParentNode();
        } else {
            compareObj.load();
        }
    });
    $('#search-x').click(function () {
        const keyword = $('#x-keyword').val();
        if (keyword === '') return;

        const tr = $('tr', '#x-list');
        tr.removeClass('table-warning');
        for (const r of tr) {
            const name = r.children[2].innerText;
            if (name.indexOf(keyword) >= 0) {
                $('#hint2').hide();
                r.classList.add('table-warning');
                return;
            }
        }
        $('#hint2').html('未能搜索到匹配项').show();
    });
    $('#select').click(function () {
        if (compareObj.data.xMatch) {
            if (!compareObj.lastData || compareObj.lastData.lib_id !== compareObj.data.lib_id || compareObj.lastData.name !== compareObj.data.name) {
                compareObj.loadParentNode();
            } else {
                $('#select-data').modal('show');
            }
        }
    });
    $('#select-ok').click(function () {
        const select = $('input[type=checkbox]:checked');
        if (select.length === 0) {
            $('#hint2').html('未选择对比项').show();
            return;
        }
        compareObj.data.selects = [];
        for (const s of select) {
            compareObj.data.selects.push(JSON.parse(s.getAttribute('x-data')));
        }
        compareObj.load();
    });
    $('#export-excel').click(function () {
        const excelIo = new GC.Spread.Excel.IO();
        const date = new Date();
        const fileName = '单元对比.' + date.Format("yyyy.MM.dd.hh.mm.ss") + '.xlsx';
        const sJson = JSON.stringify(spread.toJSON());
        excelIo.save(sJson, function(blob) {
            saveAs(blob, fileName);
        });
    });
});