'use strict';

/**
 * 变更令上报和重新上报功能js
 *
 * @author EllisRan.
 * @date 2018/11/22
 * @version
 */

$(document).ready(() => {

    gclGatherModel.loadLedgerData(ledger);
    gclGatherModel.loadPosData(pos);
    const gclGatherData = gclGatherModel.gatherGclData();
    // 先加载台账数据
    let listHtml = '';
    let list_index = 1;
    for (const gcl of gclGatherData) {
        listHtml += '<tr data-lid="' + list_index + '" data-gcl="' + (list_index-1) + '" data-index="' + list_index + '" data-detail="">' +
            '<td>' + list_index + '</td>' +
            '<td>' + gcl.b_code + '</td>' +
            '<td>' + gcl.name + '</td>' +
            '<td>' + gcl.unit + '</td>' +
            '<td>' + roundnum(gcl.unit_price, totalPriceUnit) + '</td>' +
            '<td>' + roundnum(gcl.quantity, gcl.unit) + '</td>' +
            '<td>' + roundnum(parseFloat(gcl.unit_price).mul(parseFloat(gcl.quantity)), totalPriceUnit) + '</td>' +
            '</tr>';
        list_index++;
    }
    // 再加载签约清单
    for (const db of dealBillList) {
        listHtml += '<tr data-lid="' + db.id + '" data-index="' + list_index + '" data-detail="">' +
            '<td>' + list_index + '</td>' +
            '<td>' + db.code + '</td>' +
            '<td>' + db.name + '</td>' +
            '<td>' + db.unit + '</td>' +
            '<td>' + roundnum(db.unit_price, totalPriceUnit) + '</td>' +
            '<td>' + roundnum(db.quantity, findDecimal(db.unit)) + '</td>' +
            '<td>' + roundnum(parseFloat(db.unit_price).mul(parseFloat(db.quantity)), totalPriceUnit) + '</td>' +
            '</tr>';
        list_index++;
    }
    $('#table-list-select').html(listHtml);

    // 上报时按钮点击
    $('a[data-target="#sub-ap"]').on('click', function () {
        let category = $(this).data('category');
        if (category === 'save_change') {
            // 保存修改modal
            $('.up-change').hide();
            $('.save-change').show();
        } else {
            // 上报审批modal
            $('.up-change').show();
            $('.save-change').hide();
        }
    });

    // 提交表单
    // 上报时按钮点击
    $('button[data-sumbit="sumbit_change"]').on('click', function () {
        let category = $(this).data('category');
        if (category === 'save_change') {
            // 保存修改modal
            $('#changeStatus').val(2);
            // 获取auditlist并填入input中
            getAuditList();
            if ($('input[name="code"]').val() === '') {
                toastr.error('申请编号不能为空！');
                return;
            }
            if ($('input[name="name"]').val() === '') {
                toastr.error('工程名称不能为空！');
                return;
            }
            $('#change_form').submit();
        } else {
            // 上报审批modal
            $('#changeStatus').val(1);
            getAuditList();
            let returnFlag = false;
            // 表单判断
            if ($('input[name="code"]').val() === '') {
                toastr.error('申请编号不能为空！');
                returnFlag = true;
            }
            if ($('input[name="name"]').val() === '') {
                toastr.error('工程名称不能为空！');
                returnFlag = true;
            }
            if ($('textarea[name="content"]').val() === '') {
                toastr.error('工程变更理由及内容不能为空！');
                returnFlag = true;
            }
            if ($('#change-list').val() === '' && $('#change-whitelist').val() === '') {
                toastr.error('请添加变更清单！');
                returnFlag = true;
            } else {
                let changeList = [];
                if ($('#change-list').val() !== '') {
                    changeList = $('#change-list').val().split('^_^');
                }
                let changeWhiteList = [];
                if ($('#change-whitelist').val() !== '') {
                    changeWhiteList = $('#change-whitelist').val().split('^_^');
                }
                changeList.push.apply(changeList, changeWhiteList);
                for (const [index, cl] of changeList.entries()) {
                    const clInfo = cl.split(';');
                    if (clInfo[0] === '' || clInfo[1] === '' || clInfo[3] === '' || clInfo[4] === '' || clInfo[5] === '') {
                        toastr.error('变更清单第' + (index+1) + '行未完整填写数据（变更详情可空）');
                        returnFlag = true;
                    }
                }
            }
            if ($('#changeaudit').val() === '') {
                toastr.error('请添加审批流程！');
                returnFlag = true;
            }
            if (returnFlag) {
                return;
            }
            $('#change_form').submit();
            $(this).attr('disabled', true);
        }
    });

    // 搜索用户
    $('#search_audit_btn').click(function () {
        const keyword = $('#search_audit_input').val();
        if (keyword === '') {
            toastr.error('请输入姓名进行检索！');
        } else {
            $('#search_audit_list').html('');
            const data = { keyword: keyword, type: 'more' };
            postData('/search/user', data, function (result) {
                const searchList = result;
                $('#search_audit_list').html('');
                if (searchList.length === 0) {
                    toastr.error('不存在该用户姓名！');
                } else {
                    let search_audit_html = '';
                    for (const s of searchList) {
                        search_audit_html += '<div class="card border-primary" style="margin-bottom: 5px;">' +
                            '<div class="card-body">' +
                            '<h5 class="card-title">' +
                            '<a class="btn btn-primary btn-sm pull-right add_audit_btn" ' +
                            'href="javascript:void(0);" data-user="' + s.id + '/%/' + s.name + '/%/' + s.role + '/%/' + s.company + '">添加</a>' + s.name +
                            '</h5>' +
                            '<h6 class="card-subtitle mb-2 text-muted">' + s.role + '</h6>' +
                            '<p class="card-text">' + s.company + '</p>' +
                            '</div>' +
                            '</div>';
                    }
                    $('#search_audit_list').html(search_audit_html);
                }
            });
        }
    });

    // 添加到审批流程中
    $('body').on('click', '.add_audit_btn', function () {
        const userData = $(this).data('user').split('/%/');
        // 先判断是否已存在该审批流程的审批人，再添加（不包括上报）
        let auditListIdData = [];
        $('#auditList li').each(function () {
           let aid = $(this).data('auditid');
           auditListIdData.push(aid);
        });
        if (!in_array(auditListIdData, userData[0])) {
            // 令其它的审批人流程图标转换
            $('#auditList li i').removeClass('fa-stop-circle').addClass('fa-chevron-circle-down');
            // 添加新审批人
            const addhtml = '<li class="list-group-item" data-auditmsg="' + $(this).data('user') + '"' +
                'data-auditid="' + userData[0] + '" >' +
                '<a href="javascript:void(0);" class="text-danger pull-right remove_audit_btn">移除</a>' +
                '<i class="fa fa-stop-circle"></i>' +
                userData[1] + '<small class="text-muted">' + userData[2] + '</small>' +
                '</li>';
            $('#auditList').append(addhtml);
        } else {
            toastr.error('审批流程中已存在该用户！');
        }
    });

    // 移除审批流程的审批人
    $('body').on('click', '.remove_audit_btn', function () {
        $(this).parents('li').remove();
        // 令最后一个图标转换
        if ($('#auditList li').length !== 0 && !$('#auditList li i').hasClass('fa-stop-circle')) {
            $('#auditList li').eq($('#auditList li').length-1).children('i')
                .removeClass('fa-chevron-circle-down').addClass('fa-stop-circle');
        }
    });

    // 打开签约清单modal并删除之前的操作
    $('#open-list-modal').click(function () {
       $('#table-list-select tr').removeClass('table-success');
       $('#table-list-select tr').attr('data-detail', '');
       $('#code-list').html('');
    });

    // 清单选中和移除
    $('body').on('click', '#table-list-select tr', function () {
        const isCheck = $(this).hasClass('table-success') ? true : false;
        const detail = $(this).attr('data-detail');
        const isDeal = $(this).data('gcl') !== undefined ? true : false;
        let codeHtml = '<tr><td colspan="3">自行编辑变更详情</td><td><input type="checkbox"></td></tr>';
        if (isDeal) {
            const gcl = gclGatherData[$(this).data('gcl')];
            codeHtml = '<tr><td colspan="3">自行编辑变更详情</td><td><input type="checkbox" ';
            codeHtml += detail == 0 && isCheck ? 'checked' : '';
            codeHtml += '></td></tr>';
            for (const leaf of gcl.leafXmjs) {
                const isChecked = detail == leaf.code + '_' + leaf.bwmx && isCheck ? 'checked' : '';
                codeHtml += '<tr><td>' + leaf.code + '</td>' +
                    '<td>' + leaf.jldy + '</td>' +
                    '<td>' + leaf.bwmx + '</td>' +
                    '<td><input type="checkbox"' + isChecked +
                    '></td></tr>'
            }
        } else if (!isDeal && isCheck) {
            codeHtml = '<tr><td colspan="3">自行编辑变更详情</td><td><input type="checkbox" checked></td></tr>';
        }
        $('#code-list').attr('data-index', $(this).children('td').eq(0).text());
        $('#code-list').html(codeHtml);
    });

    // 右边项目节选择
    $('body').on('click', '#code-list input', function () {
        let index = $('#code-list').attr('data-index');
        if ($(this).is(':checked')) {
            // 去除其它可能已选的checked
            $('#code-list input').prop('checked', false);
            $(this).prop('checked', true);
            // 左边表单传值并添加class
            $('#table-list-select tr[data-index="' + index + '"]').addClass('table-success');
            // 判断是否选择了自行编辑变更详情
            const tr = $(this).parents('tr');
            const length = tr.children('td').length;
            const detail = length === 4 ? tr.children('td').eq(0).text() + '_' + tr.children('td').eq(2).text() : '0';
            $('#table-list-select tr[data-index="' + index + '"]').attr('data-detail', detail);
        } else {
            $('#table-list-select tr[data-index="' + index + '"]').removeClass('table-success');
            $('#table-list-select tr[data-index="' + index + '"]').attr('data-detail', '');
        }
    });

    // 添加空白清单or签约清单
    $('.add-list-btn').on('click', function () {
        //生成table清单
        if($(this).hasClass('btn-outline-primary')){
            maketablelist('addwhite');
        }else{
            maketablelist();
        }
        $('#addlist').modal('hide');
    });

    // 选中input所有值
    $('body').on('focus', ".clist input", function() {
        $(this).select();
    });

    // 移除已选清单并重新编号
    $('body').on('click', '#list td a', function () {
        const index = $(this).parents('tr').data('index');
        const lid = $(this).parents('tr').data('lid');
        // 判断属于空白还是普通清单，并删除对应的index值
        const changelist = isNaN(lid) ? $('#change-list').val().split('^_^') : $('#change-whitelist').val().split('^_^');
        if($.trim(changelist) != ''){
            changelist.splice(index, 1);
            if (isNaN(lid)) {
                $('#change-list').val(changelist.join('^_^'));
            } else {
                $('#change-whitelist').val(changelist.join('^_^'));
            }
        }

        // 重新绘制table
        maketablelist();
    });

    // 清单输入监控并更新
    $('body').on('valuechange', '.clist input', function (e, previous) {
        const index = $(this).parents('tr').data('index');
        const lid = $(this).parents('tr').data('lid');
        const isWhite = !isNaN(lid) ? true : false;
        const tr = $('#list tr[data-lid="' + lid + '"]').eq(0);
        const site = parseInt($(this).parents('td').data('site'));
        switch (site) {
            case 0:
            case 1:
            case 2:
            case 4:
                tr.children('td[data-site="' + site + '"]').children('input').val($(this).val());
                break;
            case 5:
            case 7:
            default:
                break;
        }
        const code = $.trim(tr.children('td[data-site="0"]').children('input').val()) || $.trim(tr.children('td[data-site="0"]').text());
        const name = $.trim(tr.children('td[data-site="1"]').children('input').val()) || $.trim(tr.children('td[data-site="1"]').text());
        const unit = $.trim(tr.children('td[data-site="3"]').children('select').val()) || $.trim(tr.children('td[data-site="3"]').text());
        const price = (tr.children('td[data-site="4"]').children('input').val() != '-' ? tr.children('td[data-site="4"]').children('input').val() : '') || tr.children('td[data-site="4"]').text();
        const oamount = (tr.children('td[data-site="5"]').children('input').val() != '-' ? tr.children('td[data-site="5"]').children('input').val() : '') || tr.children('td[data-site="5"]').text();
        const scnum = tr.children('td[data-site="7"]').children('input').val() != '-' ? tr.children('td[data-site="7"]').children('input').val() : '';
        const detail = $.trim(tr.children('td[data-site="2"]').children('input').val());
        const trlist = [code,name,unit,price,oamount,scnum,detail];
        if (isWhite) {
            let changelist = $('#change-whitelist').val().split('^_^');
            trlist.push(0);
            changelist.splice(index, 1, trlist.join(';'));
            $('#change-whitelist').val(changelist.join('^_^'));
        } else {
            let changelist = $('#change-list').val().split('^_^');
            trlist.push(lid.split('_')[0]);
            changelist.splice(index, 1, trlist.join(';'));
            $('#change-list').val(changelist.join('^_^'));
        }
        tr.children('td[data-site="6"]').text(price != '' && oamount != '' ? roundnum(parseFloat(price).mul(parseFloat(oamount)),totalPriceUnit) : '');
        tr.children('td[data-site="8"]').text(price != '' && scnum != '' ? roundnum(parseFloat(price).mul(parseFloat(scnum)),totalPriceUnit) : '');
        totalamount(totalPriceUnit);
    });

    // 空白清单单位选择监控并更新小数位数
    $('body').on("change", '.clist select', function () {
        const index = $(this).parents('tr').data('index');
        const tr = $('#list tr[data-lid="' + index + '"]');
        const code = $.trim(tr.children('td[data-site="0"]').children('input').val());
        const name = $.trim(tr.children('td[data-site="1"]').children('input').val());
        const unit = $(this).val();
        const price = tr.children('td[data-site="4"]').children('input').val() != '-' ? tr.children('td[data-site="4"]').children('input').val() : '';
        let oamount = tr.children('td[data-site="5"]').children('input').val() != '-' ? tr.children('td[data-site="5"]').children('input').val() : '';
        let scnum = tr.children('td[data-site="7"]').children('input').val() != '-' ? tr.children('td[data-site="7"]').children('input').val() : '';
        const detail = $.trim(tr.children('td[data-site="2"]').children('input').val());

        // 根据单位更新数量位数和合计
        const numdecimal = findDecimal(unit);
        oamount = roundnum(oamount, numdecimal);
        scnum = roundnum(scnum, numdecimal);
        tr.children('td[data-site="5"]').children('input').val(oamount);
        tr.children('td[data-site="5"]').children('input').attr('onkeyup','RegNum(this,event,'+ numdecimal +')');
        tr.children('td[data-site="7"]').children('input').val(scnum);
        tr.children('td[data-site="7"]').children('input').attr('onkeyup','RegNum(this,event,'+ numdecimal +')');
        const trlist = [code,name,unit,price,oamount,scnum,detail,0];
        let changelist = $('#change-whitelist').val().split('^_^');
        changelist.splice(index, 1, trlist.join(';'));
        $('#change-whitelist').val(changelist.join('^_^'));
        tr.children('td[data-site="6"]').text(price != '' && oamount != '' ? roundnum(parseFloat(price).mul(parseFloat(oamount)),totalPriceUnit) : '');
        tr.children('td[data-site="8"]').text(price != '' && scnum != '' ? roundnum(parseFloat(price).mul(parseFloat(scnum)),totalPriceUnit) : '');
        totalamount(totalPriceUnit);
    });

    // 自动编号
    $('.reduction-code').click(function () {
       const code = $(this).data('code');
       $('input[name="code"]').val(code);
    });

});

//判断元素是否在数组中，相当于php的in_array();
function in_array(arr, obj) {
    let i = arr.length;
    while (i--) {
        if (arr[i] == obj) {
            return true;
        }
    }
    return false;
}

// 获取审批流程中审批人列表数据
function getAuditList() {
    if ($('#auditList li').length === 0) {
        $('#changeaudit').val('');
    } else {
        let auditInfoArray = [];
        $('#auditList li').each(function () {
            const aMsg = $(this).data('auditmsg');
            auditInfoArray.push(aMsg);
        });
        $('#changeaudit').val(auditInfoArray.join(','));
    }
}

// 重新生成清单
function maketablelist(status){
    // 金额位数
    const decimal = totalPriceUnit;

    let html = '';

    // 原有清单（不含空白清单）
    let radionList = $('#change-list').val() !== '' ? $('#change-list').val().split('^_^') : [];
    // 获取选中的签约清单并插入到原有清单中
    $('#table-list-select .table-success').each(function(){
        let code = $(this).children('td').eq(1).text();
        let name = $(this).children('td').eq(2).text();
        let unit = $(this).children('td').eq(3).text();
        let price = $(this).children('td').eq(4).text();
        let oamount = $(this).children('td').eq(5).text();

        // 根据单位获取数量的位数，并得出
        let numdecimal = findDecimal(unit);

        let scnum = makedecimalzero(numdecimal);
        let detail = $(this).attr('data-detail') != 0 ? $(this).attr('data-detail').split('_')[1] : '';
        let lid = $(this).data('lid');
        let trlist = [code, name, unit, price, oamount, scnum, detail, lid];
        radionList.push(trlist.join(';'));
    });
    // 排序
    radionList.sort();
    let index = 0;
    let whiteIndex = 0;
    let deteletr = '<td><a class="text-danger">移除</a></td>';
    for (const radion of radionList) {
        const radionArray = radion.split(';');
        let code = radionArray[0];
        let name = radionArray[1];
        let unit = radionArray[2];
        let price = radionArray[3];
        let oamount = radionArray[4];
        let scnum = radionArray[5];
        let detail = radionArray[6];
        let lid = radionArray[7];
        let sctotal = scnum !== '' && scnum !== '-' ? roundnum(parseFloat(price).mul(parseFloat(scnum)),decimal) : '';

        // 根据单位获取数量的位数，并得出
        let numdecimal = findDecimal(unit);

        html += '<tr class="clist clid" data-lid="' + lid + '_' + index + '" data-index="' + index + '">' +
            '<td data-site="0">'+ code +'</td>' +
            '<td data-site="1">'+ name +'</td>' +
            '<td data-site="2"><input class="form-control input-sm" type="text" placeholder="变更详情" value="' + detail + '"></td>' +
            '<td data-site="3">'+ unit +'</td>' +
            '<td data-site="4">'+ roundnum(price, decimal) +'</td>' +
            '<td data-site="5">'+ roundnum(oamount, numdecimal) +'</td>' +
            '<td data-site="6">'+ roundnum(parseFloat(price).mul(parseFloat(oamount)),decimal) +'</td>' +
            '<td data-site="7"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ numdecimal +')" placeholder="请输入变更数量" value="'+ (scnum != '-' ? roundnum(scnum, numdecimal) : '') +'"></td>' +
            '<td data-site="8">'+ sctotal +'</td>'+
            deteletr +'</tr>';
        index ++;
    }
    $('#change-list').val(radionList.join('^_^'));


    let radionWhiteList = $('#change-whitelist').val() !== '' ? $('#change-whitelist').val().split('^_^') : [];
    //判断是否添加空白清单
    if(status == 'addwhite'){
        let trlist = ['','',changeUnits.t.unit,makedecimalzero(decimal),makedecimalzero(changeUnits.t.value),makedecimalzero(changeUnits.t.value),'',0];
        radionWhiteList.push(trlist.join(';'));
    }

    for (const rw of radionWhiteList) {
        const radionArray = rw.split(';');
        let code = radionArray[0];
        let name = radionArray[1];
        let unit = radionArray[2];
        let price = radionArray[3];
        let oamount = radionArray[4];
        let scnum = radionArray[5];
        let detail = radionArray[6];
        let ototal = price != '' && oamount != '' ? roundnum(parseFloat(price).mul(parseFloat(oamount)),decimal) : '';
        let sctotal = price != '' && scnum != '' ? roundnum(parseFloat(price).mul(parseFloat(scnum)),decimal) : '';

        let optionlist = '';
        for (const j in changeUnits) {
            if (changeUnits[j].unit !== undefined && changeUnits[j].unit === unit) {
                optionlist += '<option selected="selected">'+ changeUnits[j].unit +'</option>';
            } else if(changeUnits[j].unit !== undefined) {
                optionlist += '<option>'+ changeUnits[j].unit +'</option>';
            }
        }

        // 根据单位获取数量的位数，并得出
        let numdecimal = findDecimal(unit);

        html += '<tr class="clist" data-lid="' + whiteIndex + '" data-index="' + whiteIndex + '">' +
            '<td data-site="0"><input class="form-control input-sm" type="text" value="'+ code +'" placeholder="请输入清单编号"></td>' +
            '<td data-site="1"><input class="form-control input-sm" type="text" value="'+ name +'" placeholder="请输入名称"></td>' +
            '<td data-site="2"><input class="form-control input-sm" type="text" value="'+ detail +'" placeholder="变更详情"></td>' +
            '<td data-site="3"><select class="form-control input-sm">'+ optionlist +'</select></td>' +
            '<td data-site="4"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ decimal +')" value="'+ roundnum(price, decimal) +'" placeholder="请输入单价"></td>' +
            '<td data-site="5"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ numdecimal +')" value="'+ roundnum(oamount, numdecimal) +'" placeholder="请输入数量"></td>' +
            '<td data-site="6">'+ ototal +'</td>' +
            '<td data-site="7"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ numdecimal +')" value="'+ roundnum(scnum, numdecimal) +'" placeholder="请输入变更数量"></td>' +
            '<td data-site="8">'+ sctotal +'</td>'+
            deteletr +'</tr>';
        whiteIndex ++;
    }

    $('#change-whitelist').val(radionWhiteList.join('^_^'));

    table.destroy();
    $('#list').html(html);
    table = $('#tablelist').removeAttr('width').DataTable({
        columnDefs: [
            { className: 'allwidth1', width: 100, targets: 0 },
            { className: 'allwidth2', width: 150, targets: [1,2] },
            { className: 'allwidth4', width: 40, targets: 9 },
            { className: 'allwidth5', width: 60, targets: 3 },
            { className: 'allwidth3',width: 80, targets: '_all' }
        ],
        fixedColumns: {
            leftColumns: 5
        }
    });
    // 判断是否显示变更详情
    if (!$('.change-detail-checkbox').is(':checked')) {
        const column = table.column(2);
        column.visible(!column.visible());
    }
    totalamount(decimal);
    $('#table-list-select tr').removeClass('table-success');
}

//统计合计金额
function totalamount(decimal){
    let zero = makedecimalzero(decimal);
    let ctotalnum = 0;
    let ototalnum = 0;
    $('.clist').each(function(){
        let ctotal = $(this).children('td[data-site="8"]').text();
        ctotalnum = ctotal != '' ? parseFloat(ctotalnum).add(parseFloat(ctotal)) : parseFloat(ctotalnum);
        let ototal = $(this).children('td[data-site="6"]').text();
        ototalnum = ototal != '' ? parseFloat(ototalnum).add(parseFloat(ototal)) : parseFloat(ototalnum);
    });
    $('.ctatalamount').eq(1).text(ctotalnum != 0 ? roundnum(ctotalnum,decimal) : zero);
    $('.otatalamount').eq(1).text(ototalnum != 0 ? roundnum(ototalnum,decimal) : zero);
}

// 找出单位对应的小数位数值
function findDecimal(unit) {
    let value = 2;
    for (const d in changeUnits) {
        if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
            value = changeUnits[d].value;
            break;
        }
    }
    return value;
}
