const mongoose = require('mongoose').set('debug', false)
const Schema = mongoose.Schema;

const shared_consts = require('../tools/shared_nodejs');

const Order = require('../models/order');
var { User } = require('../models/user');

const tools = require('../tools/general');

const { ObjectID } = require('mongodb');

const OrdersCartSchema = new Schema({
  idapp: {
    type: String
  },
  numorder: { type: Number },
  userId: { type: Schema.Types.ObjectId, ref: 'User' },
  totalQty: { type: Number, default: 0 },
  totalPrice: { type: Number, default: 0 },
  department: {
    type: String, ref: 'Department'
  },
  items: [
    {
      order:
        { type: Schema.Types.ObjectId, ref: 'Order' }
    }
  ],
  status: {
    type: Number,
    Default: 0,
  },
  note: {
    type: String
  },
  modify_at: {
    type: Date
  },
  created_at: {
    type: Date
  },
  completed_at: {
    type: Date
  },
});

var OrdersCart = module.exports = mongoose.model('OrdersCart', OrdersCartSchema);

module.exports.findAllIdApp = async function (idapp, userId) {
  const myfind = { idapp, userId };

  return await await OrdersCart.find(myfind);
};

module.exports.executeQueryTable = function (idapp, params) {
  params.fieldsearch = this.getFieldsForSearch();
  return tools.executeQueryTable(this, idapp, params);
};

module.exports.getFieldsForSearch = function () {
  return [{ field: 'note', type: tools.FieldType.string }]
};


module.exports.getNewNumOrder = async function (uid, idapp) {
  let query = { userId: uid, idapp }
  let numorder = 1;
  let numorderrec = await OrdersCart.find(query).sort({ numorder: -1 }).limit(1);
  if (numorderrec.length <= 0)
    numorder = 1;
  else
    numorder = numorderrec[0].numorder;

  if (numorder) {
    numorder++
  } else {
    numorder = 1;
  }

  return numorder;

};

module.exports.getStatusCartByUserId = async function (uid, idapp, numorder) {
  let query = { userId: uid, idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
  let myorderscart = null;
  if (numorder > 0) {
    query = { userId: uid, idapp, numorder, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
  }

  myorderscart = await OrdersCart.findOne(query);

  if (!!myorderscart)
    return myorderscart.status;
  else
    return shared_consts.OrderStatus.NONE

}
module.exports.getOrdersCartByUserId = async function (uid, idapp, numorder) {

  let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
  let myorderscart = null;
  if (numorder > 0) {
    query.numorder = numorder;
  }

  if (uid !== 'ALL') {
    query.userId = uid;
  }

  myorderscart = await OrdersCart.find(query).lean();

  for (let ind = 0; ind < myorderscart.length; ind++) {
    for (const idkey in myorderscart[ind].items) {
      try {
        let idorder = myorderscart[ind].items[idkey]._id.toString();
        const myorder = myorderscart[ind].items[idkey].order;
        if (!!myorder) {
          idorder = myorderscart[ind].items[idkey].order._id.toString();
        }
        myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId);
        const myord = await Order.getTotalOrderById(idorder);
        if (myord.length > 0) {
          myorderscart[ind].items[idkey].order = myord[0];
        }
      } catch (e) {
        console.log('err', e);
      }
    }
  }

  /*  if (!!mycart) {
      for (const idkey in mycart.items) {
        try {
          idorder = mycart.items[idkey]._id.toString();
          const myorder = mycart.items[idkey].order;
          if (!!myorder) {
            idorder = mycart.items[idkey].order._id.toString();
          }
          const myord = await Order.getTotalOrderById(idorder);
          if (myord.length > 0) {
            mycart.items[idkey]._doc.order = myord[0];
          }
        } catch (e) {
          console.log('err', e);
        }
      }
      return mycart;
    }*/
  return myorderscart
  // return null;
}

module.exports.getOrdersCartByDepartmentId = async function (depId, idapp) {
  let query = { idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
  const myorderscart = await OrdersCart.find(query).lean();

  for (let ind = 0; ind < myorderscart.length; ind++) {
    for (const idkey in myorderscart[ind].items) {
      try {
        let idorder = myorderscart[ind].items[idkey]._id.toString();
        const myorder = myorderscart[ind].items[idkey].order;
        if (!!myorder) {
          idorder = myorderscart[ind].items[idkey].order._id.toString();
        }
        myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId);
        const myord = await Order.getTotalOrderById(idorder);
        if (myord.length > 0) {
          myorderscart[ind].items[idkey].order = myord[0];
        }
      } catch (e) {
        console.log('err', e);
      }
    }
  }

  return myorderscart
  // return null;
}

module.exports.getOrderById = async function (Id, idapp) {
  let query = { _id: Id, idapp, status: { $gte: shared_consts.OrderStatus.CHECKOUT_SENT } }
  const myorderscart = await OrdersCart.find(query).lean();

  for (let ind = 0; ind < myorderscart.length; ind++) {
    for (const idkey in myorderscart[ind].items) {
      try {
        let idorder = myorderscart[ind].items[idkey]._id.toString();
        const myorder = myorderscart[ind].items[idkey].order;
        if (!!myorder) {
          idorder = myorderscart[ind].items[idkey].order._id.toString();
        }
        myorderscart[ind].nameSurname = await User.getNameSurnameById(idapp, myorderscart[ind].userId);
        const myord = await Order.getTotalOrderById(idorder);
        if (myord.length > 0) {
          myorderscart[ind].items[idkey].order = myord[0];
        }
      } catch (e) {
        console.log('err', e);
      }
    }
  }

  return myorderscart
  // return null;
}

module.exports.updateOrdersCartById = function (id, newOrdersCart, callback) {
  let query = { id: id }
  OrdersCart.find(query, function (err, c) {
    if (err) throw err

    //exist cart in databse
    if (c.length > 0) {
      OrdersCart.findOneAndUpdate(
        { _id: id },
        {
          $set: {
            items: newOrdersCart.items,
            totalQty: newOrdersCart.totalQty,
            totalPrice: newOrdersCart.totalPrice,
            userId: userId,
            status: newOrdersCart.status,
            numorder: newOrdersCart.numorder,
            note: newOrdersCart.note,
            modify_at: new Date(),
          }
        },
        { new: true },
        callback
      )
    } else {
      //no cart in database
      newOrdersCart.save(callback)
    }
  })
}

module.exports.createOrdersCart = async function (newOrdersCart) {
  return await newOrdersCart.save()
}

OrdersCartSchema.pre('save', async function (next) {

  try {
    if (this.isNew) {
      try {
        const myrec = await User.findOne({ idapp: this.idapp }).limit(1).sort({ neworder: -1 });

        if (!!myrec) {
          this.neworder = myrec._doc.neworder + 1;
        } else {
          this.neworder = 1;
        }
      } catch (e) {
        this.neworder = 2;
      }
    }

    /*
    if (user.isModified('password')) {
      bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(user.password, salt, (err, hash) => {
          user.password = hash;
          next();
        });
      });
    } else {
      next();
    }
    */

    next();
  } catch (e) {
    console.error(e.message);
  }
});
