import conn from "../database/connect.js";
import md5 from "md5";
export async function login(username, password) {
  const sql = "select * from admin where username=?";
  const [result, fields] = await conn.query(sql, username);
  if (result.length == 0) throw new Error("用户不存在");
  const user = result[0];
  if (md5(password) != user.password) {
    throw new Error("用户名或密码错误");
  }
  return user;
}

export async function createProduct(params) {
  const { name, cat_id, size,
    price, image, content,
    keywords, sort }
    = params;
  if (!name || !price || !size) throw new Error("商品参数不能为空");
  const sql = `insert into product (
    name, cat_id, size,
    price, image, content,
    keywords, sort) values (?, ?, ?, ?, ?, ?, ?, ?)`
  const [result, fields] = await conn.query(sql, [name, cat_id,
    size, price,
    image, content,
    keywords, sort]);
  if (result.affectedRows == 0) throw new Error("添加失败");
}


export async function getProductList(params) {
  const sql = `select * from product`;
  const [result] = await conn.query(sql);
  return result;
}

export async function getProductDetail(productId) {
  const sql = `select * from product where id=?`;
  const [result] = await conn.query(sql, productId);
  if (result.length === 0) throw new Error("查询失败");
  return result[0];
}


export async function updateProduct(params) {
  const { id, name, cat_id, size,
    price, image, content,
    keywords, sort }
    = params;
  if (!id) throw new Error("商品ID缺失");
  if (!name || !price || !size) throw new Error("商品参数不能为空");

  const sql = `update product set name=?, cat_id=?, size=?,
    price=?, image=?, content=?,
    keywords=?, sort=?  where id=?`
  const [result, fields] = await conn.query(sql, [name, cat_id,
    size, price,
    image, content,
    keywords, sort, id]);
  if (result.affectedRows == 0) throw new Error("更新失败");
}


export async function deleteProduct(productId) {
  const sql = `delete from product where id=?`;
  const [result] = await conn.query(sql, productId);
  if (result.affectedRows == 0) throw new Error("删除失败");
}