using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFrameGenerate.Model;
using RFramework.SQLQuery;
using RFramework.SQLQuery.SQLExpands;

namespace RFrameGenerate.BLL
{
    public class MemberBindMerchantManage
    {
        public static T_BAS_MemberBindMerchant Get(string openid)
        {
            using (var query = SQLModelFactory.CreateSqlModel<T_BAS_MemberBindMerchant>())
            {
                return query.SqlSelect().SqlWhere(a => a.OpenID == openid).First();
            }
        }

        public static void Add(T_BAS_MemberBindMerchant model)
        {
            using (var query = SQLModelFactory.CreateSqlModel<T_BAS_MemberBindMerchant>())
            {
                query.SqlAdd(model);
            }
        }

        public static void Update(T_BAS_MemberBindMerchant model)
        {
            using (var query = SQLModelFactory.CreateSqlModel<T_BAS_MemberBindMerchant>())
            {
                query.SqlUpdate(a => new object[]
                { 
                    a.NewOpenID==model.NewOpenID,
                    a.UserID==model.UserID,
                }, b => b.MemberBindMerchantGuid == model.MemberBindMerchantGuid);
            }
        }

        public static BindMemberInfo GetMemberInfo(string openid)
        {
            using (var query = SQLModelFactory.CreateSqlModel<T_BAS_Member, T_BAS_Merchants>())
            {
                var m = query
                    .SqlSelect((a, b) => new { b.UserID })
                    .SqlJionInner((a, b) => b)
                    .SqlOn((a, b) => a.MerchantGuid == b.MerchantGuid)
                    .SqlWhere((a, b) => a.MemberOpenID == openid && a.IsDistributor == true)
                    .FirstOrDefault();

                if (m != null)
                {
                    BindMemberInfo member = new BindMemberInfo() { openid = openid, userid = m.UserID };
                    return member;
                }
                else
                {
                    return null;
                }
            }
        }


        public static void DeleteRel(string userid,string openid)
        {
            using (var query = SQLModelFactory.CreateSqlModel<T_BAS_MemberBindMerchant>())
            {
                query.SqlDelete(a => a.UserID == userid && a.NewOpenID == openid);
            }
        }
    }
}
