using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
using Senparc.NeuChar.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using YBDevice.Entity;

namespace YBDevice.WX.DBServices
{
    /// <summary>
    /// 设备管理
    /// </summary>
    public partial class DeviceApp : Repository<YB_Device>
    {
        /// <summary>
        /// 插入或者更新八电极绑定信息
        /// </summary>
        /// <param name="fansid"></param>
        /// <param name="equid"></param>
        /// <param name="appid"></param>
        /// <param name="openid"></param>
        public async Task<ResultInfo> InsertOrUpdateBodyBindInfoAsync(string fansid, string equid, string appid, string openid)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                try
                {
                    int devid = equid.ToInt();
                    var devdata = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Id == devid);
                    if (devdata == null)
                    {
                        return new ResultInfo(ResultState.FAIL, "设备未找到");
                    }
                    Guid wxfansid = Guid.Parse(fansid);
                    var fansdata = await dbClient.Queryable<YB_WXFans>().FirstAsync(x => x.Id == wxfansid);
                    if (fansdata == null)
                    {
                        return new ResultInfo(ResultState.FAIL, "用户未找到");
                    }
                    //增加绑定记录,如果存在则更新,否则插入
                    if (await dbClient.Queryable<YB_WifiBind>().AnyAsync(x => x.FansId == wxfansid && x.PublicId == appid && x.DevId == devid))
                    {
                        await dbClient.Updateable<YB_WifiBind>().SetColumns(x => new YB_WifiBind
                        {
                            Subscribe = 1,
                            BindStatus = 1,
                            BindTime = DateTime.Now
                        }).Where(x => x.FansId == wxfansid && x.PublicId == appid && x.DevId == devid).ExecuteCommandAsync();
                    }
                    else
                    {
                        var binddata = new YB_WifiBind
                        {
                            DevCode = devdata.Ecode,
                            BindStatus = 1,
                            BindTime = DateTime.Now,
                            Subscribe = 1,
                            CreateTime = DateTime.Now,
                            DevId = devdata.Id,
                            FansId = wxfansid,
                            FansUnionId = fansdata.FansId,
                            OpenId = openid,
                            PublicId = appid,
                            UnBindTime = null
                        };
                        await dbClient.Insertable(binddata).ExecuteCommandAsync();
                    }
                    //增加粉丝关注记录
                    await InsertOrUpdateSubscribeAsync(appid, openid, wxfansid, 1);
                    return new ResultInfo(ResultState.SUCCESS, "绑定成功");
                }
                catch (Exception ex)
                {
                    var errmsg = $"fansid:{fansid},equid={equid},appid={appid},openid={openid}";
                    new LoggerApp().InsertErrorLog(ex, errmsg, "插入或者更新八电极绑定信息");
                    return new ResultInfo(ResultState.FAIL, ex.Message);
                }
            }
        }
        /// <summary>
        /// 更新/增加粉丝关注记录
        /// </summary>
        /// <param name="appid">公众号原始id</param>
        /// <param name="openid">用户openid</param>
        /// <param name="wxfansid">用户ID</param>
        /// <param name="subscribe">关注状态,0-取关,1-关注,2-重复关注</param>
        /// <param name="type">类型,1-固定贴纸二维码,2-带参数二维码,3-其他</param>
        public async Task<string> InsertOrUpdateSubscribeAsync(string appid, string openid, Guid? wxfansid, int subscribe, int type = 3)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                if (subscribe == 1 || subscribe == 2)
                {
                    if (await dbClient.Queryable<YB_WXFansExt>().AnyAsync(x => x.AppId == appid && x.OpenId == openid))
                    {
                        await dbClient.Updateable<YB_WXFansExt>().SetColumns(x => new YB_WXFansExt
                        {
                            Subscribe = subscribe,
                            SubscribeTime = DateTime.Now,
                            ResultId = wxfansid.Value
                        }).Where(x => x.AppId == appid && x.OpenId == openid).ExecuteCommandAsync();
                    }
                    else if (wxfansid.HasValue)
                    {
                        await dbClient.Insertable(new YB_WXFansExt
                        {
                            AppId = appid,
                            Subscribe = subscribe,
                            SubscribeTime = DateTime.Now,
                            OpenId = openid,
                            ResultId = wxfansid.Value
                        }).ExecuteCommandAsync();
                    }
                    //如果是固定贴纸二维码
                    if (type == 1)
                    {
                        var fansid = wxfansid.Value.ToString();
                        var result = await dbClient.Queryable<YB_ScanResult>().Where(x => x.FansId == fansid && x.PublicId == appid)
                            .OrderBy(x => x.CreateTime, SqlSugar.OrderByType.Desc)
                            .FirstAsync()
                            ;
                        //如果计费
                        if (result != null && result.Subscribe == 0)
                        {
                            //更新关注记录
                            await dbClient.Updateable<YB_ScanResult>().SetColumns(x => new YB_ScanResult
                            {
                                Subscribe = subscribe,
                                TakeTime = DateTime.Now
                            }).Where(x => x.Id == result.Id).ExecuteCommandAsync();
                            if(subscribe == 1)
                            {
                                //更新订单
                                await dbClient.Updateable<YB_Order>().SetColumns(x => new YB_Order
                                {
                                    RealCount = x.RealCount + 1,
                                    DayRealCount = x.DayRealCount + 1
                                }).Where(x => x.Id == result.OrderId).ExecuteCommandAsync();

                                //更新设备数据
                                await dbClient.Updateable<YB_EquRealData>().SetColumns(x => new YB_EquRealData
                                {
                                    TodayRealCnt = x.TodayRealCnt + 1,
                                    TotalRealCnt = x.TotalRealCnt + 1
                                }).Where(x => x.Id == result.EquId).ExecuteCommandAsync();

                                //更新商户数据
                                await dbClient.Updateable<YB_BusinessRealData>().SetColumns(x => new YB_BusinessRealData
                                {
                                    TodayRealCnt = x.TodayRealCnt + 1,
                                    TotalRealCnt = x.TotalRealCnt + 1
                                }).Where(x => x.BusinessId == result.BusinessId).ExecuteCommandAsync();
                            }
                            return result.Id.ToString();
                        }
                    }
                    else if(type == 2)
                    {
                        var fansid = wxfansid.Value.ToString();
                        var result = await dbClient.Queryable<YB_ScanResult>().Where(x => x.FansId == fansid && x.PublicId == appid)
                            .OrderBy(x => x.CreateTime, SqlSugar.OrderByType.Desc)
                            .FirstAsync()
                            ;
                        //如果计费
                        if (result != null && result.Subscribe == 0)
                        {
                            //更新关注记录
                            await dbClient.Updateable<YB_ScanResult>().SetColumns(x => new YB_ScanResult
                            {
                                Subscribe = subscribe,
                                TakeTime = DateTime.Now
                            }).Where(x => x.Id == result.Id).ExecuteCommandAsync();
                            if(subscribe == 1)
                            {
                                //更新订单
                                await dbClient.Updateable<YB_Order>().SetColumns(x => new YB_Order
                                {
                                    RealCount = x.RealCount + 1,
                                    DayRealCount = x.DayRealCount + 1
                                }).Where(x => x.Id == result.OrderId).ExecuteCommandAsync();

                                //更新设备数据
                                await dbClient.Updateable<YB_EquRealData>().SetColumns(x => new YB_EquRealData
                                {
                                    TodayRealCnt = x.TodayRealCnt + 1,
                                    TotalRealCnt = x.TotalRealCnt + 1
                                }).Where(x => x.Id == result.EquId).ExecuteCommandAsync();

                                //更新商户数据
                                await dbClient.Updateable<YB_BusinessRealData>().SetColumns(x => new YB_BusinessRealData
                                {
                                    TodayRealCnt = x.TodayRealCnt + 1,
                                    TotalRealCnt = x.TotalRealCnt + 1
                                }).Where(x => x.BusinessId == result.BusinessId).ExecuteCommandAsync();
                            }
                            return result.Id.ToString();
                        }
                    }
                }
                else
                {
                    if (await dbClient.Queryable<YB_WXFansExt>().AnyAsync(x => x.AppId == appid && x.OpenId == openid))
                    {
                        await dbClient.Updateable<YB_WXFansExt>().SetColumns(x => new YB_WXFansExt
                        {
                            Subscribe = subscribe,
                            UnSubscribeTime = DateTime.Now
                        }).Where(x => x.AppId == appid && x.OpenId == openid).ExecuteCommandAsync();
                    }
                    if(await dbClient.Queryable<YB_WifiBind>().AnyAsync(x=>x.PublicId == appid && x.OpenId == openid))
                    {
                        await dbClient.Updateable<YB_WifiBind>().SetColumns(x => new YB_WifiBind {
                            Subscribe=subscribe
                        }).Where(x => x.PublicId == appid && x.OpenId == openid).ExecuteCommandAsync();
                    }
                }
                return null;
            }
        }
        /// <summary>
        /// 处理关键字回复事件
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="openid"></param>
        /// <param name="encode">关键字</param>
        public async Task<WXTextResponseData> HandlerTextAsync(string appid, string openid, string encode)
        {
            WXTextResponseData returndata = new WXTextResponseData();
            using (var dbClient = ReadDbContext.GetInstance())
            {
                //检查健康码是否存在
                var data = await dbClient.Queryable<YB_WXMessage>().FirstAsync(x => x.EnCode == encode);
                if (data != null)
                {
                    //如果是固定贴纸二维码
                    if (data.Type == 2)
                    {
                        //更新扫码关注记录
                        var resultid = Guid.Parse(data.ResultId);
                        returndata.wxfansid = (await dbClient.Queryable<YB_ScanResult>().FirstAsync(x => x.Id == resultid)).FansId;
                        returndata.type = data.Type;
                        returndata.resultid = data.ResultId;
                    }
                    else
                    {
                        var resultid = Guid.Parse(data.ResultId);
                        returndata.wxfansid = (await dbClient.Queryable<YB_ScanResult>().FirstAsync(x => x.Id == resultid)).FansId;
                        returndata.type = data.Type;
                        returndata.resultid = data.ResultId;
                    }
                    //更新wxfansext
                    if (await dbClient.Queryable<YB_WXFansExt>().AnyAsync(x => x.AppId == appid && x.OpenId == openid))
                    {
                        await dbClient.Updateable<YB_WXFansExt>().SetColumns(x => new YB_WXFansExt
                        {
                            Subscribe = 1,
                            SubscribeTime = DateTime.Now
                        }).Where(x => x.AppId == appid && x.OpenId == openid).ExecuteCommandAsync();
                    }
                    else
                    {
                        var fansdata = new YB_WXFansExt
                        {
                            AppId = appid,
                            OpenId = openid,
                            ResultId = Guid.Parse(returndata.wxfansid),
                            Subscribe = 1,
                            SubscribeTime = DateTime.Now
                        };
                        await dbClient.Insertable(fansdata).ExecuteCommandAsync();
                    }
                }
                return returndata;
            }
        }

        /// <summary>
        /// 获取微信图文
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="openid"></param>
        /// <param name="fansid"></param>
        /// <param name="type">1-认证的服务号关注事件,2-认证的服务号扫码事件,3-非认证关注事件,4-回复关键字,5-第一次打开落地页,6-非认证扫码事件</param>
        /// <param name="resultid">记录ID</param>
        /// <returns></returns>
        public List<Article> GetWXMessageNews(string appid, string openid, string fansid, int type, string resultid = null)
        {
            var apiurl = Configs.GetString("APIURL");
            var url = HttpUtility.HtmlEncode($"{apiurl}/qr/s?openid={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(openid))}&aid={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(appid))}&fansid={fansid}&type={type}&rid={resultid}")
                    .Replace("&amp;", "&");
            var result = new List<Article>();
            var art = new Article
            {
                Title = "Hi~点击查看您的健康测量报告！",
                Description = "邀你查看报告详情",
                PicUrl = "",
                Url = url
            };
            result.Add(art);
            return result;
        }
        /// <summary>
        /// 获取固定贴纸图文信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="openid"></param>
        /// <param name="fansid"></param>
        /// <param name="type">1-认证的服务号关注事件,2-认证的服务号扫码事件,3-非认证关注事件,4-回复关键字,5-第一次打开落地页,6-非认证扫码事件</param>
        /// <param name="resultid">记录ID</param>
        /// <returns></returns>
        public List<Article> GetStickyWXMessageNews(string appid, string openid, string fansid, int type, Guid? resultid = null)
        {
            var apiurl = Configs.GetString("APIURL");
            var url = HttpUtility.HtmlEncode($"{apiurl}/qr/t?openid={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(openid))}&aid={Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(appid))}&fansid={fansid}&type={type}&rid={resultid}")
                    .Replace("&amp;", "&");
            var result = new List<Article>();
            var art = new Article
            {
                Title = "Hi~点击查看您的健康测量报告！",
                Description = "邀你查看报告详情",
                PicUrl = "",
                Url = url
            };
            result.Add(art);
            return result;
        }
    }
}
