'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;
                }
            }
        }
    }
    const preUrl = window.location.pathname.split('/').slice(0, 4).join('/');
    let changeListData;
    let gclGatherData;
    postData(preUrl + '/defaultBills', {}, function (result) {
        gclGatherModel.loadLedgerData(result.bills);
        gclGatherModel.loadPosData(result.pos);
        gclGatherData = gclGatherModel.gatherGclData();
        for (const ggd in gclGatherData) {
            gclGatherData[ggd].code = gclGatherData[ggd].b_code;
        }
        // 数组去重
        const dealBillList = result.dealBills;
        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);
            }
        }
        changeListData = gclGatherData.concat(dealBillList).sort(sortByCode);
        console.log(changeListData);
        // 先加载台账数据
        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;
            const lid = gcl.leafXmjs !== undefined && gcl.leafXmjs !== null ? gcl.leafXmjs[0].gcl_id : gcl.id;
            listHtml += '
' +
                '' + list_index + ' ' +
                '' + gcl.code + ' ' +
                '' + gcl.name + ' ' +
                '' + unit + ' ' +
                '' + roundnum(unit_price, unitPriceUnit) + ' ' +
                '' + quantity + ' ' +
                // '' + roundnum(parseFloat(gcl.unit_price).mul(parseFloat(gcl.quantity)), totalPriceUnit) + ' ' +
                ' ';
            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 += '' +
        //         '' + list_index + ' ' +
        //         '' + db.code + ' ' +
        //         '' + db.name + ' ' +
        //         '' + unit + ' ' +
        //         '' + roundnum(unit_price, unitPriceUnit) + ' ' +
        //         '' + quantity + ' ' +
        //         // '' + roundnum(parseFloat(db.unit_price).mul(parseFloat(db.quantity)), totalPriceUnit) + ' ' +
        //         ' ';
        //     list_index++;
        // }
        $('#table-list-select').html(listHtml);
        tableDataRemake(changeListData);
        maketablelist();
    });
    // 上报时按钮点击
    $('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();
        }
    });
    // 多层modal关闭后的滚动bug修复
    $('#sub-sp2').on('hidden.bs.modal', function (e) {
        $(document.body).addClass('modal-open');
    });
    // 重新上报时按钮点击
    $('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] === '') {
                    if (clInfo[0] === '' || clInfo[1] === '' || 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_btn').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) {
                $('.reduction-code').attr('data-code', $('input[name="code"]').val());
                toastr.success(result.msg);
                $('#show-save-btn').hide();
                $('.title-main').removeClass('bg-warning');
                $('#back-change-list').val($('#change-list').val());
                $('#back-change-whitelist').val($('#change-whitelist').val());
                back_changeInfo = Object.assign({}, changeInfo);
            } else {
                toastr.error(result.msg);
            }
        });
        return false;
    });
    $('#cancel_change').on('click', function () {
        $('#show-save-btn').hide();
        $('.title-main').removeClass('bg-warning');
        if (!isObjEqual(changeInfo, back_changeInfo)) {
            changeFormRemake();
        }
        if ($('#change-list').val() !== $('#back-change-list').val() ||  $('#change-whitelist').val() !== $('#back-change-whitelist').val()) {
            $('#change-list').val($('#back-change-list').val());
            $('#change-whitelist').val($('#back-change-whitelist').val());
            tableDataRemake(changeListData);
            // 重新绘制table
            maketablelist();
            if(!$('#bills').hasClass('first-bill-pane') && !$('a[aria-controls="bills"]').hasClass('active')) {
                $('#bills').addClass('first-bill-pane');
            }
        }
        toastr.success('已还原到上次保存状态');
    });
    // 审批人分组选择
    $('#account_group').change(function () {
        let account_html = '选择审批人 ';
        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 += '' + account.name + role + company + ' ';
            }
        }
        $('#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 = '' +
                    '移除 ' +
                    '' + (auditListIdData.length+1) + '  ' + accountInfo.name + '  ' + accountInfo.role + ' ' +
                    '' + accountInfo.company + ' 
' +
                    ' ';
                $('#auditList').append(addhtml);
                // 重新上报时。令其它的审批人流程图标转换
                $('#shenpi-audit-list li i').removeClass('fa-stop-circle').addClass('fa-chevron-circle-down');
                $('#shenpi-audit-list2 li i').removeClass('fa-stop-circle').addClass('fa-chevron-circle-down');
                // 添加新审批人
                const addhtml1 = '' +
                    '' + accountInfo.role + ' 终审 ' +
                    ' ';
                const addhtml2 = '' +
                    '' + accountInfo.role + ' 终审 ' +
                    ' ';
                for (let i = 0; i < $('#shenpi-audit-list li').length; i++) {
                    $('#shenpi-audit-list li').eq(i).find('.pull-right').text(transFormToChinese(i) + '审');
                    $('#shenpi-audit-list2 li').eq(i).find('.pull-right').text(transFormToChinese(i) + '审');
                }
                $('#shenpi-audit-list li').eq(0).find('.pull-right').text('原报');
                $('#shenpi-audit-list2 li').eq(0).find('.pull-right').text('原报');
                $('#shenpi-audit-list li i').eq(0).removeClass('fa-chevron-circle-down').addClass('fa-play-circle');
                $('#shenpi-audit-list2 li i').eq(0).removeClass('fa-chevron-circle-down').addClass('fa-play-circle');
                $('#shenpi-audit-list').append(addhtml1);
                $('#shenpi-audit-list2').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();
        $('#shenpi-audit-list2 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');
            $('#shenpi-audit-list2 li').eq($('#shenpi-audit-list2 li').length-1).children('i')
                .removeClass('fa-chevron-circle-down').addClass('fa-stop-circle');
        }
        for (let i = 0; i < $('#shenpi-audit-list li').length; i++) {
            $('#shenpi-audit-list li').eq(i).find('.pull-right').text((i+1 === $('#shenpi-audit-list li').length ? '终' : transFormToChinese(i+1)) + '审');
            $('#shenpi-audit-list2 li').eq(i).find('.pull-right').text((i+1 === $('#shenpi-audit-list2 li').length ? '终' : transFormToChinese(i+1)) + '审');
        }
        $('#shenpi-audit-list li').eq(0).find('.pull-right').text('原报');
        $('#shenpi-audit-list2 li').eq(0).find('.pull-right').text('原报');
        $('#shenpi-audit-list li i').eq(0).removeClass('fa-chevron-circle-down').addClass('fa-play-circle');
        $('#shenpi-audit-list2 li i').eq(0).removeClass('fa-chevron-circle-down').addClass('fa-play-circle');
    });
    // 打开签约清单modal并删除之前的操作
    $('#open-list-modal').click(function () {
        // tableDataRemake(changeListData);
    });
    // 清单选中和移除
    $('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 = '  ' + leaf.code + ' ' +
                    '' + leaf.jldy + ' ' +
                    '' + bwmx + ' ' +
                    '' + roundnum(quantity, findDecimal(gcl.unit)) + ' ' +
                    '  移除 ' +
            ''+ code +' ' +
            ''+ name +' ' +
            ''+ bwmx +' ' +
            ''+ unit +' ' +
            ''+ roundnum(price, updecimal) +' ' +
            ''+ roundnum(oamount, numdecimal) +' ' +
            ''+ roundnum(parseFloat(price).mul(parseFloat(oamount)),decimal) +' ' +
            ''+ sctotal +' '+
            deteletr +' ';
        index ++;
    }
    $('#change-list').val(newTableList.join('^_^'));
    let radionWhiteList = $('#change-whitelist').val() !== '' ? $('#change-whitelist').val().split('^_^') : [];
    //判断是否添加空白清单
    if(status == 'addwhite'){
        let trlist = ['','','','','',makedecimalzero(findDecimal(3)),makedecimalzero(findDecimal(3)),'',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 = ''+ changeUnits[j].unit +' ';
            } else if(changeUnits[j].unit !== undefined) {
                optionlist += ''+ changeUnits[j].unit +' ';
            }
        }
        // 根据单位获取数量的位数,并得出
        let numdecimal = findDecimal(unit);
        html += '' +
            ''+ optionlist +' '+ ototal +' ' +
            ''+ sctotal +' '+
            deteletr +' ';
        whiteIndex ++;
    }
    $('#change-whitelist').val(radionWhiteList.join('^_^'));
    if (table) {
        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);
    judgeChange();
}
// 找出单位对应的小数位数值
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;
}
// 判断是否有更改过
function judgeChange() {
    let change = false;
    if ($('#change-list').val() !== $('#back-change-list').val()) {
        change = true;
    }
    if ($('#change-whitelist').val() !== $('#back-change-whitelist').val()) {
        change = true;
    }
    if (!isObjEqual(changeInfo, back_changeInfo)) {
        change = true;
    }
    if (change) {
        $('#show-save-btn').show();
        $('.title-main').addClass('bg-warning');
    } else {
        $('#show-save-btn').hide();
        $('.title-main').removeClass('bg-warning');
    }
}
function isObjEqual(o1,o2){
    var props1 = Object.getOwnPropertyNames(o1);
    var props2 = Object.getOwnPropertyNames(o2);
    if (props1.length != props2.length) {
        return false;
    }
    for (var i = 0,max = props1.length; i < max; i++) {
        var propName = props1[i];
        if (o1[propName] !== o2[propName]) {
            return false;
        }
    }
    return true;
}