'use strict';

/**
 *
 *
 * @author Mai
 * @date 2018/5/15
 * @version
 */

$(document).ready(function () {
    const spreadNS = GC.Spread.Sheets;

    class CompareObj {
        constructor (obj) {
            this.spread = new spreadNS.Workbook(obj, {sheetCount: 1});
            this.spread.options.tabStripVisible = false;
            this.spread.options.scrollbarMaxAlign = true;
            this.spread.options.cutCopyIndicatorVisible = false;
            this.spread.options.allowCopyPasteExcelStyle = false;
            this.spread.options.allowUserDragDrop = false;

            this.sheet = this.spread.getActiveSheet();
            //this.sheet.options.rowHeaderVisible = false;
            //this.sheet.options.colHeaderVisible = false;

            this.borderLine = new spreadNS.LineBorder('black', spreadNS.LineStyle.thin);
            this.paperSize = new spreadNS.Print.PaperSize(spreadNS.Print.PaperKind.a4);

            this.initCompareHeader([]);
        }
        initCompareHeader (tenders) {
            this.tenders = tenders;
            const cols = {}, colsName = [];
            const indexColCount = this.tenders.length > 0 ? this.tenders.length + 1 : 0;

            SpreadJsObj.beginMassOperationSheet(this.sheet);

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

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

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

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

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

            if (this.tenders.length > 0) {
                this.sheet.getCell(0, cols.unit2+1).text('经济指标').hAlign(hCenter).vAlign(vCenter);
                //this.sheet.removeSpan(0, cols.unit2+1, spreadNS.SheetArea.viewport);
                this.sheet.addSpan(0, cols.unit2+1, 1, this.tenders.length);
                for (let i = 0, iLen = this.tenders.length; i < iLen; i++) {
                    colsName.push('lib_' + this.tenders[i].lib_id);
                    cols['lib_' + this.tenders[i].lib_id] = 4+i;
                    this.sheet.getCell(1, cols['lib_' + this.tenders[i].lib_id])
                        .text(this.tenders[i].filename).hAlign(hCenter).vAlign(vCenter);
                    this.sheet.setColumnWidth(cols['lib_' + this.tenders[i].lib_id], 100);
                }

                colsName.push('averageIndex');
                cols.averageIndex = 4+this.tenders.length;
                this.sheet.getCell(0, cols.averageIndex).text('平均指标').hAlign(hCenter).vAlign(vCenter);
                //this.sheet.removeSpan(0, cols.averageIndex, spreadNS.SheetArea.viewport);
                this.sheet.addSpan(0, cols.averageIndex, 2, 1);
                this.sheet.setColumnWidth(cols.averageIndex, 100);
            }

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

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

            this.colsName = colsName;
            this.cols = cols;
            this.sheet.getRange(0, 0, this.sheet.getRowCount(), this.sheet.getColumnCount()).setBorder(this.borderLine, {all: true});

            SpreadJsObj.endMassOperationSheet(this.sheet);
        }
        sortData (data) {
            function findTenderData (data, tenderId) {
                for (const tender of data) {
                    if (tender.lib_id === tenderId) {
                        return tender.data;
                    }
                }
                return null;
            }
            function findNode(data, src, tenderId) {
                for (const node of data) {
                    const field = 'bills_id' + tenderId;
                    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 tender of this.tenders) {
                const searchData = findTenderData(data, tender.lib_id);
                for (const node of searchData) {
                    let sortNode = findNode(result, node, tender.lib_id);
                    if (!sortNode) {
                        sortNode = {
                            code: node.code,
                            name: node.name,
                            indexes: [],
                        };
                        result.push(sortNode);
                    }
                    sortNode['bills_id' + tender.lib_id] = node.bills_id;
                    for (const index of node.children) {
                        let sortIndex = findIndex(sortNode.indexes, index);
                        if (!sortIndex) {
                            sortIndex = {
                                code: index.code,
                                name: index.name,
                                unit1: index.unit1,
                                unit2: index.unit2,
                                sumValue: 0,
                                rule: index.rule,
                                memo: index.memo,
                            };
                            sortNode.indexes.push(sortIndex)
                        }
                        sortIndex['lib_' + tender.lib_id] = index.value;
                        sortIndex.sumValue += index.value;
                    }
                }
            }
            return result;
        }
        loadData (data) {
            const self = this;
            const colCount = compareObj.tenders.length > 0 ? 6+compareObj.tenders.length+1 : 6;
            this.searchData = data;
            this.showData = this.sortData(this.searchData);
            function loadNode (node, row) {
                self.sheet.getCell(row, self.cols.code).text(node.code).wordWrap(true);
                self.sheet.getCell(row, self.cols.name).text(node.name).wordWrap(true);
                self.sheet.getRange(row, 0, 1, colCount).backColor('#dae5ee');
                self.sheet.autoFitRow(row);
            }
            function loadIndex(index, row) {
                for (const colName of self.colsName) {
                    if (colName === 'averageIndex') {
                        const aver = Number((index.sumValue / self.tenders.length).toFixed(2));
                        self.sheet.getCell(row, self.cols[colName]).value(aver).wordWrap(true);
                    } else if (index[colName]) {
                        self.sheet.getCell(row, self.cols[colName]).value(index[colName]).wordWrap(true);
                    }
                }
                self.sheet.autoFitRow(row);
            }
            let iRow = 2;
            SpreadJsObj.massOperationSheet(this.sheet, function () {
                self.sheet.setRowCount(2);
                for (const node of self.showData) {
                    self.sheet.addRows(iRow, 1);
                    loadNode(node, iRow);
                    iRow += 1;
                    for (const index of node.indexes) {
                        self.sheet.addRows(iRow, 1);
                        loadIndex(index, iRow);
                        iRow += 1;
                    }
                }
                self.sheet.getRange(-1, -1, self.sheet.getRowCount(), self.sheet.getColumnCount()).setBorder(self.borderLine, {all: true});
            });
        }
        searchIndex (keyword) {
            const self = this;
            const data = {
                tenders: this.tenders,
                keyword: keyword,
            };
            postData('/compare/search', data, function (datas) {
                self.loadData(datas);
            });
        }
    }
    const compareObj = new CompareObj($('#compare-spread')[0]);

    $('#generate-ok').click(function () {
        const select = $('tr[class!=table-secondary][lib_id]');
        const tender= [];
        for (let i = 0, iLen = select.length; i < iLen; i++) {
            tender.push({
                lib_id: parseInt($(select[i]).attr('lib_id')),
                filename: $('td:first', $(select[i])).text(),
            });
        }
        $('a[href="#generate-data"]').text('造价文件: ' + tender.length);
        compareObj.initCompareHeader(tender);
        $('#generate-data').modal('hide');
    });

    $('#search').click(function () {
        compareObj.searchIndex($('#keyword').val());
    });

    $('#export-excel').click(function () {
        const excelIo = new GC.Spread.Excel.IO();
        const fileName = '指标对比.xlsx';
        const sJson = JSON.stringify(compareObj.spread.toJSON());
        excelIo.save(sJson, function(blob) {
            saveAs(blob, fileName);
        });
    })

    // $.contextMenu({
    //     selector: '#compare-spread',
    //     build: function ($trigger, e) {
    //         const target = SpreadJsObj.safeRightClickSelection($trigger, e, compareObj.spread);
    //         return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
    //     },
    //     items: {
    //         'print': {
    //             name: '打印',
    //             icon: 'fa-sign-in',
    //             callback: function (key, opt) {
    //                 const printInfo = new spreadNS.Print.PrintInfo();
    //                 printInfo.showBorder(false);
    //                 printInfo.showGridLine(false);
    //                 printInfo.paperSize(compareObj.paperSize);
    //                 printInfo.orientation(spreadNS.Print.PrintPageOrientation.landscape);
    //                 printInfo.margin({top:20, bottom:20, left:20, right:20, header:10, footer:20});
    //                 //printInfo.qualityFactor(6);
    //                 compareObj.sheet.printInfo(printInfo);
    //                 compareObj.spread.print();
    //             }
    //         },
    //         'exportExcel': {
    //             name: '导出excel',
    //             callback: function (key, opt) {
    //                 const excelIo = new GC.Spread.Excel.IO();
    //                 const fileName = '1.xlsx';
    //                 const sJson = JSON.stringify(compareObj.spread.toJSON());
    //                 excelIo.save(sJson, function(blob) {
    //                     saveAs(blob, fileName);
    //                 });
    //             }
    //         },
    //         'exportPDF': {
    //             name: '导出PDF',
    //             callback: function (key, opt) {
    //                  compareObj.spread.savePDF();
    //             }
    //         }
    //     }
    // });
});