using System;
using System.Collections.Generic;
using System.Text;
using IDDal;
using Model;
using System.Data.Common;
using System.Data;

namespace ImpDDal
{
    public class ImpItemMsg:DbCommandStore,IItemMsg<ItemMsg>
    {
        #region IItemMsg<ItemMsg> 成员
        DbCommand cmd = GetCommand();

        #region 增加一个菜肴的评论
        public int AddItemMsg(ItemMsg itemMsg)
        {
            cmd.CommandText = "INSERT INTO UT_ItemMsg(ItemsId,UserName,Commment,UserIp) VALUES(@iid,@un,@c,@ip)";
            System.Data.Common.DbParameter[] p = new DbParameter[4];
            p[0] = new System.Data.SqlClient.SqlParameter("iid", itemMsg.Itemid);
            p[1] = new System.Data.SqlClient.SqlParameter("un", itemMsg.Username);
            p[2] = new System.Data.SqlClient.SqlParameter("c", itemMsg.Comment);
            p[3] = new System.Data.SqlClient.SqlParameter("ip", itemMsg.Userip);

            cmd.Parameters.Add(p[0]);
            cmd.Parameters.Add(p[1]);
            cmd.Parameters.Add(p[2]);
            cmd.Parameters.Add(p[3]);

            try
            {
                if (cmd.Connection.State == System.Data.ConnectionState.Closed)
                    cmd.Connection.Open();
                return cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception("增加留言失败", ex);
            }
        }
        #endregion

        #region 返回一个菜肴的评论
        public IList<ItemMsg> GetItemMsg(long itemId)
        {
            cmd.CommandText = "SELECT * FROM UT_ItemMsg WHERE ItemsId=@iid";
            DbParameter p=new System.Data.SqlClient.SqlParameter("iid",itemId);
            cmd.Parameters.Add(p);

            try
            {
                if (cmd.Connection.State == System.Data.ConnectionState.Closed)
                    cmd.Connection.Open();
                DbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                IList<ItemMsg> list = new List<ItemMsg>();
                ItemMsg itemMsg = null;
                while (reader.Read())
                {
                    itemMsg = new ItemMsg(long.Parse(reader.GetValue(1).ToString()), reader.GetString(2), reader.GetString(3), reader.GetString(4));
                    list.Add(itemMsg);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw new Exception("查询留言失败", ex);
            }
        }
        #endregion

        #endregion
    }
}
