using Nirvana.Common;
using Nirvana.Data;
using Senparc.Weixin.Open.ComponentAPIs;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.WX.DBServices
{
    /// <summary>
    /// 公众号管理
    /// </summary>
    public partial class OfficialApp : Repository<YB_OfficlaAccount>
    {
        /// <summary>
        ///  更新或者插入授权token
        /// </summary>
        /// <param name="result"></param>
        /// <param name="authorizerId">公众号appid</param>
        /// <param name="componentAppId">开放平台id</param>
        public async Task InsertOrUpdateAuthorizerTokenAsync(RefreshAuthorizerTokenResult result, string authorizerId, string componentAppId)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    if (await dbClient.Queryable<YB_OfficlaAccount>().AnyAsync(x => x.authorizer_appid == authorizerId && x.componentappid == componentAppId))
                    {
                        await dbClient.Updateable<YB_OfficlaAccount>().SetColumns(x => new YB_OfficlaAccount
                        {
                            authorizer_access_token = result.authorizer_access_token,
                            authorizer_refresh_token = result.authorizer_refresh_token
                        }).Where(x => x.authorizer_appid == authorizerId && x.componentappid == componentAppId).ExecuteCommandAsync();
                    }
                }
                catch (Exception ex)
                {
                    var errmsg = $"result:{result.ToJson()},authorizerid={authorizerId},componentAppid={componentAppId}";
                    new LoggerApp().InsertErrorLog(ex, errmsg, "更新或者插入授权token");
                }
            }
        }

        /// <summary>
        /// 获取公众号的刷新token
        /// </summary>
        /// <param name="authorizerId">公众号appid</param>
        /// <param name="componentAppId">开放平台appid</param>
        /// <returns></returns>
        public async Task<string> GetRefreshToken(string authorizerId, string componentAppId)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    var data = await dbClient.Queryable<YB_OfficlaAccount>().FirstAsync(x => x.authorizer_appid == authorizerId && x.componentappid == componentAppId);
                    if (data != null)
                    {
                        return data.authorizer_refresh_token;
                    }
                    return "";
                }
                catch (Exception ex)
                {
                    var errmsg = $"authorizerid={authorizerId},componentAppid={componentAppId}";
                    new LoggerApp().InsertErrorLog(ex, errmsg, "获取公众号的刷新token");
                    return "";
                }
            }
        }
        /// <summary>
        /// 插入或者更新公众号信息
        /// </summary>
        /// <param name="model"></param>
        /// <param name="bid"></param>
        /// <returns></returns>
        public async Task InsertOrUpdateAsync(YB_OfficlaAccount model, string bid)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    if (await dbClient.Queryable<YB_OfficlaAccount>().AnyAsync(x => x.authorizer_appid == model.authorizer_appid && x.componentappid == model.componentappid))
                    {
                        await dbClient.Updateable<YB_OfficlaAccount>().SetColumns(x => new YB_OfficlaAccount
                        {
                            authorizer_access_token = model.authorizer_access_token,
                            authorizer_refresh_token = model.authorizer_refresh_token,
                            head_img = model.head_img,
                            nick_name = model.nick_name,
                            user_name = model.user_name,
                            alias = model.alias,
                            service_type_info = model.service_type_info,
                            verify_type_info = model.verify_type_info,
                            lastmodifytime = DateTime.Now,
                            func_info = model.func_info,
                            qrcode_url = model.qrcode_url,
                            isauthorize = 1,
                            type = model.type
                        })
                         .Where(x => x.authorizer_appid == model.authorizer_appid && x.componentappid == model.componentappid).ExecuteCommandAsync();
                    }
                    else
                    {
                        var data = new YB_OfficlaAccount
                        {
                            alias = model.alias.ToStr(),
                            service_type_info = model.service_type_info.ToStr(),
                            authorizer_access_token = model.authorizer_access_token.ToStr(),
                            authorizer_appid = model.authorizer_appid.ToStr(),
                            authorizer_refresh_token = model.authorizer_refresh_token.ToStr(),
                            componentappid = model.componentappid.ToStr(),
                            createtime = DateTime.Now,
                            func_info = model.func_info.ToStr(),
                            head_img = model.head_img.ToStr(),
                            isauthorize = 1,
                            lastmodifytime = DateTime.Now,
                            nick_name = model.nick_name.ToStr(),
                            qrcode_url = model.qrcode_url.ToStr(),
                            user_name = model.user_name.ToStr(),
                            verify_type_info = model.verify_type_info.ToStr(),
                            type = model.type,
                            authorizeationcode = model.authorizeationcode.ToStr()
                        };
                        await dbClient.Insertable<YB_OfficlaAccount>(data).ExecuteCommandAsync();
                    }
                    if (!string.IsNullOrEmpty(bid))
                    {
                        var businessid = bid.ToInt();
                        if (businessid > 0 && !await dbClient.Queryable<YB_BusinessOffice>().AnyAsync(x => x.BusinessId == businessid && x.AppId == model.authorizer_appid))
                        {
                            await dbClient.Insertable<YB_BusinessOffice>(new YB_BusinessOffice
                            {
                                AppId = model.authorizer_appid,
                                BusinessId = businessid,
                                CreateTime = DateTime.Now
                            }).ExecuteCommandAsync();
                        }
                    }
                }
                catch (Exception ex)
                {
                    var msg = $"{model.ToJson()}";
                    new LoggerApp().InsertErrorLog(ex, msg, "公众号更新");
                }
            }
        }
        /// <summary>
        /// 更新公众号授权信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task NoticeUpdateAsync(YB_OfficlaAccount model)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    if (await dbClient.Queryable<YB_OfficlaAccount>().AnyAsync(x => x.authorizer_appid == model.authorizer_appid && x.componentappid == model.componentappid))
                    {
                        //成功授权
                        if (model.isauthorize == 1)
                        {
                            await dbClient.Updateable<YB_OfficlaAccount>().SetColumns(x => new YB_OfficlaAccount
                            {
                                authorizeationcode = model.authorizeationcode,
                                authorizationcodeexpiredtime = model.authorizationcodeexpiredtime,
                                isauthorize = model.isauthorize
                            }).Where(x => x.authorizer_appid == model.authorizer_appid && x.componentappid == model.componentappid).ExecuteCommandAsync();
                        }
                    }
                    //取消授权
                    else
                    {
                        //更新公众号
                        await dbClient.Updateable<YB_OfficlaAccount>().SetColumns(x => new YB_OfficlaAccount
                        {
                            isauthorize = 0
                        }).Where(x => x.componentappid == model.componentappid && x.authorizer_appid == model.authorizer_appid).ExecuteCommandAsync();
                    }
                }
                catch (Exception ex)
                {
                    var msg = $"{model.ToJson()}";
                    new LoggerApp().InsertErrorLog(ex, msg, "更新公众号授权信息");
                }
            }
        }

        /// <summary>
        /// 更新提交的审核状态
        /// </summary>
        /// <param name="appid">微信原始id</param>
        /// <param name="status">审核状态,-1-代码已上传,0-审核成功,1-审核被拒绝,2-审核中,3-已撤回,4-审核延后</param>
        /// <param name="remark">状态备注</param>
        /// <param name="screenshot">不通过时的截图,mediaid形式</param>
        /// <param name="time">时间戳</param>
        /// <returns></returns>
        public async Task UpdateMiniInfoAsync(string appid, int status, string remark, string screenshot, string time)
        {
            new LoggerApp().InsertErrorLog($"小程序审核状态:appid:{appid},status={status},remark={remark},screenshot={screenshot},time={time}");
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var office = await dbClient.Queryable<YB_OfficlaAccount>().FirstAsync(x => x.user_name == appid);
                if (office != null)
                {
                    var data = await dbClient.Queryable<YB_MiniProgramHistory>().Where(x => x.appid == office.authorizer_appid).OrderBy(x => x.CreateTime, OrderByType.Desc).FirstAsync();
                    DateTime lasttime = time.ToDatetimeFromTimeStamp();
                    remark = remark.ToStr();
                    screenshot = screenshot.ToStr();
                    if (data != null)
                    {
                        await dbClient.Updateable<YB_MiniProgramHistory>().SetColumns(x => new YB_MiniProgramHistory
                        {
                            Status = status,
                            StatusRemark = remark,
                            ScreenShot = screenshot,
                            LastTime = lasttime
                        }).Where(x => x.Id == data.Id).ExecuteCommandAsync();
                    }
                }
            }
        }
        /// <summary>
        /// 检查是否为认证的服务号
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        public async Task<bool> CheckIsRZFAsync(string appid)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                return await dbClient.Queryable<YB_OfficlaAccount>().AnyAsync(x => x.user_name == appid && x.verify_type_info == "微信认证" && x.service_type_info == "服务号");
            }
        }
    }
}
