using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Common.Data;
using Mall.Common.Plugin;
using Mall.Model.Extend.BaseSetUp;
using Mall.Module.BaseSetUp;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace Mall.WebApi.Controllers.MallBase
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class DestinationController : BaseController
    {

        /// <summary>
        /// 地区模块处理类
        /// </summary>
        private DestinationModule destinationModule = new DestinationModule();

        /// <summary>
        /// 根据父节点编号获取子列表
        /// </summary>
        /// <param name="ParentID">父节点编号</param>
        /// <returns></returns>
        public ApiResult GetChildList()
        {
            JObject parm = JObject.Parse(RequestParm.msg.ToString());
            int ID = parm.GetInt("Id");
            if (ID > 0)
            {
                var CommonList = Mall.Common.Data.AreaDataHelper.GetAreaList();
                if (CommonList != null && CommonList.Count > 0)
                {
                    return ApiResult.Success("", CommonList.Where(qitem => qitem.P == ID).Select(qitem => new { ID = qitem.I, Name = qitem.N }));
                }
                var list = destinationModule.GetChildList(ID).Select(item => new { item.ID, item.Name });
                return ApiResult.Success("", list);
            }
            else
            {
                return ApiResult.Failed("未找到相关数据!");
            }
        }


        [HttpPost]
        public ApiResult GetAllList()
        {
            JObject parm = JObject.Parse(RequestParm.msg.ToString());
            var list = destinationModule.GetAllList();

            var result = GetData(list);

            return ApiResult.Success("", result);

        }



        public static List<RB_Destination_Extend> GetData(List<RB_Destination_Extend> nodeList)
        {
            List<RB_Destination_Extend> nodes = nodeList.Where(x => x.ParentID == 2).ToList();
            foreach (RB_Destination_Extend item in nodes)
            {
                item.Children = GetChildrens(nodeList, item);
            }
            return nodes;
        }
        //递归获取子节点
        public static List<RB_Destination_Extend> GetChildrens(List<RB_Destination_Extend> nodeList, RB_Destination_Extend node)
        {
            List<RB_Destination_Extend> childrens = nodeList.Where(x => x.ParentID == node.ID).ToList();
            foreach (RB_Destination_Extend item in childrens)
            {
                item.Children = GetChildrens(nodeList, item);
            }
            return childrens;
        }


    }
}