using BPA.SAAS.Manage.Application.Org.Dtos.Company;
using BPA.SAAS.Manage.Application.Org.Dtos.Role;
using BPA.SAAS.Manage.Application.Org.Dtos.Users;
using BPA.SAAS.Manage.Application.Org.Interface;
using BPA.SAAS.Manage.Comm.Const;
using BPA.SAAS.Manage.Comm.Enum;
using BPA.SAAS.Manage.Core.Base;
using BPA.SAAS.Manage.Core.Org;
using BPA.SAAS.Manage.Core.System;
using Furion.LinqBuilder;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BPA.SAAS.Manage.Application.Org.Services
{
    public class CompanyService: ICompanyService, ITransient
    {
        private readonly ISqlSugarClient _db;
        public CompanyService(ISqlSugarClient db)
        {
            _db = db;
        }
        /// <summary>
        /// 查询企业信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PageUtil> CompanyPage(CompanyDtoPageInput input)
        {
            RefAsync<int> total = 0;
            var data =await _db.Queryable<BPA_Company>()
                       .Where((a) => a.IsDeleted == 0)
                       .WhereIF(!input.Name.IsNullOrEmpty(), (a) => a.Name.Contains(input.Name))
                       .WhereIF(!input.AdminName.IsNullOrEmpty(), (a) => a.AdminName.Contains(input.AdminName))
                       .WhereIF(!input.Email.IsNullOrEmpty(), (a) => a.Email.Contains(input.Email))
                       .Filter(null, true)
                       .Select((a) => new CompanyDtoInput
                       {
                           Id = a.Id.SelectAll(),
                           SysRoleId =SqlFunc.Subqueryable< BPA_Roles>().Where(x=>x.GroupId == a.Id).Select(x => x.Id),
                       })
                       .OrderBy(a => a.CreateAt, OrderByType.Desc)
                       .ToPageListAsync(input.Current, input.PageSize,  total);
        

            PageUtil util = new PageUtil()
            {
                Total = total,
                Data = data

            };
            return util;
        }
        /// <summary>
        /// 添加企业信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> AddCompany(CompanyDtoInput input)
        {
            _db.Ado.BeginTran();
            var company = input.Adapt<BPA_Company>();
            var Companycheck = _db.Queryable<BPA_Company>().Where(x => x.IsDeleted == 0).First(x => x.Email == company.Email);

            if (Companycheck != null)
                throw Oops.Oh($"账号已存在");

            var res =await _db.Insertable(company).CallEntityMethod(t => t.Create()).ExecuteReturnEntityAsync();

            input.Email = input.Email.IsNullOrEmpty() ? input.Phone : input.Email;
            //创建企业，管理员用户，管理员角色
            var adduser = await _db.Insertable(new BPA_Users()
            {
                GroupId = res.Id,
                Account = input.Email,
                AdminType = 2,
                Name = input.Name,
                Password = MD5Encryption.Encrypt("123456").ToLower()
            }).CallEntityMethod(t => t.Create()).ExecuteCommandAsync()>0;

            if (adduser)
            {
                var addrole =await _db.Insertable(new BPA_Roles
                {
                    GroupId = res.Id,
                    Name = input.Name + "管理员",
                    Remark = "系统默认创建管理员角色不允许修改",
                    Code = "sys_manager_role",
                    RoleType=1
                }).CallEntityMethod(t => t.Create()).ExecuteCommandAsync() > 0;
                // 查询用户
                var UserRes = _db.Queryable<BPA_Users>().Filter(null, true).Where(a => a.GroupId == res.Id && a.Account == input.Email).ToList();
                ////查询角色
                var RoleRes = _db.Queryable<BPA_Roles>().Filter(null, true).
                    Where(a => a.GroupId == res.Id && a.Code == "sys_manager_role").ToList();
                if (UserRes.Count() > 0 && RoleRes.Count() > 0)
                {
                    BPA_UserRole userRole = new BPA_UserRole();
                    userRole.Id= Guid.NewGuid().ToString();
                    userRole.SysUserId = UserRes.First().Id;
                    userRole.SysRoleId = RoleRes.First().Id;
                    _db.Insertable(userRole).ExecuteReturnEntity();
                }
                _db.Ado.CommitTran();
            }
            else
            {
                _db.Ado.RollbackTran();
                //_db.Deleteable(res).ExecuteCommand();
                return false;
            }

            return true;
        }
        /// <summary>
        /// 修改企业信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<bool> UpdateCompany(CompanyDtoInput input)
        {
            var company = input.Adapt<BPA_Company>();
            company.CreateAt= DateTime.Now;
            var check = _db.Queryable<BPA_Company>().Where(x => x.IsDeleted == 0).First(t => t.Id == company.Id);

            if (check == null)
                return false;
            if (check.Email != input.Email)
                return false;
            return await _db.Updateable(company).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandHasChangeAsync();

        }
        /// <summary>
        /// 删除企业信息
        /// </summary>
        /// <param name="inputList"></param>
        /// <returns></returns>
        public async Task<bool> BatchDelCompany(List<string> inputList)
        {
            try
            {
                _db.Ado.BeginTran();
                // 查询数据库中是否存在未删除的活动信息
                var resEntitites = _db.Queryable<BPA_Company>().In(inputList).ToList();
                resEntitites.ForEach(x =>
                {
                    x.IsDeleted = 1;
                });
                //删除加盟商下面的角色和用户以及相关的菜单权限
                var Roles=_db.Queryable<BPA_Roles>().Where(x=> inputList.Contains(x.GroupId)).ToList();
                var Roleids= Roles.Select(x=>x.Id).ToList();    
                var Users = _db.Queryable<BPA_Users>().Where(x => inputList.Contains(x.GroupId)).ToList();
                var Usersids = Users.Select(x => x.Id).ToList();
                var UserRole=_db.Queryable<BPA_UserRole>().Where(x => Usersids.Contains(x.SysUserId)).ToList();
                var RoleMenu = _db.Queryable<BPA_RoleMenu>().Where(x => Roleids.Contains(x.SysRoleId)).ToList();
                await _db.Deleteable(Roles).ExecuteCommandAsync();
                await _db.Deleteable(Users).ExecuteCommandAsync();
                await _db.Deleteable(UserRole).ExecuteCommandAsync();
                await _db.Deleteable(RoleMenu).ExecuteCommandAsync();
                var res = await _db.Updateable(resEntitites).ExecuteCommandAsync();
                _db.Ado.CommitTran();
                return true;
            }
            catch (Exception)
            {
                _db.Ado.RollbackTran();
                return false;
            }
        }
        /// <summary>
        /// 启用
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> Enable(string Id)
        {
            var resEntitites = _db.Queryable<BPA_Company>().In(Id).ToList();
            resEntitites.ForEach(x =>
            {
                x.Status = CommonStatus.ENABLE;
            });
            var res =await _db.Updateable(resEntitites).ExecuteCommandAsync();
            return true;
        }
        /// <summary>
        /// 禁用
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> Disable(string Id)
        {
            var resEntitites = _db.Queryable<BPA_Company>().In(Id).ToList();
            resEntitites.ForEach(x =>
            {
                x.Status = CommonStatus.DISABLE;
            });
            var res =await _db.Updateable(resEntitites).ExecuteCommandAsync();
            return true;
        }
    }
}
