'use strict';
/**
 * 奖罚金
 *
 * @author Mai
 * @date 2020/2/12
 * @version
 */
const isPre = function (data) {
    return data && data.sid !== stageId;
};
$(document).ready(() => {
    autoFlashHeight();
    let datepicker;
    const spreadSetting = {
        cols: [
            {title: '名称', colSpan: '1', rowSpan: '1', field: 'name', hAlign: 0, width: 235, formatter: '@', readOnly: isPre, },
            {title: '类型', colSpan: '1', rowSpan: '1', field: 'b_type', hAlign: 0, width: 40, formatter: '@', readOnly: isPre, },
            {title: '金额', colSpan: '1', rowSpan: '1', field: 'tp', hAlign: 2, width: 100, type: 'Number', readOnly: isPre, },
            {
                title: '时间', colSpan: '1', rowSpan: '1', field: 'real_time', hAlign: 2, width: 150, readOnly: true,
                formatter: 'yyyy-MM-dd', cellType: 'activeImageBtn', normalImg: '#ellipsis-icon', indent: 5,
                showImage: function (data) {
                    return data !== undefined && data !== null;
                },
            },
            {title: '编号', colSpan: '1', rowSpan: '1', field: 'code', hAlign: 0, width: 150, formatter: '@', readOnly: isPre, },
            {title: '发文单位', colSpan: '1', rowSpan: '1', field: 'doc_co', hAlign: 0, width: 150, formatter: '@', readOnly: isPre},
            {
                title: '依据材料证明', colSpan: '1', rowSpan: '1', field: 'proof_file', hAlign: 1, width: 80, formatter: '@',
                readOnly: true, cellType: 'imageBtn', normalImg: '#rela-file-icon', hoverImg: '#rela-file-hover',
                getValue: function (data) {
                    return data.proof_file ? data.proof_file.length : 0;
                },
                showImage: function (data) {
                    return data !== undefined && data !== null;
                },
            },
            // {title: '依据材料证明', colSpan: '1', rowSpan: '1', field: 'proof', hAlign: 0, width: 150, formatter: '@', readOnly: isPre},
            {
                title: '计量期', colSpan: '1', rowSpan: '1', field: 'sorder', hAlign: 1, width: 100, formatter: '@',
                getValue: function (data) {
                    return '第' + data.sorder + '期';
                }, readOnly: true,
            },
            {title: '备注', colSpan: '1', rowSpan: '1', field: 'memo', hAlign: 0, width: 180, formatter: '@', cellType: 'ellipsisAutoTip', readOnly: isPre, }
        ],
        emptyRows: readOnly ? 0 : 3,
        headRows: 1,
        headRowHeight: [32],
        defaultRowHeight: 21,
        headerFont: '12px 微软雅黑',
        font: '12px 微软雅黑',
        readOnly: readOnly,
        localCache: {
            key: 'stage-extra-bonus',
            colWidth: true,
        },
        imageClick: function (data, hitinfo) {
            if (!data) return;
            const setting = hitinfo.sheet.zh_setting;
            if (!setting) return;
            const col = setting.cols[hitinfo.col];
            if (!col) return;
            if (col.field === 'proof_file') {
                fileObj.canUpload(data);
                fileObj.generateFilesHtml(data);
                $('#file').modal('show');
            }
            if (col.field === 'real_time' && !readOnly) {
                const pos = SpreadJsObj.getObjPos(hitinfo.sheet.getParent().qo);
                if (!datepicker) {
                    datepicker = $('.datepicker-here').datepicker({
                        language: 'zh',
                        dateFormat: 'yyyy-MM-dd',
                        autoClose: true,
                        onSelect: function (formattedDate, date, inst) {
                            if (!inst.visible) return;
                            const sels = hitinfo.sheet.getSelections();
                            if (!sels || !sels[0]) return;
                            const node = SpreadJsObj.getSelectObject(hitinfo.sheet);
                            const uData = { update: {id: node.id, real_time: date} };
                            postData(window.location.pathname + '/update', uData, function (result) {
                                bonusObj.loadUpdateData(result);
                                SpreadJsObj.reLoadRowData(hitinfo.sheet, sels[0].row);
                            }, function () {
                                SpreadJsObj.reLoadRowData(hitinfo.sheet, sels[0].row);
                            });
                        }
                    }).data('datepicker');
                }
                const value = hitinfo.sheet.getValue(hitinfo.row, hitinfo.col);
                if (value) {
                    datepicker.selectDate(new Date(value));
                } else {
                    datepicker.clear();
                }
                datepicker.show();
                if (hitinfo.cellRect.y + pos.y + 272 > $('.main-panel').height()) {
                    datepicker.update({
                        position: 'top left',
                    })
                } else {
                    datepicker.update({
                        position: 'bottom left',
                    })
                }
                $('#datepickers-container').css('top', hitinfo.cellRect.y + pos.y).css('left', hitinfo.cellRect.x + pos.x);
            }
        }
    };
    const bonusSpread = SpreadJsObj.createNewSpread($('#bonus-spread')[0]);
    const bonusSheet = bonusSpread.getActiveSheet();
    spreadSetting.readOnly = readOnly;
    SpreadJsObj.initSheet(bonusSheet, spreadSetting);
    $.subMenu({
        menu: '#sub-menu', miniMenu: '#sub-mini-menu', miniMenuList: '#mini-menu-list',
        toMenu: '#to-menu', toMiniMenu: '#to-mini-menu',
        key: 'menu.1.0.0',
        miniHint: '#sub-mini-hint', hintKey: 'menu.hint.1.0.1',
        callback: function (info) {
            if (info.mini) {
                $('.panel-title').addClass('fluid');
                $('#sub-menu').removeClass('panel-sidebar');
            } else {
                $('.panel-title').removeClass('fluid');
                $('#sub-menu').addClass('panel-sidebar');
            }
            autoFlashHeight();
            bonusSpread.refresh();
        }
    });
    const fileObj = {
        generateFilesHtml(data) {
            const id = data.id, files = data.proof_file;
            let html = [];
            if (files !== null && files !== undefined) {
                for (const [i, f] of files.entries()) {
                    html.push('
');
                    html.push('| ', f.filename + f.fileext, '');
                    html.push(' | ', f.username, '');
                    html.push(' | ', f.in_time, '');
                    html.push(' | ');
                    // 下载
                    html.push('');
                    // 删除
                    if (!readOnly && !isPre(data)) {
                        html.push('');
                    }
                    html.push('');
                    html.push(' | 
');
                }
            }
            $('#file-list').html(html.join(''));
        },
        uploadFile() {
            const files = this.files;
            const select = SpreadJsObj.getSelectObject(bonusSheet);
            const formData = new FormData();
            formData.append('bonus_id', select.id);
            for (const file of files) {
                if (file === undefined) {
                    toastr.error('未选择上传文件。');
                    return false;
                }
                if (file.size > 30 * 1024 * 1024) {
                    toastr.error('上传文件大小超过30MB。');
                    return false;
                }
                const fileext = '.' + file.name.toLowerCase().split('.').splice(-1)[0];
                if (whiteList.indexOf(fileext) === -1) {
                    toastr.error('仅支持office文档、图片、压缩包格式,请勿上传' + fileext + '格式文件。');
                    return false;
                }
                formData.append('size[]', file.size);
                formData.append('file[]', file);
            }
            postDataWithFile('upload/file', formData, function (data) {
                select.proof_file = data;
                fileObj.generateFilesHtml(select);
                SpreadJsObj.reLoadNodesData(bonusSheet, [select]);
            });
            $(this).val('');
        },
        deleteFile() {
            const data = {
                b_id: $(this).attr('data-id'),
                index: parseInt($(this).attr('file-index')),
            };
            postData('delete/file', data, function (data) {
                const select = SpreadJsObj.getSelectObject(bonusSheet);
                select.proof_file = data;
                fileObj.generateFilesHtml(select);
                SpreadJsObj.reLoadNodesData(bonusSheet, [select]);
            });
        },
        canUpload(data) {
            if (data.sid === stageId) {
                $('#upload-file-panel').show();
            } else {
                $('#upload-file-panel').hide();
            }
        }
    };
    class Bonus {
        constructor () {
            this.data = [];
        }
        resortData() {
            this.data.sort(function (a, b) {
                return a.sorder !== b.sorder ? a.sorder - b.sorder : a.order - b.order;
            });
        }
        loadDatas(datas) {
            this.data = datas;
            this.resortData();
        }
        loadUpdateData(updateData) {
            if (updateData.add) {
                for (const a of updateData.add) {
                    this.data.push(a);
                }
            }
            if (updateData.update) {
                for (const u of updateData.update) {
                    const d = this.data.find(function (x) {
                        return u.id === x.id;
                    });
                    if (d) {
                        _.assign(d, u);
                    } else {
                        this.data.push(d);
                    }
                }
            }
            if (updateData.del) {
                _.remove(this.data, function (d) {
                    return updateData.del.indexOf(d.id) >= 0;
                });
            }
            this.resortData();
        }
        getCurStageNewOrder() {
            const cur = this.data.filter(function (x) {
                return x.sid === stageId;
            });
            return cur && cur.length > 0 ? cur.length + 1 : 1;
        }
        checkCurFirst(bonusData) {
            const cur = this.data.filter(function (x) {
                return x.sid === stageId;
            });
            return cur.indexOf(bonusData) === 0;
        }
        checkCurLast(bonusData) {
            const cur = this.data.filter(function (x) {
                return x.sid === stageId;
            });
            return cur.indexOf(bonusData) === cur.length - 1;
        }
    }
    const bonusObj = new Bonus();
    postData(window.location.pathname + '/load', null, function (result) {
        bonusObj.loadDatas(result);
        SpreadJsObj.loadSheetData(bonusSheet, SpreadJsObj.DataType.Data, bonusObj.data);
    });
    if (!readOnly) {
        const bonusOprObj = {
            /**
             * 删除按钮响应事件
             * @param sheet
             */
            deletePress: function (sheet) {
                if (!sheet.zh_setting || readOnly) return;
                const sortData = sheet.zh_data;
                const datas = [];
                const sels = sheet.getSelections();
                if (!sels || !sels[0]) return;
                const hint = {
                    name: {type: 'warning', msg: '名称不能为空,如需删除甲供材料请使用右键删除'},
                };
                for (let iRow = sels[0].row; iRow < sels[0].row + sels[0].rowCount; iRow++) {
                    let bDel = false;
                    const node = sortData[iRow];
                    if (node) {
                        const data = {id: node.id};
                        for (let iCol = sels[0].col; iCol < sels[0].col + sels[0].colCount; iCol++) {
                            const colSetting = sheet.zh_setting.cols[iCol];
                            if (colSetting.field === 'name') {
                                toastMessageUniq(hint.name);
                                return;
                            }
                            const style = sheet.getStyle(iRow, iCol);
                            if (!style.locked) {
                                const colSetting = sheet.zh_setting.cols[iCol];
                                data[colSetting.field] = null;
                                bDel = true;
                            }
                        }
                        if (bDel) {
                            datas.push(data);
                        }
                    }
                }
                if (datas.length > 0) {
                    postData(window.location.pathname + '/update', {update: datas}, function (result) {
                        bonusObj.loadUpdateData(result);
                        SpreadJsObj.reLoadSheetData(bonusSheet);
                    }, function () {
                        SpreadJsObj.reLoadSheetData(bonusSheet);
                    });
                }
            },
            delete: function () {
                const sheet = bonusSheet;
                if (!sheet.zh_setting || readOnly) return;
                const sortData = sheet.zh_data;
                const datas = [];
                const sels = sheet.getSelections();
                if (!sels || !sels[0]) return;
                const hint = {
                    isOld: {type: 'warning', msg: '本项为往期数据,不可删除'},
                    invalidDel: {type: 'warning', msg: '本项不是您新增的,只有原报和新增人可删除'},
                };
                for (let iRow = sels[0].row, iLen = sels[0].row + sels[0].rowCount; iRow < iLen; iRow++) {
                    const node = sortData[iRow];
                    if (node.sid !== stageId) {
                        toastMessageUniq(hint.isOld);
                        continue;
                    } else {
                        if (node.uid !== userID && stageUserId !== userID) {
                            toastMessageUniq(hint.invalidDel);
                            continue;
                        }
                        datas.push(node.id);
                    }
                }
                if (datas.length > 0) {
                    postData(window.location.pathname + '/update', {del: datas}, function (result) {
                        bonusObj.loadUpdateData(result);
                        SpreadJsObj.reLoadSheetData(sheet);
                    }, function () {
                        SpreadJsObj.reLoadSheetData(sheet);
                    });
                }
            },
            editEnded: function (e, info) {
                if (!info.sheet.zh_setting || !info.sheet.zh_data) return;
                const node = info.sheet.zh_data[info.row];
                const col = info.sheet.zh_setting.cols[info.col];
                const data = {};
                if (node) {
                    data.update = {};
                    data.update.id = node.id;
                    const oldValue = node ? node[col.field] : null;
                    const newValue = trimInvalidChar(info.editingText);
                    if (oldValue == info.editingText || ((!oldValue || oldValue === '') && (newValue === ''))) {
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        return;
                    }
                    data.update[col.field] = newValue;
                } else {
                    if (col.field !== 'name') {
                        toastr.warning('新增奖罚金,请先输入名称');
                        SpreadJsObj.reLoadRowData(info.sheet, info.row);
                        return;
                    }
                    data.add = {};
                    data.add.order = bonusObj.getCurStageNewOrder();
                    data.add.name = trimInvalidChar(info.editingText);
                }
                postData(window.location.pathname + '/update', data, function (result) {
                    bonusObj.loadUpdateData(result);
                    SpreadJsObj.reLoadSheetData(info.sheet);
                }, function () {
                    SpreadJsObj.reLoadRowData(info.sheet, info.row);
                });
            },
            clipboardPasting(e, info) {
                const setting = info.sheet.zh_setting, sortData = info.sheet.zh_data;
                info.cancel = true;
                if (!setting || !sortData) return;
                const pasteData = info.pasteData.html
                    ? SpreadJsObj.analysisPasteHtml(info.pasteData.html)
                    : (info.pasteData.text === ''
                        ? SpreadJsObj.Clipboard.getAnalysisPasteText()
                        : SpreadJsObj.analysisPasteText(info.pasteData.text));
                const hint = {
                    name: {type: 'warning', msg: '奖罚金名称不可为空,已过滤'},
                    tp: {type: 'warning', msg: '输入的 金额 非法,已过滤'},
                };
                const uDatas = [], iDatas = [], maxOrder = bonusObj.getCurStageNewOrder();
                for (let iRow = 0; iRow < info.cellRange.rowCount; iRow++) {
                    const curRow = info.cellRange.row + iRow;
                    const node = sortData[curRow];
                    let bPaste = false;
                    const data = {};
                    for (let iCol = 0; iCol < info.cellRange.colCount; iCol++) {
                        const curCol = info.cellRange.col + iCol;
                        const colSetting = setting.cols[curCol];
                        const value = trimInvalidChar(pasteData[iRow][iCol]);
                        if (colSetting.field === 'name' && (!value || value === '')) {
                            toastMessageUniq(hint.name);
                            break;
                        }
                        if (colSetting.type === 'Number') {
                            const num = _.toNumber(value);
                            if (num) {
                                data[colSetting.field] = num;
                                bPaste = true;
                            }
                        } else {
                            data[colSetting.field] = value;
                            bPaste = true;
                        }
                    }
                    if (bPaste) {
                        if (node) {
                            data.id = node.id;
                            uDatas.push(data);
                        } else {
                            data.order = maxOrder + iRow;
                            iDatas.push(data);
                        }
                    }
                }
                const updateData = {};
                if (uDatas.length > 0) updateData.update = uDatas;
                if (iDatas.length > 0) updateData.add = iDatas;
                if (uDatas.length > 0 || iDatas.length > 0) {
                    postData(window.location.pathname + '/update', updateData, function (result) {
                        bonusObj.loadUpdateData(result);
                        SpreadJsObj.reLoadSheetData(info.sheet);
                    });
                } else {
                    SpreadJsObj.reLoadSheetData(info.sheet);
                }
            },
            upMove: function () {
                const sheet = bonusSheet;
                const sels = sheet.getSelections(), sortData = sheet.zh_data;
                const node = sortData[sels[0].row];
                const preNode = sortData[sels[0].row - 1];
                const data = [
                    {id: node.id, order: preNode.order},
                    {id: preNode.id, order: node.order}
                ];
                postData(window.location.pathname + '/update', {update: data}, function (result) {
                    bonusObj.loadUpdateData(result);
                    SpreadJsObj.reLoadRowsData(sheet, [sels[0].row, sels[0].row - 1]);
                    sheet.setSelection(sels[0].row - 1, sels[0].col, sels[0].rowCount, sels[0].colCount);
                });
            },
            downMove: function () {
                const sheet = bonusSheet;
                const sels = sheet.getSelections(), sortData = sheet.zh_data;
                const node = sortData[sels[0].row];
                const nextNode = sortData[sels[0].row + 1];
                const data = [
                    {id: node.id, order: nextNode.order},
                    {id: nextNode.id, order: node.order}
                ];
                postData(window.location.pathname + '/update', {update: data}, function (result) {
                    bonusObj.loadUpdateData(result);
                    SpreadJsObj.reLoadRowsData(sheet, [sels[0].row, sels[0].row + 1]);
                    sheet.setSelection(sels[0].row + 1, sels[0].col, sels[0].rowCount, sels[0].colCount);
                });
            }
        };
        bonusSheet.bind(spreadNS.Events.EditEnded, bonusOprObj.editEnded);
        bonusSheet.bind(spreadNS.Events.ClipboardPasting, bonusOprObj.clipboardPasting);
        SpreadJsObj.addDeleteBind(bonusSpread, bonusOprObj.deletePress);
        $.contextMenu({
            selector: '#bonus-spread',
            build: function ($trigger, e) {
                const target = SpreadJsObj.safeRightClickSelection($trigger, e, bonusSpread);
                return target.hitTestType === spreadNS.SheetArea.viewport || target.hitTestType === spreadNS.SheetArea.rowHeader;
            },
            items: {
                del: {
                    name: '删除',
                    icon: 'fa-remove',
                    callback: function (key, opt) {
                        bonusOprObj.delete();
                    },
                    disabled: function (key, opt) {
                        const sels = bonusSheet.getSelections();
                        if (!sels || !sels[0]) return true;
                        const row = sels[0].row;
                        const node = bonusObj.data[row];
                        return node === undefined || node === null || node.sid !== stageId;
                    },
                    visible: function (key, opt) {
                        return !readOnly;
                    }
                },
                sprDel: '------------',
                upMove: {
                    name: '上移',
                    icon: 'fa-arrow-up',
                    callback: function (key, opt) {
                        bonusOprObj.upMove();
                    },
                    disabled: function (key, opt) {
                        const sels = bonusSheet.getSelections();
                        if (!sels || !sels[0] || sels[0].row === 0) return true;
                        const row = sels[0].row;
                        const node = bonusObj.data[row];
                        return node === undefined || node === null || node.sid !== stageId || bonusObj.checkCurFirst(node);
                    },
                    visible: function (key, opt) {
                        return !readOnly;
                    }
                },
                downMove: {
                    name: '下移',
                    icon: 'fa-arrow-down',
                    callback: function (key, opt) {
                        bonusOprObj.downMove();
                    },
                    disabled: function (key, opt) {
                        const sels = bonusSheet.getSelections();
                        if (!sels || !sels[0] || sels[0].row >= bonusObj.data.length - 1) return true;
                        const row = sels[0].row;
                        const node = bonusObj.data[row];
                        return node === undefined || node === null || node.sid !== stageId || bonusObj.checkCurLast(node);
                    },
                    visible: function (key, opt) {
                        return !readOnly;
                    }
                }
            },
        });
    }
    $('#exportExcel').click(function () {
        SpreadExcelObj.exportSimpleXlsxSheet(spreadSetting, bonusObj.data, $('h2')[0].innerHTML + "-奖罚金.xlsx");
    });
    $('#upload-file').change(fileObj.uploadFile);
    $('body').on('click', '.delete-att', fileObj.deleteFile);
});