
using AutoMapper;
using OASystem.Domain;
using OASystem.Domain.Dtos.QiYeWeChat;
using OASystem.Domain.Dtos.System;
using OASystem.Domain.Dtos.UserDto;
using OASystem.Domain.Entities.System;
using OASystem.Domain.ViewModels.System;
using OASystem.Infrastructure.Repositories.System;
using SqlSugar;

namespace OASystem.Infrastructure.Repositories.Login
{
    public class LoginRepository : BaseRepository<Sys_Users, LoginView>
    {

        public LoginRepository(SqlSugarClient sqlSugar, UsersRepository usersRep) : 
            base(sqlSugar){}

        /// <summary>
        /// 用户登录
        /// 返回Token
        /// </summary>
        /// <param name="_loginRep"></param>
        /// <param name="loginDto"></param>
        /// <returns></returns>
        public async Task<Result> Login(LoginDto loginDto)
        {
            Result result = new Result() { Code = -2 };
            string SQLWhere = string.Format("Where Number='{0}' And Isdel = 0", loginDto.Number);
            string sql = string.Format("Select * From Sys_Users With(NoLock) {0}", SQLWhere);
            Sys_Users _entity = await GetSingleInfoBySqlWithNolockAsync(sql);

            if (_entity == null)
            {
                result.Msg = "暂无该账户信息!";
                return result;
            }

            if (!_entity.Password.Equals(loginDto.Password))
            {
                result.Msg = "账户或密码错误!";
                return result;
            }

            //人事审核是否通过
            if (_entity.HrAudit != 1)
            {
                result.Msg = "该员工账号暂无登录权限,人事审核未通过!";
                return result;
            }

            //该用户是否已删除
            if (_entity.HrAudit != 1)
            {
                result.Msg = "已离职员工没有登录权限!";
                return result;
            }

            //portType 处理端口 
            dynamic longinData = null;

            //员工数据
            string sqlWhere = string.Format(" Where su.Id={0}", _entity.Id);
            string userSqlWhere = string.Format(@"Select sc.CompanyName,sd.DepName,sjp.JobName,su.Id UserId,su.CnName,su.Email
                                                  From Sys_Users su 
                                                  Inner Join Sys_Company sc On su.CompanyId = sc.Id
                                                  Inner Join Sys_Department sd On su.DepId = sd.Id
                                                  Inner Join Sys_JobPost sjp On su.JobPostId = sjp.Id {0}", sqlWhere);
           

            if (loginDto.PortType == 1) //web
            {
                var _userBasicInfo = await _sqlSugar.SqlQueryable<UserLoginInfoView>(userSqlWhere).FirstAsync();

                longinData = _userBasicInfo;

            }
            else if (loginDto.PortType == 2) // Android
            {
                var _userBasicInfo = await _sqlSugar.SqlQueryable<UserLoginInfoView>(userSqlWhere).FirstAsync();
                longinData = _userBasicInfo;
            }

            result.Code = 0;
            result.Msg = "登录成功!";
            result.Data = longinData;
            return result;

        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="_loginRep"></param>
        /// <param name="registerDto"></param>
        /// <returns></returns>
        public async Task<Result> Register( RegisterDto registerDto)
        {
            Result result = new Result();

            string IdCrad = registerDto.IdCrad;
            string birthDay = IdCrad.Substring(6, 4) + "-" + IdCrad.Substring(10, 2) + "-" + IdCrad.Substring(12, 2);

            string number = await CreateNumber(registerDto.DepId);

            if (string.IsNullOrEmpty(number))
            {
                result.Code = -2;
                result.Msg = "Number 设置失败,请前往对应部门 备注；里 设置Number前缀!";

                return result;
            }

            Sys_Users _userInfo = new Sys_Users()
            {
                CnName = registerDto.CnName,
                EnName = registerDto.EnName,
                Sex = registerDto.Sex,
                Number = number,    //员工编号 人事审核通过了 由信息部经理分配
                Password = registerDto.Password, //密码由用户自己设置
                CompanyId = registerDto.CompanyId,
                DepId = registerDto.DepId,
                JobPostId = registerDto.JobPostId,
                Ext = "", //由部门主管/信息部经理 分配
                Phone = registerDto.Phone,
                UrgentPhone = registerDto.UrgencyPhone,
                Email = registerDto.Email,
                Address = registerDto.Address,
                Edate = Convert.ToDateTime(registerDto.Edate),  //入职时间默认当前数据提交时间
                Rdate = new DateTime(1990, 1, 1),  //离职时间默认最原始时间
                Seniority = 0, //工龄默认 0
                Birthday = Convert.ToDateTime(birthDay),
                IDCard = registerDto.IdCrad,
                StartWorkDate = "1900-01-01 00:00:00.000",  //开始工作时间默认最原始时间
                GraduateInstitutions = registerDto.GraduationSchhol,
                Professional = registerDto.Major,
                Education = registerDto.Education, //学历类型
                TheOrAdultEducation = registerDto.EducationType, //教育类型
                MaritalStatus = registerDto.MaritalStatus, // 未婚/已婚
                WorkExperience = registerDto.WorkExperience, // 工作经历
                HomeAddress = registerDto.HomeAddress,  //身份证上 家庭住址
                UsePeriod = "", //试用期 由该人员入职部门主管手动操作
                Certificate = "", //证件上传地址  多个证件由 | 隔开
                CreateUserId = registerDto.CreateUserId,
                CreateTime = DateTime.Now, //默认当前时间
                DeleteUserId = null,  //删除用户时操作该字段
                DeleteTime = null,   //删除用户时操作该字段
                Remark = "",         //备注
                IsDel = 0
            };

            var _AddId = await _sqlSugar.Insertable(_userInfo).ExecuteReturnIdentityAsync();
            if (_AddId < 0)
            {
                result.Code = -2;
                result.Msg = "用户添加失败!";

                return result;
            }

            _userInfo.CreateUserId = _AddId;

            var updateStatus = await _sqlSugar.Updateable(_userInfo).UpdateColumns(it => new { it.CreateUserId }).Where(it => it.Id == _AddId).ExecuteCommandAsync();


            result.Code = 0;
            //result.Msg = string.Format("账号：{0}\r\n密码：{1}\r\n申请成功!\r\n人事主管审核后,即可登录OA!", number, registerDto.Password);
            result.Msg = string.Format("账号：{0}\r\n申请成功!\r\n人事主管审核后,即可登录OA!", number);
            return result;
        }
        
        /// <summary>
        /// 生成 Number
        /// </summary>
        /// <param name="depId"></param>
        /// <returns></returns>
        public async Task<string> CreateNumber(int depId) {
            string number = string.Empty;

            string userSql = string.Format("Select * From  Sys_Users Where DepId = {0} And Number != '' Order By Id Desc", depId);
            var userData = await _sqlSugar.SqlQueryable<Sys_Users>(userSql).ToListAsync();
            if (userData.Count <= 0) return number;

            string depSql = string.Format("Select * From  Sys_Department Where IsDel= 0 And Id = {0} ", depId);
            var depData = await _sqlSugar.SqlQueryable<Sys_Department>(depSql).FirstAsync();
            if (depData == null) return number;

            string numPrefix = depData.Remark; 
            if (string.IsNullOrEmpty(numPrefix)) return number;

            int numSuffix = 1;
            while (true) 
            {
                number = numPrefix + numSuffix.ToString();
                var userData1 = userData.Where(it => it.Number == number).FirstOrDefault();
                if (userData1 == null) break;
                numSuffix++;
            }

            return number;
        }
    }
}
