using Ewide.Core;
using Ewide.Core.Extension;
using Ewide.Core.Service;
using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Ewide.Application.Service
{
    /// <summary>
    /// 片区相关
    /// </summary>
    [ApiDescriptionSettings(Name = "HouseZone", Order = 180)]
    public class HouseZoneService : IHouseZoneService, IDynamicApiController, ITransient
    {
        private readonly IUserManager _userManager;
        private readonly IRepository<SysOrg> _sysOrgRep;
        private readonly IRepository<SysEmp> _sysEmpRep;
        private readonly ISysOrgService _sysOrgService;

        public HouseZoneService(
            IUserManager userManager,
            IRepository<SysOrg> sysOrgRep,
            IRepository<SysEmp> sysEmpRep,
            ISysOrgService sysOrgService
        )
        {
            _userManager = userManager;
            _sysOrgRep = sysOrgRep;
            _sysEmpRep = sysEmpRep;
            _sysOrgService = sysOrgService;
        }

        /// <summary>
        /// 获取片区列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("/houseZone/list")]
        public async Task<dynamic> GetHouseZoneList([FromQuery] HouseZoneInput input)
        {
            var areaCode = input.AreaCode.Substring(0, 9);
            var road = await _sysOrgRep.DetachedEntities.FirstOrDefaultAsync(p => p.AreaCode == areaCode);
            if (road == null) throw Oops.Oh("未在组织机构中配置街道");
            return await _sysOrgRep.DetachedEntities
                .Where(p => p.Pid == road.Id)
                .Where(p => p.Type == (int)OrgType.片区)
                .OrderBy(p => p.Sort)
                .Select(p => new
                {
                    p.Id,
                    p.Name
                })
                .ToListAsync();
        }

        [HttpGet("/houseZone/getById")]
        public async Task<dynamic> GetById([Required] string zoneId)
        {
            return await _sysOrgRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == zoneId);
        }

        /// <summary>
        /// 分页查询片区
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/houseZone/page")]
        public async Task<dynamic> QueryZonePageList([FromBody] PageOrgInput input)
        {
            var dataScopeList = _sysOrgService.GetDataScopeList(await _userManager.GetUserAllDataScopeList());

            var name = !string.IsNullOrEmpty(input.Name?.Trim());
            var id = !string.IsNullOrEmpty(input.Id?.Trim());
            var pId = !string.IsNullOrEmpty(input.Pid?.Trim());
            var orgs = await _sysOrgRep.DetachedEntities
                                       .Where((name, u => EF.Functions.Like(u.Name, $"%{input.Name.Trim()}%")), // 根据机构名称模糊查询
                                              (id, u => u.Id == input.Id.Trim()), // 根据机构id查询
                                              (pId, u => EF.Functions.Like(u.Pids, $"%[{input.Pid.Trim()}]%")
                                                         || u.Id == input.Pid.Trim())) // 根据父机构id查询
                                       .Where(dataScopeList.Count > 0, u => dataScopeList.Contains(u.Id)) // 非管理员范围限制
                                       .Where(u => u.Status != CommonStatus.DELETED)
                                       .Where(u => u.Type == (int)OrgType.片区)
                                       .OrderBy(u => u.Sort)
                                       .ToPageData<SysOrg, OrgOutput>(input);
            return PageDataResult<OrgOutput>.PageResult(orgs);
        }

        /// <summary>
        /// 根据用户Id获取所在片区的Id
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet("/houseZone/getByUser")]
        public async Task<string> GetZoneByUser([FromQuery][Required(ErrorMessage = "用户Id不能为空")] string userId)
        {
            var data = await _sysEmpRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == userId);
            if(data == null) throw Oops.Oh("用户不在组织机构中");
            var org = await _sysOrgRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == data.OrgId && p.Type == (int)OrgType.片区);
            if(org == null) throw Oops.Oh("用户不在片区中");
            return org.Id;
        }

        [HttpGet("/houseZone/autoIncrement")]
        public async Task<dynamic> AutoIncrement([FromQuery] string roadId)
        {
            var road = await _sysOrgRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == roadId && p.Type == 3);
            if (road == null) throw Oops.Oh("组织机构错误");
            return await AutoIncrement(road);
        }

        [NonAction]
        public async Task<dynamic> AutoIncrement(SysOrg road)
        {
            var maxZone = (await _sysOrgRep.DetachedEntities.Where(p => p.Pid == road.Id && p.Type == (int)OrgType.片区).MaxAsync(p => p.Code)) ?? "000";
            return Convert.ToInt32(maxZone[^3..]) + 1;
        }

        [HttpPost("/houseZone/add")]
        public async Task AddZone(AddHouseZoneInput input)
        {
            /*
             * 区县市限定所属区域/上级机构是否为当前区
             * 街道自动获取所属区域/上级机构
             * 自动生成唯一编码, 街道Code+三位编号
             * 
             * 机构类型默认为片区
             */

            var org = await _userManager.GetUserOrgInfo();

            var areaManager = Enum.GetName(HouseManagerRole.AreaManager).ToUnderScoreCase();
            var roadManager = Enum.GetName(HouseManagerRole.RoadManager).ToUnderScoreCase();
            var roles = await _userManager.GetUserRoleList();
            if (roles.Any(p => p.Code == areaManager))
            {
                var road = await _sysOrgRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == input.Pid);
                if (!road.Pids.Contains(org.Id)) throw Oops.Oh("当前用户组织机构错误");

                input.AreaCode = road.AreaCode;
                input.Code = road.Code + (await AutoIncrement(road)).ToString().PadLeft(3, '0');
            }
            else if (roles.Any(p => p.Code == roadManager))
            {
                input.AreaCode = org.AreaCode;

                input.Code = org.Code + (await AutoIncrement(org)).ToString().PadLeft(3, '0');
            }

            input.Type = (int)OrgType.片区;

            AddOrgInput addOrgInput = input.Adapt<AddOrgInput>();
            await _sysOrgService.AddOrg(addOrgInput);
        }

        [HttpPost("/houseZone/edit")]
        public async Task EditZone(UpdateHouseZoneInput input)
        {
            var zone = await _sysOrgRep.DetachedEntities.FirstOrDefaultAsync(z => z.Id == input.Id);
            if(zone == null) throw Oops.Oh("修改失败：数据有误，刷新列表后再尝试修改");
            zone.Remark = input.Remark;
            await zone.UpdateIncludeAsync(new[] { nameof(SysOrg.Remark) }, true);
        }
    }
}
