'use strict';
/**
 *
 *
 * @author Mai
 * @date 2018/6/21
 * @version
 */
function getMid() {
    return window.location.pathname.split('/')[3];
}
// 新增计量范围
function addMeasurePos(pid) {
    postData('/measure/pos', {
        mid: window.location.pathname.split('/')[3],
        operate: 'add',
        pid: pid,
    }, function (data) {
        const tr = [];
        tr.push('
');
        tr.push('| ' + data.code + '');
        tr.push(' | ' + data.name + '');
        tr.push(' | 移除');
        tr.push(' | 
');
        $('#measurePosList').append(tr.join(''));
    })
}
// 移除计量范围
function removeMeasurePos(pid) {
    postData('/measure/pos', {
        mid: getMid(),
        operate: 'remove',
        pid: pid,
    }, function (data) {
        $('tr[id='+ pid +']', '#measurePosList').remove();
    })
}
//
function getAuditorHtml(audit) {
    const html = [];
    html.push('移除');
    html.push('');
    html.push(audit.order + ' ');
    html.push(audit.name + ' ');
    html.push('');
    html.push('');
    html.push(audit.role);
    html.push('')
    return html.join('');
}
function bindRemoveAuditor(obj) {
    obj.click(function () {
        const li = $(this).parent();
        const data = {
            mid: getMid(),
            auditorId: parseInt(li.attr('auditorId')),
        }
        postData('/measure/audit/remove', data, (data) => {
            li.remove();
            for (const a of data) {
                const aLi = $('li[auditorId=' + a.audit_id + ']');
                $('span', aLi).text(a.order + ' ' + a.name + ' ');
            }
        });
    });
}
function getAuditStatuHtml(measure) {
    const html = [];
    if (measure.status === auditConst.status.checkNo) {
        html.push('报审退回');
    } else if (measure.status === auditConst.status.checking) {
        html.push('审批中');
    } else if (measure.status === auditConst.status.checked) {
        html.push('审批完成');
    }
    if (measure.user_id === userId ) {
        if (!measure.status || measure.status === auditConst.status.uncheck) {
            html.push('上报审批');
        } else if (measure.status === auditConst.status.checkNo) {
            html.push('重新上报');
        }
        html.push('删除' + measure.code + '');
    }
    return html.join('');
}
function getAuditListHtml(measure) {
    const html = [];
    for (const auditor of measure.auditors) {
        html.push('');
        if (auditor.status !== auditConst.status.uncheck) {
            html.push('' + auditConst.statusString[auditor.status] + '');
        }
        html.push('' + auditor.order + ' ' + auditor.name + ' ' + auditor.role + '
');
        html.push('', (auditor.opinion ? auditor.opinion : ''), ' ', (auditor.end_time ? moment(auditor.end_time).format('YYYY-MM-DD') : ''), '
');
        html.push('');
    }
    return html.join('');
}
$(document).ready(() => {
    autoFlashHeight();
    // 上报审批 搜索
    $('#searchAccount').click(() => {
        const data = {
            keyword: $('#searchName').val(),
        }
        postData('/search/user', data, (data) => {
            const resultDiv = $('#searchResult');
            $('h5>span', resultDiv).text(data.name);
            $('#addAuditor').attr('auditorId', data.id);
            $('h6', resultDiv).text(data.role);
            $('p', resultDiv).text(data.company);
            resultDiv.show();
        }, () => {
            $('#searchResult').hide();
        });
    });
    // 上报审批 添加审批人
    $('#addAuditor').click(() => {
        const data = {
            mid: getMid(),
            auditorId: $('#addAuditor').attr('auditorId'),
        };
        postData('/measure/audit/add', data, (data) => {
            $('#auditors').append(getAuditorHtml(data));
            bindRemoveAuditor($('li[auditorId=' + data.audit_id + ']>a'));
        });
    });
    // 上报审批
    $('#auditStart').click(() => {
        const data = { mid: getMid() };
        postData('/measure/audit/start', data, function (data) {
            $('#sub-sp').modal('hide');
            // 审批状态等
            $('#operate').html(getAuditStatuHtml(data));
            // 审批流程列表
            $('ul', '#sp-list').html(getAuditListHtml(data));
        });
    });
    // 重新上报
    $('#auditRestart').click(() => {
        const data = { mid: getMid() };
        postData('/measure/audit/start', data, function (data) {
            $('#sub-sp2').modal('hide');
            // 审批状态等
            $('#operate').html(getAuditStatuHtml(data));
            // 审批流程列表
            $('ul', '#sp-list').html(getAuditListHtml(data));
        });
    });
    const billsTree = createNewPathTree('measure', {
        id: 'ledger_id',
        pid: 'ledger_pid',
        order: 'order',
        level: 'level',
        rootId: -1,
        keys: ['id', 'tender_id', 'ledger_id'],
    });
    let billsSpread;
    // 获取中间计量详细数据
    function getMeasureDetail(mid) {
        postData('/measure/detail', { mid: mid }, function(data) {
            // 计量范围
            const posHtml = [];
            for (const p of data.pos) {
                const tr = [];
                tr.push('');
                tr.push('| ' + p.code + '');
                tr.push(' | ' + p.name + '');
                tr.push(' | 移除');
                tr.push(' | 
');
                posHtml.push(tr.join(''));
            }
            $('#measurePosList').html(posHtml.join(''));
            // 计量清单
            billsTree.loadDatas(data.billsTree);
            treeCalc.calculateAll(billsTree, ['total_price', 'deal_totalprice', 'qc_totalprice']);
            if (!billsSpread) {
                billsSpread = SpreadJsObj.createNewSpread($('#billsSpread')[0]);
                const sheet = billsSpread.getActiveSheet();
                SpreadJsObj.initSheet(sheet, measureSpreadSetting);
                SpreadJsObj.loadSheetData(sheet, 'tree', billsTree);
                /**
                 * 父项不可编辑
                 * sender - {type: 'EditStarting'}
                 * args - {sheet, sheetName, row, col, cancel}
                 */
                sheet.bind(spreadNS.Events.EditStarting, function (sender, args) {
                    const sheet = args.sheet;
                    if (sheet.zh_tree) {
                        const node = sheet.zh_tree.nodes[args.row];
                        args.cancel = node ? !node.is_leaf : true;
                    } else {
                        args.cancel = true;
                    }
                });
                /**
                 * 最底层清单编辑后,提交
                 * sender - {type: 'EditEnding'}
                 * args - {sheet, sheetName, row, col, editor, editingText cancel}
                 */
                sheet.bind(spreadNS.Events.EditEnding, function (sender, args) {
                    const sheet = args.sheet;
                    if (sheet.zh_tree || sheet.zh_setting) {
                        const node = sheet.zh_tree.nodes[args.row];
                        const col = sheet.zh_setting.cols[args.col];
                        if (node && node.is_leaf) {
                            const updateData = {
                                mid: getMid(),
                                bid: node.ledger_id,
                                update: {},
                            }
                            updateData.update[col.field] = col.type === 'Number' ? parseFloat(args.editingText) : args.editingText;
                            postData('/measure/billsUpdate', updateData, function (data) {
                                if (sheet.zh_tree.loadLeafData) {
                                    sheet.zh_tree.loadLeafData(data);
                                    const nodes = treeCalc.calculateParent(sheet.zh_tree, node, ['deal_totalprice', 'qc_totalprice']);
                                    SpreadJsObj.reLoadNodesData(sheet, nodes);
                                }
                            }, function () {
                                args.cancel = true;
                            });
                        } else {
                            args.cancel = true;
                        }
                    } else {
                        args.cancel = true;
                    }
                });
            } else {
                SpreadJsObj.reLoadSheetData(billsSpread.getActiveSheet());
            }
            // 审批状态等
            $('#operate').html(getAuditStatuHtml(data));
            $('ul', '#sp-list').html(getAuditListHtml(data));
            // 上报审批 审批人列表
            const ad = [];
            for (const auditor of data.auditors) {
                ad.push(getAuditorHtml(auditor));
            }
            $('#auditors').html(ad.join(''));
            // 重新上报 审批人列表
            if (data.status === auditConst.status.checkNo) {
                $('#re-hint').text('重新上报后,将由 ' + data.auditors[0].name +' 继续审批');
                $('#re-auditors').html(getAuditListHtml(data));
            }
            // 绑定移除方法
            bindRemoveAuditor($('a', '#auditors'));
        });
    }
    // 新增计量清单
    function addMeasureBills (bid) {
        const data = {
            mid: getMid(),
            operate: 'add',
            bid: bid,
        };
        postData('/measure/bills', data, function (data) {
            billsTree.addData(data);
            SpreadJsObj.reLoadSheetData(billsSpread.getActiveSheet());
        });
    }
    // 移除计量清单
    function removeMeasureBills (bid) {
        const data = {
            mid: getMid(),
            operate: 'remove',
            bid: bid,
        };
        postData('/measure/bills', data, function (data) {
            billsTree.removeData(data);
            SpreadJsObj.reLoadSheetData(billsSpread.getActiveSheet());
        });
    }
    // 勾选计量清单
    function checkMeasureBills() {
        const bid = $(this).parent().parent().attr('id');
        if (!bid) { return; }
        if (this.checked) {
            addMeasureBills(bid);
        } else {
            removeMeasureBills(bid);
        }
    }
    // 添加计量清单
    $('#addMeasureBills').click(function () {
        if ($('#measurePosList').children().length === 0) {
            $('#add-pos').modal('show');
        } else {
            $('#add-qd').modal('show');
        }
    });
    // 搜索项目节部位
    $('#search-pos').click(function () {
        const keyword = $('input', '#add-pos').val();
        if (keyword !== '') {
            postData('/measure/search', {
                mid: getMid(),
                searchType: 'pos',
                keyword: keyword
            }, function (data) {
                const html = [];
                for (const d of data) {
                    const tr = [];
                    tr.push('');
                    tr.push('| ' + d.code + '');
                    tr.push(' | ' + d.name + '');
                    tr.push(' | 添加');
                    tr.push(' | 
');
                    html.push(tr.join(''));
                }
                $('#searchedPosList').html(html.join(''));
            });
        }
    });
    // 选择计量清单
    $('#chooseBills').click(function () {
        $('#add-pos').modal('hide');
        $('#add-qd').modal('show');
    });
    // 搜索计量清单
    $('#search-bills').click(function () {
        const keyword = $('input', '#add-qd').val();
        if (keyword !== '') {
            postData('/measure/search', {
                mid: getMid(),
                searchType: 'bills',
                keyword: keyword
            }, function (data) {
                const html = [];
                for (const d of data) {
                    const tr = [];
                    const check = billsTree.getItems(d.ledger_id) ? 'checked' : '';
                    tr.push('');
                    tr.push('| ' + d.b_code + '');
                    tr.push(' | ' + d.name + '');
                    tr.push(' | ' + d.unit + '');
                    tr.push(' | ' + (d.unit_price ? d.unit_price : '') + '');
                    tr.push(' | 已选择');
                    tr.push(' | 
');
                    html.push(tr.join(''));
                }
                $('#searchedBillsList').html(html.join(''));
                $('input[type=checkbox]', '#add-qd').click(checkMeasureBills);
            });
        }
    });
    // 选择计量范围
    $('#choosePos').click(function () {
        $('#add-qd').modal('hide');
        $('#add-pos').modal('show');
    });
    getMeasureDetail(getMid());
});