/**
 * 对账模块-采购快速创建开票申请首页
 *
 * Created by li.kui on 2020/8/30.
 */
'use strict';
var el = {
    searchForm: '#searchForm',
    isSupplier: '#isSupplier',
    companyCode: '#companyCode',
    purchaseGroup: '#purchaseGroup',
    orderTypeCode: '#orderTypeCode',
    supCodeOrName: '#supCodeOrName',
    statementNo: '#statementNo',
    orderType: '#orderType',
    receiveCode: '#receiveCode',
    poCode: '#poCode',
    poItemNo: '#poItemNo',
    materialCode: '#materialCode',
    materialName: '#materialName',
    createTimeStart: '#createTimeStart',
    createTimeEnd: '#createTimeEnd',
    mvPostDateStart: '#mvPostDateStart',
    mvPostDateEnd: '#mvPostDateEnd',
    tb: '#tb',
    fastAddDialog: null,
    optConfirmDialog: null,
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    initPageComCoBox();
    
    initPageDataGrid();
});


/**
 * 初始化页面下拉框
 */
function initPageComCoBox() {
    var isSupplier = $(el.isSupplier).val(), comUrl = g.ctx + 'pc/sys/company/rest/listAll?isAuthority=1';
    if(Number(isSupplier) === 1){
        comUrl = g.ctx + 'pc/sys/company/rest/listAll?isAuthority=0';
    }
    // 初始化采购公司下拉框
    $(el.companyCode).combobox({
        url: comUrl,
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });

    // 初始化单据类型下拉框
    // 单据类型 -1:全部 1:材料类 2:运费类
    $(el.orderType).combobox({
        valueField: 'value',
        textField: 'label',
        value: -1,
        data: [
            {label: '全部', value: -1},
            {label: '材料类', value: 1},
            {label: '运费类', value: 2}
        ],
        editable: false,
        panelHeight: 'auto'
    });
}


/**
 * 初始化页面表格
 */
function initPageDataGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    $(el.tb).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        emptyMsg: '暂无数据',
        height: el.bodyHeight - searchHeight,
        url: g.ctx + 'pc/finance/account/statement/detail/rest/fast/list',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: pager.pageList[pager.pageList.length - 1],
        pageList: pager.pageList,
        idField: 'id',
        queryParams: {},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'receiveCode',
                    title: '入库凭证号',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'receiveRowNo',
                    title: '凭证行号',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'receiveDate',
                    title: '入库日期',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD');
                    }
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'asQuantity',
                    title: '对账数量',
                    width: 70,
                    sortable: true,
                    formatter: function (value) {
                        if(value < 0){
                            return '<span style="color: red;">' + value + '</span>';
                        }
                        return value;
                    }
                },
                {
                    field: 'taxDesc',
                    title: '对账税率',
                    width: 160,
                    sortable: true,
                    formatter: function (value, row) {
                        if(!value){
                            return '';
                        }
                        return '(' + row.taxCode + ')' + value;
                    }
                },
                {
                    field: 'notTaxPrice',
                    title: '对账未税单价',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'notTaxAmount',
                    title: '对账未税金额',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if(value < 0){
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxPrice',
                    title: '对账含税单价',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'taxAmount',
                    title: '对账含税金额',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        if(value < 0){
                            return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'diffTaxAmount',
                    title: '对账税额',
                    width: 100,
                    sortable: true,
                    formatter: function (value) {
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'zlsdh',
                    title: 'SC订单号',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'poCode',
                    title: 'SAP订单号',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'finConf', title: '财务确认', align: 'center', width: 70,
                    formatter: function (value, row) {
                        console.log(value);
                        if (value === 0) {
                            return "<span style=\"color: red;\">否</span>"
                        } else {
                            return "是"
                        }
                    }
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'orderTypeCode',
                    title: '订单类型编码',
                    width: 110
                },
                {
                    field: 'orderTypeName',
                    title: '订单类型描述',
                    width: 110
                },
                {
                    field: 'paymentTermCodeName',
                    title: '付款条件',
                    width: 200
                },
                {
                    field: 'purchaseGroupName',
                    title: '采购组',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'materialName',
                    title: '物料名称',
                    width: 320,
                    sortable: true
                },
                {
                    field: 'specs',
                    title: '规格',
                    width: 120
                },
                {
                    field: 'asNo',
                    title: '对账单号',
                    width: 120,
                    sortable: true
                },
                {
                    field: 'itemNo',
                    title: '对账单行号',
                    width: 80,
                    sortable: true
                },
                // {
                //     field: 'orderType',
                //     title: '对账单类型',
                //     width: 90,
                //     sortable: true,
                //     formatter: function (value) {
                //         if(Number(value) === 1){
                //             return '材料类';
                //         }
                //         if(Number(value) === 1){
                //             return '运费类';
                //         }
                //         return '';
                //     }
                // },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270,
                    sortable: true
                },
                // {
                //     field: 'freightType',
                //     title: '运费类型',
                //     width: 80,
                //     sortable: true
                // },
                {
                    field: 'currencyCode',
                    title: '货币代码',
                    width: 70,
                    sortable: true
                },
                {
                    field: 'companyName',
                    title: '采购公司',
                    width: 260,
                    sortable: true,
                    formatter: function (value, row) {
                        return '(' + row.companyCode + ')' + value
                    }
                },
                {
                    field: 'purchaseGroup',
                    title: '采购组',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'factoryName',
                    title: '工厂',
                    width: 200,
                    sortable: true,
                    formatter: function (value, row) {
                        return '(' + row.factoryCode + ')' + value
                    }
                },
                // {
                //     field: 'materialSupplierCode',
                //     title: '材料商编码',
                //     width: 90,
                //     sortable: true
                // },
                // {
                //     field: 'materialSupplierName',
                //     title: '材料商名称',
                //     width: 180,
                //     sortable: true
                // },
                // 集采订单信息
                // {
                //     field: 'jcPoCode',
                //     title: '集采SAP订单号',
                //     width: 110,
                //     sortable: true
                // },
                // {
                //     field: 'jcPoItemNo',
                //     title: '行号',
                //     width: 70,
                //     sortable: true
                // },
                // {
                //     field: 'jcFactoryCode',
                //     title: '集采工厂',
                //     width: 80,
                //     sortable: true
                // },
                {
                    field: 'createTime',
                    title: '创建时间',
                    width: 130,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                }
            ]
        ],
        toolbar: [
            {
                text: '创建开票申请',
                iconCls: 'icon-add',
                handler: function () {
                    addInvoicedApply();
                }
            }
        ],
        onLoadSuccess: function () {
            // $(el.tb).datagrid('clearSelections');
        }
    });
}


/**
 * 创建开票申请
 */
function addInvoicedApply() {
    var rows = $(el.tb).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择对账单明细行进行操作', {icon: 0});
        return false;
    }

    // SAP发票明细行不得超过999行
    // if(rows.length > 900){
    //     topWin.layer.alert('由于系统原因, 开票申请明细不得超过900行', {icon: 0});
    //     return false;
    // }
    let flag = true, msg = [];
    // for (let i = 0 ; i < rows.length ; i ++){
    //     if (!rows[i].finConf || Number(rows[i].finConf)===0){
    //         msg.push('SAP订单号：' +rows[i].poCode + '，订单行号：'+rows[i].poItemNo+'财务未确认;');
    //         flag = false;
    //     }
    // }
    if(!flag){
        layer.confirm(msg.join('<br/>'), {icon: 2, title: '温馨提示'});
        return false;
    }
    var supCode = '', supName = '', comCode = '', comName = '', facCode = '', facName = '',purchaseGroup = '',
        curCode = '',paymentCode = '', taxCode = '',orderTypeCode = '', orderType = 0, asdIds = [], rvIds = [];
    for(var i = 0; i < rows.length; i++){
        var item = rows[i];
        if(supCode !== '' && supCode !== item.supplierCode){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的供应商与上一行的供应商不一致', {icon: 0});
            return false;
        }
        supCode = item.supplierCode;
        supName = item.supplierName;

        if(comCode !== '' && comCode !== item.companyCode){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的采购公司与上一行的采购公司不一致', {icon: 0});
            return false;
        }
        comCode = item.companyCode;
        comName = item.companyName;

        if(facCode !== '' && facCode !== item.factoryCode){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的工厂与上一行的工厂不一致', {icon: 0});
            return false;
        }
        facCode = item.factoryCode;
        facName = item.factoryName;

        if(curCode !== '' && curCode !== item.currencyCode){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的币种与上一行的币种不一致', {icon: 0});
            return false;
        }
        curCode = item.currencyCode;

        if(paymentCode !== '' && paymentCode !== item.paymentTermCode){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的付款条件与上一行的付款条件不一致', {icon: 0});
            return false;
        }
        paymentCode = item.paymentTermCode;

        if(taxCode !== '' && taxCode !== item.taxCode){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的对账税率与上一行的对账税率不一致', {icon: 0});
            return false;
        }
        taxCode = item.taxCode;


        // if(orderTypeCode !== '' && orderTypeCode !== item.orderTypeCode){
        //     topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的订单类型与上一行的订单类型不一致', {icon: 0});
        //     return false;
        // }
        orderTypeCode = item.orderTypeCode;

        if(Number(orderType) !== 0 && Number(orderType) !== Number(item.orderType)){
            topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的对账单类型与上一行的对账单类型不一致', {icon: 0});
            return false;
        }
        orderType = item.orderType;
        // if(purchaseGroup !== '' && purchaseGroup !== item.purchaseGroup){
        //     topWin.layer.alert('选择的对账单明细: ' + item.asNo + '#' + item.itemNo + '中的对账单采购组与上一行的对账单类型不一致', {icon: 0});
        //     return false;
        // }
        purchaseGroup = item.purchaseGroup;

        asdIds.push(item.id);
        rvIds.push(item.receiveId);
    }

    var loading = topWin.layer.msg('校验选中的行是否可以创建, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/receipt/voucher/rest/check/write/off',
        data: {
            supplierCode: supCode,
            rvIds: JSON.stringify(rvIds),
            receiveType: orderType
        },
        success: function () {
            topWin.layer.close(loading);
            var url = g.ctx + 'pc/finance/invoiced/apply/add/fast?orderType=' + orderType + '&supplierCode=' + supCode + '&paymentTermCode=' + paymentCode +
                '&supplierName=' + supName + '&companyCode=' + comCode + '&companyName=' + comName + '&purchaseGroup='+purchaseGroup+
                '&factoryCode=' + facCode + '&factoryName=' + facName + '&currencyCode=' + curCode + '&asdIds=' + asdIds.join(',');
            openFastAddDialog(url);
        },
        error: function (data) {
            topWin.layer.close(loading);
            var message = "必须选择以下凭证数据(原因:选中的入库凭证中存在冲销, 后续需要一起过账): </br>";
            topWin.layer.alert(message + data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 打开快速创建开票申请单弹框
 *
 * @param url 弹框URL
 */
function openFastAddDialog(url) {
    el.fastAddDialog = openDialog('fastAddIa', url, {
        title: '新增开票申请单',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.fastAddDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '暂存',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['fastAddIa'].dataSave(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        $(el.tb).datagrid('load');
                        el.fastAddDialog.dialog('close');
                    });
                }
            },
            // {
            //     text: '提交',
            //     iconCls: 'icon-ok',
            //     handler: function () {
            //         topWin.frames['fastAddIa'].dataSave(function (data) {
            //             topWin.layer.msg('数据保存成功', {icon: 1});
            //             $(el.tb).datagrid('load');
            //             el.fastAddDialog.dialog('close');
            //
            //             dataSaveSubmit(data.id);
            //         });
            //     }
            // },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.fastAddDialog.dialog('close');
                }
            }
        ]
    });
}



/**
 * 数据保存后提交
 *
 * @param applyId 开票申请单ID
 */
function dataSaveSubmit(applyId) {
    var ids = [];
    ids.push(applyId);

    topWin.layer.confirm('您确定要提交开票申请单吗?', {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        console.log("aaaaaaaaaaa");
        $.ajax({
            url: g.ctx + 'fin/invoiced/apply/rest/submit/confirm',
            type: 'POST',
            data: {ids: JSON.stringify(ids)},
            success: function () {
                topWin.layer.close(loading);
                if(0 === Number($(el.isSupplier).val())){
                    var url = g.ctx + 'fin/invoiced/apply/opt/confirm?id=' + applyId + '&roleType=1';
                    openPurchaseConfirmDialog(url);
                }else {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    $(el.tb).datagrid('load');
                }
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 打开对账单确认页面
 *
 * @param url 页面URL
 */
function openPurchaseConfirmDialog(url) {
    el.optConfirmDialog = openDialog('optConfirm', url, {
        title: '采购到票确认',
        width: '99%',
        height: '100%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.optConfirmDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '通过',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['optConfirm'].dataSave(function (dataParams) {
                        purchaseApprove(dataParams, 1);
                    });
                }
            },
            {
                text: '拒绝',
                iconCls: 'icon-cancel',
                handler: function () {
                    topWin.frames['optConfirm'].dataSave(function (dataParams) {
                        purchaseApprove(dataParams, 0);
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-clear',
                handler: function () {
                    el.optConfirmDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 采购审批
 *
 * @param dataParams 提交数据
 * @param approveStatus 0:拒绝 1:通过
 */
function purchaseApprove(dataParams, approveStatus) {
    dataParams.roleType = 1;
    dataParams.approveStatus = approveStatus;

    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'fin/invoiced/apply/rest/approve/confirm',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            el.optConfirmDialog.dialog('close');
            $(el.tb).datagrid('reload');

            if(Number(data) === 4){
                topWin.layer.alert('确认数据保存成功, 但推送OA审批失败请尝试手动推送', {icon: 1});
            }else {
                topWin.layer.msg('操作成功', {icon: 1});
            }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}


/**
 * 查询对账单明细
 */
function searchStatementItem() {
    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.statementNo = $.trim($(el.statementNo).val());
    queryParams.supCodeOrName = $.trim($(el.supCodeOrName).val());
    queryParams.poCode = $.trim($(el.poCode).val());
    queryParams.poItemNo = $.trim($(el.poItemNo).val());
    queryParams.materialCode = $.trim($(el.materialCode).val());
    queryParams.materialName = $.trim($(el.materialName).val());
    queryParams.receiveCode = $.trim($(el.receiveCode).val());
    queryParams.companyCode = $(el.companyCode).combobox('getValue');
    queryParams.purchaseGroup = $(el.purchaseGroup).combobox('getValue');
    queryParams.orderTypeCode = $(el.orderTypeCode).combobox('getValue');
    // queryParams.orderType = $(el.orderType).combobox('getValue');
    queryParams.createTimeStart = $(el.createTimeStart).datebox('getValue');
    queryParams.createTimeEnd = $(el.createTimeEnd).datebox('getValue');
    queryParams.mvPostDateStart = $(el.mvPostDateStart).datebox('getValue');
    queryParams.mvPostDateEnd = $(el.mvPostDateEnd).datebox('getValue');
    $(el.tb).datagrid('load');
}


/**
 * 重新查询结果
 */
function resetSearchStatementItem() {
    $(el.statementNo).val('');
    $(el.supCodeOrName).val('');
    $(el.poCode).val('');
    $(el.poItemNo).val('');
    $(el.materialCode).val('');
    $(el.materialName).val('');
    $(el.receiveCode).val('');
    $(el.companyCode).combobox('setValue', '');
    $(el.orderTypeCode).combobox('setValue', '');
    $(el.purchaseGroup).combobox('setValue', '');
    // $(el.orderType).combobox('setValue', -1);
    $(el.createTimeStart).datebox('setValue', '');
    $(el.createTimeEnd).datebox('setValue', '');
    $(el.mvPostDateStart).datebox('setValue', '');
    $(el.mvPostDateEnd).datebox('setValue', '');
    searchStatementItem();
}


/**
 * 检查数组元素是否都相同
 *
 * @param array 待检查数组
 * @returns {boolean} 结果
 */
function checkIsAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function (value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
}