//@ sourceURL=yf_inventory_list.js
var pharmacyGroupNo;//药房编码
$(function () {
    $('#fyClass').selectpicker('refresh');
    $("#pharmacyModal").modal("show");
    $("input").each(function () {
        this.onkeydown = function (e) { // 监听键盘事件
            let theEvent = window.event || e;
            let code = theEvent.keyCode || theEvent.which;
            if (code == 13) {//回车事件
                $("#btn_search").click(); //触发搜索按钮点击事件
            }
        }
    });
    $(".selectpicker").selectpicker();
    $('#searchText').on('input propertychange',function(e){
        initTable();
    });
});



/**
 * 初始化参数
 */
function init() {
    pharmacyGroupNo = $("#pharmacyGroupNo").val();
    $("#pharmacyModal").modal("hide");
    initTable();
    initTree();
}


/**
 * 重置查询表单
 */
function resetSearch() {
    $("#searchText").val(null);
}

/**
 * 加载药品类型树
 */
function initTree() {
    $.ajax({
        type: "GET",
        url: '/thmz/getYpZdClassTreeListByCode?code=0',
        contentType: "application/json;charset=UTF-8",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        dataType: 'json',
        success: function(res){
            if(res.code == 0){
                var tree = new Array();
                $.each( res.data,function(index, item){
                    item.isParent==1?tree[index]={text:item.text,code:item.code,nodes:[]}:tree[index]={text:item.text,code:item.code};
                });
                $('#tree').treeview({
                    data: tree, //节点数据
                    backColor: '#EBEBE4',//背景颜色
                    onNodeSelected: function (event, node) {//选中节点时调用的方法
                        var nodes = $('#tree').treeview('getSelected', node.nodeId);
                        initTable(node.code);
                        if(nodes[0].nodes != undefined && nodes[0].nodes.length == 0){
                            getChildCom(node);
                        }
                        $('#tree').treeview('expandNode', [ node.nodeId, { levels: 2, silent: true } ]);
                    },
                    emptyIcon: "fa fa-medkit",//设置子节点图标样式
                })
            }else{
                errorMesage(res);
            }
        }
    });
}

/**
 * 获取子类型信息
 * @param code
 */
function getChildCom(node){
    $.ajax({
        processData: false,  // 告诉jQuery不要去处理发送的数据
        contentType: false,  // 告诉jQuery不要去设置Content-Type请求头
        type: "GET",
        url: '/thmz/getYpZdClassTreeListByCode?code='+node.code,
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        success: function (r) {
            if(r.code == 0) {
                $.each(r.data, function (index, item) {
                    var addNodes = new Array();
                    addNodes[0] = node.nodeId;
                    item.isParent==1?addNodes[1]={node: {text: item.text, code: item.code,nodes:[]}}:addNodes[1]={node: {text: item.text, code: item.code}};
                    $("#tree").treeview("addNode", addNodes);
                });
            }
        }
    });
}

/**
 * 查询列表
 */
function initTable(classCode) {
    if(typeof(classCode) == "undefined"){
        classCode = null;
    }
    var isMultiple = $("#isMultiple").val();
    $('#tb_table').bootstrapTable('destroy');
    $('#tb_table').bootstrapTable({
        url: '/thmz/getYpZdBaseYfPage',         //请求后台的URL（*）
        method: 'GET',                      //请求方式（*）
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        queryParams: function(params) {
            var temp = {
                pageSize: params.limit,   //页面大小
                pageIndex: params.offset / params.limit,  //页码
                searchText: $("#searchText").val(),
                groupNo: pharmacyGroupNo,
                classCode: classCode,
                isMultiple: isMultiple
            };
            return temp;
        },           //传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 20,                       //每页的记录行数（*）
        pageList: [20, 40, 50, 100],        //可供选择的每页的行数（*）
        search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
        strictSearch: true,
        showColumns: false,                  //是否显示所有的列
        showRefresh: false,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
        showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,
        ajaxOptions: {
            headers: {
                'Accept': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem("token")
            }
        },
        columns: [
            {
                field: 'checked',
                checkbox: true,
                align: "center",
                valign: 'middle',
                visible: $('#isMultiple').val()==0?true:false
            },{
                field: 'location',
                title: '货位号',
                align: "center",
                valign: 'middle',
                visible: isMultiple==1?false:true
            }, {
                field: 'code',
                title: '药品编码',
                align: "center",
                valign: 'middle'
            }, {
                field: 'name',
                title: '药品名',
                align: "center",
                valign: 'middle'
            },
            {
                field: 'stockAmountMz',
                title: '西药房存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                },
                cellStyle:function (value, row, index) {
                    if(row.visibleFlagMz == 0){
                        return {css:{background:'red'}};
                    }
                    return {css:{}};
                },
            },
            {
                field: 'stockAmountDz',
                title: '呆账药房存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                }
            },
            {
                field: 'stockAmountYk',
                title: '药库存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                },
                cellStyle:function (value, row, index) {
                    if(row.visibleFlagYk == 0){
                        return {css:{background:'red'}};
                    }
                    return {css:{}};
                },
            },
            {
                field: 'specificationMin',
                title: '小规格',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true
            },
            {
                field: 'stockAmountLargeMz',
                title: '西药房大规格存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                },
                cellStyle:function (value, row, index) {
                    if(row.visibleFlagMz == 0){
                        return {css:{background:'red'}};
                    }
                    return {css:{}};
                },
            },
            {
                field: 'stockAmountLargeDz',
                title: '呆账药房大规格存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                }
            },
            {
                field: 'stockAmountLargeYk',
                title: '药库大规格存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                },
                cellStyle:function (value, row, index) {
                    if(row.visibleFlagYk == 0){
                        return {css:{background:'red'}};
                    }
                    return {css:{}};
                },
            },
            {
                field: 'specificationMax',
                title: '大规格',
                align: "center",
                valign: 'middle',
                visible: isMultiple==0?false:true
            },
            {
                field: 'specification',
                title: '规格',
                align: "center",
                valign: 'middle',
                visible: isMultiple==1?false:true
            },
            {
                field: 'packRetprice',
                title: '零售价',
                align: "center",
                valign: 'middle',
                visible: isMultiple==1?false:true,
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'stockAmount',
                title: '库存量',
                align: "center",
                valign: 'middle',
                visible: isMultiple==1?false:true,
                formatter: function (value, row, index) {
                    return Math.floor(value * 100) / 100;
                }
            }, {
                field: 'stockValue',
                title: '库存金额',
                align: "center",
                valign: 'middle',
                visible: isMultiple==1?false:true,
                formatter: function (value, row, index) {
                    return value.toFixed(2);
                }
            }, {
                field: 'stockAmountVirtual',
                title: '当前虚存',
                align: "center",
                valign: 'middle',
                visible: isMultiple==1?false:true
            }, {
                field: 'manufactoryName',
                title: '生产厂家',
                align: "center",
                valign: 'middle'
            }
        ],
        rowStyle: function (row, index) {
            if (isMultiple == 0 && row.visibleFlagMz == 1 && row.visibleFlagZy == 1) {
                return { css: { 'background-color': 'red' } };
            }
            return {css:{}}
        },
        responseHandler: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            var ress = eval(res);
            if (ress.code == -1) {
                errorMesage(res);
                return {
                    "total": 0,//总页数
                    "rows": {}   //数据
                };
            }

            return {
                "total": ress.total,//总页数
                "rows": ress.data   //数据
            };
        }
    });
}

/**
 * 平虚库存
 */
function resetVirtual() {
    var row = $("#tb_table").bootstrapTable('getSelections');
    if(row.length < 1){
        return errorMesageSimaple('请选择需要平虚库存的药品');
    }
    var datas = [];
    var i = 0;
    row.forEach(function (item, index, arr) {
        if (item.stockAmountVirtual != item.stockAmount) {
            var tem = {
                "code": item.code,
                "serial": item.serial,
                "groupNo": pharmacyGroupNo
            }
            datas[i] = tem;
            i++;
        }
    })
    if (datas.length == 0) {
        return errorMesageSimaple('没有可平虚库存的药品');
    }
    $.ajax({
        type: "POST",
        url: '/thmz/resetVirtual',
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        headers: {'Accept': 'application/json', 'Authorization': 'Bearer ' + localStorage.getItem("token")},
        data: JSON.stringify(datas),
        success: function (res) {
            if (res == '401' || res == 401) {
                window.location.href = '/thmz/login/view'
                return;
            }
            if (res.code == 0) {
                successMesage(res);
                initTable();
            } else {
                errorMesage(res);
            }
        }
    });
}