'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 id="' + data.pid +'">');
        tr.push('<td>' + data.code + '</td>');
        tr.push('<td>' + data.name + '</td>');
        tr.push('<td><a href="javascript: void(0)" class="text-danger" onclick="removeMeasurePos(' + data.pid + ')">移除</a></td>');
        tr.push('</tr>');
        $('#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('<li class="list-group-item" auditorId="'+ audit.audit_id +'"><a href="javascript: void(0)" class="text-danger pull-right">移除</a>');
    html.push('<span>');
    html.push(audit.order + ' ');
    html.push(audit.name + ' ');
    html.push('</span>');
    html.push('<small class="text-muted">');
    html.push(audit.role);
    html.push('</small></li>')
    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('<a href="#sp-list" data-toggle="modal" data-target="#sp-list" class="btn btn-outline-warning btn-sm pull-right text-dark">报审退回</a>');
    } else if (measure.status === auditConst.status.checking) {
        html.push('<a href="#sp-list" data-toggle="modal" data-target="#sp-list" class="btn btn-outline-warning btn-sm pull-right text-dark">审批中</a>');
    } else if (measure.status === auditConst.status.checked) {
        html.push('<a href="#sp-list" data-toggle="modal" data-target="#sp-list" class="btn btn-outline-secondary btn-sm pull-right">审批完成</a>');
    }
    if (measure.user_id === userId ) {
        if (!measure.status || measure.status === auditConst.status.uncheck) {
            html.push('<a href="#sub-sp" data-toggle="modal" data-target="#sub-sp" class="btn btn-primary btn-sm pull-right">上报审批</a>');
        } else if (measure.status === auditConst.status.checkNo) {
            html.push('<a href="#sub-sp" data-toggle="modal" data-target="#sub-sp2" class="btn btn-primary btn-sm pull-right">重新上报</a>');
        }
        html.push('<a href="#del" data-toggle="modal" data-target="#del" class="btn btn-outline-danger btn-sm pull-right">删除' + measure.code + '</a>');
    }
    return html.join('');
}
function getAuditListHtml(measure) {
    const html = [];
    for (const auditor of measure.auditors) {
        html.push('<li class="list-group-item" auditorId="' + auditor.audit_id + '">');
        if (auditor.status !== auditConst.status.uncheck) {
            html.push('<span class="' + auditConst.statusClass[auditor.status] + ' pull-right">' + auditConst.statusString[auditor.status] + '</span>');
        }
        html.push('<h5 class="card-title">' + auditor.order + ' ' + auditor.name + ' <small class="text-muted">' + auditor.role + '</small></h5>');
        html.push('<p class="card-text">', (auditor.opinion ? auditor.opinion : ''), ' ', (auditor.end_time ? moment(auditor.end_time).format('YYYY-MM-DD') : ''), '</p>');
        html.push('</li>');
    }
    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 id="' + p.pid +'">');
                tr.push('<td>' + p.code + '</td>');
                tr.push('<td>' + p.name + '</td>');
                tr.push('<td><a href="javascript: void(0)" class="text-danger" onclick="removeMeasurePos(' + p.pid + ')">移除</a></td>');
                tr.push('</tr>');
                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 id="' + d.ledger_id +'">');
                    tr.push('<td>' + d.code + '</td>');
                    tr.push('<td>' + d.name + '</td>');
                    tr.push('<td><a href="javascript: void(0)" onclick="addMeasurePos(' + d.ledger_id + ')">添加</a></td>');
                    tr.push('</tr>');
                    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 id="' + d.ledger_id +'">');
                    tr.push('<td>' + d.b_code + '</td>');
                    tr.push('<td>' + d.name + '</td>');
                    tr.push('<td>' + d.unit + '</td>');
                    tr.push('<td>' + (d.unit_price ? d.unit_price : '') + '</td>');
                    tr.push('<td><input type="checkbox" ' + check + '> 已选择</td>');
                    tr.push('</tr>');
                    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());
});