using DeviceRepair.DataAccess.Data;
using DeviceRepair.Models.SFC;
using DeviceRepair.Utils;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using DeviceRepair.DataAccess.Utils;
using DeviceRepair.Models;
using DeviceRepair.Models.History;

namespace DeviceRepair.DataAccess.SFC
{
    public class UserDa: BaseDa
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();
        
        public UserDa(IDictionary<string, string> apiParams) : base(apiParams)
        {

        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="userCode"></param>
        /// <param name="pwd"></param>
        /// <param name="dsDatas"></param>
        /// <returns></returns>
        public APIResponseData UserLogin(string userCode, string pwd, out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                dsDatas = sfcData.Ado.UseStoredProcedure().GetDataSetAll(SQLConstants.SP_USER_LOGIN, new
                {
                    UserCode = userCode,
                    Pwd = pwd,
                    cType = "I",
                    ClientIP = ApiParameters["CLIENTIP"],
                    ClientMAC = ApiParameters["CLIENTMAC"],
                    ClientName = ApiParameters["CLIENTNAME"]
                });
                return new APIResponseData() { Code = 1, Message = "用户登陆成功！" };
            }
            catch (Exception ex)
            {
                log.Error(ex);
                return new APIResponseData { Code = -1, Message = ex.Message };
            }
        }

        /// <summary>
        /// 获取全部SFC用户信息
        /// </summary>
        /// <returns></returns>
        public DataSet Get_User_Datas()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                List<TsSFCUserInfo> Datas = sfcData.Ado.SqlQuery<TsSFCUserInfo>("SELECT Id,GUID,UserCode,UserName,UserType,Status FROM dbo.UserInfo ");
                DataTable table = Datas.ToDataTable();
                dsDatas.Tables.Add(table);
                return dsDatas;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 电子签
        /// </summary>
        /// <param name="Data"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public APIResponseData UserConfirm(DataTable Data, out DataTable dtData)
        {
            try
            {
                dtData = null;
                DateTime CurrentTime = DateTime.Now;

                if (Data == null || Data.Rows.Count == 0)
                    throw new ArgumentException($"电子签用户对象不能为空");

                UserConfirmHistory Model = Data.Rows[0].ToObject<UserConfirmHistory>();
                Model.ClientIP = ApiParameters["CLIENTIP"];
                Model.ClientMAC = ApiParameters["CLIENTMAC"];
                Model.ClientName = ApiParameters["CLIENTNAME"];
                Model.CreateOn = CurrentTime;

                TsSFCUserInfo user = sfcData.Ado.SqlQuery<TsSFCUserInfo>(" SELECT * FROM dbo.UserInfo WHERE UserCode = @UserCode", new { UserCode = Model.UserCode }).FirstOrDefault();
                if (user == null)
                {
                    Model.cContent = "用户认证失败：用户{userConfirm.UserCode}不存在！";
                    Model.bSuccess = false;
                    devLog.Insertable(Model).ExecuteCommand();
                    throw new Exception($"用户认证失败：用户{Model.UserCode}不存在！");
                }

                if (!user.Status.Equals("A", StringComparison.OrdinalIgnoreCase))
                {
                    Model.cContent = "用户认证失败：用户{userConfirm.UserCode}已被锁定！";
                    Model.bSuccess = false;
                    devLog.Insertable(Model).ExecuteCommand();
                    throw new Exception($"用户认证失败：用户{Model.UserCode}已被锁定！");
                }

                if (!user.Password.Equals(Model.PassWord, StringComparison.OrdinalIgnoreCase))
                {
                    Model.cContent = $"用户认证失败：密码不正确！";
                    Model.bSuccess = false;
                    devLog.Insertable(Model).ExecuteCommand();
                    throw new Exception($"用户认证失败：密码不正确！");
                }

                if (!string.IsNullOrWhiteSpace(Model.ConfirmAuth))
                {
                    if (!sfcData.Ado.SqlQuery<int>("SELECT 1 FROM dbo.v_UserAuths WHERE UserCode = @UserCode AND AuthCode = @AuthCode ", new { UserCode = Model.UserCode, AuthCode = Model.ConfirmAuth }).Any())
                    {
                        Model.cContent = $"用户认证失败：缺少权限：{Model.ConfirmAuth}！";
                        Model.bSuccess = false;
                        devLog.Insertable(Model).ExecuteCommand();
                        throw new Exception($"用户认证失败：缺少权限：{Model.ConfirmAuth}！");
                    }
                }

                Model.bSuccess = true;
                int bSuccess = devLog.Insertable(Model).ExecuteCommand();
                if (bSuccess == 1)
                {
                    ApiOperationRtn apiOperationRtn = new ApiOperationRtn()
                    {
                        OperationDate = CurrentTime,
                        Operation = user.Id,
                        OperationName = user.UserName
                    };

                    dtData = apiOperationRtn.toDataTable();
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    return new APIResponseData { Code = -1 };
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }
        
        public DataSet GetAuths()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                string UserCode = GetParamString("UserCode", "用户账号");
                Guid UserGuid = GetParamGuid("UserGuid", "用户唯一标识");

                string sql =
                    @" SELECT UserGuid, UserCode, UserName, UserStatus, AuthCode, AuthName, FatherAuthCode, AuthCreateBy AS CreateBy, AuthCreateOn AS CreateOn, AuthNote AS Note, AuthModifyBy AS ModifyBy, AuthModifyOn AS ModifyOn FROM dbo.v_UserAuths WITH (NOLOCK) WHERE UserCode = @UserCode AND UserGuid = @UserGuid ";
                List<TsSFCAuths> Datas = sfcData.Ado.SqlQuery<TsSFCAuths>(sql, new { UserCode, UserGuid });
                if (Datas.IsNull())
                    return dsDatas;
                
                DataTable table = Datas.ToDataTable();
                dsDatas.Tables.Add(table);

                return dsDatas;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
        
    }
}