using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using JLHHJSvr.BLL;
using JLHHJSvr.Com;
using JLHHJSvr.DBA.DBModle;
using LJLib.DAL.SQL;
using LJLib.Net.SPI.Server;
using LJLib.Tools.DEncrypt;
using LJLib.Tools.Encry;

namespace JLHHJSvr.Excutor
{
    internal sealed class LoginExcutor : ExcutorBase<LoginRequest, LoginResponse>
    {
        protected override void ExcuteInternal(LoginRequest request, object state, LoginResponse rslt)
        {
            if (string.IsNullOrEmpty(request.usercode))
            {
                rslt.ErrMsg = "用户名不能为空";
                return;
            }

            //if (string.IsNullOrEmpty(request.psw))
            //{
            //    rslt.ErrMsg = "密码不能为空";
            //}

            u_user_jlhprice stUser = new u_user_jlhprice();
            rslt.rsltFunids = new List<int>();
            using (var con = new SqlConnection(GlobalVar.ConnectionString))
            using (var cmd = con.CreateCommand())
            {
                con.Open();

                if (DbSqlHelper.SelectOne(cmd, "u_user_jlhprice", "userid = @usercode",
                    new Dictionary<string, object>() {{"@usercode", request.usercode}}, stUser,
                    "userid, empid, username, usermode, psw") != 1)
                {
                    rslt.ErrMsg = "用户名不存在或密码错误";
                    return;
                }

                psw_bczh3 pswhelper = new psw_bczh3();
                if (pswhelper.GetEntrypt(request.psw, 0, "123457851239866") != stUser.psw)
                {
                    rslt.ErrMsg = "用户名不存在或密码错误";
                    return;
                }

                rslt.rsltFunids = UserHelper.FilterMyFunids(cmd, stUser.empid);
            }

            string token = Guid.NewGuid().ToString();
            rslt.token = token;
            rslt.username = stUser.username;
            rslt.usercode = stUser.userid;
            rslt.empid = stUser.empid;
            rslt.usermode = stUser.usermode;
            var tokenData = new TokenData
            {
                empid = stUser.empid,
                usercode = stUser.userid,
                userid = stUser.empid,
                username = stUser.username,
                usermode = stUser.usermode
        };
            BllHelper.SetToken(token,tokenData);
        }
    }
}