'use strict';

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

$(document).ready(() => {
    // 编号排序，多重判断
    function sortByCode(a, b) {
        let code1 = a.code.split('-');
        let code2 = b.code.split('-');
        let code1length = code1.length;
        let code2length = code2.length;
        for (let i = 0; i < code1length; i ++) {
            if (i+1 <= code2length) {
                if (code1[i] != code2[i]) {
                    if (!/^\d+$/.test(code1[i])) {
                        return code1[i].charCodeAt() - code2[i].charCodeAt();
                    } else {
                        return parseInt(code1[i]) - parseInt(code2[i]);
                    }
                } else if (i+1 == code1length && code1[i] == code2[i]) {
                    if (code1length == code2length) {
                        return 0;
                    } else {
                        return code1length - code2length;
                    }
                }
            } else {
                if (i+1 >= code1length) {
                    return 1;
                } else {
                    return -1;
                }
            }
        }
    }

    gclGatherModel.loadLedgerData(ledger);
    gclGatherModel.loadPosData(pos);
    const gclGatherData = gclGatherModel.gatherGclData();
    for (const ggd in gclGatherData) {
        gclGatherData[ggd].code = gclGatherData[ggd].b_code;
    }
    console.log(gclGatherData);
    // 数组去重
    for (const db of gclGatherData) {
        const exist_index = dealBillList.findIndex(function (item) {
            return item.code === db.code && item.name === db.name && item.unit === db.unit && item.unit_price === db.unit_price;
        });
        if (exist_index !== -1) {
            dealBillList.splice(exist_index, 1);
        }
    }
    const changeListData = gclGatherData.concat(dealBillList).sort(sortByCode);
    // 先加载台账数据
    let listHtml = '';
    let list_index = 1;
    let gcl_index = 0;
    for (const gcl of changeListData) {
        const unit = gcl.unit !== undefined && gcl.unit !== null ? gcl.unit : '';
        const quantity = gcl.quantity !== null && gcl.quantity !== undefined ? (unit !== '' ? roundnum(gcl.quantity, findDecimal(gcl.unit)) : gcl.quantity) : 0;
        const unit_price = gcl.unit_price !== null && gcl.unit_price !== undefined ? gcl.unit_price : 0;
        let gclhtml = gcl.leafXmjs !== undefined && gcl.leafXmjs !== null ? ' data-gcl="' + gcl_index + '"': '';
        gcl_index = gclhtml !== '' ? ++gcl_index : gcl_index;
        listHtml += '<tr data-lid="' + list_index + '"'+ gclhtml +' data-index="' + list_index + '" data-bwmx="">' +
            '<td>' + list_index + '</td>' +
            '<td>' + gcl.code + '</td>' +
            '<td>' + gcl.name + '</td>' +
            '<td>' + unit + '</td>' +
            '<td>' + roundnum(unit_price, unitPriceUnit) + '</td>' +
            '<td>' + quantity + '</td>' +
            // '<td>' + roundnum(parseFloat(gcl.unit_price).mul(parseFloat(gcl.quantity)), totalPriceUnit) + '</td>' +
            '</tr>';
        list_index++;
    }
    // // 再加载签约清单
    // for (const db of dealBillList) {
    //     const unit = db.unit !== undefined && db.unit !== null ? db.unit : '';
    //     const quantity = db.quantity !== null && db.quantity !== undefined ? (unit !== '' ? roundnum(db.quantity, findDecimal(db.unit)) : db.quantity) : 0;
    //     const unit_price = db.unit_price !== null && db.unit_price !== undefined ? db.unit_price : 0;
    //     listHtml += '<tr data-lid="' + db.id + '" data-index="' + list_index + '" data-bwmx="">' +
    //         '<td>' + list_index + '</td>' +
    //         '<td>' + db.code + '</td>' +
    //         '<td>' + db.name + '</td>' +
    //         '<td>' + unit + '</td>' +
    //         '<td>' + roundnum(unit_price, unitPriceUnit) + '</td>' +
    //         '<td>' + quantity + '</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).attr('data-category');
        if (category === 'save_change') {
            // 保存修改modal
            $('.up-change').hide();
            $('.save-change').show();
        } else {
            // 上报审批modal
            $('.up-change').show();
            $('.save-change').hide();
        }
    });

    // 重新上报时按钮点击
    $('a[data-target="#sub-sp2"]').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();
        }
        $('#hideSp').attr('data-category', category);
    });

    // 提交表单
    // 上报时按钮点击
    $('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);
        }
    });

    // 保存修改ajax提交（不刷新页面）
    $('#save_change').on('click', function () {
        // 保存修改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').ajaxSubmit(function (result) {
            if ( result.err === 0) {
                toastr.success(result.msg);
            } else {
                toastr.error(result.msg);
            }
        });
        return false;
    });

    // 审批人分组选择
    $('#account_group').change(function () {
        let account_html = '<option value="0">选择审批人</option>';
        for (const account of accountList) {
            if (parseInt($(this).val()) === 0 || parseInt($(this).val()) === account.account_group) {
                const role = account.role !== '' ? '（' + account.role + '）' : '';
                const company = account.company !== '' ? ' -' + account.company : '';
                account_html += '<option value="' + account.id + '">' + account.name + role + company + '</option>';
            }
        }
        $('#account_list').html(account_html);
    });

    $('#hideSp').click(function () {
       $('#sub-sp2').modal('hide');
    });

    // 添加到审批流程中
    $('body').on('change', '#account_list', function () {
        let id = $(this).val();
        id = parseInt(id);
        if (id !== 0) {
            let auditListIdData = [];
            $('#auditList li').each(function () {
                let aid = $(this).data('auditid');
                auditListIdData.push(aid);
            });
            if (!in_array(auditListIdData, id)) {
                const accountInfo = accountList.find(function (item) {
                    return item.id === id;
                });
                const user = accountInfo.id + '/%/' + accountInfo.name + '/%/' + accountInfo.role + '/%/' + accountInfo.company;
                const addhtml = '<li class="list-group-item" data-auditmsg="' + user + '"' +
                    'data-auditid="' + accountInfo.id + '" >' +
                    '<a href="javascript:void(0);" class="text-danger pull-right remove_audit_btn">移除</a>' +
                    '<span>' + (auditListIdData.length+1) + '</span> ' + accountInfo.name + '  <small class="text-muted">' + accountInfo.role + '</small>' +
                    '<p class="m-0 ml-2"><small class="text-muted">' + accountInfo.company + '</small></p>' +
                    '</li>';
                $('#auditList').append(addhtml);

                // 重新上报时。令其它的审批人流程图标转换
                $('#shenpi-audit-list li i').removeClass('fa-stop-circle').addClass('fa-chevron-circle-down');
                // 添加新审批人
                const addhtml2 = '<li class="list-group-item" data-auditid="' + accountInfo.id + '" >' +
                    '<i class="fa fa-stop-circle"></i>' +
                    accountInfo.name + ' <small class="text-muted">' + accountInfo.role + '</small>' +
                    '</li>';
                $('#shenpi-audit-list').append(addhtml2);
            } else {
                toastr.error('审批流程中已存在该用户！');
            }
        }
    });

    // 移除审批流程的审批人
    $('body').on('click', '.remove_audit_btn', function () {
        const uid = $(this).parents('li').attr('data-auditid');
        $(this).parents('li').remove();
        let index = 1;
        $('#auditList li').each(function () {
            $(this).children('span').text(index);
            index++;
        });
        if (index === 1) {
            $('#account_list').val(0);
        }

        // 重新上报时。移除审批流程
        // 令最后一个图标转换
        $('#shenpi-audit-list li[data-auditid="' + uid + '"]').remove();
        if ($('#shenpi-audit-list li').length !== 0 && !$('#shenpi-audit-list li i').hasClass('fa-stop-circle')) {
            $('#shenpi-audit-list li').eq($('#shenpi-audit-list 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-bwmx', '');
       $('#code-list').html('');
    });

    // 清单选中和移除
    $('body').on('click', '#table-list-select tr', function () {
        $('#table-list-select tr').removeClass('table-warning');
        $(this).addClass('table-warning');
        const isCheck = $(this).hasClass('table-success') ? true : false;
        const data_bwmx = $(this).attr('data-bwmx').split('$#$');
        const isDeal = $(this).data('gcl') !== undefined ? true : false;
        let codeHtml = '<tr quantity="0"><td colspan="4" class="colspan_1">&nbsp;</td><td class="colspan_2"><input type="checkbox"></td></tr>';
        if (isDeal) {
            const gcl = gclGatherData[$(this).data('gcl')];
            codeHtml = '';
            for (const leaf of gcl.leafXmjs) {
                const quantity = leaf.quantity !== undefined ? leaf.quantity : 0;
                const bwmx = leaf.bwmx !== undefined ? leaf.bwmx : '';
                const isChecked = data_bwmx.indexOf(leaf.code + '_' + bwmx + ';' + quantity) !== -1 && isCheck ? 'checked' : '';
                codeHtml += '<tr quantity="' + quantity + '"><td>' + leaf.code + '</td>' +
                    '<td>' + leaf.jldy + '</td>' +
                    '<td>' + bwmx + '</td>' +
                    '<td>' + roundnum(quantity, findDecimal(gcl.unit)) + '</td>' +
                    '<td><input type="checkbox"' + isChecked +
                    '></td></tr>';
            }
        } else if (!isDeal && isCheck) {
            codeHtml = '<tr quantity="0"><td colspan="4" class="colspan_1">&nbsp;</td><td class="colspan_2"><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');
            // 去除部分data-detail值
            let data_bwmx = [];
            $('#code-list input:checked').each(function () {
                const tr = $(this).parents('tr');
                const length = tr.children('td').length;
                const bwmx = length === 5 ? tr.children('td').eq(0).text() + '_' + tr.children('td').eq(2).text() : '0';
                const quantity = tr.attr('quantity');
                const de_qu = bwmx + ';' + quantity;
                data_bwmx.push(de_qu);
            });
            data_bwmx = data_bwmx.join('$#$');
            $('#table-list-select tr[data-index="' + index + '"]').attr('data-bwmx', data_bwmx);
        } else {
            // 判断还有无选中项目节编号
            if ($('#code-list input').is(':checked')) {
                // 去除部分data-detail值
                let data_bwmx = [];
                $('#code-list input:checked').each(function () {
                    const tr = $(this).parents('tr');
                    const length = tr.children('td').length;
                    const bwmx = length === 5 ? tr.children('td').eq(0).text() + '_' + tr.children('td').eq(2).text() : '0';
                    const quantity = tr.attr('quantity');
                    const de_qu = bwmx + ';' + quantity;
                    data_bwmx.push(de_qu);
                });
                data_bwmx = data_bwmx.join('$#$');
                $('#table-list-select tr[data-index="' + index + '"]').attr('data-bwmx', data_bwmx);
            } else {
                $('#table-list-select tr[data-index="' + index + '"]').removeClass('table-success');
                $('#table-list-select tr[data-index="' + index + '"]').attr('data-bwmx', '');
            }
        }
    });

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

    // 添加空白清单
    $('#add-white-btn').on('click', function () {
        maketablelist('addwhite');
    });

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

    // 取消选中清单
    $('#cancel-list-btn').click(function () {
        $('#table-list-select tr').removeClass('table-success');
        $('#table-list-select tr').attr('data-bwmx', '');
        $('#code-list').html('');
    });

    // 移除已选清单并重新编号
    $('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 3:
            case 5:
                tr.children('td[data-site="' + site + '"]').children('input').val($(this).val());
                break;
            case 6:
            case 8:
            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 bwmx = $.trim(tr.children('td[data-site="2"]').children('input').val()) || $.trim(tr.children('td[data-site="2"]').text());
        const unit = $.trim(tr.children('td[data-site="4"]').children('select').val()) || $.trim(tr.children('td[data-site="4"]').text());
        const price = (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 oamount = (tr.children('td[data-site="6"]').children('input').val() != '-' ? tr.children('td[data-site="6"]').children('input').val() : '') || tr.children('td[data-site="6"]').text();
        const scnum = tr.children('td[data-site="8"]').children('input').val() != '-' ? tr.children('td[data-site="8"]').children('input').val() : '';
        const detail = $.trim(tr.children('td[data-site="3"]').children('input').val());
        const trlist = [code,name,bwmx,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="7"]').text(price != '' && oamount != '' ? roundnum(parseFloat(price).mul(parseFloat(oamount)),totalPriceUnit) : '');
        tr.children('td[data-site="9"]').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 bwmx = $.trim(tr.children('td[data-site="2"]').children('input').val());
        const unit = $(this).val();
        const price = tr.children('td[data-site="5"]').children('input').val() != '-' ? tr.children('td[data-site="5"]').children('input').val() : '';
        let oamount = tr.children('td[data-site="6"]').children('input').val() != '-' ? tr.children('td[data-site="6"]').children('input').val() : '';
        let scnum = tr.children('td[data-site="8"]').children('input').val() != '-' ? tr.children('td[data-site="8"]').children('input').val() : '';
        const detail = $.trim(tr.children('td[data-site="3"]').children('input').val());

        // 根据单位更新数量位数和合计
        const numdecimal = findDecimal(unit);
        oamount = roundnum(oamount, numdecimal);
        scnum = roundnum(scnum, numdecimal);
        tr.children('td[data-site="6"]').children('input').val(oamount);
        tr.children('td[data-site="6"]').children('input').attr('onkeyup','RegNum(this,event,'+ numdecimal +')');
        tr.children('td[data-site="8"]').children('input').val(scnum);
        tr.children('td[data-site="8"]').children('input').attr('onkeyup','RegNum(this,event,'+ numdecimal +')');
        const trlist = [code,name,bwmx,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="7"]').text(price != '' && oamount != '' ? roundnum(parseFloat(price).mul(parseFloat(oamount)),totalPriceUnit) : '');
        tr.children('td[data-site="9"]').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;
    // 单价位数
    const updecimal = unitPriceUnit;

    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 data_bwmx = $(this).attr('data-bwmx').split('$#$');
        for (const b of data_bwmx) {
            const oamount = b.split(';')[1];
            let bwmx = b.split(';')[0] != 0 ? b.split(';')[0].split('_')[1] : '';
            let trlist = [code, name, bwmx, unit, price, oamount, scnum, '', 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 bwmx = radionArray[2];
        let unit = radionArray[3];
        let price = radionArray[4];
        let oamount = radionArray[5];
        let scnum = radionArray[6];
        let detail = radionArray[7];
        let lid = radionArray[8];
        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">'+ bwmx +'</td>' +
            '<td data-site="3"><input class="form-control input-sm" type="text" placeholder="变更详情" value="' + detail + '"></td>' +
            '<td data-site="4">'+ unit +'</td>' +
            '<td data-site="5">'+ roundnum(price, updecimal) +'</td>' +
            '<td data-site="6">'+ roundnum(oamount, numdecimal) +'</td>' +
            '<td data-site="7">'+ roundnum(parseFloat(price).mul(parseFloat(oamount)),decimal) +'</td>' +
            '<td data-site="8"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ numdecimal +')" placeholder="请输入变更数量" value="'+ (scnum != '-' ? roundnum(scnum, numdecimal) : '') +'"></td>' +
            '<td data-site="9">'+ 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.m.unit,makedecimalzero(decimal),makedecimalzero(findDecimal(changeUnits.m.unit)),makedecimalzero(findDecimal(changeUnits.m.unit)),'',0];
        radionWhiteList.push(trlist.join(';'));
    }

    for (const rw of radionWhiteList) {
        const radionArray = rw.split(';');
        let code = radionArray[0];
        let name = radionArray[1];
        let bwmx = radionArray[2];
        let unit = radionArray[3];
        let price = radionArray[4];
        let oamount = radionArray[5];
        let scnum = radionArray[6];
        let detail = radionArray[7];
        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="'+ bwmx +'" placeholder="变更部位"></td>' +
            '<td data-site="3"><input class="form-control input-sm" type="text" value="'+ detail +'" placeholder="变更详情"></td>' +
            '<td data-site="4"><select class="form-control input-sm">'+ optionlist +'</select></td>' +
            '<td data-site="5"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ updecimal +')" value="'+ roundnum(price, updecimal) +'" placeholder="请输入单价"></td>' +
            '<td data-site="6"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ numdecimal +')" value="'+ roundnum(oamount, numdecimal) +'" placeholder="请输入数量"></td>' +
            '<td data-site="7">'+ ototal +'</td>' +
            '<td data-site="8"><input class="form-control input-sm" type="text" onkeyup="RegNum(this,event,'+ numdecimal +')" value="'+ roundnum(scnum, numdecimal) +'" placeholder="请输入变更数量"></td>' +
            '<td data-site="9">'+ 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,3] },
            { className: 'allwidth4', width: 40, targets: 10 },
            { className: 'allwidth5', width: 60, targets: 4 },
            { className: 'allwidth3',width: 80, targets: '_all' }
        ],
        fixedColumns: {
            leftColumns: 6
        }
    });
    // 判断是否显示变更详情
    if (!$('.change-detail-checkbox').is(':checked')) {
        const column = table.column(3);
        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="9"]').text();
        ctotalnum = ctotal != '' ? parseFloat(ctotalnum).add(parseFloat(ctotal)) : parseFloat(ctotalnum);
        let ototal = $(this).children('td[data-site="7"]').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 = precision.other.value;
    const changeUnits = precision;
    for (const d in changeUnits) {
        if (changeUnits[d].unit !== undefined && changeUnits[d].unit === unit) {
            value = changeUnits[d].value;
            break;
        }
    }
    return value;
}
