using Ewide.Application.Entity;
using Ewide.Core;
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.Threading.Tasks;
using Dapper;
using Ewide.Core.Extension;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Collections.Generic;

namespace Ewide.Application.Service.HouseCode
{
    /// <summary>
    /// 房屋编码相关
    /// </summary>
    [ApiDescriptionSettings(Name = "HouseCode", Order = 180)]
    public class HouseCodeService : IHouseCodeService, IDynamicApiController, ITransient
    {
        private readonly IRepository<BsHouseCode> _houseCodeRep;
        private readonly IDapperRepository _dapperRepository;

        private readonly IUserManager _userManager;
        private readonly IHouseLogService _houseLogService;

        public HouseCodeService(IRepository<BsHouseCode> HouseCodeRep, IDapperRepository dapperRepository, IUserManager userManager, IHouseLogService houseLogService)
        {
            _houseCodeRep = HouseCodeRep;
            _dapperRepository = dapperRepository;

            _userManager = userManager;
            _houseLogService = houseLogService;
        }

        [HttpPost("/houseCode/add")]
        [UnitOfWork]
        public async Task AddHouseCode(AddHouseCodeInput input)
        {
            var houseProjectInfoRep = Db.GetRepository<BsHouseProjectInfo>();
            var houseProject = await houseProjectInfoRep.FirstOrDefaultAsync(p => p.Id == input.ProjectId);
            if (houseProject == null) throw Oops.Oh("项目参数有误，添加失败");

            var areaCodeRep = Db.GetRepository<SysAreaCode>();
            var areaCode = await areaCodeRep.DetachedEntities.FirstOrDefaultAsync(a => a.Code == input.AreaCode && a.LevelType == 4);
            if(areaCode == null) throw Oops.Oh("区域编码有误，添加失败");
            input.HouseCode = areaCode.AdCode + houseProject.Sort.ToString().PadLeft(3, '0') + input.No.ToString().PadLeft(3, '0');
            var id = System.Guid.NewGuid().ToString().ToLower();
            var houseCode = input.Adapt<BsHouseCode>();
            houseCode.Id = id;
            var isExist = await _houseCodeRep.AnyAsync(p => p.HouseCode == houseCode.HouseCode);
            if (isExist) throw Oops.Oh("房屋编码已存在，不可重复添加");
            await houseCode.InsertAsync();

            // 添加到流转日志
            var sort = await _houseLogService.AddThenDone(id, _userManager.User, HouseLogType.CreateCode);
            sort = await _houseLogService.Add(id, _userManager.User, HouseLogType.SelectMember, sort: sort);
        }

        [HttpPost("/houseCode/edit")]
        public async Task EditHouseCode(EditHouseCodeInput input)
        {
            var houseCode = input.Adapt<BsHouseCode>();
            await houseCode.UpdateExcludeAsync(new[] { nameof(BsHouseCode.HouseCode) }, true);
        }

        [HttpPost("/houseCode/delete")]
        public async Task DeleteHouseCode(DeleteHouseCodeInput input)
        {
            var houseCode = _houseCodeRep.FirstOrDefault(p => p.Id == input.Id);
            await houseCode.DeleteNowAsync();
        }

        [HttpPost("/houseCode/page")]
        public async Task<dynamic> QueryPage([FromBody] QueryHouseCodeInput input)
        {
            var sql = @"SELECT 
HC.*,AA.Name AreaName,RA.Name RoadName,CA.Name CommName,Proj.AreaCode,Proj.Note,CONCAT(Proj.`Name`, IFNULL(CONCAT('(',Proj.Note,')'), '')) FullProjName 
FROM bs_house_code HC
LEFT JOIN bs_house_projectinfo Proj ON Proj.Id=HC.ProjectId
LEFT JOIN sys_area_code CA ON CA.Code = Proj.AreaCode
LEFT JOIN sys_area_code RA ON RA.AdCode = SUBSTR(CA.AdCode,1,9)
LEFT JOIN sys_area_code AA ON AA.AdCode = SUBSTR(CA.AdCode,1,6) ";
            return await _dapperRepository.QueryPageDataDynamic(sql, input, filterFields: new string[] {"Type", "Address", "HouseCode","AreaCode"});
        }

        [HttpGet("/houseCode/detail")]
        public async Task<dynamic> GetHouserCode([FromQuery] GetHouseCodeInput input)
        {
            var houseCode = await _houseCodeRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == input.Id);
            var areaCode = (await Db.GetRepository<BsHouseProjectInfo>().DetachedEntities.FirstOrDefaultAsync(p => p.Id == houseCode.ProjectId)).AreaCode;
            var result = houseCode.Adapt<GetHouseCodeOutput>();
            result.AreaCode = areaCode;
            return result;
        }

        /// <summary>
        /// 获取同一区域下的下一个编号
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("/houseCode/getNextNoByCode")]
        public async Task<dynamic> GetNextNoByFullNumber([Required] string projectId)
        {
            var areaCodeRep = Db.GetRepository<SysAreaCode>();
            var houseProjectInfoRep = Db.GetRepository<BsHouseProjectInfo>();
            var houseProject = await houseProjectInfoRep.FirstOrDefaultAsync(p => p.Id == projectId);
            if(houseProject == null) throw Oops.Oh("项目参数有误，房屋编码生成失败");
            //取到社区编码
            var commAreaCode = await areaCodeRep.FirstOrDefaultAsync(a => a.Code == houseProject.AreaCode && a.LevelType == 4);
            if(commAreaCode == null) throw Oops.Oh("项目区域编码有误，房屋编码生成失败");
            var maxNo = await _houseCodeRep.DetachedEntities
                .Where(h => h.HouseCode.Contains(commAreaCode.AdCode + houseProject.Sort.ToString().PadLeft(3, '0')))
                .MaxAsync(h => (int?)h.No);
            return maxNo.GetValueOrDefault(0) + 1;
        }
    }
}
