using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFramework.SQLServer;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using Wechat;
using weixinopen.Model;

namespace RFrameGenerate.BLL
{
    public class WeChatManage
    {
        public static List<T_WX_WeChat> GetList()
        {
            using (var query = Factory.CreateT_WX_WeChat())
            {
                return query.GetList(null, null, DAL.Enums.OrderMethods.Default, RFramework.SQLServer.Enums.LockType.Default, false);
            }
        }

        public static void UpdateRQ(string url, Guid wechatguid)
        {
            using (var query = Factory.CreateT_WX_WeChat())
            {
                query.Update(a => new object[] { a.qrcode_url == url }, b => b.WeChatGuid == wechatguid, false);
            }
        }

        public static T_WX_WeChat GetWeChatByMearchantID(Guid wechatGuid)
        {
            using (var query = Factory.CreateT_WX_WeChat())
            {
                return query.GetFirstData(a => a.WeChatGuid == wechatGuid);
            }
        }
        /// <summary>
        /// 根据原始id获取公众号
        /// </summary>
        /// <param name="user_name">原始id</param>
        /// <returns></returns>
        public static T_WX_WeChat GetWeChatByUserName(string user_name)
        {
            using (var query = Factory.CreateT_WX_WeChat())
            {
                return query.GetFirstData(a => a.user_name == user_name);
            }
        }
        static object lockwechat = new object();
        /// <summary>
        /// 授权成功添加公众号信息,不存在添加,存在修改
        /// </summary>
        /// <param name="uxue"></param>
        /// <param name="merchantguid">有可能是guid有可能是userid</param>
        /// <returns></returns>
        public static Result UpdateWeChat(Uxuezhang uxue, string merchid, string imagepath)
        {
            lock (lockwechat)
            {
                if (string.IsNullOrEmpty(merchid) != true)
                {
                    var download_qrcode_url = uxue.qrcode_url;
                    string qrcodeurl;
                    using (SqlRTransaction tran = new SqlRTransaction())
                    {
                        var queryMer = Factory.CreateT_BAS_Merchants(tran);
                        var query = Factory.CreateT_WX_WeChat(tran);

                        #region 查询商家
                        T_BAS_Merchants merch;
                        Guid merGuid;
                        if (Guid.TryParse(merchid, out merGuid) == true)
                        {
                            merch = queryMer.GetFirstData(a => a.MerchantGuid == Guid.Parse(merchid));
                        }
                        else
                        {
                            merch = queryMer.GetFirstData(a => a.UserID == merchid);
                        }
                        merGuid = merch.MerchantGuid;
                        #endregion

                        Guid wechatguid;

                        tran.BeginTransaction();

                        #region 新逻辑
                        //先清空原来的关系
                        var wechatlist = query.GetList(a => a.appid == uxue.appid, isFilterMerchant: false);
                        if (wechatlist.Count() > 0)
                        {
                            query.Delete(a => a.appid == uxue.appid, isFilterMerchant: false);
                            foreach (var v in wechatlist)
                            {
                                queryMer.Update(a => new object[] { a.WeChatGuid == null }, b => b.WeChatGuid == v.WeChatGuid);
                            }
                        }
                        //添加新的关系
                        wechatguid = Guid.NewGuid();
                        qrcodeurl = "/upload/wechatqr/" + wechatguid.ToString() + ".jpg";
                        query.Add(new T_WX_WeChat()
                        {
                            alias = uxue.alias,
                            appid = uxue.appid,
                            authorization_info = uxue.authorization_info,
                            func_info = uxue.func_info,
                            head_img = uxue.head_img,
                            nick_name = uxue.nick_name,
                            qrcode_url = qrcodeurl,
                            service_type_info = uxue.service_type_info,
                            user_name = uxue.user_name,
                            verify_type_info = uxue.verify_type_info,
                            WeChatGuid = wechatguid,
                            IsAuthorize = true,
                        });
                        queryMer.Update(a => new object[] { a.WeChatGuid == wechatguid }, b => b.MerchantGuid == merGuid);
                        #endregion

                        #region 原来逻辑
                        /*
                        if (merch.WeChatGuid != null)
                        {
                            #region
                            wechatguid = merch.WeChatGuid.Value;
                            qrcodeurl = "/upload/wechatqr/" + wechatguid.ToString() + ".jpg";
                            if (query.IsExist(a => a.WeChatGuid == merch.WeChatGuid) == true)
                            {
                                query.Update(a => new object[] 
                                {
                                    a.alias==uxue.alias,
                                    a.appid==uxue.appid,
                                    a.authorization_info==uxue.authorization_info,
                                    a.func_info==uxue.func_info,
                                    a.head_img==uxue.head_img,
                                    a.nick_name==uxue.nick_name,
                                    a.qrcode_url==qrcodeurl,
                                    a.service_type_info==uxue.service_type_info,
                                    a.user_name==uxue.user_name,
                                    a.verify_type_info==uxue.verify_type_info,
                                    a.IsAuthorize==true,
                                }, b => b.WeChatGuid == merch.WeChatGuid);
                            }
                            else
                            {
                                wechatguid = Guid.NewGuid();
                                qrcodeurl = "/upload/wechatqr/" + wechatguid.ToString() + ".jpg";
                                query.Add(new T_WX_WeChat()
                                {
                                    alias = uxue.alias,
                                    appid = uxue.appid,
                                    authorization_info = uxue.authorization_info,
                                    func_info = uxue.func_info,
                                    head_img = uxue.head_img,
                                    nick_name = uxue.nick_name,
                                    qrcode_url = qrcodeurl,
                                    service_type_info = uxue.service_type_info,
                                    user_name = uxue.user_name,
                                    verify_type_info = uxue.verify_type_info,
                                    WeChatGuid = wechatguid,
                                    IsAuthorize = true,
                                });
                                queryMer.Update(a => new object[] { a.WeChatGuid == wechatguid }, b => b.MerchantGuid == merGuid);
                            }
                            #endregion
                        }
                        else
                        {
                            #region
                            wechatguid = Guid.NewGuid();
                            qrcodeurl = "/upload/wechatqr/" + wechatguid.ToString() + ".jpg";
                            query.Add(new T_WX_WeChat()
                            {
                                alias = uxue.alias,
                                appid = uxue.appid,
                                authorization_info = uxue.authorization_info,
                                func_info = uxue.func_info,
                                head_img = uxue.head_img,
                                nick_name = uxue.nick_name,
                                qrcode_url = qrcodeurl,
                                service_type_info = uxue.service_type_info,
                                user_name = uxue.user_name,
                                verify_type_info = uxue.verify_type_info,
                                WeChatGuid = wechatguid,
                                IsAuthorize = true,
                            });
                            queryMer.Update(a => new object[] { a.WeChatGuid == wechatguid }, b => b.MerchantGuid == merGuid);
                            #endregion
                        }
                        */
                        #endregion

                        #region
                        Image image = DowloadingImage.Request(download_qrcode_url);
                        if (image != null)
                        {
                            try
                            {
                                if (System.IO.Directory.Exists(imagepath) != true)
                                    System.IO.Directory.CreateDirectory(imagepath);
                                imagepath += "\\" + wechatguid.ToString() + ".jpg";
                                if (System.IO.File.Exists(imagepath) == true)
                                    System.IO.File.Delete(imagepath);
                                image.Save(imagepath);

                            }
                            catch (Exception ex)
                            {
                                LogManage.Log("授权保存公众号二维码:" + ex.Message);
                            }
                        }
                        #endregion

                        tran.Commit();

                        return new Result(true);
                    }
                }
                else
                {
                    return new Result(false, "授权失败,请重新发起授权");
                }
            }
        }
        /// <summary>
        /// 取消授权
        /// </summary>
        /// <param name="appid">取消授权appid</param>
        /// <returns></returns>
        public static Result CancelAuthorization(string appid)
        {
            try
            {
                using (var tran = new SqlRTransaction())
                {
                    var query = Factory.CreateT_WX_WeChat(tran);
                    //query.Update(a => new object[] 
                    //{ 
                    //    a.IsAuthorize==false,
                    //}, b => b.appid == appid);
                    var model = query.GetFirstData(a => a.appid == appid);
                    if (model != null)
                    {
                        var queryMer = Factory.CreateT_BAS_Merchants(tran);
                        queryMer.Update(a => new object[] { a.WeChatGuid == null }, b => b.WeChatGuid == model.WeChatGuid, false);
                        query.Delete(a => a.appid == appid, false);
                    }
                }
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
        }

        public static Result Remind(bool state, Guid? guid, string AttentionUrl, bool IsAttentionUrl)
        {
            using (var query = Factory.CreateT_WX_WeChat())
            {
                try
                {
                    query.Update(a => new Object[] {
                        a.IsRemind==state,
                        a.AttentionUrl==AttentionUrl,
                        a.IsAttentionUrl==IsAttentionUrl,
                    }, a => a.WeChatGuid == guid.Value);
                    return new Result(true);
                }
                catch (Exception err)
                {
                    return new Result(false, err.Message);
                }

            }
        }

        public static T_WX_WeChat GetWeChat(string appid)
        {
            using (var query = Factory.CreateT_WX_WeChat())
            {
                return query.GetFirstData(a => a.appid == appid);
            }
        }
    }
}
