using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using RFrameGenerate.Common;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using RFramework.SQLQuery;

namespace RFrameGenerate.BLL.DIVShop
{
    public class WinportMainManage
    {
        #region 数据读取

        public static List<T_WP_WinportMain> GetComponents(Guid pageGuid)
        {
            var list = PageCacheManage.GetCacheComponents(pageGuid);

            if (list != null && list.Count > 0) return list;

            using (var query = Factory.CreateT_WP_WinportMain())
            {
                list = query.GetList(m => m.WinportPageGuid == pageGuid, false, v => v.Sort);
            }

            PageCacheManage.SetCacheComponents(pageGuid, list);

            return list;
        }

        #endregion

        #region 数据操作

        public static Result DeletePage(Guid pageGuid)
        {
            if (pageGuid == Guid.Empty || !ExistsPage(pageGuid)) return new Result(false, "不存在页面");

            SqlRTransaction trans = null;
            IQuery<T_WP_WinportPage> queryPage = null;
            IQuery<T_WP_WinportMain> queryMain = null;
            IQuery<T_WP_AttributeData> queryData = null;
            try
            {
                trans = new SqlRTransaction();
                trans.BeginTransaction();

                queryPage = Factory.CreateT_WP_WinportPage(trans);
                queryMain = Factory.CreateT_WP_WinportMain(trans);


                queryPage.Delete(m => m.WinportPageGuid == pageGuid);

                var list = queryMain.GetList(m => m.WinportPageGuid == pageGuid);

                queryMain.Delete(m => m.WinportPageGuid == pageGuid);

                if (list != null && list.Count > 0)
                {
                    queryData = Factory.CreateT_WP_AttributeData(trans);
                    var ids = list.Select(m => m.WinportMainGuid).ToArray();
                    queryData.Delete(m => m.WinportMainGuid.SqlIn(ids));
                }

                trans.Commit();

                PageCacheManage.RemoveCache(pageGuid);

                return new Result(true);
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 删除DIV页面失败！ Message :" + ex.Message);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 删除DIV页面失败！ Source :" + ex.Source);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 删除DIV页面失败！ StackTrace :" + ex.StackTrace);

                return new Result(false, ex.Message);
            }
            finally
            {
                if (queryPage != null) queryPage.Dispose();
                if (queryMain != null) queryMain.Dispose();
                if (queryData != null) queryData.Dispose();

                if (trans != null)
                {
                    trans.Dispose();

                    if (trans.SqlConnection != null && trans.SqlConnection.State != System.Data.ConnectionState.Closed)
                    {
                        trans.SqlConnection.Close();
                    }
                }
            }
        }

        public static Result SavePage(T_WP_WinportPage page, List<T_WP_WinportMain> components, List<T_WP_AttributeData> attributeDatas)
        {
            var cbState = CheckError(page, components, attributeDatas);

            if (!cbState.State) return new Result(false, cbState.Msg);

            if (!ExistsPage(page.WinportPageGuid)) return Save(page, components, attributeDatas);

            return Update(page, components, attributeDatas);
        }

        private static Result Update(T_WP_WinportPage page, List<T_WP_WinportMain> components, List<T_WP_AttributeData> attributeDatas)
        {
            SqlRTransaction trans = null;
            IQuery<T_WP_WinportPage> queryPage = null;
            IQuery<T_WP_WinportMain> queryMain = null;
            IQuery<T_WP_AttributeData> queryData = null;

            page.LastAlertTime = DateTime.Now;

            foreach (var item in components)
            {
                var attribute = attributeDatas.First(m => m.WinportMainGuid == item.WinportMainGuid);

                if (attribute == null) return new Result(false, "属性数据为空！请联系管理员!");

                item.WinportPageGuid = page.WinportPageGuid;
                item.WinportMainGuid = Guid.NewGuid();
                item.EntityState = EntityStates.ToBeAdd;

                attribute.AttributeDataGuid = Guid.NewGuid();
                attribute.WinportMainGuid = item.WinportMainGuid;
                attribute.EntityState = EntityStates.ToBeAdd;
            }
            try
            {
                trans = new SqlRTransaction();
                trans.BeginTransaction();

                queryPage = Factory.CreateT_WP_WinportPage(trans);
                queryMain = Factory.CreateT_WP_WinportMain(trans);
                queryData = Factory.CreateT_WP_AttributeData(trans);

                queryPage.Update(m => new object[] { m.PageName == page.PageName, m.State == page.State, m.LastAlertTime == page.LastAlertTime }, v => v.WinportPageGuid == page.WinportPageGuid);

                if (page.State == 1)
                {
                    queryPage.Update(m => new object[] 
                    {
                        m.State == 0,
                        m.LastAlertTime == DateTime.Now
                    },
                    v => v.State == 1 && v.WinportPageGuid != page.WinportPageGuid && v.MerchantGuid == CurrentManage.MerchantGuid);
                }

                var list = queryMain.GetList(m => m.WinportPageGuid == page.WinportPageGuid);

                queryMain.Delete(m => m.WinportPageGuid == page.WinportPageGuid);
                queryMain.AddList(components);

                if (list != null && list.Count > 0)
                {
                    var array = list.Select(m => m.WinportMainGuid).ToArray();
                    queryData.Delete(m => m.WinportMainGuid.SqlIn(array));
                }

                queryData.AddList(attributeDatas);

                trans.Commit();
                PageCacheManage.RemoveCache(page.WinportPageGuid);
                return new Result(true);
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 添加DIV页面失败！ Message :" + ex.Message);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 添加DIV页面失败！ Source :" + ex.Source);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 添加DIV页面失败！ StackTrace :" + ex.StackTrace);

                return new Result(false, ex.Message);
            }
            finally
            {
                if (queryPage != null) queryPage.Dispose();
                if (queryMain != null) queryMain.Dispose();
                if (queryData != null) queryData.Dispose();

                if (trans != null)
                {
                    trans.Dispose();

                    if (trans.SqlConnection != null && trans.SqlConnection.State != System.Data.ConnectionState.Closed)
                    {
                        trans.SqlConnection.Close();
                    }
                }
            }
        }

        private static Result Save(T_WP_WinportPage page, List<T_WP_WinportMain> components, List<T_WP_AttributeData> attributeDatas)
        {
            SqlRTransaction trans = null;
            IQuery<T_WP_WinportPage> queryPage = null;
            IQuery<T_WP_WinportMain> queryMain = null;
            IQuery<T_WP_AttributeData> queryData = null;

            page.MerchantGuid = CurrentManage.MerchantGuid;
            page.WinportPageGuid = Guid.NewGuid();
            page.LastAlertTime = DateTime.Now;

            foreach (var item in components)
            {
                var attribute = attributeDatas.First(m => m.WinportMainGuid == item.WinportMainGuid);

                if (attribute == null) return new Result(false, "属性数据为空！请联系管理员!");

                item.WinportPageGuid = page.WinportPageGuid;
                item.WinportMainGuid = Guid.NewGuid();
                item.EntityState = EntityStates.ToBeAdd;

                attribute.AttributeDataGuid = Guid.NewGuid();
                attribute.WinportMainGuid = item.WinportMainGuid;
                attribute.EntityState = EntityStates.ToBeAdd;
            }
            try
            {
                trans = new SqlRTransaction();
                trans.BeginTransaction();

                queryPage = Factory.CreateT_WP_WinportPage(trans);
                queryMain = Factory.CreateT_WP_WinportMain(trans);
                queryData = Factory.CreateT_WP_AttributeData(trans);

                queryPage.Add(page);
                if (page.State == 1)
                {
                    queryPage.Update(m => new object[] 
                    {
                        m.State == 0,
                        m.LastAlertTime == DateTime.Now
                    },
                    v => v.State == 1 && v.WinportPageGuid != page.WinportPageGuid && v.MerchantGuid == CurrentManage.MerchantGuid);
                }
                queryMain.AddList(components);
                queryData.AddList(attributeDatas);

                trans.Commit();
                return new Result(true);
            }
            catch (Exception ex)
            {
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 添加DIV页面失败！ Message :" + ex.Message);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 添加DIV页面失败！ Source :" + ex.Source);
                Wechat.LogManage.Log("Thread ID : " + System.Threading.Thread.CurrentThread.ManagedThreadId + " 添加DIV页面失败！ StackTrace :" + ex.StackTrace);

                return new Result(false, ex.Message);
            }
            finally
            {
                if (queryPage != null) queryPage.Dispose();
                if (queryMain != null) queryMain.Dispose();
                if (queryData != null) queryData.Dispose();

                if (trans != null)
                {
                    trans.Dispose();

                    if (trans.SqlConnection != null && trans.SqlConnection.State != System.Data.ConnectionState.Closed)
                    {
                        trans.SqlConnection.Close();
                    }
                }
            }
        }

        #endregion

        private static bool ExistsPage(Guid pageGuid)
        {
            if (pageGuid == Guid.Empty) return false;

            using (var query = Factory.CreateT_WP_WinportPage())
            {
                return query.IsExist(m => m.WinportPageGuid == pageGuid);
            }
        }

        private static Result CheckError(T_WP_WinportPage page, List<T_WP_WinportMain> components, List<T_WP_AttributeData> attributeDatas)
        {
            if (page == null) return new Result(false, "页面内容不能为空！");

            if (components == null || components.Count <= 0) return new Result(false, "至少选择一个控件！");

            if (attributeDatas == null || attributeDatas.Count <= 0) return new Result(false, "属性数据为空！请联系管理员！");

            foreach (var item in components)
            {
                if (item.WinportMainGuid == Guid.Empty) return new Result(false, "组件ID不能为空！");

                if (!attributeDatas.Exists(m => m.WinportMainGuid == item.WinportMainGuid)) return new Result(false, "属性数据为空！请联系管理员！");
            }

            return new Result(true);
        }
    }
}
