using Nirvana.Common;
using Nirvana.Common.ApiBase;
using Nirvana.Data;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using Senparc.Weixin.Open;
using Senparc.Weixin.Open.Containers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.NApi.DBServices
{
    /// <summary>
    /// 扫码订单处理
    /// </summary>
    public partial class OrderApp : WebBaseApp
    {
        /// <summary>
        /// 获取可用的订单
        /// </summary>
        /// <param name="equ">设备信息</param>
        /// <param name="height">身高,CM</param>
        /// <param name="weight">体重,KG</param>
        /// <param name="imp">阻抗</param>
        /// <param name="time">测量时间</param>
        /// <param name="userinfo">用户资料</param>
        /// <param name="isdefault">是否取默认订单,0-否,1-是</param>
        public async Task<OrderInfo> GetAsync(YB_Device equ, decimal height, decimal weight, decimal imp, DateTime time, OAuthUserInfo userinfo, int isdefault = 1)
        {
            try
            {
                using (var dbClient = ReadDbContext.GetInstance())
                {
                    //检查设备绑定的订单
                    var orderlist = (await dbClient.Ado.UseStoredProcedure().GetDataTableAsync("PROC_GetScanOrder", new
                    {
                        equid = equ.Id,
                        fansid = userinfo.unionid,
                        isdefault = isdefault
                    })).ToList<YB_Order>();
                    if (orderlist.Count == 0)
                    {
                        return null;
                    }
                    //返回取出的订单,如果订单id为1,则为系统默认关注公众号的订单,如果订单id为2,则为系统默认的打开链接的订单
                    var order = orderlist.FirstOrDefault();
                    var returndata = new OrderInfo
                    {
                        id = order.Id,
                        type = order.Type
                    };
                    //如果是关注公众号
                    string publicid = "";
                    if (order.Type == (int)OrderType.Office)
                    {
                        var office = await dbClient.Queryable<YB_OfficlaAccount>().Where(x => x.authorizer_appid == order.Url && x.type == 1).FirstAsync();
                        if (office == null)
                        {
                            returndata.code = (int)ErrorInfoDesc.wxinfoerror;
                            return returndata;
                        }
                        publicid = office.user_name;
                        //如果是认证的服务号
                        if (office.service_type_info == ServiceType.服务号.ToString()
                            && office.verify_type_info == VerifyType.微信认证.ToString())
                        {
                            //带参二维码格式:yb1|fansid
                            var sceneid = $"yb1|{userinfo.unionid}";
                            var token = await AuthorizerContainer.TryGetAuthorizerAccessTokenAsync(componentAppid, office.authorizer_appid);
                            var qrresult = await QrCodeApi.CreateAsync(token, 10000, 0, QrCode_ActionName.QR_STR_SCENE, sceneid);
                            if (qrresult.ErrorCodeValue != 0)
                            {
                                returndata.code = (int)ErrorInfoDesc.ercodeerror;
                                return returndata;
                            }
                            returndata.officetype = (int)OfficeType.RZFW;
                            returndata.content = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={qrresult.ticket}";
                        }
                        else if (office.service_type_info == "个人")
                        {
                            //个人回复由第三方插件自动回复
                            returndata.officetype = (int)OfficeType.FRZ;
                            returndata.content = $"{WXURL}/open/qr/{office.user_name}.jpg";
                        }
                        else
                        {
                            returndata.officetype = (int)OfficeType.GR;
                            returndata.vrcode = new Random().Next(100000, 999999).ToString().Substring(1, 4);
                            returndata.content = $"{WXURL}/open/qr/{office.user_name}.jpg";

                        }
                    }
                    else if (order.Type == (int)OrderType.URL)
                    {
                        returndata.content = order.Url;
                    }
                    else
                    {
                        returndata.code = (int)ErrorInfoDesc.develop;
                        return returndata;
                    }
                    //保存记录
                    await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("proc_saveresult", new
                    {
                        vrcode = "",
                        weight = weight,
                        height = height,
                        imp = imp,
                        fansid = userinfo.unionid.ToStr(),
                        oldopenid = userinfo.openid,
                        equid = equ.Id,
                        ecode = equ.Ecode,
                        facecode = equ.FacCode,
                        orderid = order.Id,
                        businessid = equ.BusinessId,
                        publicid = publicid,
                        headimgurl = userinfo.headimgurl.ToStr(),
                        nickname = userinfo.nickname.ToStr(),
                        sex = userinfo.sex,
                        city = userinfo.city.ToStr(),
                        province = userinfo.province.ToStr(),
                        country = userinfo.country.ToStr(),
                        language = "",
                        ordertype = order.Type,
                        resulttime = DateTime.Now
                    });
                    return returndata;
                }
            }
            catch (Exception ex)
            {
                //写入异常日志
                var param = $"equ={equ.ToJson()},height={height},weight={weight},imp={imp},time={time},userinfo={userinfo.ToJson()},isdefault={isdefault}";
                new LoggerApp().InsertErrorLog(ex, param, "获取订单");
                return new OrderInfo
                {
                    code = (int)ErrorInfoDesc.systemerror
                };
            }
        }
        /// <summary>
        /// 获取可用的订单
        /// </summary>
        /// <param name="equ">设备信息</param>
        /// <param name="userinfo">用户资料</param>
        /// <param name="isdefault">是否取默认订单,0-否,1-是</param>
        /// <returns></returns>
        public async Task<OrderInfo> GetAsync(YB_Device equ, OAuthUserInfo userinfo, int isdefault = 1)
        {
            try
            {
                using (var dbClient = ReadDbContext.GetInstance())
                {
                    //检查设备绑定的订单
                    var orderlist = (await dbClient.Ado.UseStoredProcedure().GetDataTableAsync("PROC_GetScanOrder", new
                    {
                        equid = equ.Id,
                        fansid = userinfo.unionid,
                        isdefault = isdefault
                    })).ToList<YB_Order>();
                    if (orderlist.Count == 0)
                    {
                        return null;
                    }
                    //返回取出的订单,如果订单id为1,则为系统默认关注公众号的订单,如果订单id为2,则为系统默认的打开链接的订单
                    var order = orderlist.FirstOrDefault();
                    var returndata = new OrderInfo
                    {
                        id = order.Id,
                        type = order.Type
                    };
                    //如果是关注公众号
                    string publicid = "";
                    if (order.Type == (int)OrderType.Office)
                    {
                        var office = await dbClient.Queryable<YB_OfficlaAccount>().Where(x => x.authorizer_appid == order.Url && x.type == 1).FirstAsync();
                        if (office == null)
                        {
                            returndata.code = (int)ErrorInfoDesc.wxinfoerror;
                            return returndata;
                        }
                        publicid = office.user_name;
                        //如果是认证的服务号
                        if (office.service_type_info == ServiceType.服务号.ToString()
                            && office.verify_type_info == VerifyType.微信认证.ToString())
                        {
                            //带参二维码格式:yb#设备id#粉丝唯一标识
                            var sceneid = $"yb#1#{equ.Id}#{userinfo.unionid}";
                            var token = await AuthorizerContainer.TryGetAuthorizerAccessTokenAsync(componentAppid, office.authorizer_appid);
                            var qrresult = await QrCodeApi.CreateAsync(token, 10000, 0, QrCode_ActionName.QR_STR_SCENE, sceneid);
                            if (qrresult.ErrorCodeValue != 0)
                            {
                                returndata.code = (int)ErrorInfoDesc.ercodeerror;
                                return returndata;
                            }
                            returndata.officetype = (int)OfficeType.RZFW;
                            returndata.content = $"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket={qrresult.ticket}";
                        }
                        else if (office.service_type_info == "个人")
                        {
                            //个人回复由第三方插件自动回复
                            returndata.officetype = (int)OfficeType.FRZ;
                            returndata.content = $"{WXURL}/open/qr/{office.user_name}.jpg";
                        }
                        else
                        {
                            returndata.officetype = (int)OfficeType.GR;
                            returndata.vrcode = new Random().Next(100000, 999999).ToString().Substring(1, 4);
                            returndata.content = $"{WXURL}/open/qr/{office.user_name}.jpg";

                        }
                    }
                    else if (order.Type == (int)OrderType.URL)
                    {
                        returndata.content = order.Url;
                    }
                    else
                    {
                        returndata.code = (int)ErrorInfoDesc.develop;
                        return returndata;
                    }
                    //保存记录
                    await dbClient.Ado.UseStoredProcedure().ExecuteCommandAsync("proc_body_binduser", new
                    {
                        fansid = userinfo.unionid.ToStr(),
                        oldopenid = userinfo.openid,
                        equid = equ.Id,
                        ecode = equ.Ecode,
                        facecode = equ.FacCode,
                        orderid = order.Id,
                        businessid = equ.BusinessId,
                        publicid = publicid,
                        headimgurl = userinfo.headimgurl.ToStr(),
                        nickname = userinfo.nickname.ToStr(),
                        sex = userinfo.sex,
                        city = userinfo.city.ToStr(),
                        province = userinfo.province.ToStr(),
                        country = userinfo.country.ToStr(),
                        language = "",
                        ordertype = order.Type
                    });
                    return returndata;
                }
            }
            catch (Exception ex)
            {
                //写入异常日志
                var param = $"equ={equ.ToJson()},userinfo={userinfo.ToJson()},isdefault={isdefault}";
                new LoggerApp().InsertErrorLog(ex, param, "获取订单");
                return new OrderInfo
                {
                    code = (int)ErrorInfoDesc.systemerror
                };
            }
        }

        /// <summary>
        /// 设备状态描述
        /// </summary>
        /// <param name="status">设备状态</param>
        /// <returns></returns>
        private string EquStatusMsg(int status)
            => (status) switch
            {
                _ when status == (int)DeviceStatus.Stop => "设备已停止运行",
                _ when status == (int)DeviceStatus.UnActive => "设备还未激活",
                _ => "正常运行"
            };

        /// <summary>
        /// 获取设备
        /// </summary>
        /// <param name="ecode"></param>
        /// <returns></returns>
        public async Task<DeviceAndTypeModel> GetEquAsync(string ecode)
        {
            using (var dbClient = ReadDbContext.GetInstance())
            {
                var data = await dbClient.Queryable<YB_Device>().FirstAsync(x => x.Ecode == ecode);
                var types =  await dbClient.Queryable<YB_DeviceType>().ToListAsync();
                return new DeviceAndTypeModel
                {
                    equ = data,
                    types = types
                };
            }
        }
    }
}
