using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GxPress.Entity;
using SqlKata;

namespace GxPress.Service.Implement.Department
{
    public partial class DepartmentService
    {
        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeleteAsync(int id)
        {
            var departments = new List<Entity.Department>();
            var department = await _departmentRepository.GetAsync(id);
            departments.Add(department);
            //获取下级部门
            departments = await _departmentRepository.GetDepartmentById(id, departments);
            foreach (var item in departments)
            {
                var users = await _userRepository.GetUserByDepartmentIdAsync(item.Id);
                var enumerable = users as User[] ?? users.ToArray();
                if (enumerable.Any())
                {
                    await _userService.DeleteUsersAsync(enumerable.Select(n => n.Id));
                }
            }
            //删除部门
            Query q = new Query();
            q.WhereIn(nameof(department.Id), departments.Select(n => n.Id));
            return await _departmentRepository.DeleteAsync(q);
            //return true;
        }
    }
}
