var el = {
    searchForm: '#searchForm',
    tb: '#tb',
    purchaseGroupCode: '#purchaseGroupCode',
    status: '#status',
    postStatus: '#postStatus',
    type: '#type',
    payment_matching_add: '#payment_matching_add',
    payment_matching_edit: '#payment_matching_edit',
    payment_matching_search: '#payment_matching_search',
    payment_matching_push_confirm: '#payment_matching_push_confirm',
    payment_matching_push_post: '#payment_matching_push_post',
    btn_remove: '#btn_remove',
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    initDict('unit,currency,payment_method,hkpp_type')
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll');
    initCombo();
    loadGrid();
});

function initCombo(){
    $(el.status).combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        prompt: '--- 请选择 ---',
        data: [
            {label: '暂存', value: 1},
            {label: '待财务确认', value: 7},
            {label: '财务拒绝', value: 8},
            {label: '已确认', value: 9}
        ],
    });
    $(el.postStatus).combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        prompt: '--- 请选择 ---',
        data: [
            {label: '未过账', value: 1},
            {label: '预制失败', value: 3},
            {label: '预制成功', value: 4},
            {label: '过账成功', value: 5}
        ],
    });
    $(el.type).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        data: getDictList('hkpp_type')
    });

    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data: getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll')
    });
}


function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight - 20, 37, 40);
    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        url: g.ctx + 'pc/finance/payment/matching/rest/list',
        singleSelect: false,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        loadMsg: '数据加载中......',
        rownumbers: true,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'postStatus',
                title: '状态',
                width: '120',
                exportEnum:[
                    {code:1,codeWithDesc:'未过账'},
                    {code:2,codeWithDesc:'待预制'},
                    {code:3,codeWithDesc:'预制失败'},
                    {code:4,codeWithDesc:'预制成功'},
                    {code:5,codeWithDesc:'过账成功'},
                    {code:6,codeWithDesc:'无需过账'},
                    {code:7,codeWithDesc:'已冲销'}
                ],
                formatter: function (value, row) {
                    switch (value) {
                        case 1:
                            return '未过账';
                        case 2:
                            return '<span style="color: orange;">待预制</span>';
                        case 3:
                            return '<span style="color: red;" title="'+row.postMsg+'">预制失败</span>';
                        case 4:
                            return '<span style="color: blue;">预制成功</span>';
                        case 5:
                            return '<span style="color: green;">过账成功</span>';
                        case 6:
                            return '<span style="color: grey;">无需过账</span>';
                        case 7:
                            return '<span  style="color: red;">已冲销</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'deleteFlag',
                title: '删除标记',
                width: 80,
                sortable: true,
                exportEnum:[
                    {code:0,codeWithDesc:'未删除'},
                    {code:1,codeWithDesc:'已删除'}
                ],
                formatter:function (value) {
                    if(value === 0){
                        return "未删除"
                    }else{
                        return "<span style='color: red;'>已删除</span>"
                    }
                }
            },
            {
                field: 'type',
                title: '单据类型',
                width: '120',
                exportEnum:getDictList('hkpp_type'),
                formatter: function (value) {
                    return getDicName('hkpp_type',value);
                }
            },
            {
                field: 'code',
                title: '单据流水号',
                width: '120',
                align: 'left'
            },
            {
                field: 'customsDeclarationDetailCode',
                title: '委托单号',
                width: '120',
                align: 'left'
            },
            // {
            //     field: 'costMatchingFlag',
            //     title: '是否存在费用匹配单',
            //     width: '120',
            //     align: 'left',
            //     formatter: function (value) {
            //         if (isBlank(value)){
            //             return '否';
            //         }
            //         if (Number(value)===0){
            //             return '否';
            //         }else {
            //             return '<span style="color: green;">是</span>';
            //         }
            //     }
            // },
            // {
            //     field: 'purchaseGroupCode',
            //     title: '采购组',
            //     width: '120',
            //     align: 'left',
            //     formatter: function (value) {
            //         return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
            //     }
            // },
            {
                field: 'supplierCode',
                title: '供应商编码',
                width: '100',
                align: 'left'
            },
            {
                field: 'supplierName',
                title: '供应商名称',
                width: '200',
                align: 'left'
            },
            {
                field: 'taxAmount',
                title: '进口总金额',
                width: '100',
                align: 'left'
            },
            // {
            //     field: 'currencyCode',
            //     title: '币种',
            //     width: '120',
            //     align: 'left'
            // },
            {
                field: 'companyCode',
                title: '交易主体',
                width: '120',
                align: 'left'
            },
            {
                field: 'remark',
                title: '备注',
                width: '120',
                align: 'left'
            },
            {
                field: 'createUserName',
                title: '创建人',
                width: '120',
                align: 'left'
            },
            {
                field: 'createTime',
                title: '创建时间',
                width: '120',
                align: 'center',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                    return '';
                }
            },
            {
                field: 'invoiceVoucher',
                title: 'MIRO凭证号',
                width: '120',
                align: 'left'
            },
            {
                field: 'voucherYear',
                title: '发票年度',
                width: '120',
                align: 'left'
            },
            {
                field: 'postDate',
                title: '过账日期',
                width: '120',
                align: 'center',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD');
                    }
                    return '';
                }
            },
            {
                field: 'attachmentFiles', title: '附件', width: 120, align: 'left', formatter: function (value, row) {
                    if (value !== "") {
                        return "<a href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.code +"')\">" + "点击查看(已上传)" + "</a>";
                    } else {
                        return "<a style='color:red;' href='javascript:void(0)' onclick=\"viewAttachmentFileDetail('" + row.id + "', '" + row.code +"')\">" + "点击上传(未上传)" + "</a>";
                    }
                }
            },
            {
                field: 'paymentExpireDate',
                title: '付款到期日',
                width: 120,
                sortable: true,
                exportDateFormatter:'date',
                formatter: function (value, row) {
                    if (!value) {
                        return '';
                    }
                    return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
                }
            },
        ]],
        toolbar: [
            {
                text: '新增',
                iconCls: 'icon-add',
                id:'payment_matching_add',
                handler: function () {
                    detail(0);
                }
            },
            // {
            //     text: '编辑',
            //     iconCls: 'icon-edit',
            //     id:'payment_matching_edit',
            //     handler: function () {
            //         detail(1);
            //     }
            // },
            "-",{
                text: '查看',
                iconCls: 'icon-search',
                id:'payment_matching_search',
                handler: function () {
                    detail(2);
                }
            }
            ,"-",{
                text: '过账',
                iconCls: 'icon-ok',
                id: 'payment_matching_push_post',
                handler: function () {
                    financePostDialog();
                }
            },
            "-",
            {
                text: '删除',
                iconCls: 'icon-remove',
                id: 'btn_remove',
                handler: function () {
                    remove();
                }
            },
            "-",
            {
                text: '附件上传',
                iconCls: 'icon-add',
                id: 'btn_attachment_file',
                handler: function () {
                    let rows = $(el.tb).datagrid('getChecked');
                    if (rows.length !== 1) {
                        layer.msg("请选中一条记录");
                        return;
                    }
                    openCommonFileDialog('commonFileDialog',{
                        //业务类型编码
                        title:'附件上传',
                        //业务类型编码
                        businessTypeCode:eSignBusinessTypeCodeEnum.PAYMENT_MATCHING,
                        businessCode:rows[0].code,
                        //业务唯一id
                        businessId:rows[0].id,
                        callBack : function () {
                            $(el.tb).datagrid('reload');
                        },
                    });
                }
            }
            ,"-",{
                text: '修改过账状态',
                iconCls: 'icon-edit',
                id: 'btn_update_post',
                handler: function () {
                    updateFinancePostDialog();
                }
            },
        ],
        onBeforeLoad:function () {
            displayButtonByUserRole('payment_matching_list');
        },
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var postStatus = rows[rowIndex].postStatus;
            var deleteFlag = rows[rowIndex].deleteFlag;
            //过账状态 1:未过账 2:待预制 3:预制失败 4:预制成功 5-过账成功
            switch (Number(postStatus)) {
                case 1:
                    $(el.payment_matching_edit).linkbutton('enable');
                    $(el.payment_matching_push_confirm).linkbutton('enable');
                    $(el.payment_matching_push_post).linkbutton('enable');
                    $(el.btn_remove).linkbutton('enable');
                    break;
                case 2:
                    $(el.payment_matching_edit).linkbutton('disable');
                    $(el.payment_matching_push_confirm).linkbutton('disable');
                    $(el.payment_matching_push_post).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    break;
                case 3:
                    $(el.payment_matching_edit).linkbutton('enable');
                    $(el.payment_matching_push_confirm).linkbutton('enable');
                    $(el.payment_matching_push_post).linkbutton('enable');
                    $(el.btn_remove).linkbutton('enable');
                    break;
                case 4:
                    $(el.payment_matching_edit).linkbutton('disable');
                    $(el.payment_matching_push_confirm).linkbutton('disable');
                    $(el.payment_matching_push_post).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    break;
                case 5:
                    $(el.payment_matching_edit).linkbutton('disable');
                    $(el.payment_matching_push_confirm).linkbutton('disable');
                    $(el.payment_matching_push_post).linkbutton('disable');
                    $(el.btn_remove).linkbutton('disable');
                    break;
                default:
                    break;
            }
            if (Number(deleteFlag === 1)){
                $(el.payment_matching_edit).linkbutton('disable');
                $(el.payment_matching_push_confirm).linkbutton('disable');
                $(el.payment_matching_push_post).linkbutton('disable');
            }
        }
    });
}
function financePostDialog(){
    var row = $(el.tb).datagrid('getSelections');
    if (!row) {
        topWin.layer.alert('请选择一条单据进行操作', {icon: 0});
        return false;
    }
    var ids = [];
    for(var i = 0; i < row.length; i++) {
        ids.push(row[i].id); // 假设每行数据都有一个 'id' 字段
    }
    console.log(ids);
    var url = g.ctx + 'pc/finance/payment/matching/financePost?id='+ids[0];
    el.financePostDialog = openDialog('financePostDialog', url, {
        title: '发票过账',
        width: '500',
        height: '450',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.financePostDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '过账',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['financePostDialog'].confirm(function (param) {
                        var loading = topWin.layer.msg('数据推送中, 请耐心等待......', {icon: 16,time: 100000,shade : [0.5 , '#000' , true]});
                        //预制发票
                        $.ajax({
                            type: 'POST',
                            url: g.ctx + 'pc/finance/payment/matching/rest/create/prefabricate/invoice',
                            data: {ids:ids.join(','),type:1,invoicePostDate:param.invoicePostDate,statementType:param.statementType},
                            success: function (data) {
                                topWin.layer.close(loading);
                                $(el.tb).datagrid('reload');
                                topWin.layer.msg("过账成功");
                                el.financePostDialog.dialog('close');
                            },
                            error:function (data) {
                                topWin.layer.close(loading);
                                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                            }
                        });
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.financePostDialog.dialog('close');
                }
            }
        ]
    });
}
function updateFinancePostDialog(){
    var row = $(el.tb).datagrid('getSelections');
    if (!row) {
        topWin.layer.alert('请选择一条单据进行操作', {icon: 0});
        return false;
    }
    if (row.length>1) {
        topWin.layer.alert('请选择一条单据进行操作', {icon: 0});
        return false;
    }
    var ids = [];
    for(var i = 0; i < row.length; i++) {
        ids.push(row[i].id); // 假设每行数据都有一个 'id' 字段
    }
    console.log(ids);
    var url = g.ctx + 'pc/finance/payment/matching/updateFinancePost?id='+ids[0];
    el.financePostDialog = openDialog('financePostDialog', url, {
        title: '发票过账',
        width: '500',
        height: '550',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.financePostDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '过账',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['financePostDialog'].confirm(function (param) {
                        var loading = topWin.layer.msg('数据操作中, 请耐心等待......', {icon: 16,time: 100000,shade : [0.5 , '#000' , true]});
                        //预制发票
                        $.ajax({
                            type: 'POST',
                            url: g.ctx + 'pc/finance/payment/matching/rest/create/prefabricate/updateInvoice',
                            data: {
                                ids:ids.join(','),
                                type:1,
                                invoiceVoucher:param.invoiceVoucher,
                                // invoicePostDate:param.invoicePostDate,
                                paymentExpireDate:param.paymentExpireDate,
                                voucherYear:param.voucherYear,
                                postStatus:param.postStatus
                            },
                            success: function (data) {
                                topWin.layer.close(loading);
                                $(el.tb).datagrid('reload');
                                topWin.layer.msg("过账成功");
                                el.financePostDialog.dialog('close');
                            },
                            error:function (data) {
                                topWin.layer.close(loading);
                                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                            }
                        });
                    });
                }
            },
            {
                text: '取消',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.financePostDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 删除
 */
function remove(){
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    var id = row.id;
    parent.layer.confirm('是否确认删除？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/payment/matching/rest/remove',
            method: "post",
            data: {id: id},
            success: function () {
                parent.layer.close(index);
                $(el.tb).datagrid('reload');
                $(el.tb).datagrid('clearSelections');
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

/**
 * 提交
 */
function pushConfirm() {
    var cbox = $(el.tb).datagrid('getSelected');
    if (cbox === null || cbox === undefined) {
        layer.msg("请选中一条记录");
        return;
    }

    var id = cbox.id;

    parent.layer.confirm('是否确认提交？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        var url= g.ctx + 'pc/finance/payment/matching/rest/pushConfirm';
        $.ajax({
            url: url,
            method: "post",
            data: {id: id},
            success: function (data) {
                parent.layer.close(index);
                $(el.tb).datagrid('reload');
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

