using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Mvc;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using SqlSugar;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using Waste.Domain;

namespace Waste.Application
{
    /// <summary>
    /// 系统管理
    /// </summary>
    public class SystemService : ISystemService, IDynamicApiController, ITransient
    {
        private readonly ISqlSugarRepository<W_Menu> repository;
        private readonly SqlSugarClient dbClient;
        public SystemService(ISqlSugarRepository<W_Menu> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [QueryParameters]
        public async Task<ResultInfo> DeleteMenuAsync(Guid id)
        {
            if (!await dbClient.Queryable<W_Menu>().AnyAsync(x => x.Id == id))
            {
                return new ResultInfo() { code = ResultState.FAIL, message = "此菜单未找到!" };
            }
            await dbClient.Deleteable<W_Menu>().Where(x => x.Id == id).ExecuteCommandAsync();
            await dbClient.Deleteable<W_Menu>().Where(x => x.ParentId == id).ExecuteCommandAsync();
            return new ResultInfo() { code = ResultState.SUCCESS, message = "删除成功!" };
        }
        /// <summary>
        /// 获取菜单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<W_Menu> MenuDetailAsync(Guid id)
        {
            return await dbClient.Queryable<W_Menu>().FirstAsync(x => x.Id == id);
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<W_Menu>> GetMenuListAsync(Guid roleid)
        {
            var data = new List<W_Menu>();
            var tempquery = dbClient.Queryable<W_Menu, W_RoleAuthorize>(
                (m, ra) => new object[] {
                            JoinType.Left,m.Id==ra.MenuId
                })
                .Where((m, ra) => ra.RoleId == roleid && m.Status == 1)
                ;
            data = await tempquery
                .OrderBy((m,ra)=>m.SortCode,OrderByType.Asc)
                .ToListAsync();
            return data;
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<W_Menu>> GetMenuListAsync()
        {
            var modulequery = dbClient.Queryable<W_Menu>();
            return await modulequery.OrderBy(x => x.SortCode, OrderByType.Asc).ToListAsync();
        }
        /// <summary>
        /// 菜单编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultInfo> SubmitFormMenuAsync(W_Menu model)
        {
            if (model.Id == Guid.Empty)
            {
                model.CreateTime = DateTime.Now;
                model.Status = 1;
                model.Id = IDGen.NextID();
                await dbClient.Insertable<W_Menu>(model).ExecuteCommandAsync();
                return new ResultInfo() { code = ResultState.SUCCESS, message = "添加成功!" };
            }
            else
            {
                await dbClient.Updateable<W_Menu>().SetColumns(x => new W_Menu
                {
                    ParentId = model.ParentId,
                    Icon = model.Icon,
                    SortCode = model.SortCode,
                    UrlAddress = model.UrlAddress,
                    Name = model.Name
                })
                 .Where(x => x.Id == model.Id)
                     .ExecuteCommandAsync();
                return new ResultInfo() { code = ResultState.SUCCESS, message = "修改成功!" };
            }
        }

        /// <summary>
        /// 获取菜单树形结构
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetMenuTreeJson(QueryParams param)
        {
            //获取菜单json树列表
            var tempquery = dbClient.Queryable<W_Menu>();
            if (param != null
                 && param.queryParam != null
                 && param.queryParam.Count > 0)
            {
                List<IConditionalModel> conModels = new List<IConditionalModel>();
                param.queryParam.ForEach(x =>
                {
                    if (!string.IsNullOrEmpty(x.Value))
                    {
                        conModels.Add(new ConditionalModel()
                        {
                            FieldName = x.Name,
                            ConditionalType = (ConditionalType)x.Type,
                            FieldValue = x.Value.Trim()
                        });
                    }
                });
                if (conModels.Count > 0)
                {
                    tempquery = tempquery.Where(conModels);
                }
            }
            var data = await tempquery.OrderBy(x => x.SortCode, OrderByType.Asc).ToListAsync();
            var treeList = new List<TreeSelectModel>();
            foreach (var item in data)
            {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.Id + "";
                treeModel.text = item.Name;
                treeModel.parentId = item.ParentId + "";
                treeModel.data = item;
                treeList.Add(treeModel);
            }
            var result = treeList.TreeSelectGuidJson();
            return result;
        }
        /// <summary>
        /// 获取城市列表
        /// </summary>
        /// <param name="code">国标码</param>
        /// <param name="level">级别</param>
        /// <returns></returns>
        [QueryParameters]
        public async Task<List<W_AreaInfo>> GetCityListAsync(string code = "", int level = 1)
        {
            var tempquery = repository.Change<W_AreaInfo>().Context.Queryable<W_AreaInfo>();
            if (!string.IsNullOrEmpty(code) && code != "0")
            {
                var data = await dbClient.Queryable<W_AreaInfo>().FirstAsync(x => x.code == code);
                if (data != null)
                {
                    tempquery = tempquery.Where(x => x.pid == data.Id);
                }
            }
            else
            {
                tempquery = tempquery.Where(x => x.level == 1);
            }
            return await tempquery.ToListAsync();
        }
        /// <summary>
        /// 获取城市列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<CityListModel>> GetListAsync()
        {
            var tempquery = repository.Change<W_AreaInfo>().Context.Queryable<W_AreaInfo>().Where(x => x.level == 1);
            var query = await tempquery
               .Select(x => new CityListModel
               {
                   Id = x.Id,
                   name = x.name,
                   level = x.level,
                   code = x.code
               })
               .Mapper((it, cache) =>
               {
                   var allcity = cache.Get(list =>
                   {
                       var ids = list.Select(e => e.Id).ToList();
                       return repository.Change<W_AreaInfo>().Context.Queryable<W_AreaInfo>().Where(e => ids.Contains(e.pid)).ToList();
                   });
                   it.children = allcity.Where(e => e.pid == it.Id).ToList();
               }).ToListAsync();
            return query;
        }
    }
}