using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using RFrameGenerate.Common.DatabaseConfig;
using RFrameGenerate.DAL.Enums;
using RFrameGenerate.Model;
using RFramework.Helper;
using RFramework.SQLQuery;
using RFramework.SQLServer;
namespace RFrameGenerate.BLL.WX_BaseCommon
{
    public class BaseCommonBLL
    {

        #region 素材管理



        public static void MaterialSubmit(T_WX_Material model)
        {

            if (model.MaterialGuid != new Guid())
            {
                using (var query = Factory.CreateT_WX_Material())
                {
                    //update
                    var oModel = query.GetDataByGuid(model.MaterialGuid);
                    oModel.MaterialTitle = model.MaterialTitle;
                    oModel.MaterialReplyType = model.MaterialReplyType;
                    oModel.MaterialOutUrl = model.MaterialOutUrl;
                    oModel.MaterialCoverFace = model.MaterialCoverFace;
                    oModel.MaterialContent = model.MaterialContent;
                    oModel.MaterialAbstract = model.MaterialAbstract;

                    query.Update(oModel);
                }
            }
            else
            {
                model.MaterialCode = 1;

                using (var query = Factory.CreateT_WX_Material())
                {
                    var res = query.GetFirstData(null, false, s => s.MaterialCode, OrderMethods.DESC);
                    if (res != null)
                    {
                        if (res.MaterialCode != null)
                        {
                            model.MaterialCode = res.MaterialCode + 1;
                        }
                    }
                    model.MaterialGuid = Guid.NewGuid();
                    model.Createdate = DateTime.Now;
                    model.MaterialState = BaseCommomDictionaryConst.MaterialState.Normal;
                    query.Add(model);
                }
            }
        }

        public static void DeleteMaterial(Guid guid)
        {
            using (var query = Factory.CreateT_WX_Material())
            {
                query.Delete(guid);
            }
        }

        /// <summary>
        /// 用于系统管理的获取素材
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static T_WX_Material GetMaterialByGuid(Guid guid)
        {
            using (var query = Factory.CreateT_WX_Material())
            {
                return query.GetDataByGuid(guid);
            }
        }



        public static T_WX_Material GetMaterialByCode(int ID)
        {
            using (var query = Factory.CreateT_WX_Material())
            {
                var model = query.GetFirstData(s => s.MaterialCode == ID);
                if (model == null || model.MaterialState == BaseCommomDictionaryConst.MaterialState.Pause)
                {
                    throw new Exception("年代已经久远了，文章已经不存在");
                }
                else
                {
                    return model;
                }
            }
        }



        public static void EditMaterial(T_WX_Material model)
        {
            using (var query = Factory.CreateT_WX_Material())
            {
                var oModel = query.GetDataByGuid(model.MaterialGuid);
                oModel.MaterialTitle = model.MaterialTitle;
                oModel.MaterialReplyType = model.MaterialReplyType;
                oModel.MaterialOutUrl = model.MaterialOutUrl;
                oModel.MaterialCoverFace = model.MaterialCoverFace;
                oModel.MaterialContent = model.MaterialContent;
                //oModel.MaterialCategory = model.MaterialCategory;
                oModel.MaterialAbstract = model.MaterialAbstract;
                query.Update(oModel);
            }
        }

        public static List<T_WX_Material> GetMaterialPageList(GridModel gridModel, string title)
        {

            List<T_WX_Material> list = new List<T_WX_Material>();
            using (var query = Factory.CreateT_WX_Material())
            {
                return query.GetPageList(gridModel, a => a.MaterialState == BaseCommomDictionaryConst.MaterialState.Normal && a.MaterialTitle.SqlLike(title), true);
            }
        }

        public static List<T_WX_Material> GetMaterialList()
        {
            using (var query = Factory.CreateT_WX_Material())
            {
                return query.GetList(a => a.MaterialState == BaseCommomDictionaryConst.MaterialState.Normal);
            }
        }

        public static List<T_WX_Material> GetMaterialPageList(GridModel gridModel)
        {
            using (var query = Factory.CreateT_WX_Material())
            {
                return query.GetPageList(gridModel, a => a.MaterialState == BaseCommomDictionaryConst.MaterialState.Normal);
            }
        }
        #endregion        

        public static Result AddTextKeyword(string keyword, string content, string rulename)
        {
            try
            {
                using (var query = Factory.CreateT_WX_AutoReply())
                {
                    var dnonematch = query.GetFirstData(a => a.Keyword == keyword);
                    if (dnonematch == null)
                    {
                        query.Add(new T_WX_AutoReply()
                        {
                            AutoReplyGuid = Guid.NewGuid(),
                            Keyword = keyword,
                            RuleName = rulename,
                            Value = content,
                            IsEnable = true,
                            Createdate = DateTime.Now,
                            Type = RFrameGenerate.BLL.BaseCommomDictionaryConst.AutoReply.text.ToString(),

                        });
                    }
                    else
                    {
                        return new Result(false, keyword + "关键字已存在");
                    }
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public static Result UpdateTextKeyword(Guid guid, string keyword, string content, string rulename)
        {
            try
            {
                using (var query = Factory.CreateT_WX_AutoReply())
                {
                    var dnonematch = query.GetFirstData(a => a.AutoReplyGuid == guid);
                    if (dnonematch.Keyword == keyword)
                    {
                        query.Update(a => new object[] { a.Value == content, a.RuleName == rulename }, b => b.AutoReplyGuid == guid);
                    }
                    else
                    {
                        var nonematch = query.GetFirstData(a => a.Keyword == keyword);
                        if (nonematch != null)
                        {
                            return new Result(false, "已存在关键字" + keyword);
                        }
                        else
                        {
                            query.Update(a => new object[] { a.Value == content, a.Keyword == keyword, a.RuleName == rulename }, b => b.AutoReplyGuid == guid);
                        }
                    }
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public static Result DelTextKeyword(Guid guid)
        {
            try
            {
                using (var query = Factory.CreateT_WX_AutoReply())
                {
                    query.Delete(a => a.AutoReplyGuid == guid);
                    return new Result(true);
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static Result SaveEventKeyword(string subscribe, string nonematch)
        {
            try
            {
                using (var query = Factory.CreateT_WX_AutoReply())
                {
                    var dnonematch = query.GetFirstData(a => a.Keyword == RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.NoneMatch);
                    if (dnonematch == null)
                    {
                        query.Add(new T_WX_AutoReply()
                        {
                            AutoReplyGuid = Guid.NewGuid(),
                            Keyword = RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.NoneMatch,
                            Value = nonematch,
                            IsEnable = true,
                            Createdate = DateTime.Now,
                            Type = RFrameGenerate.BLL.BaseCommomDictionaryConst.AutoReply.text.ToString(),

                        });
                    }
                    else
                    {
                        query.Update(a => new object[] { a.Value == nonematch }, b => b.Keyword == RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.NoneMatch);
                    }

                    var dsubscribe = query.GetFirstData(a => a.Keyword == RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.Subscribe);
                    if (dsubscribe == null)
                    {
                        query.Add(new T_WX_AutoReply()
                        {
                            AutoReplyGuid = Guid.NewGuid(),
                            Keyword = RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.Subscribe,
                            Value = nonematch,
                            IsEnable = true,
                            Createdate = DateTime.Now,
                            Type = RFrameGenerate.BLL.BaseCommomDictionaryConst.AutoReply.text.ToString(),

                        });
                    }
                    else
                    {
                        query.Update(a => new object[] { a.Value == subscribe }, b => b.Keyword == RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.Subscribe);
                    }
                    return new Result(true);
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static void GetEventKeyword(out string subscribe, out string nonematch)
        {
            subscribe = nonematch = string.Empty;
            using (var query = Factory.CreateT_WX_AutoReply())
            {
                var dnonematch = query.GetFirstData(a => a.Keyword == RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.NoneMatch);
                if (dnonematch != null)
                {
                    nonematch = dnonematch.Value;
                }

                var dsubscribe = query.GetFirstData(a => a.Keyword == RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.Subscribe);
                if (dsubscribe != null)
                {
                    subscribe = dsubscribe.Value;
                }
            }
        }

        public static List<T_WX_AutoReply> LoadKeywordDataToText(GridModel gridModel)
        {
            using (var query = Factory.CreateT_WX_AutoReply())
            {
                return query.GetPageList(gridModel, a => a.Type == RFrameGenerate.BLL.BaseCommomDictionaryConst.AutoReply.text.ToString() && a.Keyword != RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.NoneMatch && a.Keyword != RFrameGenerate.BLL.BaseCommomDictionaryConst.ReplyKeyword.Subscribe);
            }
        }

        public static List<T_WX_AutoReply> LoadKeywordDataToTxt(GridModel gridModel)
        {
            using (var query = Factory.CreateT_WX_AutoReply())
            {
                return query.GetPageList(gridModel, a => a.Type == RFrameGenerate.BLL.BaseCommomDictionaryConst.AutoReply.txt.ToString());
            }
        }

        public static Result AddTxt(string keyword, string guids, string rulenametxt)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    tran.BeginTransaction();
                    var query = Factory.CreateT_WX_AutoReply(tran);
                    var queryreplyma = Factory.CreateT_WX_AutoReply_Material(tran);
                    var dnonematch = query.GetFirstData(a => a.Keyword == keyword);

                    if (dnonematch == null)
                    {

                        T_WX_AutoReply auto = new T_WX_AutoReply()
                        {
                            AutoReplyGuid = Guid.NewGuid(),
                            Keyword = keyword,
                            RuleName = rulenametxt,
                            IsEnable = true,
                            Createdate = DateTime.Now,
                            Type = RFrameGenerate.BLL.BaseCommomDictionaryConst.AutoReply.txt.ToString(),

                        };
                        query.Add(auto);

                        foreach (var v in guids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (string.IsNullOrEmpty(v) != true)
                            {
                                var replyma = new T_WX_AutoReply_Material()
                                {
                                    AutoReplyGuid = auto.AutoReplyGuid,
                                    AutoReplyT_WX_MaterialGuid = Guid.NewGuid(),
                                    MaterialGuid = Guid.Parse(v),
                                };
                                queryreplyma.Add(replyma);
                            }
                        }



                        tran.Commit();
                    }
                    else
                    {
                        return new Result(false, keyword + "关键字已存在");
                    }
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static Result UpdateTxt(string keyword, string guids, Guid guid, string rulenametxt)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    tran.BeginTransaction();
                    var query = Factory.CreateT_WX_AutoReply(tran);
                    var queryreplyma = Factory.CreateT_WX_AutoReply_Material(tran);
                    var dnonematch = query.GetFirstData(a => a.AutoReplyGuid == guid);

                    if (dnonematch.Keyword == keyword)
                    {
                        query.Update(a => new object[] { a.RuleName == rulenametxt }, b => b.AutoReplyGuid == guid);
                        queryreplyma.Delete(a => a.AutoReplyGuid == dnonematch.AutoReplyGuid);
                        foreach (var v in guids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                        {
                            if (string.IsNullOrEmpty(v) != true)
                            {
                                var replyma = new T_WX_AutoReply_Material()
                                {
                                    AutoReplyGuid = dnonematch.AutoReplyGuid,
                                    AutoReplyT_WX_MaterialGuid = Guid.NewGuid(),
                                    MaterialGuid = Guid.Parse(v),
                                };
                                queryreplyma.Add(replyma);
                            }
                        }
                    }
                    else
                    {
                        var nonematch = query.GetFirstData(a => a.Keyword == keyword);
                        if (nonematch != null)
                        {
                            return new Result(false, "已存在关键字" + keyword);
                        }
                        else
                        {
                            query.Update(a => new object[] { a.Keyword == keyword, a.RuleName == rulenametxt }, b => b.AutoReplyGuid == guid);
                            queryreplyma.Delete(a => a.AutoReplyGuid == dnonematch.AutoReplyGuid);
                            foreach (var v in guids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                if (string.IsNullOrEmpty(v) != true)
                                {
                                    var replyma = new T_WX_AutoReply_Material()
                                    {
                                        AutoReplyGuid = dnonematch.AutoReplyGuid,
                                        AutoReplyT_WX_MaterialGuid = Guid.NewGuid(),
                                        MaterialGuid = Guid.Parse(v),
                                    };
                                    queryreplyma.Add(replyma);
                                }
                            }
                        }
                    }



                    tran.Commit();
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static Result DelTxt(Guid guid)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    tran.BeginTransaction();
                    var query = Factory.CreateT_WX_AutoReply(tran);
                    var queryreplyma = Factory.CreateT_WX_AutoReply_Material(tran);

                    query.Delete(a => a.AutoReplyGuid == guid);
                    queryreplyma.Delete(a => a.AutoReplyGuid == guid);
                    tran.Commit();
                    return new Result(true);
                }
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }
        public static List<T_WX_Material> GetTxtByID(Guid guid)
        {
            using (var tran = new SqlRTransaction())
            {
                var query = Factory.CreateT_WX_Material(tran);
                var queryreplyma = Factory.CreateT_WX_AutoReply_Material(tran);

                var repyma = queryreplyma.GetList(a => a.AutoReplyGuid == guid);
                Guid[] guids = repyma.Select(a => a.MaterialGuid.Value).ToArray();
                return query.GetList(a => a.MaterialGuid.SqlIn(guids));
            }
        }
    }
}
