using Ewide.Application.Entity;
using Ewide.Application.Service.HouseProjectInfo.Dto;
using Ewide.Core;
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.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace Ewide.Application.Service.HouseProjectInfo
{
    /// <summary>
    /// 项目管理相关服务
    /// </summary>
    [ApiDescriptionSettings(Name = "HouseProjectInfo", Order = 170)]
    public class HouseProjectInfoService : IHouseProjectInfoService, ITransient, IDynamicApiController
    {
        private readonly IRepository<BsHouseProjectInfo> _houseProjectInfoRep;

        public HouseProjectInfoService(IRepository<BsHouseProjectInfo> houseProjectInfoRep)
        {
            _houseProjectInfoRep = houseProjectInfoRep;
        }

        /// <summary>
        /// 添加项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/houseProjectInfo/add")]
        public async Task AddProject(AddProjectInput input)
        {
            await _houseProjectInfoRep.InsertNowAsync(input.Adapt<BsHouseProjectInfo>());
        }

        /// <summary>
        /// 删除项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/houseProjectInfo/delete")]
        public async Task DeleteProject(DeleteProjectInput input)
        {
            var project = _houseProjectInfoRep.FirstOrDefault(p => p.Id == input.Id);
            await project.DeleteNowAsync();
        }

        /// <summary>
        /// 编辑项目
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/houseProjectInfo/edit")]
        public async Task UpdateProject(UpdateProjectInput input)
        {
            var project = input.Adapt<BsHouseProjectInfo>();
            await project.UpdateExcludeAsync(new[] { nameof(BsHouseProjectInfo.AreaCode) }, true);
        }

        /// <summary>
        /// 通过ID获取项目
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        [HttpGet("/houseProjectInfo/getById")]
        public async Task<BsHouseProjectInfo> GetById([Required] string projectId)
        {
            return await _houseProjectInfoRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == projectId);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/houseProjectInfo/page")]
        public async Task<dynamic> QueryProjectPageList([FromBody] PageProjectInput input)
        {
            var areaCodeRep = Db.GetRepository<SysAreaCode>();
            var projects = await _houseProjectInfoRep.DetachedEntities
                .Join(areaCodeRep.DetachedEntities, p => p.AreaCode, a => a.Code, (p, a) => new { p, AreaName = a.Name })
                .Where(input.Type>0, x => x.p.Type == input.Type)
                .Where(!string.IsNullOrEmpty(input.Name), x => x.p.Name.Contains(input.Name))
                .Where(!string.IsNullOrEmpty(input.Note), x => x.p.Note.Contains(input.Note))
                .Where(!string.IsNullOrEmpty(input.AreaCode), x => x.p.AreaCode == input.AreaCode)
                .Where(!string.IsNullOrEmpty(input.pid) , x=> x.p.AreaCode.Contains(input.pid))
                .Select(x => new { x.p.Id, x.p.Name, x.p.Note, x.p.Sort, x.p.AreaCode, x.AreaName, x.p.Type }.Adapt<HouseProjectOutput>()).ToPagedListAsync(input.PageIndex, input.PageSize);
            return PageDataResult<HouseProjectOutput>.PageResult(projects);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("/houseProjectInfo/detail")]
        public async Task<dynamic> GetProject([FromQuery] QueryProjectInput input)
        {
            var user = await _houseProjectInfoRep.DetachedEntities.FirstOrDefaultAsync(p => p.Id == input.Id);
            var userDto = user.Adapt<UserOutput>();

            return userDto;
        }

        [HttpGet("/houseProjectInfo/nextSort")]
        public async Task<int> GetNextProjectSortByAreaCode([FromQuery] ListHouseProjectInfoInput input)
        {
            //var projects = await _houseProjectInfoRep.DetachedEntities
            //    .Where(p => p.AreaCode == input.AreaCode && p.Type == input.Type)
            //    .Select(p => p.Sort)
            //    .DefaultIfEmpty()
            //    .MaxAsync();
            if (input.Type > 2 || input.Type < 1)
            {
                throw Oops.Oh("类型参数异常");
            }
            var p = await _houseProjectInfoRep.DetachedEntities
                .Where(p => p.AreaCode == input.AreaCode && p.Type == input.Type)
                .MaxAsync(p => (int?)p.Sort);

            return p.GetValueOrDefault(0) + 1;
        }

        /// <summary>
        /// 获取项目下拉列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("houseProjectInfo/list")]
        public async Task<dynamic> GetProjectList([FromQuery] ListHouseProjectInfoInput input)
        {
            return await _houseProjectInfoRep.DetachedEntities
                .Where(p => p.AreaCode == input.AreaCode && p.Type == input.Type)
                .OrderBy(p => p.Sort)
                .ToListAsync();
        }
    }
}
