
using PageAdmin.BLL;
using PageAdmin.Common;using PageAdmin.Utils.ORM;using PageAdmin.Utils;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;

namespace PageAdmin.Web.Areas.E.Controllers
{
    public class SelectData
    {

        string _ShowField = "id";
        string _Order = "";
        int _IsMultiLevel;
        int _PageSize = 20;
        bool _CanContinue = true;
        string _DataSourceTable = "";
        string _DataSourceField = "";
        string _ZdyWhere = "";
        private DataBaseContext _DbContext;

        public SelectData()
        {
            _DbContext = DbHelper.DbContext();
        }
        /// <summary>
        /// 根据id加载数据到select
        /// </summary>
        /// <param name="form"></param>
        /// <param name="zdyWhere"></param>
        /// <returns></returns>
        public IEnumerable<dynamic> LoadList(NameValueCollection form, CurrentUser currentUser)
        {
            if (_CanContinue)
            {
                GetFieldSet(form, currentUser);
                CreateWhereByIds(form, ref _ZdyWhere);
                if (_ZdyWhere == "")
                {
                    return null;
                }
                IEnumerable<dynamic> dataList = _DbContext.Query(_DataSourceTable, _ShowField, _ZdyWhere).ToList() ;
                if (_IsMultiLevel == 1)
                {
                    foreach (var item in dataList)
                    {
                        string parentIds =CommonDataHelper.GetParentIds(_DataSourceTable,item.Id);
                        List<string> parentNode = CommonDataHelper.GetParentNodeName(_DataSourceTable, "name", parentIds);
                        if (parentNode.Count > 0)
                        {
                            item.Name = string.Join(">", parentNode) + ">" + item.Name;
                        }
                    }
                }
                return dataList;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 获取数据,不分页
        /// </summary>
        /// <param name="form"></param>
        /// <param name="currentUser"></param>
        /// <param name="zdyWhere"></param>
        /// <returns></returns>
        public IEnumerable<dynamic> ListData(NameValueCollection form,CurrentUser currentUser, string zdyWhere = "")
        {
            if (_CanContinue)
            {
                GetFieldSet(form, currentUser);
                CreateWhereByKw(form, ref _ZdyWhere);
                return _DbContext.Query(_DataSourceTable, _ShowField, _ZdyWhere, _Order);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        public IEnumerable<dynamic> PageListData(NameValueCollection form, PageInfo pageInfo,CurrentUser currentUser)
        {
            if (_CanContinue)
            {
                GetFieldSet(form, currentUser);
                pageInfo.PageSize = _PageSize;
                if (StringHelper.IsInt(form["page"]))
                {
                    pageInfo.CurrentPage = int.Parse(form["page"]);
                }
                int pageSize = pageInfo.PageSize;
                if (StringHelper.IsInt(form["pagesize"]))
                {
                    pageInfo.PageSize = int.Parse(form["pagesize"]);
                }
                int currentPage = 1;

                if (StringHelper.IsInt(form["page"]))
                {
                    currentPage = int.Parse(form["page"]);
                    pageInfo.CurrentPage = currentPage;
                }
                CreateWhereByKw(form, ref _ZdyWhere);
                return _DbContext.Query(_DataSourceTable, _ShowField, _ZdyWhere, _Order, pageInfo);
            }
            else
            {
                return null;
            }
        }

        private void CreateWhereByIds(NameValueCollection form, ref string where)
        {
            string ids = form["ids"];
            if (string.IsNullOrWhiteSpace(ids))
            {
                return;
            }
            string[] arrIds = ids.Split(',');
            for (int i = 0; i < arrIds.Length; i++)
            {
                if (!StringHelper.IsInt(arrIds[i]))
                {
                    return;
                }
            }
            if (where != "")
            {
                where += " and ";
            }
            if (StringHelper.IsInt(ids))
            {
                _DbContext.AddDbParamter("id", int.Parse(ids));
                where += " id=@id";
            }
            else
            {
                where += " id in(" + ids + ")";
            }
        }

        private void CreateWhereByKw(NameValueCollection form, ref string where)
        {
            string kw = form[_DataSourceField];
            if (string.IsNullOrWhiteSpace(kw))
            {
                return;
            }
            if (where != "")
            {
                where += " and ";
            }
            _DbContext.AddDbParamter(_DataSourceField, "%" + kw + "%");
            where += " [" + _DataSourceField + "] like @" + _DataSourceField;
        }


        //获取字段设置参数
        private void GetFieldSet(NameValueCollection form,CurrentUser currentUser)
        {
            //获取字段数据
            int fieldId = StringHelper.Format<int>(form["fieldId"]);
            int uid = currentUser.Uid;
            string userName = currentUser.UserName;
            dynamic fieldData = GetField(fieldId);

            string tableName = fieldData.TableName;
            string fieldName = fieldData.Name;
            string fieldType = fieldData.FieldType;
            string datasource_open = fieldData.DatasourceOpen.ToString();
            _DataSourceTable = fieldData.DatasourceTable;
            string datasource_valuefield = fieldData.DatasourceValueField;
            string datasource_textfield = fieldData.DatasourceTextField;
            _DataSourceField = datasource_textfield;
            _ShowField = "[" + datasource_valuefield + "],[" + datasource_textfield + "]";

            _ZdyWhere = fieldData.DatasourceWhere.ToString();
            _ZdyWhere = _ZdyWhere.Replace("{Uid}", uid.ToString()).Replace("{Table}", tableName).Replace("{Field}", fieldName).Replace("{UserName}", userName);

            _IsMultiLevel = StringHelper.Format<int>(fieldData.DatasourceMultiLevel.ToString());

            _Order = fieldData.Orderby.ToString();
            if (StringHelper.IsInt(fieldData.Pagesize.ToString()))
            {
                _PageSize = int.Parse(fieldData.Pagesize.ToString());
            }

            if (_IsMultiLevel == 1)
            {
                _ShowField += ",[level],[isFinal],[xuhao],[parentId]";
            }
            if (datasource_open == "1" && StringHelper.IsStr(_DataSourceTable) && StringHelper.IsStr(datasource_valuefield) && StringHelper.IsStr(datasource_textfield))
            {

            }
            else
            {
                _CanContinue = false; //字段数据源参数未设置好
            }

        }

        public dynamic GetField(int fieldId)
        {
            FieldBLL fieldBll = new FieldBLL();
            dynamic fieldData = fieldBll.GetData(fieldId);
            if (fieldData == null)
            {
                throw new Exception("无效的fieldid参数!");
            }
            return fieldData;
        }


    }
}

