using System.Collections.Generic;
using System.Linq;
using PageAdmin.Common;using PageAdmin.Utils.ORM;using PageAdmin.Utils;
using PageAdmin.Web.Filter;
using PageAdmin.BLL;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.E.Controllers
{
    public class ColumnController : BaseController
    {
        private string _Table = "pa_column";

        [AjaxOnly]
        [HttpGet]
        public JsonResult GetList()
        {
            int tableId = StringHelper.Format<int>(Request.QueryString["tableId"]);
            int uid = StringHelper.Format<int>(Request.QueryString["uid"]);
            if (tableId>0 && uid>0)
            {
                return GetList(tableId, uid);
            }
            else if (tableId > 0)
            {
                return GetList(tableId);
            }
            else
            {
                return null;
            }
        }

        private JsonResult GetList(int table_id, int uid)
        {
            IEnumerable<dynamic> list = new List<dynamic>();
            DataBaseContext dbContext = DbHelper.DbContext();
            ColumnBLL columnBll = new ColumnBLL();
            string ids = columnBll.GetColumnIds(table_id, uid);
            ids = StringHelper.Unique<int>(ids);
            if (string.IsNullOrEmpty(ids))
            {
                return base.Json(null);
            }
            else
            {
                string[] arrIds = ids.Split(',');
                list = dbContext.CacheQuery(_Table, c => arrIds.Contains((string)(c.id)));
            }
            list = Select(list);
            return base.Json(list);
        }

        private JsonResult GetList(int table_id)
        {
            IEnumerable<dynamic> list = new List<dynamic>();
            DataBaseContext dbContext = DbHelper.DbContext();
            ColumnBLL columnBll = new ColumnBLL();
            string ids = columnBll.GetColumnIds(table_id);
            ids = StringHelper.Unique<int>(ids);
            if (string.IsNullOrEmpty(ids))
            {
                return base.Json(null);
            }
            else
            {
                string[] arrIds = ids.Split(',');
                list = dbContext.CacheQuery(_Table, c => arrIds.Contains((string)(c.Id.ToString())));
            }
            list = Select(list);
            return base.Json(list);
        }

        /// <summary>
        /// 映射，限制输出的字段
        /// </summary>
        /// <param name="dataList"></param>
        /// <returns></returns>
        private IEnumerable<dynamic> Select(IEnumerable<dynamic> dataList)
        {
            dataList = dataList.Select(c => new
            {
                Name = c.Name,
                Level = c.Level,
                ParentId= c.ParentId,
                Id = c.Id,
                IsFinal = c.IsFinal,
                Xuhao = c.Xuhao
            });
            return dataList;
        }



    }
}