const { DataTypes, Model, Op } = require('../../azeroth').sequelize;
const sequelize = require("../class/db").sequelize;
const Table = {};
// 获取所有stock 得到节点状态
Table.getStockRowColumn = async (shelveId) => {
    let data = await sequelize.query(`SELECT * FROM stock  WHERE shelve_id = ${shelveId}`);
    let info = await Table.getStockNesInfoByShelveId(shelveId);
    data = data ? data[0] : [];
    for(let item of data) {
        if(item.status != 2) {
            let rowColInfo = info[`${item.row}-${item.column}`]|| {};
            item.status = rowColInfo.new_status ||  item.status;
            item.new_status = item.status;
        }
    }
    let rowCol = {};
    data.forEach(item=>{
        rowCol[`${item.row}-${item.column}`] = item;
    })
    return rowCol;
}

Table.getStockNesInfoByShelveId = async (shelveId) => {
    let data = await sequelize.query(`SELECT * FROM stock_log WHERE shelve_id = ${shelveId} order by shelve_id ASC, \`row\` ASC, \`column\` ASC ;`);
    let rowColumn = {};
    (data[0] || []).forEach(item=>{
        try {
            item = {
                ...item,
                ...JSON.parse(item.content),
            };
            rowColumn[`${item.row}-${item.column}`] = item;
        }catch (e) {
            console.error(e);
        }
    });
    return rowColumn;
}

Table.getStockRowColumnNesInfo = async (shelveId, row, column) => {
    let data = await sequelize.query(`SELECT * FROM stock_log WHERE shelve_id = ${shelveId} AND row = ${row} AND \`column\` = ${column} order by id DESC limit 0,1;`);
    try {
        console.log(data);
        data = data[0][0];
        data.content = data.content.replace(/'/g, '"');
        data = {
            ...data,
            ...JSON.parse(data.content)
        };
    }catch (e) {
        console.error(e);
        data = false;
    }
    return data;
}

module.exports = Table;
