using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFrameGenerate.BLL;
using RFrameGenerate.DAL;
using RFrameGenerate.Model;
using RFramework.SQLQuery;
using RFramework.SQLServer;
using RFrameGenerate.DAL.Enums;

namespace RFrameGenerate.BLL
{
     public class ShareManage
     {
         public static List<T_ST_SharePeriodListView> GetSharePageList(GridModel gridModel)
         {
             using (var query = Factory.CreateT_ST_SharePeriodListView())
             {
                 return query.GetPageList(gridModel, a => a.MemberGuid == RFrameGenerate.Common.CurrentUser.GetCurrUserGuid(), false, b => b.ProductCrowdPeriodGuid, OrderMethods.DESC);
             }
         }
         public static List<T_ST_SharePeriodListView> GetAllSharePageList(GridModel gridModel, Guid productGuid)
         {
             using (var query = Factory.CreateT_ST_SharePeriodListView())
             {
                 return query.GetPageList(gridModel, a => a.ProductCrowdGuid == productGuid, false, b => b.ProductCrowdPeriodGuid, OrderMethods.DESC);
             }
         }

         public static T_CR_Share GetShare(Guid shareGuid)
         {
             using (var query = Factory.CreateT_CR_Share())
             {
                 return query.GetFirstData(a=>a.ShareGuid==shareGuid);
             }
         }

         public static bool IsShared(Guid memberGuid, Guid crowdPeriodGuid)
         {
             using (var query = Factory.CreateT_CR_Share())
             {
                 return query.IsExist(m => m.MemberGuid == memberGuid && m.ProductCrowdPeriodGuid == crowdPeriodGuid);
             }
         }

         public static Result AddShare(T_CR_Share share)
         {
             if (share == null) return new Result(false, "分享对象不能为空！");

             if (share.ProductCrowdPeriodGuid == null || share.ProductCrowdPeriodGuid.Value == Guid.Empty) return new Result(false, "分享期数不能为空！");

             var currentUser = RFrameGenerate.Common.CurrentUser.GetCurrUserGuid();

             if(currentUser == Guid.Empty) return new Result(false,"不存在当前用户，请重新授权登陆！");

             var isShare = IsShared(currentUser, share.ProductCrowdPeriodGuid.Value);

             if (isShare) return new Result(false, "已分享，请不要重复提交！");

             if (string.IsNullOrEmpty(share.Title)) return new Result(false, "分享标题不能为空！");

             if (string.IsNullOrEmpty(share.Details)) return new Result(false, "分享内容不能为空！");

             if (string.IsNullOrEmpty(share.Img1)) return new Result(false, "分享图片不能为空！");

             using (var query = Factory.CreateT_CR_Share())
             {
                 share.MemberGuid = currentUser;
                 share.ShareGuid = Guid.NewGuid();
                 share.ShareDate = DateTime.Now;
                 share.MerchantGuid = RFrameGenerate.Common.CurrentManage.MerchantGuid;
                 query.Add(share);
             }
             return new Result(true);
         }
    }
}
