using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using Domain;

namespace Dao.Implement
{
    public class SysOauth2Repository : RepositoryBase<SysOauth2>, ISysOauth2Repository
    {
        public IQueryable<SysOauth2> LoadAllByPage(out long total, int page, int rows, string order, string sort)
        {
            var list = this.LoadAll();
            total = list.LongCount();
            list = list.OrderBy(sort + " " + order);
            list = list.Skip((page - 1) * rows).Take(rows);
            return list;
        }

        public SysOauth2 Get(string code)
        {
            return LoadAll().Where(r => r.Code == code).OrderByDescending(r => r.ID).FirstOrDefault();
        }

        public SysOauth2 GetByRefreshToken(string refreshToken)
        {
            return LoadAll().Where(r => r.RefreshToken == refreshToken).OrderByDescending(r => r.ID).FirstOrDefault();
        }
        /// <summary>
        /// 获取小度token统一接口
        /// </summary>
        /// <returns></returns>
        public string GetXiaoDuToken()
        {
            var sysOauth2 = LoadAll().Where(r => r.RedirectUri == "https://dueros.baidu.com/business/oauth/v2/token").OrderByDescending(r => r.ID).FirstOrDefault();
            if (sysOauth2 == null || sysOauth2.CreatedDate < DateTime.Now)
            {
                Common.XiaoDuError error = Common.XiaoDuOperation.GetXiaoDuAccessToken();
                if (null != error && error.errno == 0)
                {
                    if (sysOauth2 == null)
                    {
                        sysOauth2 = new SysOauth2()
                        {
                            Code = "1001BLWXiaoDu",
                            RedirectUri = "https://dueros.baidu.com/business/oauth/v2/token",
                            Account = "system"
                        };
                    }
                    sysOauth2.AccessToken = error.data.access_token;
                    sysOauth2.RefreshToken = error.data.refresh_token;
                    sysOauth2.ExpiresIn = error.data.expires_in;
                    sysOauth2.CreatedDate = Common.TimeHelper.ToDateTime(error.data.deadline);

                    SaveOrUpdate(sysOauth2);

                    return sysOauth2.AccessToken;
                }
                else
                {
                    return "";
                }
            }
            return sysOauth2.AccessToken;
        }
    }
}
