using NFine.Code;
using NFine.Domain.Entity.SystemManage;
using NFine.Domain.IRepository.SystemManage;
using NFine.Repository.SystemManage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.Common;
using System.Text;
using NFine.Data.Extensions;

namespace NFine.Application.SystemManage
{
    public class UserApp
    {
        private IUserRepository service = new UserRepository();
        private UserLogOnApp userLogOnApp = new UserLogOnApp();

        public List<UserEntity> GetList()
        {
            return service.IQueryable().OrderBy(t => t.F_CreatorTime).ToList();
        }

        public List<UserEntity> GetList(Pagination pagination, string keyword)
        {
            var expression = ExtLinq.True<UserEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                expression = expression.And(t => t.F_Account.Contains(keyword));
                expression = expression.Or(t => t.F_RealName.Contains(keyword));
                expression = expression.Or(t => t.F_MobilePhone.Contains(keyword));
            }
          
            expression = expression.And(t => t.F_Account != "admin");
            if (NFine.Code.OperatorProvider.Provider.GetCurrent().RoleEnCode == "Vendor")
            {
                string UserCode = NFine.Code.OperatorProvider.Provider.GetCurrent().UserCode;
                expression = expression.And(t => t.F_Account== UserCode);
            }
            return service.FindList(expression, pagination);
        }

        public UserEntity GetForm(string keyValue)
        {
            if (keyValue == "SYS")
                keyValue = NFine.Code.OperatorProvider.Provider.GetCurrent().UserId;
            return service.FindEntity(keyValue);
        }

        public void DeleteForm(string keyValue)
        {
            service.DeleteForm(keyValue);
        }

        public void SubmitForm(UserEntity userEntity, UserLogOnEntity userLogOnEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                userEntity.Modify(keyValue);
            }
            else
            {
                userEntity.Create();
            }
            service.SubmitForm(userEntity, userLogOnEntity, keyValue);
        }

        public void UpdateForm(UserEntity userEntity)
        {
            service.Update(userEntity);
        }

        public UserEntity CheckLogin(string username, string password, string WorkPoint)
        {
            UserEntity userEntity = service.FindEntity(t => t.F_Account == username && t.F_Location== WorkPoint);
            if (userEntity != null)
            {
                if (userEntity.F_EnabledMark == true)
                {
                    UserLogOnEntity userLogOnEntity = userLogOnApp.GetForm(userEntity.F_Id);
                    string dbPassword = Md5.md5(DESEncrypt.Encrypt(password.ToLower(), userLogOnEntity.F_UserSecretkey).ToLower(), 32).ToLower();
                    if (dbPassword == userLogOnEntity.F_UserPassword)
                    {
                        DateTime lastVisitTime = DateTime.Now;
                        int LogOnCount = (userLogOnEntity.F_LogOnCount).ToInt() + 1;
                        if (userLogOnEntity.F_LastVisitTime != null)
                        {
                            userLogOnEntity.F_PreviousVisitTime = userLogOnEntity.F_LastVisitTime.ToDate();
                        }
                        userLogOnEntity.F_LastVisitTime = lastVisitTime;
                        userLogOnEntity.F_LogOnCount = LogOnCount;
                        userLogOnApp.UpdateForm(userLogOnEntity);
                        return userEntity;
                    }
                    else
                    {
                         throw new Exception("密码不正确,请重新输入");
                    }
                }
                else
                {
                    throw new Exception("账户被系统锁定,请联系管理员");
                }
            }
            else
            {
                throw new Exception("账户不存在,请重新输入");
            }
        }

        public void AgentUserAndVenCode()
        {
            string sql = @"SELECT UserCode,UserName,WorkPointCode FROM dbo.Sys_User
                           WHERE UserCode NOT IN (SELECT F_Account FROM dbo.Sys_SRM_User)";
            DataTable dtUser = SqlHelper.GetDataTableBySql(sql);
            foreach (DataRow dr in dtUser.Rows)
            {
                string sqlUser = string.Empty;
                string NewGuid = Common.GuId();
                sqlUser = @"INSERT INTO dbo.Sys_SRM_User
                                    ( F_Id ,F_Account ,F_RealName ,F_NickName ,
                                      F_RoleId ,F_IsAdministrator , F_EnabledMark ,
                                      F_CreatorTime ,F_CreatorUserId ,F_Location ,
                                      F_VenCode)
                            SELECT '"+ NewGuid + @"',UserCode,UserName,UserName,
                            		'5130ce87-a5ed-409f-b035-9277f65e1d7f',0,1,
                            		GETDATE(),'9f2ec079-7d0f-4fe2-90ab-8b09a8302aba','"+dr["WorkPointCode"].ToString() +@"',''
                            FROM dbo.Sys_User WHERE UserCode='"+dr["UserCode"].ToString()+ "' and WorkPointCode='" + dr["WorkPointCode"].ToString() + @"'";
                try
                {
                    SqlHelper.ExecuteNonQuery(sqlUser);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                string UserSecretkey = Md5.md5(Common.CreateNo(), 16).ToLower();
                string pwd = Md5.md5(DESEncrypt.Encrypt(Md5.md5("123456", 32).ToLower(), UserSecretkey).ToLower(), 32).ToLower();
                sqlUser = @"INSERT INTO dbo.Sys_SRM_UserLogOn
                                    ( F_Id ,F_UserId ,F_UserPassword ,F_UserSecretkey 
                                    )
                            VALUES  ( '" + NewGuid + @"','" + NewGuid + @"','"+ pwd + "','" + UserSecretkey + "')";
                try
                {
                    SqlHelper.ExecuteNonQuery(sqlUser);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }

            }
           
        }

    }
}