var el = {
    searchForm: '#searchForm',
    tb: '#tb',
    status: '#status',
    purchaseGroupCode: '#purchaseGroupCode',
    inquiryType: '#inquiryType',
    purchaseType: '#purchaseType',
    btn_efficacy: '#btn_efficacy',
    btn_effect: '#btn_effect',
    btn_close: '#btn_close',
    price_edit: '#price_edit',
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    initDict('currency,payment_method');
    initNecessaryDatas('pc/sys/purchaseOrg/rest/listAll,pc/sys/purchaseGroup/rest/listAll,pc/sys/tax/rest/listAll,pc/sys/company/rest/listAll');
    initCombo();
    loadGrid();
});

function initCombo() {

    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data: getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll')
    });
    //价格信息记录状态；1-新建（ERP待录入）；2-审批中；3-审核拒绝；4-生效；5-失效
    $(el.status).combobox({
        editable: false,
        panelHeight: 'auto',
        valueField: 'value',
        textField: 'label',
        prompt: '--- 请选择 ---',
        data: [
            {value: '1', label: 'ERP待录入'},
            {value: '2', label: '审批中'},
            {value: '3', label: '审核拒绝'},
            {value: '4', label: '生效'},
            {value: '5', label: '失效'}
        ],
        // multiple: true,
    });
    //采购类型
    $(el.purchaseType).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '标准', 'code': '0'},
            {'name': '寄售', 'code': '2'},
            {'name': '委外', 'code': '3'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
}

function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        url: g.ctx + 'pc/inquiry/price/rest/list',
        singleSelect: false,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        loadMsg: '数据加载中......',
        rownumbers: true,
        queryParams: {},
        columns: [[
            {
                field: 'ck', checkbox: true
            },
            {
                field: 'status',
                title: '状态',
                width: '80',
                exportEnum:[
                    {code:1,codeWithDesc:'ERP待录入'},
                    {code:2,codeWithDesc:'审批中'},
                    {code:3,codeWithDesc:'审核拒绝'},
                    {code:4,codeWithDesc:'生效'},
                    {code:5,codeWithDesc:'失效'},
                    {code:6,codeWithDesc:'关闭'},
                ],
                formatter: function (value, row) {
                    switch (Number(value)) {
                        case 1:
                            return '<a style="color: grey">ERP待录入</a>'
                        case 2:
                            return '<a style="color: red">审批中</a>'
                        case 3:
                            return '<a style="color: orange">审核拒绝</a>'
                        case 4:
                            return '<a style="color: blue">生效</a>'
                        case 5:
                            return '<a style="color: orange">失效</a>'
                        case 6:
                            return '<a style="color: red">关闭</a>'
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'purchaseType',
                title: '采购类型',
                width: '120',
                align: 'left',
                exportEnum:[
                    {code:0,codeWithDesc:'标准'},
                    {code:2,codeWithDesc:'寄售'},
                    {code:3,codeWithDesc:'委外'}
                ],
                formatter: function (value, row) {
                    if (Number(value) === 0) {
                        return "标准"
                    } else if (Number(value) === 2) {
                        return '寄售'
                    } else if (Number(value) === 3) {
                        return '标准委外'
                    }
                }
            },
            {
                field: 'priceCode',
                title: '信息记录编号',
                width: '120',
                align: 'left'
            },
            {
                field: 'materialCode',
                title: '物料号',
                width: '150',
                align: 'left'
            },
            {
                field: 'materialName',
                title: '物料名称',
                width: '150',
                align: 'left',
                formatter: function (value, row) {
                    return '<span title="'+value+'">'+value+'</span>';
                }
            },
            {
                field: 'materialSpec', title: '详细规格参数', width: 150
            },
            // {
            //     field: 'productName', title: '品名', width: 100
            // },
            // {
            //     field: 'brand', title: '品牌', width: 100
            // },
            {
                field: 'orderUnit', title: '采购单位', width: '80', align: 'left'
            },
            {
                field: 'taxPrice', title: '含税单价', width: '70', align: 'left',
            },
            {
                field: 'noTaxPrice', title: '未税单价', width: '80', align: 'left',
            },
            {
                field: 'conversionPrice', title: '转换后价格', width: '80', align: 'left',
            },
            {
                field: 'exchangeRate', title: '汇率', width: '80', align: 'left',
            },
            {
                field: 'quota', title: '配额', width: '80', align: 'left',
            },
            {
                field: 'supplierCode', title: '供应商编码', width: '100', align: 'left'
            },
            {
                field: 'supplierName', title: '供应商名称', width: '100', align: 'left'
            },
            {
                field: 'createUserName', title: '创建人名称', width: '70',
                align: 'left'
            },
            {
                field: 'createTime',
                title: '创建时间',
                width: '130',
                exportDateFormatter:'dateTime',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD HH:mm:ss");
                    }
                    return '';
                }
            },
            {
                field: 'taxCode',
                title: '税率',
                width: '50',
                exportEnum:getNecessaryDataList('pc/sys/tax/rest/listAll'),
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
                }
            },
            {
                field: 'currencyCode',
                title: '货币',
                width: '50',
                exportEnum:getDictList('currency'),
                formatter: function (value) {
                    return getDicName('currency',value);
                }
            },
            {
                field: 'paymentMethod',
                title: '付款条件',
                width: '200',
                exportEnum:getDictList('payment_method'),
                formatter: function (value) {
                    return getDicName('payment_method',value);
                }
            },

            {
                field: 'effectDate',
                title: '生效日期',
                width: '130',
                exportDateFormatter:'date',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD");
                    }
                    return '';
                }
            }, {
                field: 'invalidDate',
                title: '失效日期',
                width: '130',
                exportDateFormatter:'date',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD");
                    }
                    return '';
                }
            },
            {
                field: 'purchaseGroupCode',
                title: '采购组',
                width: '150',
                exportEnum:getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                }
            },
            {
                field: 'purchaseOrgCode',
                title: '采购组织',
                width: 200,
                exportEnum:getNecessaryDataList('pc/sys/purchaseOrg/rest/listAll'),
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/purchaseOrg/rest/listAll',value);
                }
            },
            // {
            //     field: 'vendorSite',
            //     title: '供应商地点',
            //     width: '150',
            //     align: 'left'
            // },
            {
                field: 'companyCode',
                title: '公司',
                width: '80',
                align: 'center',
                exportEnum:getNecessaryDataList('pc/sys/company/rest/listAll'),
                formatter: function (value) {
                return getNecessaryDataName('pc/sys/company/rest/listAll',value);
            }
            },
            {
                field: 'factoryCode', title: '工厂编码', width: '80', align: 'left'
            },
            // {
            //     field: 'applyCode', title: '采购申请号/行号', width: '150', align: 'center'
            // },
            {
                field: 'sourceCode', title: '寻源单号', width: '150', align: 'center'
            },
            // {
            //     field: 'invalidRemark', title: '失效原因', width: '250', align: 'left'
            // },
            {
                field: 'remark', title: '备注', width: '150', align: 'left'
            },
            {
                field: 'stageNum1',
                title: '数量1',
                width: '120',
                align: 'left'
            },
            {
                field: 'stagePrice1',
                title: '阶梯报价1',
                width: '120',
                align: 'left'
            },
            {
                field: 'stageNum2',
                title: '数量2',
                width: '120',
                align: 'left'
            },
            {
                field: 'stagePrice2',
                title: '阶梯报价2',
                width: '120',
                align: 'left'
            }, {
                field: 'stageNum3',
                title: '数量3',
                width: '120',
                align: 'left'
            },
            {
                field: 'stagePrice3',
                title: '阶梯报价3',
                width: '120',
                align: 'left'
            },
            {
                field: 'stageNum4',
                title: '数量4',
                width: '120',
                align: 'left'
            },
            {
                field: 'stagePrice4',
                title: '阶梯报价4',
                width: '120',
                align: 'left'
            },
            {
                field: 'stageNum5',
                title: '数量5',
                width: '120',
                align: 'left'
            },
            {
                field: 'stagePrice5',
                title: '阶梯报价5',
                width: '120',
                align: 'left'
            },
            // {
            //     field: 'processState',
            //     title: 'ERP处理状态',
            //     width: '130',
            //     formatter: function (val) {
            //         if (!val) return '';
            //         return val === 'S' ? "<span style='color: green;'>成功</span>" : '<span style="color: red;">失败</span>';
            //     }
            // },
            // {
            //     field: 'processMsg', title: 'ERP处理反馈', width: '130', //hidden:true,
            //     align: 'center'
            // },
            // {
            //     field: 'erpSrmCode', title: 'ERP报价单号', width: '130', //hidden:true,
            //     align: 'center'
            // },
            // {
            //     field: 'processDate',
            //     title: 'ERP处理日期', width: '130', //hidden:true,
            //     align: 'center',
            //     formatter: function (value) {
            //         if (value) {
            //             return moment(value).format("YYYY-MM-DD");
            //         }
            //         return '';
            //     }
            // },
        ]],
        toolbar: [
            {
                text: '生效',
                iconCls: 'icon-ok',
                id: 'btn_effect',
                handler: function () {
                    updateStatus(0);
                }
            }, "-",
            {
                text: '失效',
                iconCls: 'icon-remove',
                id: 'btn_efficacy',
                handler: function () {
                    updateStatus(1);
                }
            },"-",
            {
                text: '关闭',
                iconCls: 'icon-delete',
                id: 'btn_close',
                handler: function () {
                    updateStatus(2);
                }
            }, "-",
            {
                text: '导出',
                iconCls: 'icon-print',
                id: 'btn_export',
                handler: function () {
                    openExportDialog('pc/inquiry/price/rest/export','tb',searchParams());
                }
            }, "-",
            {
                text: '价格延用',
                iconCls: 'icon-edit',
                id: 'price_edit',
                handler: function () {
                    priceEdit(3);
                }
            }, "-",
            {
                text: '期初导入',
                iconCls: 'icon-import',
                id: 'btn_import',
                handler: function () {
                    priceImport();
                }
            }
        ],
        onLoadSuccess: function () {
            displayButtonByUserRole("price_info_record");
            $(el.tb).datagrid('clearSelections');
        },
        onCheck: function (rowIndex) {
            var rows = $(el.tb).datagrid('getRows');
            var status = rows[rowIndex].status;
            //价格信息记录状态；1-新建（ERP待录入）；2-审批中；3-审核拒绝；4-生效；5-失效；6-关闭
            switch (Number(status)) {
                case 1:
                    $(el.btn_effect).linkbutton('enable');
                    $(el.btn_efficacy).linkbutton('disable');
                    $(el.btn_close).linkbutton('enable');
                    $(el.price_edit).linkbutton('disable');
                    break;
                case 2:
                    $(el.btn_effect).linkbutton('disable');
                    $(el.btn_efficacy).linkbutton('disable');
                    $(el.btn_close).linkbutton('disable');
                    $(el.price_edit).linkbutton('disable');
                    break;
                case 3:
                    $(el.btn_effect).linkbutton('enable');
                    $(el.btn_efficacy).linkbutton('enable');
                    $(el.btn_close).linkbutton('enable');
                    $(el.price_edit).linkbutton('disable');
                    break;
                case 4:
                    $(el.btn_effect).linkbutton('disable');
                    $(el.btn_efficacy).linkbutton('enable');
                    $(el.btn_close).linkbutton('enable');
                    $(el.price_edit).linkbutton('enable');
                    break;
                case 5:
                    $(el.btn_effect).linkbutton('enable');
                    $(el.btn_efficacy).linkbutton('disable');
                    $(el.btn_close).linkbutton('enable');
                    $(el.price_edit).linkbutton('disable');
                    break;
                case 6:
                    $(el.btn_effect).linkbutton('disable');
                    $(el.btn_efficacy).linkbutton('disable');
                    $(el.btn_close).linkbutton('disable');
                    $(el.price_edit).linkbutton('disable');
                    break;
                default:
                    break;
            }
        }
    });
}

/**
 * 更新状态
 * @param optType 0-生效；1-失效；2-关闭
 * @returns {boolean}
 */
function updateStatus(optType){
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    var id = row.id;
    if (optType===0){
        parent.layer.confirm(optType===0?'是否确认生效？':optType===1?'是否确认失效？':'是否确认关闭？', function (index) {
            updateStatusAjax(id,optType);
            parent.layer.close(index);
        });
    }else{
        topWin.layer.prompt({title: optType===1?'失效原因':'关闭原因', formType: 2}, function(text, index){
            updateStatusAjax(id,optType,text);
            topWin.layer.close(index);
        });
    }
}

function updateStatusAjax(id,optType,invalidRemark){
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/inquiry/price/rest/updateStatus',
        method: "post",
        data: {id: id,optType:optType,invalidRemark:invalidRemark},
        success: function () {
            topWin.layer.msg('数据保存成功', {icon: 1});
            $(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: '温馨提示'});
        }
    });
}

/**
 * 价格延用
 * @param optType
 * @returns {boolean}
 */
function priceEdit(optType){
    var rows = $(el.tb).datagrid('getSelections');
    if (!rows || rows.length <= 0) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    let purchaseGroupCode = "";
    let supplierCode = "";
    let companyCode = "";
    let ids = [];
    for (let i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
        if (i === 0) {
            purchaseGroupCode = rows[i].purchaseGroupCode;
            supplierCode = rows[i].supplierCode;
            companyCode = rows[i].companyCode;
            continue;
        }
        if (rows[i].purchaseGroupCode !== purchaseGroupCode) {
            layer.msg("所选采购组必须一致");
            return false;
        }
        if (rows[i].companyCode !== companyCode) {
            layer.msg("所选公司必须一致");
            return false;
        }
        if (rows[i].supplierCode !== supplierCode) {
            layer.msg("所选供应商必须一致");
            return false;
        }

    }

    for (let i = 0; i < rows.length; i++) {
        console.log(rows[i].quota)
        if (rows[i].quota !== 100&&rows[i].quota !== 0) {
            layer.msg("所选配额必须为0或100");
            return false;
        }
    }
    var dialogElement = openDialog("editDialog", g.ctx + "pc/inquiry/price/audit/detail?priceIds="+ids.join(",")+"&optType="+optType, {
        title: (optType === otpTypeEnum.ADD ? "新增" :optType===otpTypeEnum.EDIT?"编辑":optType===2?"查看":"价格延用"),
        width: '100%',
        height: '100%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dialogElement.dialog('destroy');
        },
        buttons: [
            {
                text: '提交',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['editDialog'].saveOrUpdate(function () {
                        topWin.layer.msg('数据保存成功', {icon: 1});
                        dialogElement.dialog('close');
                        $(el.tb).datagrid('reload');
                    });
                }
            }, {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    dialogElement.dialog('close');
                }
            }
        ]
    });

}

function priceImport(){
    var importDialog = openImportExcelDialog('static/excel/采购信息记录期初导入模板.xlsx','价格信息记录期初导入',function(file){
        let formData = new FormData();
        formData.append("file", file);
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/price/rest/import',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {

                if (data === 'ok') {
                    topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                        $(el.tb).datagrid('reload');
                        $(el.tb).datagrid('clearSelections');
                        topWin.layer.close(idx);
                        importDialog.dialog('close');
                    });
                } else {
                    topWin.layer.confirm('部分导入成功,是否下载未成功数据?', function (index) {
                        $(el.tb).datagrid('reload');
                        $(el.tb).datagrid('clearSelections');
                        topWin.layer.close(index);
                        window.location.href = g.ctx + 'pc/sys/file/rest/download/' + data
                    });
                }
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}