var el = {
    searchForm: '#searchForm',
    supplierCode: '#supplierCode',
    materialCode: '#materialCode',
    purchaseGroupCode: '#purchaseGroupCode',
    expireDate: '#expireDate',
    expireNum: '#expireNum',
    business:'#business',
    tt: '#tt',
    materialGroupTb: '#tb111',
    supplierGroupTb: '#tb222',
    supplierChoseDialog: null,
    mgTbCounter: 0,
    sgTbCounter: 0,
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    ceshi();
    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');
    initPageQuery();
    // 这里就是处理的事件
    loadMaterialGroupTb();
});


/**
 * 初始化查询条件
 */
function initPageQuery() {
    $(el.tt).tabs({
        border: false,
        onSelect: function(title, index){
            if(el.mgTbCounter === 0 && el.sgTbCounter === 0){
                return false;
            }
            if(el.mgTbCounter === 0 || el.sgTbCounter === 0){
                dataQuery(index);
            }
        }
    });

    $(el.expireDate).datebox('setValue', moment().format('YYYY-MM-DD'));

    // 采购组
    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll'
    });
}

var 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: 'inquiryFlag',
        title: '转询价状态',
        align : 'left',
        width: 75,
        exportEnum:[
            {code:0,codeWithDesc:'未转'},
            {code:1,codeWithDesc:'已询价'}
        ],
        formatter: function (value, row) {
            if (value === 0) {
                return "<span style='color: blue'>未转</span>"
            }
            if (value === 1) {
                return "<span style='color: blue'>已询价</span>"
            }
        }
    },
    {
        field: 'priceCode',
        title: '信息记录编号',
        width: '120',
        align: 'left'
    },
    {
        field: 'purchaseType',
        title: '采购类型',
        width: '120',
        align: 'left',
        exportEnum:[
            {code:0,codeWithDesc:'标准'},
            {code:2,codeWithDesc:'寄售'},
            {code:3,codeWithDesc:'标准委外'}
        ],
        formatter:function (value) {
            if (Number(value) === 0) {
                return "标准"
            } else if (Number(value) === 2) {
                return '寄售'
            } else if (Number(value) === 3) {
                return '标准委外'
            }
        }
    },
    {
        field: 'supplierCode',
        title: '供应商编码',
        width: '100',
        align: 'left'
    },
    {
        field: 'supplierName',
        title:'供应商名称',
        width: '150',
        //hidden:true,
        align: 'left'
    },
    {
        field: 'materialCode',
        title:'物料号' ,
        width: '150',
        align: 'left'
    },
    {
        field: 'materialName',
        title:'物料描述',
        width: '200',
        align: 'left'
    },
    {
        field: 'taxPrice', title: '含税单价', width: '70', align: 'left',
    },
    {
        field: 'noTaxPrice', title: '未税单价', width: '80', align: 'left',
    },
    {
        field: 'effectDate',
        title: '生效日期',
        width: '130',
        align: 'left'  ,
        exportDateFormatter:'date',
        formatter: function (value) {
            if (value) {
                return moment(value).format("YYYY-MM-DD");
            }
            return '';
        }
    },
    {
        field: 'invalidDate',
        title:'失效日期',
        width: '130',
        align: 'left'   ,
        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: 'factoryCode',
        title:'工厂编码',
        width: '80',
        align: 'left'
    },
    {
        field: 'taxCode',
        title: '税率',
        width: '150',
        exportEnum:getNecessaryDataList('pc/sys/tax/rest/listAll'),
        formatter: function (value) {
            return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
        }
    },
    {
        field: 'currencyCode',
        title: '货币',
        width: '100',
        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: 'companyCode',
        title: '公司',
        width: '150',
        align: 'center',
        exportEnum:getNecessaryDataList('pc/sys/company/rest/listAll'),
        formatter: function (value) {
            return getNecessaryDataName('pc/sys/company/rest/listAll',value);
        }
    },
    {
        field: 'remark',

        title:'备注',
        width: '70',
        align: 'left'
    },
    {
        field: 'createTime',
        title: '创建时间',
        width: '70',
        exportDateFormatter:'dateTime',
        formatter: function (value) {
            if (value) {
                return moment(value).format("YYYY-MM-DD HH:mm:ss");
            }
            return '';
        }
    },
];

/**
 * 按物料分组
 */
function loadMaterialGroupTb() {
    var searchHeight = $(el.searchForm).outerHeight() - 10;
    var url = '/pc/inquiry/create/warning/rest/list?groupFlag=0';
    $(el.materialGroupTb).datagrid({
        loadMsg: "数据加载中......",
        height: el.bodyHeight - searchHeight - 70,
        url: url,
        singleSelect: false,
        pagination: true,
        rownumbers: true,
        // loadFilter: pagerFilter,
        groupField: 'materialCode',
        view: groupview,
        page: 1,
        pageSize: 10,
        queryParams: {
            warningId:$(el.id).val(),
            page: 1,
            rows: 20
        },
        columns: [columns],
        toolbar: [
            {
                text: '转询价单',
                iconCls: 'icon-reload',
                handler: function () {
                    transferInquiry('material');
                }
            },
            {
                id: 'export',
                text: '导出',
                iconCls: 'icon-import',
                handler: function () {
                    var queryParams = {};
                    queryParams.supplierCode = $(el.supplierCode).textbox('getValue');
                    queryParams.materialCode = $(el.materialCode).textbox('getValue');
                    queryParams.purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
                    queryParams.expireNum = $(el.expireNum).numberbox('getValue');
                    queryParams.groupFlag = 0;
                    queryParams.expireDate = moment($(el.expireDate).datebox('getValue')).format('YYYY-MM-DD');
                    openExportDialog('pc/inquiry/create/warning/rest/export','tb111',queryParams);
                }
            }
        ],
        groupFormatter: function (value, rows) {
            return ' &nbsp;物料编号:&nbsp;' + value;
        },
        onLoadSuccess: function (data) {
            loadSupplierGroupTb();
        }
    });
}

/**
 * 按供应商分组
 */
function loadSupplierGroupTb() {
    var searchHeight = $(el.searchForm).outerHeight() - 10;
    var url = '/pc/inquiry/create/warning/rest/list?groupFlag=1';
    $(el.supplierGroupTb).datagrid({
        loadMsg: "数据加载中......",
        height: el.bodyHeight - searchHeight - 70,
        url: url,
        singleSelect: false,
        pagination: true,
        rownumbers: true,
        // loadFilter: pagerFilter,//过滤数据
        groupField: 'supplierCode',
        view: groupview,
        pageSize: 10,
        queryParams: {
            warningId:$(el.id).val(),
            page: 1,
            rows: 20
        },
        columns: [columns],
        groupFormatter: function (value, rows) {
            return '&nbsp;供应商编号:&nbsp;' + value;
        },
        toolbar: [
            {
                text: '转询价单',
                iconCls: 'icon-reload',
                handler: function () {
                    transferInquiry('supplier');
                }
            },
            // {
            //     text: '导出',
            //     iconCls: 'icon-redo',
            //     handler: function () {
            //         uploadPrice();
            //     }
            // }
            {
                id: 'export',
                text: '导出',
                iconCls: 'icon-import',
                handler: function () {
                    var queryParams = {};
                    queryParams.supplierCode = $(el.supplierCode).textbox('getValue');
                    queryParams.materialCode = $(el.materialCode).textbox('getValue');
                    queryParams.purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
                    queryParams.expireNum = $(el.expireNum).numberbox('getValue');
                    queryParams.groupFlag = 1;
                    queryParams.expireDate = moment($(el.expireDate).datebox('getValue')).format('YYYY-MM-DD');
                    openExportDialog('pc/inquiry/create/warning/rest/export','tb222',queryParams);
                }
            }
        ]
    });
}
//excel导出
function uploadPrice() {
    topWin.layer.confirm('确定导出?', function (index) {
        document.getElementById("searchForm").action = g.ctx + 'xj/price/info/excel/upload';
        document.getElementById("searchForm").submit();
        topWin.layer.close(index)
    });
}
/**
 * 将选中的价格信息记录转成询报价单
 * @param type
 */
function transferInquiry(type) {
    var rows = [];
    if(type === 'material'){
        rows = $(el.materialGroupTb).datagrid('getSelections');
    }
    if(type === 'supplier'){
        rows = $(el.supplierGroupTb).datagrid('getSelections');
    }
    if (rows.length === 0) {
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return
    }
    var purchaseGroupCode = rows[0].purchaseGroupCode;
    var companyCode = rows[0].companyCode;

    for (var i = 1 ; i < rows.length ; i++) {
        if (!rows[i].materialName){
            topWin.layer.msg("选中数据存在物料描述为空的数据，不可转询价",{icon:0});
            return
        }
        if (purchaseGroupCode !== rows[i].purchaseGroupCode) {
            topWin.layer.msg("请选择相同的采购组数据",{icon:0});
            return
        }
        if (companyCode !== rows[i].companyCode){
            topWin.layer.msg("请选择相同的公司",{icon:0});
            return
        }
    }

    var ids = [];
    $.each(rows, function (index, target) {
        ids.push(target.id);
    });
    var url = g.ctx + 'pc/inquiry/create/warning/transfer/inquiry?ids=' + ids.join(',')+"&optType="+otpTypeEnum.ADD;
    var dialogElement = openDialog("editDialog", url, {
        title: '询价新增',
        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');
            }
        }]
    });
}


/**
 * 数据查询
 *
 * @param tabIndex tab索引
 */
function dataQuery(tabIndex) {
    var expireDate = $(el.expireDate).datebox('getValue');
    if(!expireDate){
        layer.msg('临期时间请必须填写', {icon: 0});
        return false;
    }
    var expireNum = $(el.expireNum).numberbox('getValue');
    if(!expireNum){
        layer.msg('预警天数请必须填写', {icon: 0});
        return false;
    }
    var queryParams = {};
    queryParams.supplierCode = $(el.supplierCode).textbox('getValue');
    queryParams.materialCode = $(el.materialCode).textbox('getValue');
    queryParams.purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
    queryParams.expireNum = expireNum;
    queryParams.expireDate = moment(expireDate).format('YYYY-MM-DD');

    if(tabIndex === -1){
        $(el.tt).tabs('getSelected');
        var choseTab = $(el.tt).tabs('getSelected');
        tabIndex = $(el.tt).tabs('getTabIndex', choseTab);
    }
    if(tabIndex === 0){
        $(el.materialGroupTb).datagrid('options').queryParams = queryParams;
        $(el.materialGroupTb).datagrid('load');
        el.mgTbCounter = 1;
    }else {
        $(el.supplierGroupTb).datagrid('options').queryParams = queryParams;
        $(el.supplierGroupTb).datagrid('load');
        el.sgTbCounter = 1;
    }
}


/**
 * 重置查询条件
 */
function resetQuery(tabIndex) {
    $(el.supplierCode).textbox('setValue', '');
    $(el.materialCode).textbox('setValue', '');
    $(el.purchaseGroupCode).combobox('setValue', '');
    $(el.expireDate).datebox('setValue', moment().format('YYYY-MM-DD'));
    $(el.expireNum).numberbox('setValue', 30);
    var queryParams = {};
    queryParams.supplierCode = $(el.supplierCode).textbox('getValue');
    queryParams.materialCode = $(el.materialCode).textbox('getValue');
    queryParams.purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
    queryParams.expireNum = 30;
    queryParams.expireDate = moment().format('YYYY-MM-DD');

    if(tabIndex === -1){
        $(el.tt).tabs('getSelected');
        var choseTab = $(el.tt).tabs('getSelected');
        tabIndex = $(el.tt).tabs('getTabIndex', choseTab);
    }
    if(tabIndex === 0){
        $(el.materialGroupTb).datagrid('options').queryParams = queryParams;
        $(el.materialGroupTb).datagrid('load');
        el.mgTbCounter = 1;
    }else {
        $(el.supplierGroupTb).datagrid('options').queryParams = queryParams;
        $(el.supplierGroupTb).datagrid('load');
        el.sgTbCounter = 1;
    }
}


/**
 * 选择查询供应商信息
 */
function choseSupplierDialog() {
    var url = g.ctx + 'xj/price/info/chose/sup';
    el.supplierChoseDialog = openDialog('choseSupplier', url, {
        title: '选择供应商',
        width: 700,
        height: 550,
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.supplierChoseDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '保存',
                handler: function () {
                    topWin.frames['choseSupplier'].confirmChose(function (data) {
                        if(data.length === 0){
                            topWin.layer.msg('请选择供应商数据', {icon: 2});
                            return false;
                        }
                        $(el.supplierChose).textbox('setValue', data[0].supplierCode);
                        el.supplierChoseDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                handler: function () {
                    el.supplierChoseDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 加载数据时用js做前台分页
 *
 * @param data 原数据
 * @return {*} 结果
 */
function pagerFilter(data){
    // 判断数据是否是数组
    if (typeof data.length === 'number' && typeof data.splice === 'function') {
        data = {
            total: data.length,
            rows: data
        }
    }

    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function(pageNum, pageSize){
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh',{
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalRows){
        data.originalRows = (data.rows);
    }

    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalRows.slice(start, end));
    return data;
}


/**
 * 判断数组内的元素是否全部相等
 *
 * @param array 参数
 * @return {boolean} 返回结果
 */
function isAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function (value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
}
function ceshi() {
    console.log("1");
    setTimeout(function f() {
        console.log("111");
    }, 6000);
}