using DeviceRepair.Models;
using DeviceRepair.Models.History;
using DeviceRepair.Models.SFC;
using DeviceRepair.Utils;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using TsSFCDevice.Client.Biz.Base.Service;
using TsSFCDevice.Client.Biz.Base.Utils;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace TsSFCDevice.Client.Biz.Impl
{
    public class UserRepository
    {
        private readonly Logger log;
        private static UserRepository manager;

        private IDictionary<string, string> m_ApiParameters;
        /// <summary>
        /// API输入参数
        /// </summary>
        public IDictionary<string, string> ApiParameters
        {
            get
            {
                return m_ApiParameters;
            }
            set
            {
                m_ApiParameters = value;
            }
        }

        public static UserRepository Instance
        {
            get
            {
                if (manager == null)
                    manager = new UserRepository();
                return manager;
            }
        }

        public UserRepository()
        {
            log = LogManager.GetCurrentClassLogger();
            m_ApiParameters = new Dictionary<string, string>();
        }

        internal string GetParameters(string cOperator = "", bool bFlag = true)
        {

            return ParametersObject.GetInstance(cOperator).GetJsonSerialized(m_ApiParameters);
        }

        public APIResponseData UserLogin(string userCode, string pwd)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();

                // 登录介质
                ApiParameters.Add("LOGIN_KIND", "USERPWD");

                var Rtn = Utility.SfcBizService.CurrentSvc.UserLogin(userCode,
                    DeviceRepair.Utils.Security.DESEncrypt.Encrypt(pwd), GetParameters(), out btResults);

                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);

                var vCurrentUser = DTOHelper<TsSFCUserInfo>.DataTableToList(dsResults.Tables[0])?[0];
                if (vCurrentUser == null)
                {
                    throw new Exception("实例化当前用户DTO时发生空异常错误！");
                }

                var vCurrentUserAuths = DTOHelper<TsSFCAuths>.DataTableToList(dsResults.Tables[2]);
                if (vCurrentUserAuths == null || !vCurrentUserAuths.Any(x => x.AuthCode.Equals("BIZ_EQUIP", StringComparison.OrdinalIgnoreCase)))
                {
                    throw new ArgumentException("当前用户无设备相关操作权限,请联系管理员！");
                }

                /* 设置全局用户信息 */
                Utility.SystemRuntimeInfo.CurrentUser = vCurrentUser;
                Utility.SystemRuntimeInfo.CurrentAuths = vCurrentUserAuths;

                return new APIResponseData { Code = 1, Message = "用户登陆成功！" };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                return new APIResponseData() { Code = -1, Message = ex.Message };
            }
        }

        public IList<TsSFCUserInfo> GetDatas()
        {
            IList<TsSFCUserInfo> Data = new List<TsSFCUserInfo>();

            byte[] btResults = null;
            ApiParameters?.Clear();

            var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.USER_INFO, GetParameters(), out btResults);
            if (Rtn.Code != 1)
            {
                throw new Exception(Rtn.Message);
            }
            DataSet dsResults = CompressionHelper.ExactDataSet(btResults);

            return DTOHelper<TsSFCUserInfo>.DataTableToList(dsResults.Tables[0]);
        }

        /// <summary>
        /// 电子签名
        /// </summary>
        /// <param name="userConfirm"></param>
        /// <param name="dtData"></param>
        /// <returns></returns>
        public APIResponseData UserConfirm(UserConfirmHistory userConfirm, out DataTable dtData)
        {
            try
            {
                ApiParameters?.Clear();

                dtData = null;
                var Rtn = Utility.SfcBizService.CurrentSvc.UserConfirm(GetParameters(), userConfirm.toDataTable(), out dtData);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }
    }
}
