using System.Data;
using System.Data.SqlClient;
using Business.System.User.Entity;
using Common;

namespace LogisticsSystem.Control.Helper
{
    public class LoginHelper
    {
        //用户实体类,保存用户资料
        public UserEty User = new UserEty();

        /// <summary>
        /// 登录方法,登录成功更新实体类内容
        /// </summary>
        /// <param name="useracc">用户账号</param>
        /// <param name="userpwd">用户密码</param>
        /// <returns>登录信息</returns>
        public string Login(string useracc,string userpwd)
        {
            const string sql = "select * from SysUser where useraccount=@useraccount and userpassword=@userpassword and delflag=0";
            var sqlParameters = new[]
                {
                    new SqlParameter( "@useraccount",useracc),
                    new SqlParameter( "@userpassword", SecurityHelper.Md5Encrypt(userpwd))
                };
            return ExecSqlReader(sql, sqlParameters);
        }


        /// <summary>
        /// 执行sql,返回SqlDataReader
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <param name="sqlParameters">sql参数</param>
        private  string ExecSqlReader(string sql, params SqlParameter[] sqlParameters)
        {
            var con = new SqlConnection(SqlHelper.ConStr);
            var cmd = new SqlCommand { Connection = con, CommandType = CommandType.Text, CommandText = sql };
            if (sqlParameters.Length > 0)
            {
                SqlHelper.CmdGetParam(cmd, sqlParameters);
            }
            try
            {
                con.Open();
            }
            catch
            {
                return "没数据库连接";
            }
            using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
            {
                if (!reader.HasRows)
                    return "用户名或密码错误";
                while (reader.Read())
                {
                    User.Userid = SqlHelper.ReaderString("userid", reader);
                    User.Username = SqlHelper.ReaderString("username", reader);
                    User.Depid = SqlHelper.ReaderString("depid", reader);
                    User.Mobile = SqlHelper.ReaderString("mobile", reader);
                    User.Userroleid = SqlHelper.ReaderString("userroleid", reader);
                    User.Addtime = SqlHelper.ReaderDateTime("addtime", reader);
                    User.Adduserid = SqlHelper.ReaderString("adduserid", reader);
                }
            }
            return string.Empty;
        }
    }
}