using MathNet.Numerics.Distributions;
using NPOI.POIFS.Crypt.Dsig;
using NPOI.SS.Formula.Functions;
using OASystem.Domain;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.System;
using OASystem.Domain.ViewModels.QiYeWeChat;

namespace OASystem.Infrastructure.Repositories.System
{
    public class CompanyRepository : BaseRepository<Sys_Company, CompanyView>
    {
        public CompanyRepository(SqlSugarClient sqlSugar) : base(sqlSugar)
        {

        }

        public async  Task<Result> AddCompany(Sys_Company company)
        {
            Result result = new Result() { Code = -2, Msg = "未知错误" };
            try
            {
                BeginTran();
                Sys_Company Company = _sqlSugar.Queryable<Sys_Company>().First(a => a.CompanyName == company.CompanyName && a.IsDel == 0);
                if (Company != null)
                {
                    return result = new Result() { Code = -1, Msg = "该公司已存在，请勿重复添加！"};
                }
                else
                {
                    int CompanyId = 0;
                    int DepartmentId = 0;
                    int JobPostId = 0;
                    int UsersId = 0;
                    CompanyId = await AddAsyncReturnId(company);
                    if (CompanyId > 0)
                    {
                        #region 添加默认部门
                        Sys_Department _Department = new Sys_Department();
                        _Department.CompanyId = CompanyId;
                        _Department.DepName = "默认部门";
                        _Department.DepCode = "00";
                        _Department.ParentDepId = 0;
                        _Department.CreateUserId = company.CreateUserId;
                        _Department.Remark = "添加公司时默认生成部门，可修改！";
                        _Department.IsDel = 0;
                        DepartmentId = await _sqlSugar.Insertable(_Department).ExecuteReturnIdentityAsync();
                        #endregion

                        if (DepartmentId>0)
                        {
                            #region 添加默认岗位
                            Sys_JobPost _JobPost = new Sys_JobPost();
                            _JobPost.CompanyId = CompanyId;
                            _JobPost.DepId = DepartmentId;
                            _JobPost.JobName = "默认岗位";
                            _JobPost.CreateUserId = company.CreateUserId;
                            _JobPost.Remark = "添加公司时默认生成岗位，可修改！";
                            _JobPost.IsDel = 0;
                            JobPostId = await _sqlSugar.Insertable(_JobPost).ExecuteReturnIdentityAsync();
                            #endregion
                            if (JobPostId>0)
                            {
                                #region 添加默认管理员
                                Sys_Users _Users = new Sys_Users();
                                _Users.CnName = "管理员";
                                _Users.EnName = "Guan LiYuan";
                                _Users.Number = CompanyId.ToString() + DepartmentId.ToString() + JobPostId.ToString()+"01";
                                _Users.CompanyId = CompanyId;
                                _Users.DepId = DepartmentId;
                                _Users.JobPostId = JobPostId;
                                _Users.Password = "123456";
                                _Users.Sex = 0;
                                _Users.HrAudit = 1;
                                _Users.CreateUserId = company.CreateUserId;
                                _Users.Remark = "添加公司时默认生成管理员，Number可修改！";
                                _Users.IsDel = 0;
                                UsersId = await _sqlSugar.Insertable(_Users).ExecuteReturnIdentityAsync();
                                if (UsersId>0)
                                {
                                    List<int> fid = new List<int>();//功能权限
                                    List<int> SmId=new List<int>();//页面权限
                                    List<Sys_UserAuthority> adds = new List<Sys_UserAuthority>();
                                    List<Sys_PageFunctionPermission> sys_PageFunctionPermissions = _sqlSugar.Queryable<Sys_PageFunctionPermission>().Where(a=>a.IsDel==0).ToList();
                                    
                                    foreach (var item in sys_PageFunctionPermissions)
                                    {
                                        fid.Add(item.Id);
                                    }
                                    List<Sys_SystemMenuPermission> _SystemMenuPermissions = _sqlSugar.Queryable<Sys_SystemMenuPermission>().Where(a => a.IsDel == 0 && (a.Mid==12 || a.Mid==13 || a.Mid==17) &&
                                    a.WebUrl!="Null" && a.WebUrl!="/" && a.IsEnable==1).ToList();
                                    foreach(var item in _SystemMenuPermissions)
                                    {
                                        SmId.Add(item.Id);
                                    }

                                    for (int i = 0;i< SmId.Count; i++)
                                    {
                                        for (int j = 0; j < fid.Count; j++)
                                        {
                                            adds.Add(new Sys_UserAuthority
                                            {
                                                CreateTime = DateTime.Now,
                                                CreateUserId = company.CreateUserId,
                                                FId = fid[j],
                                                UId = UsersId,
                                                SmId = SmId[i],
                                                IsTemp = 0
                                            });
                                        }
                                    }
                                    _sqlSugar.Insertable<Sys_UserAuthority>(adds).ExecuteCommand();

                                }
                                else
                                {
                                    RollbackTran();
                                    result = new Result() { Code = 0, Msg = "默认管理员添加失败！" };
                                }
                                #endregion
                            }
                            else
                            {
                                RollbackTran();
                                result = new Result() { Code = 0, Msg = "默认岗位添加失败！" };
                            }
                        }
                        else
                        {
                            RollbackTran();
                            result = new Result() { Code = 0, Msg = "默认部门添加失败！" };
                        }
                        CommitTran();
                        var data = new
                        {
                            Number = CompanyId.ToString() + DepartmentId.ToString() + JobPostId.ToString() + "01",
                            Password = "123456",
                        };
                        result = new Result() { Code = 0, Msg = "添加成功！可通过Number和密码登录进去管理！初始密码为：123456", };
                    }
                    else
                    {
                        result = new Result() { Code = -1, Msg = "添加失败！请稍后重试！" };
                    }
                }
            }
            catch (Exception ex)
            {
                return result = new Result() { Code = -2, Msg = "未知错误" };
            }
            return result;
        }

        
        /// <summary>
        /// 获取所有公司数据
        /// </summary>
        /// <param name="_CompanyRepository"></param>
        /// <returns></returns>
        public Result GetCompanyData()
        {
            Result result = new Result();

            string sql = "select * from Sys_Company where isdel = 0";
            var DBdata =  GetListBySqlWithNolock(sql);
            if (DBdata == null || DBdata.Count == 0)
            {
                result.Code = -1;
                result.Msg = "暂无数据！";
                return result;
            }

            result.Code = 0;
            result.Msg = "成功！";
            result.Data = DBdata;
            return result;
        }


        /// <summary>
        /// 获取公司名称数据
        /// </summary>
        /// <param name="_CompanyRepository"></param>
        /// <returns></returns>
        public async Task<Result> GetCompanyNameData()
        {
            Result result = new Result();

            string sql = "Select Id,CompanyName From Sys_Company Where IsDel = 0";

            var companyNameData = await _sqlSugar.SqlQueryable<CompanyNameView>(sql).ToListAsync();

            if (companyNameData == null || companyNameData.Count == 0)
            {
                result.Code = -1;
                result.Msg = "暂无数据！";
                return result;
            }

            result.Code = 0;
            result.Msg = "成功！";
            result.Data = companyNameData;
            return result;
        }

    }
}
