<repo_name>shouchangfayi/mvc<file_sep>/Mvc.Web.Android/Controllers/BookController.cs
﻿using Mvc.Web.Android.Helper;
using Mvc.Web.Android.Models.Book;
using NapiService;
using NapiService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class BookController : BaseController
    {
        #region MyRegion
        /// <summary>
        /// BookService
        /// </summary>
        BookService _bookservice = new BookService();

        /// <summary>
        /// 首本书说明
        /// </summary>
        string _fristinfo = "";
        #endregion

        #region 主页面
        /// <summary>
        /// 精品页(主页)
        /// </summary>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 免费页
        /// </summary>
        public ActionResult MianFei()
        {
            return View();
        }

        /// <summary>
        /// 榜单页
        /// </summary>
        public ActionResult Bank()
        {
            return View();
        }

        /// <summary>
        /// 出版页
        /// </summary>
        public ActionResult Publish()
        {
            return View();
        }

        /// <summary>
        /// 猜你喜欢页
        /// </summary>
        public ActionResult GuessLike()
        {
            return View();
        }

        /// <summary>
        /// 更多精品页
        /// </summary>
        public ActionResult MoreJingPin(int type = (int)RecommendClass.Fine, int sort = (int)SearchSort.VipSameDayDescAndUpdateTimeDesc)
        {
            int[] types = { type, sort };
            return View(types);
        }

        /// <summary>
        /// 分类页
        /// </summary>
        /// <returns></returns>
        public ActionResult Category(int Type = (int)CategoryClass.None,int Sort=(int)CategorySort.New )
        {
            var model = new CategoryModel();
            model.Type = (CategoryClass)Type;
            model.Sort = (CategorySort)Sort;
            return View(model);
        }

        /// <summary>
        /// 专题页
        /// </summary>
        /// <returns></returns>
        public ActionResult ZhuanTi()
        {
            return View();
        }
        #endregion

        #region 部分视图页面
        /// <summary>
        /// 效果视图1
        /// </summary>
        public ActionResult GetEffectRecommend(int count, int maxcount, int recommendType)
        {
            try
            {
                var booksearchlist = _bookservice.GetEffectRecommendtion((RecommendClass)recommendType, count, maxcount, out _fristinfo);
                if (booksearchlist.Count == 0)
                    return new EmptyResult();
                return PartialView("_PartEffectList", new Tuple<List<Booksearch>, string, int>(booksearchlist, _fristinfo.ShortIntro(40), 0));
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 效果视图(没有图片)
        /// </summary>
        public ActionResult GetEffectRecommendNoImg(int count, int effecttype)
        {
            try
            {
                var bookeffectlist = _bookservice.GetEffects(effecttype, count, out _fristinfo);
                if (bookeffectlist.Count == 0)
                    return new EmptyResult();
                return PartialView("_PartEffectNoImgList", bookeffectlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 效果视图2
        /// </summary>
        public ActionResult GetEffect(int count, int effecttype)
        {
            try
            {
                var bookeffectlist = _bookservice.GetEffects(effecttype, count, out _fristinfo);
                if (bookeffectlist.Count == 0)
                    return new EmptyResult();
                return PartialView("_PartEffectList", new Tuple<List<Bookeffect>, string, int>(bookeffectlist, _fristinfo.ShortIntro(40), 1));
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 效果视图(只有图片)
        /// </summary>
        public ActionResult GetEffectImg(int count, int effecttype)
        {
            try
            {
                var bookeffectlist = _bookservice.GetEffects(effecttype, count, out _fristinfo);
                if (bookeffectlist.Count == 0)
                    return new EmptyResult();
                bookeffectlist = bookeffectlist.OrderBy(x => System.Guid.NewGuid()).ToList();
                return PartialView("_PartEffectImgList", bookeffectlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 榜单视图
        /// </summary>
        public ActionResult GetRankings(int rankingtype, int index, int size)
        {
            try
            {
                var total = 0;
                var booksearchlist = _bookservice.GetRankings((NapiService.RankingClass)rankingtype, index, size, out total);
                if (booksearchlist.Count == 0)
                    return new EmptyResult();
                ViewBag.rankingtype = rankingtype;
                ViewBag.rankindex = index;
                ViewBag.ranktotal = total;
                return PartialView("_PartRankingsList", booksearchlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 分类视图
        /// </summary>
        public ActionResult GetCategoryView(int classid = (int)CategoryClass.None, int sort = (int)CategorySort.New, int index = 0, int size = 10)
        {
            try
            {
                ViewBag.IsShow = false;
                var obj = new SearchObject();
                switch (classid)
                {
                    case (int)CategoryClass.None: ViewBag.IsShow = true; break;
                    case (int)CategoryClass.Monthly: ViewBag.IsShow = true; classid = (int)CategoryClass.None; obj.IsMonthly = true; break;
                }
                switch (sort)
                {
                    case (int)CategorySort.Free: sort = (int)CategorySort.Hot; obj.IsClientFree = true; break;
                    case (int)CategorySort.SpecialOffer: sort = (int)CategorySort.Hot; obj.IsSpecialoffer = true; break;
                    case (int)CategorySort.Finished: sort = (int)CategorySort.Hot; obj.Status = SearchBookStatus.Finished; break;
                }

                obj.Class = (SearchClass)classid;
                obj.Sort = (SearchSort)sort;
                obj.Index = index;
                obj.Size = size;

                var total = 0;
                var booksearchlist = _bookservice.Search(obj, out total);
                if (total == 0 || booksearchlist.Count == 0)
                    return new EmptyResult();
                ViewBag.total = total;
                ViewBag.size = size;
                return PartialView("_PartCategoryList", booksearchlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 猜你喜欢部分视图
        /// </summary>
        /// <param name="count"></param>
        /// <param name="effecttype"></param>
        /// <returns></returns>
        public ActionResult GetGuessLikeView(int count, int effecttype)
        {
            try
            {
                var bookeffectlist = _bookservice.GetEffects(effecttype, count, out _fristinfo);
                if (bookeffectlist.Count == 0)
                    return new EmptyResult();
                return PartialView("_PartGuessLikeList", bookeffectlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 更多精品部分视图
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public ActionResult GetMoreJingPinView(int type = (int)RecommendClass.Fine, int sort = (int)SearchSort.VipSameDay_Desc, int index = 0, int size = 10)
        {
            try
            {
                var obj = new SearchObject();
                switch ((RecommendClass)type)
                {
                    case RecommendClass.Finished: obj.Status = SearchBookStatus.Finished; break;
                    case RecommendClass.Ancient: obj.Class = SearchClass.Aerial | SearchClass.History | SearchClass.PassThrough; break;
                    case RecommendClass.Modern: obj.Class = SearchClass.Urban | SearchClass.Youth | SearchClass.PowerfulFamily; break;
                    case RecommendClass.Occult: obj.Class = SearchClass.Ability | SearchClass.Magical | SearchClass.Occult; break;
                    case RecommendClass.Free: obj.IsClientFree = true; break;
                }

                obj.Sort = (SearchSort)sort;
                obj.Index = index;
                obj.Size = size;

                var total = 0;
                var booksearchlist = _bookservice.Search(obj, out total);
                if (total == 0 || booksearchlist.Count == 0)
                    return new EmptyResult();
                ViewBag.total = total;
                ViewBag.size = size;
                return PartialView("_PartMoreJingPinList", booksearchlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }

        /// <summary>
        /// 出版部分视图
        /// </summary>
        /// <param name="type"></param>
        /// <param name="sort"></param>
        /// <param name="index"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public ActionResult GetPublishView(int type = (int)RecommendClass.Fine, int sort = (int)SearchSort.VipSameDay_Desc, int index = 0, int size = 10)
        {
            try
            {
                var obj = new SearchObject();
                switch ((RecommendClass)type)
                {
                    case RecommendClass.Finished: obj.Status = SearchBookStatus.Finished; break;
                    case RecommendClass.Ancient: obj.Class = SearchClass.Aerial | SearchClass.History | SearchClass.PassThrough; break;
                    case RecommendClass.Modern: obj.Class = SearchClass.Urban | SearchClass.Youth | SearchClass.PowerfulFamily; break;
                    case RecommendClass.Occult: obj.Class = SearchClass.Ability | SearchClass.Magical | SearchClass.Occult; break;
                    case RecommendClass.Free: obj.IsClientFree = true; break;
                }

                obj.Sort = (SearchSort)sort;
                obj.Index = index;
                obj.Size = size;

                var total = 0;
                var booksearchlist = _bookservice.Search(obj, out total);
                if (total == 0 || booksearchlist.Count == 0)
                    return new EmptyResult();
                ViewBag.total = total;
                ViewBag.size = size;
                return PartialView("_PartMoreJingPinList", booksearchlist);
            }
            catch (Exception e)
            {
                return new EmptyResult();
            }
        }
        #endregion
    }
}
<file_sep>/Mvc.Web.Android/Controllers/HomeController.cs
﻿using Mvc.Web.Android.Helper;
using Mvc.Web.Android.Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class HomeController : BaseController
    {
        /// <summary>
        /// 首页入口
        /// </summary>
        public ActionResult Index()
        {
            return RedirectToAction("Index","Book");
        }
    }
}
<file_sep>/Mvc.Web.Android/Settings/SiteSettings.cs
﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;

namespace Mvc.Web.Android.Settings
{
    /// <summary>
    /// 网站设置信息
    /// </summary>
    public static class SiteSettings
    {
        /// <summary>
        /// 客户端免费作品功能
        /// </summary>
        public static int FreeBookON = ConfigurationManager.AppSettings["FreeBookON"].To<int>();
        /// <summary>
        /// 渠道号
        /// </summary>
        public static int SubscribeChannel = ConfigurationManager.AppSettings["SubscribeChannel"].To<int>(1);
        /// <summary>
        /// 充值渠道号
        /// </summary>
        public static Dictionary<string, string> PayChannel
        {
            get
            {
                var channels = new Dictionary<string, string>();
                var items = ConfigurationManager.AppSettings["PayChannels"].To<string>(string.Empty).Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in items)
                {
                    var arr = item.Split(new[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    if (arr.Length == 2)
                    {
                        channels.Add(arr[0], arr[1]);
                    }
                }
                return channels;
            }
        }
    }
}<file_sep>/Mvc.Web.Android/Core/LoginAuthorizeAttribute.cs
﻿using NapiService;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android
{
    /// <summary>
    /// 用户登陆验证
    /// </summary>
    public partial class LoginAuthorizeAttribute : AuthorizeAttribute
    {
        private const string DEFAULT_LOGIN_URL = "/Member/Login";
        private const string DEFAULT_COOKIE_KEY = "USER_FLAG";
        private string _Url = string.Empty;
        private string _Key = string.Empty;

        public LoginAuthorizeAttribute()
        {
            _Url = ConfigurationManager.AppSettings["LoginUrl"];
            _Key = ConfigurationManager.AppSettings["LoginKey"];

            if (string.IsNullOrEmpty(_Url))
            {
                _Url = DEFAULT_LOGIN_URL;
            }

            if (string.IsNullOrEmpty(_Key))
            {
                _Key = DEFAULT_COOKIE_KEY;
            }
        }

        public LoginAuthorizeAttribute(string url)
            : this()
        {
            _Url = url;
        }

        public LoginAuthorizeAttribute(string url, string key)
            : this(url)
        {
            _Key = key;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            else
            {
                if (!filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true) && 
                    !filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
                {
                    string value = string.Empty;
                    HttpCookie cookie = filterContext.HttpContext.Request.Cookies[_Key];
                    if (cookie != null)
                    {
                        value = WebHelper.Decrypt(cookie.Value);
                    }

                    if (string.IsNullOrWhiteSpace(value))
                    {
                        filterContext.HttpContext.Response.Redirect(_Url + "?referer=" + filterContext.HttpContext.Request.RawUrl);
                        //filterContext.Result = new RedirectResult(_Url + "?referer=" + filterContext.HttpContext.Request.RawUrl);
                    }
                }
            }
        }
    }
}<file_sep>/Mvc.Web.Android/Controllers/MemberController.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class MemberController : Controller
    {
        /// <summary>
        /// 用户登录
        /// <para>@referer:跳转Url</para>
        /// </summary>
        public ActionResult Login(string referer)
        {
            if (!string.IsNullOrWhiteSpace(referer))
                ViewBag.RefererUrl = referer;
            return View();
        }

        /// <summary>
        /// 用户注册
        /// <para>@referer:跳转Url</para>
        /// </summary>
        public ActionResult Register(string referer)
        {
            if (!string.IsNullOrWhiteSpace(referer))
                ViewBag.RefererUrl = referer;
            return View();
        }

        /// <summary>
        /// 找回密码
        /// <para>@referer:跳转Url</para>
        /// </summary>
        public ActionResult FindPassword(string referer)
        {
            if (!string.IsNullOrWhiteSpace(referer))
                ViewBag.RefererUrl = referer;
            return View();
        }

        public MemberController()
        {
            ViewBag.RefererUrl = "/";
        }
    }
}<file_sep>/Mvc.Web.Android/Controllers/MasterController.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    /// <summary>
    /// 母版页
    /// </summary>
    public class MasterController : BaseController
    {
        /// <summary>
        /// 设置（版本，设备ID）
        /// </summary>
        public ActionResult SettingsCommon()
        {
            return PartialView();
        }

        /// <summary>
        /// 宣传
        /// </summary>
        public ActionResult XuanChuan()
        {
            if (ViewBag.User.ID == 0)
                return new EmptyResult();
            if (IsNewMember())
                return PartialView();

            return new EmptyResult();
        }
    }
}
<file_sep>/Mvc.Web.Android/Scripts/index.js
﻿$(document).ready(function () {

    (function ($) {
        $('.tab ul.tabs').addClass('active').find('> a:eq(0)').addClass('current');

        //$('.tab ul.tabs li a').on("touchstart", function (g) {

        //    var tab = $(this).closest('.tab'),
		//		index = $(this).closest('a').index();

        //    $('ul.tabs > li > a').removeClass('current');
        //    $(this).addClass('current');

        //    tab.find('.tab_content').find('div.tabs_item').not('div.tabs_item:eq(' + index + ')').hide();
        //    tab.find('.tab_content').find('div.tabs_item:eq(' + index + ')').show();

        //    g.preventDefault();
        //});

        $('.tab ul.tabs li a').tap(function (g) {
            var tab = $(this).closest('.tab'),
				index = $('.tab ul.tabs li a').index($(this));// $(this).closest('a').index()

            $('ul.tabs > li > a').removeClass('current');
            $(this).addClass('current');

            tab.find('.tab_content').find('div.tabs_item').not('div.tabs_item:eq(' + index + ')').hide();
            tab.find('.tab_content').find('div.tabs_item:eq(' + index + ')').show();

            g.preventDefault();
        });
    })(jQuery);
});<file_sep>/Mvc.Web.Android/Models/HttpResultModel.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mvc.Web.Android.Models
{
    /// <summary>
    /// Http响应结果 
    /// </summary>
    public partial class HttpResponseModel
    {
        /// <summary>
        /// 响应Code
        /// </summary>
        public int Code = 0;
        /// <summary>
        /// 响应信息
        /// </summary>
        public string Message = string.Empty;
        /// <summary>
        /// 响应数据
        /// </summary>
        public Object Data = default(Object);
        /// <summary>
        /// 附加数据
        /// </summary>
        public Object Attachments = default(Object);
    }
}<file_sep>/Mvc.Web.Android/Controllers/BaseController.cs
﻿using Mvc.Web.Android.Models;
using NapiService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Mvc.Web.Android.Controllers
{
    public class BaseController : Controller
    {
        /// <summary>
        /// MemberService
        /// </summary>
        public NapiService.MemberService _memberService = new NapiService.MemberService();

        /// <summary>
        /// MemberTags
        /// </summary>
        public MemberTagsModel _memberTags = new MemberTagsModel();

        /// <summary>
        /// 初始化
        /// </summary>
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            var value = WebHelper.GetCookie("USER_FLAG");

            if (!string.IsNullOrEmpty(value))
            {
                value = WebHelper.Decrypt(value);
                var memberTags = WebHelper.Json<MemberTagsModel>(value);

                if (memberTags != null && !string.IsNullOrEmpty(memberTags.Password))
                    _memberTags = WebHelper.Json<MemberTagsModel>(value);
            }
            ViewBag.User = _memberTags;
        }

        /// <summary>
        /// 是否是新用户
        /// </summary>
        /// <returns></returns>
        public bool IsNewMember()
        {
            string key = "MEMBER_FLAG_VALUE";

            string userFlag = WebHelper.GetCookie(key);
            if (userFlag == "1")
                return false;

            bool result = _memberService.IsCharged(_memberTags.ID, this.DeviceNumber);

            if (!result)
                WebHelper.SetCookie(key, "1", 60 * 24 * 900);

            return result;

        }

        /// <summary>
        /// 前往登录
        /// </summary>
        public void Login()
        {
            string returnUrl = Request.Url.OriginalString;

            Response.Redirect("Member?referer=" + HttpUtility.UrlEncode(returnUrl));
        }

        /// <summary>
        /// 设备号
        /// </summary>
        public string DeviceNumber
        {
            get
            {
                //return SiteHelper.DESDecode(WebHelper.GetCookie("AUTH_ID"), CONTENT_KEY);
                return WebHelper.Decrypt(WebHelper.GetCookie("AUTH_ID"));
            }
        }

        /// <summary>
        /// 版本号
        /// </summary>
        public double Version
        {
            get
            {
                return WebHelper.Decrypt(WebHelper.GetCookie("VerXxsy")).To<double>();
            }
        }

        /// <summary>
        /// 设置价格(2015-01-01 开始注册的用户按签字5分)
        /// </summary>
        /// <param name="oldPrice"></param>
        /// <returns></returns>
        //public int SetPayment(int oldPrice)
        //{

        //    int price = oldPrice;

        //    DateTime startTime = DateTime.Parse(SiteSettings.ChangePriceDate);
        //    DateTime setTime = DateTime.Parse("2015-01-01 00:00:00");
        //    DateTime now = DateTime.Now;

        //    if (now >= startTime)
        //    {

        //        int newPrice = (int)((oldPrice / 1.5) * 2.5);

        //        if (ViewBag.UserID == 0)
        //            return newPrice;

        //        if (SiteSettings.MaxUserId > 0)
        //        {

        //            if (ViewBag.UserID > SiteSettings.MaxUserId)
        //                price = newPrice;

        //        }
        //        else
        //        {

        //            int source = 0;
        //            if (now < setTime.AddMinutes(5))
        //                source = 1;

        //            NapiService.Model.Member member = _memberService.GetById(ViewBag.UserID);
        //            DateTime addDate = member.CreateTime;

        //            if (addDate >= setTime)
        //                price = newPrice;

        //        }

        //    }

        //    return price;
        //}

        /// <summary>
        /// 判断是否是指定时间外注册的用户
        /// </summary>
        /// <returns></returns>
        //public bool IsSpecifiedTimeMember()
        //{

        //    bool result = false;

        //    DateTime startTime = DateTime.Parse(SiteSettings.ChangePriceDate);
        //    DateTime setTime = DateTime.Parse("2015-01-01 00:00:00");
        //    DateTime now = DateTime.Now;

        //    if (now >= startTime)
        //    {

        //        if (ViewBag.UserID == 0)
        //            return true;

        //        if (SiteSettings.MaxUserId > 0)
        //        {

        //            if (ViewBag.UserID > SiteSettings.MaxUserId)
        //                result = true;

        //        }
        //        else
        //        {

        //            int source = 0;
        //            if (now < setTime.AddMinutes(5))
        //                source = 1;

        //            NapiService.Model.Member member = _memberService.GetById(ViewBag.UserID);
        //            DateTime addDate = member.CreateTime;

        //            if (addDate >= setTime)
        //                result = true;

        //        }

        //    }

        //    return result;
        //}
    }

    /// <summary>
    /// Nxp专用字典
    /// </summary>
    /// <typeparam name="TKey">键类型</typeparam>
    /// <typeparam name="TValue">值类型</typeparam>
    public partial class NxpDictionary<TKey, TValue> : Dictionary<TKey, TValue>
    {

        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="defValue">默认值</param>
        /// <returns>值</returns>
        public TValue Get(TKey key, TValue defValue = default(TValue))
        {
            if (this.ContainsKey(key))
                return this[key];
            return defValue;
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="defValue">默认值</param>
        /// <returns>int</returns>
        public int GetInt32(TKey key, int defValue = default(int))
        {
            TValue value = Get(key);
            return value.To<int>(defValue);
        }

        /// <summary>
        /// 获取bool
        /// 0-false
        /// 1-true
        /// </summary>
        /// <param name="key">键名</param>
        /// <returns>bool</returns>
        public bool GetBoolean(TKey key)
        {
            TValue value = Get(key);
            return (value.To<int>() == 1);
        }

        /// <summary>
        /// 获取时间
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="defValue">默认值</param>
        /// <returns>DateTime</returns>
        public DateTime GetDateTime(TKey key, DateTime defValue = default(DateTime))
        {
            TValue value = Get(key);
            return value.To<DateTime>(defValue);
        }

        /// <summary>
        /// 获取double
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="defValue">默认值</param>
        /// <returns>double</returns>
        public double GetDouble(TKey key, double defValue = default(int))
        {
            TValue value = Get(key);
            return value.To<double>(defValue);
        }

        /// <summary>
        /// 获取字符串
        /// </summary>
        /// <param name="key">键名</param>
        /// <param name="defValue">默认值</param>
        /// <returns>string</returns>
        public string GetString(TKey key, string defValue = default(string))
        {
            TValue value = Get(key);
            return value.To<string>(defValue);
        }
    }
}
<file_sep>/Mvc.Web.Android/Controllers/VercodeController.cs
﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class VercodeController : BaseController
    {
        /// <summary>
        /// 随机种子
        /// </summary>
        Random _random = new Random((int)DateTime.Now.Ticks);
        /// <summary>
        /// 随机线条数
        /// </summary>
        const int RANDOM_LINE_COUNT = 10;
        /// <summary>
        /// 随机点数
        /// </summary>
        const int RANDOM_PRINT_COUNT = 80;
        /// <summary>
        /// 字体数组
        /// </summary>
        string[] Fonts = new[] { 
            "Helvetica", "Geneva", "Times New Roman", "Courier New", "Arial" 
        };
        /// <summary>
        /// 生成
        /// </summary>
        public ActionResult Index()
        {
            string exp = string.Empty;
            var code = GetRandomCalc(out exp);
            Session["VALIDATE_CODE"] = code;
            CreateImage(exp);
            return new EmptyResult();
        }

        /// <summary>
        /// 随机获取一个加减表达式
        /// </summary>
        /// <returns></returns>
        public int GetRandomCalc(out string exp)
        {
            int value = 0;
            int n1 = 0;
            int n2 = 0;
            string n3 = _random.Next(0, 10) % 2 == 0 ? "+" : "-";

            if (n3 == "+")
            {
                n1 = _random.Next(0, 30);
                n2 = _random.Next(1, 30);
                value = n1 + n2;
            }
            else
            {
                n2 = _random.Next(0, 30);
                while (n1 <= n2) n1 = _random.Next(1, 60);
                value = n1 - n2;
            }

            exp = string.Format("{0}{1}{2}=?"
                , n1, n3, n2);

            return value;
        }


        /// <summary>
        /// 获取随机颜色
        /// </summary>
        public Color GetRandomColor()
        {
            var red = _random.Next(255);
            var green = _random.Next(255);
            var blue = (red + green > 400) ? 0 : 400 - red - green;
            if (blue > 255) blue = 255;
            return Color.FromArgb(red, green, blue);
        }

        /// <summary>
        /// 创建图片
        /// </summary>
        /// <param name="str"></param>
        public void CreateImage(string validateCode)
        {

            int width = validateCode.Length * 30;
            Random rand = new Random();
            Bitmap bmp = new Bitmap(width + validateCode.Length * 3, 50);

            Graphics g = Graphics.FromImage(bmp);
            g.Clear(Color.FromArgb(255, 255, 255));

            DrawLine(g, bmp, RANDOM_LINE_COUNT);
            DrawPrint(bmp, RANDOM_PRINT_COUNT);

            for (int i = 0; i < validateCode.Length; i++)
            {

                Matrix matrix = new Matrix();
                matrix.Shear((float)_random.Next(0, 300) / 1000 - 0.25f, (float)_random.Next(0, 100) / 1000 - 0.05f);
                g.Transform = matrix;
                string str = validateCode.Substring(i, 1);
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, bmp.Width, bmp.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                Point pos = new Point(i * 30 + 1 + rand.Next(3), 1 + rand.Next(5));
                Font font = new Font(Fonts[_random.Next(Fonts.Length - 1)], _random.Next(24, 30), FontStyle.Bold);
                g.DrawString(str, font, brush, pos);
            }

            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, ImageFormat.Png);
            Response.ClearContent();
            Response.ContentType = "image/png";
            Response.BinaryWrite(ms.ToArray());
            g.Dispose();
            bmp.Dispose();
            Response.End();
        }

        /// <summary>
        /// 随机画线
        /// </summary>
        /// <param name="graphics"></param>
        /// <param name="bmp"></param>
        /// <param name="count"></param>
        private void DrawLine(Graphics graphics, Bitmap bmp, int count)
        {
            var rand = new Random((int)DateTime.Now.Ticks);
            for (var i = 0; i < count; i++)
            {
                var x1 = rand.Next(bmp.Width);
                var y1 = rand.Next(bmp.Height);
                var x2 = rand.Next(bmp.Width);
                var y2 = rand.Next(bmp.Height);
                graphics.DrawLine(new Pen(GetRandomColor()), x1, y1, x2, y2);
            }
        }

        /// <summary>
        /// 随机点
        /// </summary>
        /// <param name="graphics"></param>
        /// <param name="bmp"></param>
        /// <param name="count"></param>
        private void DrawPrint(Bitmap bmp, int count)
        {
            for (var i = 0; i < count; i++)
            {
                var x = _random.Next(bmp.Width);
                var y = _random.Next(bmp.Height);
                bmp.SetPixel(x, y, GetRandomColor());
            }
        }
    }
}<file_sep>/Mvc.Web.Android/Script/Site.js
﻿/// <reference path="jQuery.Min.js" />
/// <reference path="JX.js" />

(function () {

    window.Site = {
        /*接口地址*/
        Host: "/Service",
        /*公共操作数*/
        options: {
            codeFlag: 0,
            delay: 60,
            timer: null,
            checkTimer: null
        },
        /*设置窗体标题*/
        _setBoxTitle: function (title) {
            $("#_winbox .win-header span").html(title);
        },
        /*重置窗体Top位置*/
        _resetBoxTop: function (top) {
            $("#_winbox").css({ top: top + "px" });
        },
        /*重置位置*/
        _resetPos: function () {
            var box = $("#_winbox");
            var top = ($(window).height() - box.height()) * 0.4;
            if (top < 0) top = 0;
            box.css({ top: top + "px" });
        },
        /*显示错误信息*/
        showMsg: function (id, message, flag) {
            var color = flag ? "#00F" : "#F00";
            $(id).html('<span style="color:' + color + '">' + message + '</span>');
            setTimeout(function () { $(id).html(""); }, 1500);
        },

        getTalk: function () {
            var s = [
            '亲，还能再送一张么？',
            '作者360°旋转跳跃鞠躬: 亲,还能再送一张么?',
            '作者爱你哟！么么哒！',
            '亲的投票，真真是极好的！',
            '如果在我的生命当中曾经有那张票票出现过，那么其他一切的票票都会成为将就。而我不愿意将就，就是你了~',
            '神马才是潇湘最壕？从今天起坐拥男神后宫！拿起你手中的票票！爱他就宣他宣他！',
            '票虽说少了些，但这份心意，真真是极好的~',
            '亲的投票，真真是极好的！如若能有幸再来一张，本宫便率皇帝陛下来耍个宝给亲看看',
            '亲投票累了吗？来，我煮碗面你吃，吃完继续投~',
            '给我一张票，我将告诉全世界，这个鱼塘被你承包了！',
            '十年修得同船渡，百年修得亲投票！',
            '山无棱，天地合，依旧要开口：亲，再来一张吧！',
            '多不多投，我都在这里不离不弃！',
            '看书容易，投票不易，且投且珍惜！',
            '开文这么久，终于等来了你，亲，再投一张呗\(^o^)/~',
            '终于等到你，还好我没放弃，投票来得好不容易，才会让人更加珍惜',
            '多谢亲的慷慨，大明湖畔的容嬷嬷替作者送个香吻给您~',
            '此文是我开，此字是我写，既然看我书，赶紧投票来！',
            '多订阅少订阅多少都订阅，早来投晚来投早晚都来投。【横批：订阅投票】',
            '亲，我若在你心上，再投一张又何妨？你若在我身旁，每天万更又怎样！',
            '自从得了亲的票，整个人精神多了！',
            '曾经有一张票摆在我面前我没有珍惜,等到失去时才后悔莫及。人生最悲哀的事情莫过于此。如果上天能再给我一次重来的机会,我会说：再给我一张！',
            '谢谢亲的票票，男主表示已经洗白白躺到了床上，请笑纳~',
            '我能想到最浪漫的事，就是你投票来，我狂更',
            '向来缘浅，奈何情深，缘浅的请投一张票！情深的，请再来N张！',
            '我一直很清醒，清醒地看着自己的沉沦 。沉沦在你的票票中！',
            '票票诚可贵，基情价更高；若有土豪在，多少都可抛！',
            '亲的每一张票，在我的心中，都是一句我爱你。',
            '女人，投了票就想走？好好呆在这，我陪你一起看完这本书。',
            '一切不以投票为目的的阅读都是耍流氓！来，再耍一次',
            '如果世界上曾经有那个人出现过，其他人都会变成将就。可我愿意将就在你的投票深情中！',
            '此票终需要一投，或投给你爱的我，或投个爱你的我。',
            '看到你的票票，我只想说：谢谢你爱我，谢谢你出现在我的世界里，谢谢你让我的生命里充满了温暖：可以再来一张吗',
            '我终究没能飙得过那辆宝马，只能眼看着它在夕阳中绝尘而去，不是我的引擎不好，而是我脚蹬子坏了！再投一票吧，好让我尽快换个脚蹬子。',
            '再来一发，看看会出现什么提示？' ];
            var index = Math.floor(Math.random() * s.length);
            return s[index];
        },

        /*显示浮层*/
        showWinbox: function (title, html, cover, goHis) {

            var htm = [];
            htm.push('<div id="_winbox" class="win-box">');
            htm.push('    <div class="win-padding">');
            htm.push('        <div class="win-main">');
            htm.push('            <div class="win-header">');
            htm.push('                <span>' + title + '</span>');
            htm.push('                <button class="win-box-close">×</button>');
            htm.push('            </div>');
            htm.push('              <div class="win-line"></div>');
            htm.push('             <div id="_winBody">' + html + '</div>');
            htm.push('        </div>');
            htm.push('    </div>');
            htm.push('</div>');
            $("#_winbox").remove();
            $(htm.join("")).appendTo("body");

            Site._resetPos();
            $("button[class=win-box-close]").click(function () {
                Site.closeWinbox(goHis);
            });

            if (cover) {
                $("#_winCover").remove();
                $('<div id="_winCover" class="win-cover"></div>').appendTo("body");
                $("#_winCover").height($(document).height());
            }
        },
        /*关闭浮层*/
        closeWinbox: function (goHis) {
            $("#_winbox").remove();
            $("#_winCover").remove();
            if (Site.options.timer) clearTimeout(Site.options.timer);
            if (Site.options.checkTimer) clearInterval(Site.options.checkTimer);
            if (typeof goHis != "undefined" && goHis == 1)
                history.go(-1);
        },
        /*登陆框*/
        showLoginbox: function (callback) {

            var htm = [
                '<ul class="group2 m10">',
                '    <li><input id="_txtLoginName" class="input r3" type="text" data-text="账号:手机号/潇湘账号" value="账号:手机号/潇湘账号" /></li>',
                '    <li><input id="_txtPassword" class="input r3" type="text" data-text="密码" value="密码" /></li>',
                '    <li style="text-align:right;"><a id="_lnkFindPassword" href="javascript:;">忘记密码?</a></li>',
                '    <li><a id="_lnkLogin" class="button blue r3" href="javascript:;" onclick="login();">登录</a></li>',
                '    <li><a id="_lnkQQLogin" class="button color1 r3" href="javascript:;">QQ号登录</a></li>',
                '    <li><a id="_lnkRegister" class="button color2 r3" href="javascript:;">注册账户</a></li>',
                '</ul>'
            ];

            var goHis = location.href.toLocaleLowerCase().indexOf("\content") >= 0 ? 1 : 0;
            this.showWinbox('用户登陆', htm.join(""), true, goHis);

            $(".input").click(
                function () {
                    if ($(this).val() == $(this).attr("data-text")) {
                        $(this).val("");
                        $(this).css({ color: "#555" });
                    }
                }).blur(
                    function () {
                        if ($(this).val() == "") {
                            $(this).val($(this).attr("data-text"));
                            $(this).css({ color: "#999" });
                        }
                    });
            $("#_lnkLogin").click(
                function () {
                    var userName = $("#_txtLoginName").val();
                    var userPass = $("#_txtPassword").val();
                    if (userName == $("#_txtLoginName").attr("data-text")
                        || userName == "") {
                        Util.Alert("请输入账户");
                        return;
                    }
                    if (userPass == $("#_txtPassword").attr("data-text")
                        || userPass == "") {
                        Util.Alert("请输入密码");
                        return;
                    }
                    Site._setBoxTitle("登录中....");

                    ajaxLocalService('user_login', { username: userName, userpassword: <PASSWORD>Pass }
                        , function (response) {

                            Site._setBoxTitle("用户登录");

                            if (response.Code != 0) {
                                Util.Alert(response.Message);
                                try {
                                    XiaoXiangJS.loginFailed();
                                } catch (e) { };
                                return;
                            }

                            var res = response.Data;

                            Util.Alert("登录成功了");
                            setTimeout(function () {
                                if (typeof callback == "function") callback(res.Id);
                                Site.closeWinbox();
                            }, 1500);
                            try {
                                XiaoXiangJS.loginSuccess(res.Id, res.Name);
                            } catch (e) { };
                        });
                });

            $("#_lnkRegister").click(
                function () {
                    Site.showRegisterbox(callback);
                });
            $("#_lnkFindPassword").click(
                function () {
                    Site.showFindPasswordbox(callback);
                });
            // QQ登陆支持
            $("#_lnkQQLogin").click(function () {
                location.href = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=100389624&state=androidxxsynet&scope=get_user_info&redirect_uri=" + encodeURI("http://android.xxsy.net/pages2/QQAuthorizeLogin.aspx");
                Util.CookieWrite("QQ_LOGIN_RETURN_LINK", _referer, 999);
            });

        },
        /*注册框*/
        showRegisterbox: function (callback) {

            var htm = [
             '<div id="_registerBox">',
             '   <div class="tab t3">',
             '       <ul><li class="animbg"></li></ul>',
             '       <ul id="_tabRegister">',
             '           <li data-index="0" class="curr">一键注册</li>',
             '           <li data-index="1">手机号注册</li>',
             '           <li data-index="2">昵称注册</li>',
             '       </ul>',
             '   </div>',
             '   <div id="_panels" style="border-top:2px solid #efefef;">',
             '       <div class="box" style="padding:10px;">',
             '           <div class="m8">',
             '               <a target="_blank" href="SMS:12114?body=8888;" class="button blue r3">发送短信一键注册</a>',
             '           </div>',
             '           <div class="wenxin ww bgwhite m15">',
             '               <h3>一键注册说明</h3>',
             '               <ul>',
             '                   <li>1、如点击发送按钮无效，请手工编辑短信内容<em>潇湘</em>发送到号码<em>12114</em>即可完成注册。</li>',
             '                   <li>2、发送一条短信即可完成注册。</li>',
             '                   <li>3、注册完成将收到成功提示短信。</li>',
             '                   <li>4、账号为手机号，密码为手机号后六位。</li>',
             '               </ul>',
             '           </div>',
             '           <div class="m10">',
             '               <a data-action="gologin" href="javascript:;" class="button color1 r3">已有账号前往登陆</a>',
             '           </div>',
             '       </div>',
             '       <div class="box" style=" padding:10px; display:none;">',
              '       <div data-step="1">',
             '           <ul class="group2 ww">',
             '               <li><input id="_txtMobile" class="input r3" type="tel" data-text="请输入手机号" value="请输入手机号" /></li>',
             '               <li>',
             '                   <ul class="group g2 ww">',
             '                       <li><input id="_txtResult" class="input r3" type="tel" data-text="输入答案" value="输入答案" /></li>',
             '                       <li><img src="/Vercode?r=' + new Date() + '" onclick="this.src = \'/Vercode?r=\' + new Date()" style="width:100%; height:38px;" /></li>',
             '                   </ul>',
             '               </li>',
             '               <li><a id="_lnkCode" class="button blue r3">获取短信验证码</a></li>',
             '           </ul>',
             '       </div>',
             '       <div data-step="2" style="display:none;">',
             '           <ul class="group2 ww">',
             '               <li><input id="_txtVerifyCode" class="input r3" type="tel" data-text="请输入短信验证码" value="请输入短信验证码" /></li>',
             '               <li><a id="_lnkRegister" class="button blue r3">确定注册</a></li>',
             '           </ul>',
             '           <div class="wenxin bgwhite ww">',
             '               <h3>温馨提示</h3>',
             '               <ul>',
             '                   <li>1、账号的密码为手机号最后6位数字。</li>',
             '               </ul>',
             '           </div>',
             '       </div>',
             '       <ul class="group2 ww">',
             '           <li><a data-action="gologin" href="javascript:;" class="button color2 r3">已有账号前往登陆</a></li>',
             '       </ul>',
             '       </div>',
             '       <div class="box" style="padding:10px;display:none;">',
             '           <ul class="group2 ww">',
             '               <li><input id="_txtNickname" class="input r3" type="text" data-text="昵称" value="昵称" /></li>',
             '               <li><input id="_txtPass2" class="input r3" type="text" data-text="密码" value="密码" /></li>',
             '               <li><input id="_txtNickMobile" class="input r3" type="tel" data-text="手机号(错误手机号将不能取回密码)" value="手机号(错误手机号将不能取回密码)" /></li>',
             '               <li><a id="_lnkRegister2" href="javascript:;" class="button blue r3">确定注册</a></li>',
             '               <li><a data-action="gologin" href="javascript:;" class="button color1 r3">已有账号前往登陆</a></li>',
             '           </ul>',
             '       </div>',
             '   </div>',
             '</div>'];

            this.showWinbox("账户注册", htm.join(""), true);

            $("#_tabRegister").find("li").click(function () {
                var sel = $(this);
                var index = parseInt(sel.attr("data-index"));
                var v = 33.3;
                sel.parent().siblings("ul").find(".animbg").animate({ marginLeft: (index * v) + "%" }, 200
                    , function () {
                        sel.addClass("curr")
                            .siblings().removeClass("curr");
                    });
                $("#_panels > div").eq(index)
                    .show()
                    .siblings("div").hide();
            });
            // 输入框单击事件
            $("#_registerBox .input").click(
                function () {
                    if ($(this).val() == $(this).attr("data-text")) {
                        $(this).val("");
                    }
                }).blur(
                    function () {
                        if ($(this).val() == "") {
                            $(this).val($(this).attr("data-text"));
                        }
                    });
            // 获取验证码
            $("#_lnkCode").click(
                function () {
                    if (Site.options.codeFlag == 1)
                        return;

                    var rv = $("#_txtResult").val();
                    if (rv == "" || rv == $("#_txtResult").attr("data-text")) {
                        Util.Alert("答案不能为空");
                        return;
                    }

                    var mobile = $("#_txtMobile").val();
                    if (/\d{11}/gi.test(mobile) == false) {
                        Util.Alert("手机号不正确");
                        return;
                    }

                    ajaxLocalService('user_sendregistercode', { mobile: mobile, rv: rv },
                        function (responseData) {
                            if (responseData.Code != 0) {
                                Util.Alert(responseData.Message);
                                return;
                            }
                            var res = responseData.Data;

                            Site.options.codeFlag = 1;
                            Site.options.delay = 60; //60秒之内不能重复发送
                            Site.options.timer = setInterval(
                                function () {
                                    if (Site.options.delay <= 0) {
                                        clearInterval(Site.options.timer);
                                        Site.options.codeFlag = 0;
                                        $("#lnkCode").html("获取验证码");
                                        return;
                                    }
                                    $("#lnkCode").html("获取验证码(" + (Site.options.delay--) + ")");
                                }, 1000);
                            $("div[data-step='1']").hide()
                                .siblings("div[data-step='2']").show();
                            Util.Alert(res);
                        });
                });
            // 手机号注册
            $("#_lnkRegister").click(function () {

                var mobile = $("#_txtMobile").val();
                var verifyCode = $("#_txtVerifyCode").val();

                if (/\d{11}/gi.test(mobile) == false) {
                    Util.Alert("密码不能少于6个字符");
                    return;
                }
                if (verifyCode == "") {
                    Util.Alert("请输入验证");
                    return;
                }
                Site._setBoxTitle("正在注册....");

                ajaxService2({
                    method: 'user.register',
                    username: mobile, usrepassword: <PASSWORD>.substring(mobile.length - 6),
                    usermail: mobile + <EMAIL>", usrmobile: mobile, channel: 6// XiaoXiangJS.getChannel()
                }
                , function (response) {
                    Site._setBoxTitle("账户注册");
                    if (response.Code != 0) {
                        Util.Alert(response.Message);
                        try {
                            XiaoXiangJS.loginFailed();
                        }
                        catch (e) { }
                        return;
                    }

                    ajaxLocalService('user_login', { username: mobile, userpassword: mobile.substring(mobile.length - 6) },
                        function (responseData) {

                            if (responseData.Code != 0) {
                                Util.Alert(responseData.Message);
                                try {
                                    XiaoXiangJS.loginFailed();
                                }
                                catch (e) { }
                                return;
                            }

                            var res = responseData.Data;

                            Util.Alert("注册成功了");
                            setTimeout(function () {
                                if (typeof callback == "function") {
                                    callback(res.Id);
                                }
                                Site.closeWinbox();
                            }, 1500);

                            try {
                                XiaoXiangJS.loginSuccess(res.Id, res.Name);
                            }
                            catch (e) { }
                        });
                });
            });
            // 昵称注册
            $("#_lnkRegister2").click(function () {

                var nickname = $("#_txtNickname").val();
                var userPass = $("#_txtPass2").val();
                var mobile = $("#_txtNickMobile").val();

                if (nickname == "" || nickname == $("#_txtNickname").attr("data-text")) {
                    Util.Alert("昵称不能为空");
                    return;
                }
                if (/^[(0-9A-Za-z)(\u4e00-\u9fa5)]{2,}$/ig.test(nickname) == false) {
                    Util.Alert("昵称只能包含数字、字母、汉字！");
                    return;
                }
                if (userPass.length < 6) {
                    Util.Alert("密码不能少于6个字符");
                    return;
                }
                if (/^1\d{10}$/gi.test(mobile) == false) {
                    Util.Alert("不是一个有效的手机号");
                    return;
                }

                Site._setBoxTitle("正在注册....");
                ajaxService2({
                    method: "user.register",
                    username: nickname, usrepassword: <PASSWORD>, usrmobile: mobile, channel: 6//XiaoXiangJS.getChannel()
                }
                , function (response) {
                    Site._setBoxTitle("账户注册");
                    if (response.Code != 0) {
                        Util.Alert(response.Message);
                        try {
                            XiaoXiangJS.loginFailed();
                        }
                        catch (e) { }
                        return;
                    }

                    ajaxLocalService('user_login', { username: nickname, userpassword: <PASSWORD> },
                        function (responseData) {
                            if (responseData.Code != 0) {
                                Util.Alert(responseData.Message);
                                try {
                                    XiaoXiangJS.loginFailed();
                                }
                                catch (e) { }
                                return;
                            }

                            var res = responseData.Data;

                            Util.Alert("注册成功了");
                            setTimeout(function () {
                                if (typeof callback == "function") callback(res.Id);
                                Site.closeWinbox();
                            }, 1500);
                            try {
                                XiaoXiangJS.loginSuccess(res.Id, res.Name);
                            }
                            catch (e) { }
                        });
                });
            });
            // 已有账号登陆
            $("a[data-action=gologin]").click(function () {
                Site.showLoginbox(callback);
            });

        },
        /*找回密码框*/
        showFindPasswordbox: function (callback) {

            var htm = [
                '<ul id="_step1" class="group2 m10">',
                '    <li><input id="_txtUserName" class="input r3" type="text" data-text="请输入账号" value="请输入账号" /></li>',
                '    <li>',
                '        <ul class="group g2 ww">',
                '            <li><input id="_txtResult" class="input r3" type="tel" data-text="输入答案" value="输入答案" /></li>',
                '            <li><img src="/Vercode?r=' + new Date() + '" onclick="this.src = \'/Vercode?r=\' + new Date()" style="width:100%; height:38px;" /></li>',
                '        </ul>',
                '   </li>',
                '    <li><a id="_lnkCode" class="button blue r3">获取短信验证码</a></li>',
                '</ul>',
                '<ul id="_step2" class="group2 m10" style="display:none;">',
                '    <li><input id="_txtPass" class="input r3" type="text" data-text="请输入新密码" value="请输入新密码" /></li>',
                '    <li><input id="_txtVerifyCode" class="input r3" type="tel" data-text="输入验证码" value="输入验证码" /></li>',
                '    <li><a id="_lnkUpdatePassword" class="button blue r3">确定修改密码</a></li>',
                '</ul>',
                '<ul id="_step1" class="group2 m10">',
                '    <li><a id="_lnkRegister" class="button color2 r3">前往注册</a></li>',
                '</ul>'
            ];
            this.showWinbox("找回密码", htm.join(""), true);
            var _userName = "";

            $(".input").click(
                function () {
                    if ($(this).val() == $(this).attr("data-text")) {
                        $(this).val("");
                        $(this).css({ color: "#555" });
                    }
                }).blur(
                    function () {
                        if ($(this).val() == "") {
                            $(this).val($(this).attr("data-text"));
                            $(this).css({ color: "#999" });
                        }
                    });

            $("#_lnkCode").click(
                function () {
                    var rv = $("#_txtResult").val();
                    if (rv == "" || rv == $("#_txtResult").attr("data-text")) {
                        Util.Alert("答案不能为空");
                        return;
                    }

                    var userName = $("#_txtUserName").val();
                    if (userName == "" || userName == $("#_txtUserName").attr("data-text")) {
                        Util.Alert("账户不能为空")
                        return;
                    }

                    ajaxLocalService("user_sendfindpasswordcode", { username: userName, rv: rv }
                        , function (response) {
                            if (response.Code != 0) {
                                Util.Alert(response.Message);
                                return;
                            }

                            $("#_step1").hide();
                            $("#_step2").show();
                            _userName = userName;
                        });
                });

            $("#_lnkUpdatePassword").click(function () {

                var userName = _userName;
                var userPass = $("#_txtPass").val();
                var verifyCode = $("#_txtVerifyCode").val();

                if (userPass.length < 6) {
                    Util.Alert("密码不能少于6个字符");
                    return;
                }

                if (verifyCode == "") {
                    Util.Alert("请输入验证");
                    return;
                }

                ajaxLocalService("user_findpassword", { username: userName, userpass: userPass, verifycode: verifyCode }
                    , function (response) {
                        if (response.Code != 0) {
                            try {
                                XiaoXiangJS.loginFailed();
                            } catch (e) { }
                            Util.Alert(response.Message);
                            return;
                        }

                        var res = response.Data;

                        Util.Alert("成功修改了密码");
                        setTimeout(function () {
                            if (typeof callback == "function") callback(res.Id);
                            Site.closeWinbox();
                        }, 1500);
                        try {
                            XiaoXiangJS.loginSuccess(res.Id, res.Name);
                        } catch (e) { };
                    });
            });

            // 前往注册
            $("#_lnkRegister").click(
                function () {
                    Site.showRegisterbox(callback);
                });

        },
        /*章节订阅框*/
        showChapterSubscribebox: function (userid, bookid, chapterid, callback) {

            var htm = [];
            htm.push('<div class="box">');
            htm.push('    <ul class="list">');
            htm.push('        <li>章节名:<span id="_spnChapterName"></span></li>');
            htm.push('        <li>订阅该章节需:<span id="_spnChapterPrice"></span><em>(潇湘币)</em></li>');
            htm.push('        <li>账户余额:<span id="_spanAccount"></span><em>(潇湘币)</em></li>');
            htm.push('    </ul>');
            htm.push('    <ul class="group2">');
            htm.push('        <li><a href="javascript:;" id="_lnkSubscribe" class="button blue r3">订阅本章节</a></li>');
            htm.push('        <li><a href="javascript:;" id="_lnkTejia" class="button color1 r3" style="display:none;">全本订阅只需100潇湘币</a></li>');
            htm.push('        <li><a href="javascript:;" id="_lnkBaoyue" class="button color2 r3" style="display:none;">包月作品点此订购包月</a></li>');
            htm.push('    </ul>');
            htm.push('</div>');

            Site.showWinbox("Loading....", htm.join(""), true, 1);
            $.get(Site.Host, $.param({ action: "chapter_getsubscribedetail", userid: userid, bookid: bookid, chapterid: chapterid })
                , function (data) {

                    var res = eval("(" + data + ")");
                    var i = res.result;
                    Site._setBoxTitle(i.BookName + " - 章节订阅");
                    $("#_spnChapterName").html(i.ChapterName);
                    $("#_spnChapterPrice").html(i.Price);
                    $("#_spanAccount").html(i.UserAccount);

                    if (i.Tejia > 0) {
                        $("#_lnkTejia").html("全本订阅只需" + i.Tejia + "潇湘币");
                        $("#_lnkTejia").show().click(function () {
                            Site.showQuanbenrSubscribebox(userid, bookid, callback);
                        });
                    }
                    if (i.IsBaoyue == 1) {
                        $("#_lnkBaoyue").show().click(function () {
                            Site.showBaoyuebox(userid, callback);
                        });
                    }
                    Site._resetPos();
                    $("#_lnkSubscribe").click(
                        function (data) {
                            Site._setBoxTitle("订阅中请稍后....");
                            $.get(Site.Host, $.param({ action: "chapter_subscribe", userid: userid, chapterid: chapterid })
                                , function (data) {
                                    Site._setBoxTitle("章节订阅");
                                    var res = eval("(" + data + ")");
                                    if (res.result == 0) {
                                        Util.Alert("订阅时发生了错误")
                                        return;
                                    }
                                    var str = "订阅成功";
                                    if (res.mon > 0) str += ",本次订阅获取月票1张";
                                    if (res.assess > 0) str += ",本次订阅获取评价票1张";
                                    Util.Alert(str);
                                    setTimeout(
                                        function () {
                                            if (typeof callback == "function") callback();
                                            Site.closeWinbox();
                                        }, 1400);

                                });
                        });
                });

        },
        /*包月框*/
        showBaoyuebox: function (userid, callback) {
            var htm = [
                '<div class="box ww" style="padding:10px 0;">',
                '    <div class="wenxin bgwhite">',
                '        <h3>包月说明</h3>',
                '        <ul>',
                '            <li>包月书库内有超过700多部优秀作品,购买包月服务，期间可无限制阅读任何包月书库作品任何章节。</li>',
                '        </ul>',
                '    </div>',
                '    <ul id="_monCount" class="group-price m12">',
                '        <li><a href="javascript:;" data-value="1"><span>包1个月</span><em>1500潇湘币</em></a></li>',
                '        <li><a href="javascript:;" data-value="3"><span>包3个月</span><em>4000潇湘币</em></a></li>',
                '        <li><a href="javascript:;" data-value="6"><span>包6个月</span><em>7000潇湘币</em></a></li>',
                '        <li><a href="javascript:;" data-value="12"><span>包12个月</span><em>12000潇湘币</em></a></li>',
                '        <li><a href="javascript:;" data-value="24"><span>包24个月</span><em>20000潇湘币</em></a></li>',
                '    </ul>',
                '    <ul class="group2">',
                '        <li><a id="_lnkBaoyue" href="javascript:;" class="button blue r3">确定包月</a></li>',
                '    </ul>',
                '</div>'
            ];

            var goHis = location.href.toLocaleLowerCase().indexOf("content.aspx") >= 0 ? 1 : 0;
            Site.showWinbox("包月服务", htm.join(""), true, goHis);
            var _count = 0;
            var _site = 6;

            $("#_monCount a").click(function () {
                $("#_monCount a").removeClass("current");
                $(this).addClass("current");
                _count = parseInt($(this).attr("data-value"));
            });

            $("#_lnkBaoyue").click(function () {
                Site._setBoxTitle("正在提交");

                ajaxService2({ method: "book.buy.monthly", userid: _userid, buymons: _count, site: _site }
                    , function (response) {
                        Site._setBoxTitle("包月服务");

                        if (response.Code != 0) {
                            Util.Alert(response.Message);
                            XiaoXiangJS.purchaseFailed();
                            return;
                        }

                        Util.Alert("包月成功了");
                        setTimeout(function () {
                            if (typeof callback == "function") callback();
                            Site.closeWinbox();
                        }, 1500);
                        XiaoXiangJS.purchaseSuccess();
                    });
            });
        },
        /*显示发表评论框*/
        showSendReviewbox: function (userid, bookid, callback) {

            var htm = [
                ' <ul class="group2">',
                '     <li><textarea class="area" id="_txtReviewText"></textarea></li>',
                '     <li style="text-align:right;"><span id="_spnLength">0/1000</span></li>',
                '     <li><a href="javascript:;" id="_lnkSendReview" class="button blue r3">确定发表评论</a></li>',
                ' </ul>'
            ];

            Site.showWinbox("发表评论", htm.join(""), true);
            Site.options.checkTimer = setInterval(
                function () {
                    var len = $("#_txtReviewText").val().length;
                    var spn = $("#_spnLength");
                    spn.css({ color: (len > 1000 || len < 6) ? "#f00" : "#555" });
                    spn.html(len + "/1000");
                }, 500);

            $("#_lnkSendReview").click(
                function () {

                    var txt = $("#_txtReviewText").val();
                    if (txt.length < 6) {
                        Util.Alert("评论内容不能少于6个字");
                        return;
                    }

                    if (txt.length > 1000) {
                        Util.Alert("评论内容不能1000个字");
                        return;
                    }

                    Site._setBoxTitle("发送中....");

                    $.get(Site.Host, $.param({ action: "book_sendreview", userid: userid, bookid: bookid, content: txt })
                        , function (data) {

                            Site._setBoxTitle("发表评论");

                            var res = eval("(" + data + ")");
                            if (res.result == 0) {

                                Util.Alert("成功发表了一条评论");
                                clearInterval(Site.options.checkTimer);

                                setTimeout(function () {
                                    if (typeof callback == "function") callback();
                                    Site.closeWinbox();
                                }, 1500);

                                return;
                            }

                            var err = "发表失败";
                            if (res.result == 1) err = "注册未满48小时不能发表";
                            if (res.result == 2) err = "被永久禁言";
                            if (res.result == 3) err = "禁言中";
                            if (res.result == 4) err = "您发表的太快了,休息片刻后再发表";

                            Util.Alert(err);

                        });
                });

        },
        /*粉丝互动(送鲜花、钻石、打赏等)*/
        showPropsbox: function (userid, bookid, type) {
            var htm = [
            '<div id="_propsBox" class="box ww">',
            '    <div class="tab t5" >',
            '        <ul><li class="animbg"></li></ul>',
            '        <ul>',
            '            <li data-index="0" data-props="2">鲜花</li>',
            '            <li data-index="1" data-props="1">钻石</li>',
            '            <li data-index="2" data-props="5">打赏</li>',
            '            <li data-index="3" data-props="4">月票</li>',
            '            <li data-index="4" data-props="8">评价票</li>',
            '        </ul>',
            '    </div>',
            '    <div id="_propsPanels">',
            '        <div>',
            '            <ul class="group-count">',
            '                <li><a href="javascript:;" data-type="2" data-count="1">1(朵)</a></li>',
            '                <li><a href="javascript:;" data-type="2" data-count="5">5(朵)</a></li>',
            '                <li><a href="javascript:;" data-type="2" data-count="10">10(朵)</a></li>',
            '                <li><a href="javascript:;" data-type="2" data-count="50">50(朵)</a></li>',
            '                <li><a href="javascript:;" data-type="2" data-count="100">100(朵)</a></li>',
            '                <li><a id="_btnCustom2" href="javascript:;" data-type="2" data-count="0" contenteditable="true">自定义</a></li>',
            '            </ul>',
            '            <ul class="group2"><li><a href="javascript:;" class="button blue r3" data-value="2">确定送鲜花</a></li></ul>',
            '            <div class="wenxin bgwhite m5">',
            '                <h3>温馨提示</h3>',
            '                <ul>',
            '                    <li>1、赠送一朵鲜花需要消耗20点潇湘币</li>',
            '                </ul>',
            '            </div>',
            '        </div>',
            '        <div style="display:none">',
            '            <ul class="group-count">',
            '                <li><a href="javascript:;" data-type="1" data-count="1">1(颗)</a></li>',
            '                <li><a href="javascript:;" data-type="1" data-count="5">5(颗)</a></li>',
            '                <li><a href="javascript:;" data-type="1" data-count="10">10(颗)</a></li>',
            '                <li><a href="javascript:;" data-type="1" data-count="50">50(颗)</a></li>',
            '                <li><a href="javascript:;" data-type="1" data-count="100">100(颗)</a></li>',
            '                <li><a id="_btnCustom1" href="javascript:;" data-type="1" data-count="0" contenteditable="true">自定义</a></li>',
            '            </ul>',
            '            <ul class="group2"><li><a href="javascript:;" class="button blue r3" data-value="1">确定送钻石</a></li></ul>',
            '            <div class="wenxin bgwhite m5">',
            '                <h3>温馨提示</h3>',
            '                <ul>',
            '                    <li>1、赠送一颗钻石需要消耗100点潇湘币</li>',
            '                </ul>',
            '            </div>',
            '        </div>',
            '        <div style="display:none">',
            '            <ul class="group-count">',
            '                <li><a href="javascript:;" data-type="5" data-count="188">188</a></li>',
            '                <li><a href="javascript:;" data-type="5" data-count="388">388</a></li>',
            '                <li><a href="javascript:;" data-type="5" data-count="888">888</a></li>',
            '                <li><a href="javascript:;" data-type="5" data-count="1888">1888</a></li>',
            '                <li><a href="javascript:;" data-type="5" data-count="8888">8888</a></li>',
            '                <li><a id="_btnCustom5" href="javascript:;" data-type="5" data-count="0" contenteditable="true">自定义</a></li>',
            '            </ul>',
            '            <ul class="group2"><li><a href="javascript:;" class="button blue r3" data-value="5">确定打赏</a></li></ul>',
            '            <div class="wenxin bgwhite m5">',
            '                <h3>温馨提示</h3>',
            '                <ul>',
            '                    <li>1、打赏单位为潇湘币</li>',
            '                </ul>',
            '            </div>',
            '        </div>',
            '        <div style="display:none">',
            '            <ul class="group-count">',
            '                <li><a href="javascript:;" data-type="4" data-count="1">1(张)</a></li>',
            '                <li><a href="javascript:;" data-type="4" data-count="2">2(张)</a></li>',
            '                <li><a href="javascript:;" data-type="4" data-count="3">3(张)</a></li>',
            '                <li><a href="javascript:;" data-type="4" data-count="4">4(张)</a></li>',
            '                <li><a href="javascript:;" data-type="4" data-count="5">5(张)</a></li>',
            '                <li><a id="_btnCustom4" href="javascript:;" data-type="4" data-count="0" contenteditable="true">自定义</a></li>',
            '            </ul>',
            '            <div class="box" style="font-size:14px; color:#0B3985; padding-bottom:5px;">当前月票:<span id="_shengyu4">0</span>(张)</div>',
            '            <ul class="group2"><li><a href="javascript:;" class="button blue r3" data-value="4">确定投月票</a></li></ul>',
            '            <div class="wenxin bgwhite m5">',
            '                <h3>温馨提示</h3>',
            '                <ul>',
            '                    <li>1、vip订阅消费每满10元即可获得1张月票,月票当月有效.</li>',
            '                </ul>',
            '            </div>',
            '        </div>',
            '        <div style="display:none">',
            '            <ul class="group-count">',
            '                <li><a href="javascript:;" data-type="8" data-count="1">不知所云</a></li>',
            '                <li><a href="javascript:;" data-type="8" data-count="2">随便看看</a></li>',
            '                <li><a href="javascript:;" data-type="8" data-count="3">值得一看</a></li>',
            '                <li><a href="javascript:;" data-type="8" data-count="4">不容错过</a></li>',
            '                <li><a href="javascript:;" data-type="8" data-count="5">经典必看</a></li>',
            '            </ul>',
            '            <div class="box" style="font-size:14px; color:#0B3985; padding-bottom:5px;">当前评价票:<span id="_shengyu8">0</span>(张)</div>',
            '            <ul class="group2"><li><a href="javascript:;" class="button blue r3" data-value="8">确定投评价票</a></li></ul>',
            '            <div class="wenxin bgwhite m5">',
            '                <h3>温馨提示</h3>',
            '                <ul>',
            '                    <li>1、每月消费满10元即可获赠1张评价票,每月只可获赠一次.</li>',
            '                    <li>2、可以每张200点潇湘币购买(购买无限制)</li>',
            '                    <li>3、每次评价消耗1张评价票</li>',
            '                </ul>',
            '            </div>',
            '        </div>',
            '    </div>',
            '</div>'];

            Site.showWinbox("粉丝互动", htm.join(""), true);

            var _count = 0;
            var _integral = 0;
            var _propsType = 1;
            var _userid = userid;
            var _bookid = bookid;
            var _iscus = 0;
            var _site = 6;//XiaoXiangJS.getChannel();

            var current = $("#_propsBox li[data-props=" + type + "]").addClass("curr");
            var idx = parseInt(current.attr("data-index"));
            current.parent().siblings().find(".animbg").css({ marginLeft: idx * 20 + "%" });
            $("#_propsPanels > div").eq(idx).show().siblings().hide();
            _propsType = type;

            ajaxService2({ method : "user.get", userid: _userid }
                , function (response) {
                    var user = response.Data;
                    if (user.Id > 0) {
                        $("#_shengyu8").html(user.Assesstickets);
                        $("#_shengyu4").html(user.Montickets);
                    }
                });

            // 绑定选项卡单击事件
            $("#_propsBox li[data-props]").click(function () {
                var sel = $(this);
                var index = parseInt(sel.attr("data-index"));
                sel.parent().siblings().find(".animbg").animate({ marginLeft: index * 20 + "%" }, 200
                    , function () { sel.addClass("curr").siblings().removeClass("curr"); });
                $("#_propsPanels > div").eq(index).show().siblings().hide();
                _count = 0;
                _propsType = parseInt(sel.attr("data-props"));
                Site._resetPos();
            });

            // 绑定自定义输入框单击、失去焦点事件
            $("#_propsBox a[contenteditable]").click(
                 function () {
                     var value = $(this).html();
                     value = value.replace(/<[^>]+>|\s+/gi, "");
                     if (/\d+/gi.test(value) == false)
                         $(this).html("");
                 }).blur(
                    function () {
                        var value = $(this).html();
                        value = value.replace(/<[^>]+>|\s+/gi, "");
                        if (/\d+/gi.test(value) == false)
                            $(this).html("自定义");
                    });

            $("#_propsBox a[data-type]").click(
                function () {
                    $("#_propsBox a[data-type]").removeClass("curr");
                    $(this).addClass("curr");
                    _propsType = parseInt($(this).attr("data-type"));
                    _count = parseInt($(this).attr("data-count"));

                    _iscus = (_count > 0) ? 0 : 1;

                    if (_propsType == 8) {
                        _integral = _count;
                        _count = 1;
                    }

                });

            // 绑定发送按钮事件
            $("#_propsBox .button").click(
                function () {
                    if (_propsType == 8 && _integral == 0) {
                        Util.Alert("请选择评论信息");
                        return;
                    }
                    if (_count == 0) {
                        if (_iscus == 1) {
                            var temp = $("#_btnCustom" + _propsType).html();
                            temp = temp.replace(/<[^>]+>|\s+/gi, "");
                            if (/\d+/gi.test(temp)) {
                                _count = parseInt(temp);
                            }
                        }
                    }
                    if (_propsType == 1 && _count == 0) {
                        Util.Alert("请选择钻石数量或自定义数量");
                        return;
                    }
                    if (_propsType == 2 && _count == 0) {
                        Util.Alert("请选择鲜花数量或自定义数量");
                        return;
                    }
                    if (_propsType == 4 && _count == 0) {
                        Util.Alert("请选择月票数量或自定义数量");
                        return;
                    }
                    if (_propsType == 5 && _count == 0) {
                        Util.Alert("请选择打赏数量或自定义数量");
                        return;
                    }
                    if (_propsType == 5 && _iscus == 1 && _count < 100) {
                        Util.Alert("打赏至少100潇湘币");
                        return;
                    }
                    Site._setBoxTitle("提交中....");
                    ajaxService2({ method: 'user.use.gift', userid: _userid, bookid: _bookid, gifttype: _propsType, count: _count, score: _integral, site: _site },
                        function (response) {
                            Site._setBoxTitle("粉丝互动");
                            if (response.Code != 0) {
                                Util.Alert(response.Message);
                                return;
                            }

                            if (_propsType == 4) {
                                var message = '成功投了张' + _count + '月票,' + Site.getTalk();
                                Util.Alert(message);
                            } else {
                                Util.Alert("操作成功了");
                            }

                            if (_propsType == 4 || _propsType == 8) {
                                var shengyu = $("#_shengyu" + _propsType);
                                var sh = parseInt(shengyu.html());
                                sh = sh - _count;
                                if (sh < 0) sh = 0;
                                shengyu.html(sh);
                            }
                        });
                });
        },
        /*修改密码*/
        showUpdatePasswordbox: function (userid, callback) {

            var htm = [];

            htm.push('<div>');
            htm.push('   <ul class="group2">');
            htm.push('       <li><input id="_txtOldPassword" class="input" type="text" data-text="输入旧密码" value="输入旧密码" /></li>');
            htm.push('       <li><input id="_txtNewPassword" class="input" type="text" data-text="新密码" value="新密码" /></li>');
            htm.push('       <li><a href="javascript:;" id="_lnkUpdate" class="button blue r3">确定修改</a></li>');
            htm.push('   </ul>');
            htm.push('</div>');

            this.showWinbox('密码修改', htm.join(""), true);

            $(".input").click(
                function () {
                    if ($(this).val() == $(this).attr("data-text")) {
                        $(this).val("");
                        $(this).css({ color: "#555" });
                    }
                }).blur(
                    function () {
                        if ($(this).val() == "") {
                            $(this).val($(this).attr("data-text"));
                            $(this).css({ color: "#999" });
                        }
                    });

            $("#_lnkUpdate").click(
                function () {

                    var oldPassword = $("#_txtOldPassword").val();
                    var newPassword = $("#_txtNewPassword").val();

                    if (newPassword.length < 6) {
                        Util.Alert("密码至少6个字符");
                        return;
                    }

                    Site._setBoxTitle("发送请求中....");

                    ajaxService2({ method: "user.update.password", userid: userid, oldpassword: oldPassword, newpassword: <PASSWORD> }
                        , function (response) {
                            Site._setBoxTitle("密码修改");
                            if (response.Code != 0) {
                                Util.Alert(response.Message);
                                return;
                            }

                            var res = response.Data;

                            ajaxLocalService("user_login", { username: res.Name, userpassword: res.Password },
                                function (response) {
                                    if (response.Code == 0) {
                                        Util.Alert("成功修改了密码");
                                        if (typeof callback == "function") callback();
                                        setTimeout(function () {
                                            Site.closeWinbox();
                                        }, 1500);
                                    }
                                });
                        });

                });
        },
        /*显示全本订阅框*/
        showQuanbenrSubscribebox: function (userid, bookid, callback) {

            if (userid == 0 || userid == null) {
                Site.showLoginbox(function (uid) {
                    setTimeout(function () {
                        Site.showQuanbenrSubscribebox(uid, bookid);
                    }, 300);
                });
                return;
            }

            var htm = [
                '<div class="box">',
                '    <ul id="_subscribeInfoUL" class="list ww">',
                '        <li>全本订阅价格:<span id="_spnPrice">0</span>(潇湘币)</li>',
                '        <li>当前余额:<span id="_spnAccount">0</span>(潇湘币)</li>',
                '    </ul>',
                '    <div id="_successDiv" style="display:none;color:#1C3FD4;padding:10px 0 5px;text-align:center;">订阅成功了！</div>',
                '    <ul id="_qbDingyueUL" class="group2 m10"><li><a id="_lnkDingyue" href="javascript:;" class="button blue r3">确定订阅</a></li></ul>',
                '    <div class="wenxin bgwhite m5">',
                '        <h3>全本订阅说明</h3>',
                '        <ul>',
                '            <li>1、一次性订阅特定作品的全部VIP章节，可享受特价优惠。</li>',
                '            <li>2、订阅后可永久阅读已订阅的作品。</li>',
                '        </ul>',
                '    </div>',
                '</div>'
            ];

            var goHis = location.href.toLocaleLowerCase().indexOf("content.aspx") >= 0 ? 1 : 0;
            this.showWinbox('全本订阅', htm.join(""), true, goHis);

            Site._setBoxTitle("加载中.....");
            $.get(Site.Host, $.param({ action: "book_tejia_detail", userid: userid, bookid: bookid })
                , function (data) {
                    var res = eval("(" + data + ")");

                    if (res.code == 0) {
                        Site._setBoxTitle(res.bookName + " - 全本订阅");
                        $("#_spnPrice").html(res.price);
                        $("#_spnAccount").html(res.account);

                        var isbuy = res.isbuy;
                        if (isbuy == 1) {
                            $("#_qbDingyueUL").html('<li><a href="javascript:Site.closeWinbox();" class="button color3 r3">该作品已订阅！</a></li>');
                            return;
                        }

                        if (res.isIngot == 1) {

                            var maxDeduction = res.maxDeduction;
                            var canget = res.canget;
                            var ingot = res.ingot;
                            var sli = [];

                            //if ((ingot + res.account) >= res.price) {
                            //    if (ingot > 0) {
                            //        var strbtn = "使用" + maxDeduction + "元宝";
                            //        if (res.price > maxDeduction &&
                            //            res.account > 0)
                            //            strbtn += "+" + (res.price - maxDeduction) + "潇湘币";
                            //        strbtn += "订阅";
                            //        sli.push('<li><a id="_lnkDingyueByIngot" href="javascript:;" class="button blue r3">' + strbtn + '</a></li>');
                            //    }
                            //} else {
                            //    sli.push('<li><a id="_gotoPay" href="javascript:;" class="button blue r3">余额不足前往充值</a></li>');
                            //}

                            //用户余额大于订阅点数才显示
                            if (res.account >= res.price) {
                                var str = '使用' + res.price + '潇湘币订阅';
                                //if (canget > 0)
                                //    str += '(可获赠' + canget + '元宝)';
                                sli.push('<li><a id="_lnkDingyue" href="javascript:;" class="button color1 r3">' + str + '</a></li>');
                            }

                            $("#_qbDingyueUL").html(sli.join(""));
                            //$("#_subscribeInfoUL").append('<li>剩余体验币:' + ingot + '</li>');
                        }

                        $("#_gotoPay").click(function () {
                            location.href = 'Chongzhi.aspx';
                        });

                        $("#_lnkDingyue").click(function () {
                            var strbtn2 = $("#_lnkDingyue").html();
                            $("#_lnkDingyue").html("提交中.....");
                            $.get(Site.Host, $.param({ action: "book_quanben2", userid: userid, bookid: bookid, siteid: 2 })
                                , function (data2) {
                                    $("#_lnkDingyue").html(strbtn2);
                                    var res2 = eval("(" + data2 + ")");
                                    if (res2.result == 1) {
                                        $("#_successDiv").show();
                                        setTimeout(function () {
                                            if (typeof callback == "function") callback();
                                            Site.closeWinbox();
                                        }, 2000);
                                        XiaoXiangJS.purchaseSuccess();
                                        return;
                                    }
                                    var errs = ["缺少参数", "余额不足", "已经订阅过了不能重复点阅", "不是特价书"];
                                    Util.Alert(errs[Math.abs(res2.result)]);
                                    XiaoXiangJS.purchaseFailed();
                                });
                        });

                        //$("#_lnkDingyueByIngot").click(function () {
                        //    var strbtn2 = $("#_lnkDingyueByIngot").html();
                        //    $("#_lnkDingyueByIngot").html("提交中.....");
                        //    $.get(Site.Host, $.param({ action: "book_quanben2", userid: userid, bookid: bookid, ingotnum: res.maxDeduction })
                        //        , function (data2) {
                        //            $("#_lnkDingyueByIngot").html(strbtn2);
                        //            var res2 = eval("(" + data2 + ")");
                        //            if (res2.result == 1) {
                        //                $("#_successDiv").show();
                        //                setTimeout(function () {
                        //                    if (typeof callback == "function") callback();
                        //                    Site.closeWinbox();
                        //                }, 2000);
                        //                XiaoXiangJS.purchaseSuccess();
                        //                return;
                        //            }
                        //            var errs = ["缺少参数", "余额不足", "已经订阅过了不能重复点阅", "不是特价书"];
                        //            Util.Alert(errs[Math.abs(res2.result)]);
                        //            XiaoXiangJS.purchaseFailed();
                        //        });
                        //});

                        return;
                    }
                });

        },
        /*绑定手机号*/
        showBindingMobilebox: function (userid, callback) {
            var htm = [
               '<div class="box">',
                '    <div class="tab t2">',
                '        <ul><li class="animbg"></li></ul>',
                '        <ul id="_ulBinding">',
                '            <li data-index="0" class="curr">手机绑定</li>',
                '            <li data-index="1">解除绑定</li>',
                '        </ul>',
                '    </div>',
                '    <div id="_bindingPanels" style="border-top:2px solid #efefef; padding:10px 0;">',
                '        <div>',
                '               <div data-step="1">',
                        '            <ul class="group2">',
                        '               <li><input id="_txtMobile" class="input r3" type="tel" data-text="输入手机号" value="输入手机号" /></li>',
                        '               <li>',
                        '                   <ul class="group g2 ww">',
                        '                       <li><input id="_txtResult" class="input r3" type="tel" data-text="输入答案" value="输入答案" /></li>',
                        '                       <li><img src="/Vercode?r=' + new Date() + '" onclick="this.src = \'/Vercode?r=\' + new Date()" style="width:100%; height:38px;" /></li>',
                        '                   </ul>',
                        '               </li>',
                        '                <li><a id="_lnkCode" class="button color1 r3">获取短信验证码</a></li>',
                        '            </ul>',
                '               </div>',
                '               <div id="_hasBinding" style="text-align:center; font-size:14px; display:none;"></div>',
                '               <div data-step="2" style="display:none;">',
                '                   <ul class="group2">',
                '                       <li><input id="_txtCode" class="input r3" type="tel" data-text="输入短信验证码" value="输入短信验证码" /></li>',
                '                       <li><a id="_lnkBinding" class="button blue r3">确定绑定</a></li>',
                '                   </ul>',
                        '            <div class="wenxin bgwhite m10">',
                        '                <h3>温馨提示</h3>',
                        '                <ul>',
                        '                    <li>1.绑定手机后可以通过手机号取回密码！</li>',
                        '                </ul>',
                        '            </div>',
                '               </div>',
                '       </div>',
                '        <div style="display:none;">',
                '            <ul class="group2">',
                '                <li>',
                '                   <ul class="group g2 ww">',
                '                       <li><input id="_txtSmsMobile" class="input r3" type="tel" data-text="输入绑定的手机号" value="输入绑定的手机号" /></li>',
                '                       <li><a id="_bntSendSmsCode" class="button blue r3">获取验证码</a></li>',
                '                   </ul>',
                '                </li>',
                '                <li><input id="_txtSmsCode" class="input r3" type="tel" data-text="输入收到的短信验证码" value="输入收到的短信验证码" /></li>',
                '                <li><a id="_lnkUnbinding" class="button blue r3">确定解除手机绑定</a></li>',
                '            </ul>',
                '            <div class="wenxin bgwhite m10">',
                '                <h3>温馨提示</h3>',
                '                <ul>',
                '                    <li>1.解除手机绑定后将不能通过手机号取回密码！</li>',
                '                </ul>',
                '            </div>',
                '       </div>',
                '    </div>',
                '</div>'
            ];
            this.showWinbox('手机绑定', htm.join(""), true);

            var _timer;
            var _delay = 60;

            ajaxLocalService("user_getbinding", { userid: userid },
                function (response) {
                    var res = response.Data;
                    var attements = response.Attachments;

                    if (res == 1) {
                        $("#_hasBinding").html(attements);
                        $("#_hasBinding").show().siblings().hide();
                    }
                });

            $("#_ulBinding").find("li").click(function () {
                var sel = $(this);
                var index = parseInt(sel.attr("data-index"));
                sel.parent().siblings().find(".animbg").animate({ marginLeft: index * 50 + "%" }, 200
                    , function () { sel.addClass("curr").siblings().removeClass("curr"); });
                $("#_bindingPanels > div").eq(index).show().siblings().hide();
            });

            $(".input").click(
                function () {
                    if ($(this).val() == $(this).attr("data-text")) {
                        $(this).val("");
                    }
                }).blur(
                    function () {
                        if ($(this).val() == "") {
                            $(this).val($(this).attr("data-text"));
                        }
                    });

            $("#_lnkBinding").click(
                function () {
                    var mobile = $("#_txtMobile").val();
                    var code = $("#_txtCode").val();
                    ajaxLocalService("user_binding", { userid: userid, code: code, mobile: mobile } , 
                        function (response) {
                            if (response.Code == 0) {
                                var res = response.Data;
                                Util.Alert("绑定成功");
                                if (typeof callback == "function") callback();
                                setTimeout(function () { Site.closeWinbox(); }, 1500)
                            }
                            else {
                                Util.Alert(response.Message);
                            }
                        });
                });

            $("#_lnkUnbinding").click(function () {
                var code = $("#_txtSmsCode").val();
                var mobile = $("#_txtSmsMobile").val();
                ajaxLocalService("user_unbinding", { userid: userid, code: code, mobile: mobile },
                    function (response) {
                        if (response.Code == 0) {
                            var res = response.Data;
                            Util.Alert("成功解除绑定");
                            setTimeout(function () {
                                Site.closeWinbox();
                            }, 1500);
                        }
                        else {
                            Util.Alert(response.Message);
                        }
                    });
            });

            //发送解除绑定验证码
            $('#_bntSendSmsCode').click(
                function () {
                    if (Site.options.codeFlag == 1)
                        return;

                    var mobile = $('#_txtSmsMobile').val();
                    if (/^1\d{10}$/gi.test(mobile) == false) {
                        Util.Alert('请输入正确的手机号');
                        return;
                    }

                    ajaxLocalService("user_sendunbindingcode", { mobile: mobile, userid: userid }
                    , function (response) {
                        if (response.Code == 0) {
                            var res = response.Data;
                            Util.Alert("验证码已发送");
                            Site.options.codeFlag = 1;
                            _delay = 60;
                            _timer = setInterval(
                                function () {
                                    if (_delay <= 0) {
                                        clearInterval(_timer);
                                        Site.options.codeFlag = 0;
                                        $("#_bntSendSmsCode").html("获取验证码");
                                        return;
                                    }
                                    $("#_bntSendSmsCode").html("获取验证码(" + (_delay--) + ")");
                                }, 1000);
                        }
                        else {
                            Util.Alert(response.Message);
                        }
                    });

                });

            $("#_lnkCode").click(function () {
                var mobile = $("#_txtMobile").val();
                if (/^\d{11}$/gi.test(mobile) == false) {
                    Util.Alert("请输入正确的手机号")
                    return;
                }

                var rv = $("#_txtResult").val();
                if (rv == "" || rv == $("#_txtResult").attr("data-text")) {
                    Util.Alert("答案不能为空")
                    return;
                }
                ajaxLocalService("user_sendbindingcode", {mobile: mobile, rv: rv }
                    , function (response) {
                        var res = response.Data;
                        if (response.Code == 0) {
                            Util.Alert("验证码已发送");
                            Site.options.codeFlag = 1;
                            _delay = 60;
                            _timer = setInterval(
                                function () {
                                    if (_delay <= 0) {
                                        clearInterval(_timer);
                                        Site.options.codeFlag = 0;
                                        $("#_lnkCode").html("获取验证码");
                                        return;
                                    }
                                    $("#_lnkCode").html("获取验证码(" + (_delay--) + ")");
                                }, 1000);
                            $("div[data-step='1']").hide()
                                    .siblings("div[data-step='2']").show();
                        }
                        else {
                            Util.Alert(response.Message);
                        }
                    });
            });

        },
        /*显示确认框*/
        showConfirmbox: function (msg, callback) {
            var htm = [
                '<div id="_confirmBox" class="box" style="padding:10px 0;">',
                '    <div class="box" style="padding-bottom:10px; color:#555; line-height:24px; text-indent:28px; ">',
                msg,
                '    </div>',
                '    <div class="line"></div>',
                '    <ul class="group g2 m10">',
                '        <li><a href="javascript:;" data-value="1" class="button blue r3">确定</a></li>',
                '        <li><a href="javascript:;" data-value="0" class="button color2 r3">取消</a></li>',
                '    </ul>',
                '</div>'
            ];
            this.showWinbox('提示', htm.join(""), true);
            $("#_confirmBox .button").click(function () {
                var value = parseInt($(this).attr("data-value"));
                if (typeof callback == "function")
                    callback(value);
                Site.closeWinbox();
            });
        },
        /*回顶部*/
        initGotoTop: function () {
            $("#_goTop").remove();
            $('<a id="_goTop" href="javascript:;" class="gotop"></a>').appendTo("body");
            $("#_goTop").click(function () {
                $("body").animate({ scrollTop: 0 }, 200);
            });
            setInterval(function () {
                var top = $("body").scrollTop();
                top > 10 ? $("#_goTop").show() : $("#_goTop").hide();
            }, 200);
        },
        /*显示更新*/
        showUpdate: function () {
            var html = [
                '<div>',
                '    <p class="box" style="',
                '        padding:10px;',
                '        text-indent:28px;',
                '        font-size:14px;',
                '        color:#555;',
                '        line-height:150%;',
                '        text-shadow:0 1px 0 #fff;">更新到最新版本才可以签到！</p>',
                '    <ul class="group2">',
                '        <li><a class="button blue"  href="javascript:XiaoXiangJS.checkVersion()">更新至最新版本</a></li>',
                '    </ul>',
                '</div>'
            ];
            this.showWinbox("提示", html.join(""), true);
        },
        /*绑定手机号*/
        showBindingMobileboxBySingin: function (userid, callback) {
            var htm = [
                '<div class="box">',
                '   <div style="padding:15px 10px; text-align:center; color:#555; font-size:15px; ">您需绑定手机后才能正常使用签到功能！</div>',
                '    <div id="_bindingPanels" style=" padding:0 0 10px 0;">',
                '        <div data-step="1">',
                '            <ul class="group2">',
                '                <li><input id="_txtMobile" class="input r3" type="tel" data-text="输入手机号" value="输入手机号" /></li>',
                '                <li>',
                '                   <ul class="group g2 ww">',
                '                       <li><input id="_txtResult" class="input r3" type="tel" data-text="输入答案" value="输入答案" /></li>',
                '                       <li><img src="/Vercode?r=' + new Date() + '" onclick="this.src = \'/Vercode?r=\' + new Date()" style="width:100%; height:38px;" /></li>',
                '                   </ul>',
                '                </li>',
                '                <li><a id="_lnkCode" class="button color1 r3">获取验证码</a></li>',
                '            </ul>',
                '       </div>',
                '       <div data-step="2" style="display:none;">',
                '            <ul class="group2">',
                '                <li><input id="_txtCode" class="input r3" type="tel" data-text="输入短信验证码" value="输入短信验证码" /></li>',
                '                <li><a id="_lnkBinding" class="button blue r3">确定绑定</a></li>',
                '            </ul>',
                '       </div>',
                '       <div class="wenxin bgwhite m10">',
                '            <h3>温馨提示</h3>',
                '            <ul>',
                '               <li>1. 绑定手机后可以通过手机号取回密码！</li>',
                '            </ul>',
                '        </div>',
                '    </div>',
                '</div>'
            ];
            this.showWinbox('手机绑定', htm.join(""), true);

            var _timer;
            var _delay = 60;

            ajaxLocalService("user_getbinding", { userid: userid },
                function (response) {
                    var res = response.Data;
                    var attements = response.Attachments;

                    if (res == 1) {
                        $("#_hasBinding").html(attements);
                        $("#_hasBinding").show().siblings().hide();
                    }
                });

            $(".input").click(
                function () {
                    if ($(this).val() == $(this).attr("data-text")) {
                        $(this).val("");
                    }
                }).blur(
                    function () {
                        if ($(this).val() == "") {
                            $(this).val($(this).attr("data-text"));
                        }
                    });

            $("#_lnkBinding").click(
                function () {
                    var mobile = $("#_txtMobile").val();
                    var code = $("#_txtCode").val();
                    ajaxLocalService("user_binding", {userid: userid, code: code, mobile: mobile }
                        , function (response) {
                            var res = response.Data;
                            if (response.Code == 0) {
                                Util.Alert("绑定成功");
                                if (typeof callback == "function") callback();
                                setTimeout(function () { Site.closeWinbox(); }, 1500)
                            }
                            else {
                                Util.Alert(response.Message);
                            }
                        });
                });

            $("#_lnkCode").click(function () {

                var mobile = $("#_txtMobile").val();
                if (/^\d{11}$/gi.test(mobile) == false) {
                    Util.Alert("请输入正确的手机号")
                    return;
                }

                var rv = $("#_txtResult").val();
                if (rv == "" || rv == $("#_txtResult").attr("data-text")) {
                    Util.Alert("答案不能为空")
                    return;
                }

                ajaxLocalService("user_sendbindingcode",{ mobile: mobile, rv: rv }
                    , function (response) {
                        var res = response.Data;
                        if (response.Code == 0) {
                            Util.Alert("验证码已发送");
                            Site.options.codeFlag = 1;
                            _delay = 60;
                            _timer = setInterval(
                                function () {
                                    if (_delay <= 0) {
                                        clearInterval(_timer);
                                        Site.options.codeFlag = 0;
                                        $("#_lnkCode").html("获取验证码");
                                        return;
                                    }
                                    $("#_lnkCode").html("获取验证码(" + (_delay--) + ")");
                                }, 1000);
                            $("div[data-step='1']").hide()
                                    .siblings("div[data-step='2']").show();
                        }
                        else {
                            Util.Alert(response.Message);
                        }
                    });
            });
        }
    };

})();

window.onload = function () {
    Site.initGotoTop();
}<file_sep>/Mvc.Web.Android/Models/BaseModel.cs
﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Mvc.Web.Android.Models
{
    /// <summary>
    /// 基础对象
    /// </summary>
    public partial class BaseModel
    {
        [Display(Name = "ID")]
        public int ID { get; set; }
    }
}<file_sep>/Mvc.Web.Android/Helper/Extensions.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;

namespace Mvc.Web.Android
{
    /// <summary>
    /// 公共扩展
    /// </summary>
    public static class Extensions
    {
        /// <summary>
        /// 判断一个T?是否是空值或者是默认值
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="source">源数据</param>
        /// <returns>book</returns>
        public static bool IsNullOrDefault<T>(this T? source) where T : struct
        {
            return default(T).Equals(
                source.GetValueOrDefault());
        }

        /// <summary>
        /// 数据转换
        /// </summary>
        public static T To<T>(this object source, T value = default(T))
        {
            if (source != null
                    && !(source is DBNull))
            {
                try
                {
                    value = (T)Convert.ChangeType(source, typeof(T));
                }
                catch
                { }
            }
            return value;
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source"></param>
        /// <param name="bit">位数如果为16取中间16位</param>
        /// <returns>String</returns>
        public static string MD5(this string source, int bit = 32)
        {
            var result = FormsAuthentication.HashPasswordForStoringInConfigFile(source, "md5");
            if (bit == 16)
                result = result.Substring(8, 16);
            return result.ToLower();
        }

        /// <summary>
        /// 数据转换
        /// </summary>
        public static string ShortIntro(this string str, int len = 30)
        {
            if (!string.IsNullOrWhiteSpace(str))
            {
                var pattern = @"<[^>]+>|\s+|http[a-z0-9\\\/\&\?\:\.\%]+|\&[\w\d]{2,6}\;|\*+";
                str = Regex.Replace(str, pattern, "", RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnoreCase);
                if (str.Length > len)
                {
                    str = str.Substring(0, len) + "...";
                }
            }
            return str;
        }

        /// <summary>
        /// 简写万元
        /// </summary>
        public static string ToWan(this int num)
        {
            string value = string.Empty;
            if (num > 10000)
            {
                value = int.Parse((num / 10000).ToString()).ToString() + "万";
            }
            else
                value = num.ToString();
            return value;
        }
    }
}
<file_sep>/Mvc.Web.Android/Models/Book/CategoryModel.cs
﻿using NapiService;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Mvc.Web.Android.Models.Book
{
    /// <summary>
    /// 分类页Model
    /// </summary>
    public class CategoryModel
    {
        /// <summary>
        /// 排序
        /// </summary>
        public CategorySort Sort = CategorySort.New;
        /// <summary>
        /// 分类
        /// </summary>
        public CategoryClass Type = CategoryClass.None;
    }

    /// <summary>
    /// 排序
    /// </summary>
    public enum CategorySort
    {
        /// <summary>
        /// 热门
        /// </summary>
        Hot = (int)SearchSort.VipSameDay_Desc,
        /// <summary>
        /// 免费
        /// </summary>
        Free=96,
        /// <summary>
        /// 完结
        /// </summary>
        Finished=99,
        /// <summary>
        /// 最新
        /// </summary>
        New = (int)SearchSort.VipSameDayDescAndUpdateTimeDesc,
        /// <summary>
        /// 特价
        /// </summary>
        SpecialOffer = 97,
    }

    /// <summary>
    /// 分类
    /// </summary>
    public enum CategoryClass
    {
        /// <summary>
        /// 所有分类
        /// </summary>
        None = (int)SearchClass.None,
        /// <summary>
        /// 穿越
        /// </summary>
        PassThrough = (int)SearchClass.PassThrough,
        /// <summary>
        /// 架空
        /// </summary>
        Aerial = (int)SearchClass.Aerial,
        /// <summary>
        /// 都市
        /// </summary>
        Urban = (int)SearchClass.Urban,
        /// <summary>
        /// 青春
        /// </summary>
        Youth = (int)SearchClass.Youth,
        /// <summary>
        /// 魔幻
        /// </summary>
        Magical = (int)SearchClass.Magical,
        /// <summary>
        /// 玄幻
        /// </summary>
        Occult = (int)SearchClass.Occult,
        /// <summary>
        /// 豪门
        /// </summary>
        PowerfulFamily = (int)SearchClass.PowerfulFamily,
        /// <summary>
        /// 历史
        /// </summary>
        History = (int)SearchClass.History,
        /// <summary>
        /// 异能
        /// </summary>
        Ability = (int)SearchClass.Ability,
        /// <summary>
        /// 短篇
        /// </summary>
        ShortArticle = (int)SearchClass.ShortArticle,
        /// <summary>
        /// 耽美
        /// </summary>
        Tanbi = (int)SearchClass.Tanbi,
        /// <summary>
        /// 包月
        /// </summary>
        Monthly = 98,
    }
}<file_sep>/Mvc.Web.Android/Helper/SiteHelper.cs
﻿using Mvc.Web.Android.Settings;
using NapiService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Mvc.Web.Android.Helper
{
    /// <summary>
    /// 网站常用工具
    /// </summary>
    public static class SiteHelper
    {
        /// <summary>
        /// 获取充值渠道号
        /// </summary>
        /// <param name="order">订单号</param>
        /// <returns>String</returns>
        public static string GetPayChannel(object order)
        {
            var channelName = "未知渠道";
            var arr = order.To<string>(string.Empty).Split(new[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
            if (arr.Length > 0)
            {
                var number = arr[arr.Length - 1];
                if (SiteSettings.PayChannel.Keys.Contains(number))
                    channelName = SiteSettings.PayChannel[number];
            }
            return channelName;
        }

        public static string IntroFilter(string intro)
        {
            var str = intro;
            str = Regex.Replace(str, "<p>", "<br>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var pattern = @"http[^\u4e00-\u9fa5]+|\&.*?\;";
            var regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
            str = regex.Replace(str, "");
            return str;
        }

        public static string GetEncryptDictionary(string key)
        {

            string s = "0123456789ABCDEF";

            if (string.IsNullOrEmpty(key)) key = "";
            string str = key.MD5().ToUpper();

            List<string> list = str.ToCharArray()
                .Distinct()
                .Select(o => o.ToString())
                .ToList();

            if (list.Count() < 16)
            {
                foreach (char c in s.ToCharArray())
                {
                    if (!list.Contains(c.ToString()))
                    {
                        list.Add(c.ToString());
                    }
                    if (list.Count >= 16)
                    {
                        break;
                    }
                }
            }

            return string.Join("", list);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="original">被加密字符串</param>
        /// <param name="key">加密密钥</param>
        /// <returns></returns>
        public static string XEncrypt(string original, string key)
        {

            string dic = GetEncryptDictionary(key);

            StringBuilder str = new StringBuilder();

            if (!string.IsNullOrEmpty(original))
            {

                char[] chars = original.ToCharArray();
                string bytes = string.Join("", chars.Select(o => Convert.ToString(o, 2).PadLeft(16, '0')));

                for (int i = 0; i < bytes.Length; i += 4)
                {
                    int index = Convert.ToInt32(bytes.Substring(i, 4), 2);
                    str.Append(dic[index].ToString());
                }
            }

            return str.ToString();
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encrypted"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string XDecrypt(string encrypted, string key)
        {

            string dic = GetEncryptDictionary(key);

            if (string.IsNullOrEmpty(encrypted))
            {
                return "";
            }

            StringBuilder str = new StringBuilder();

            foreach (char ch in encrypted.ToCharArray())
            {
                int index = dic.IndexOf(ch);
                string bytes = Convert.ToString(index, 2).PadLeft(4, '0');
                str.Append(bytes);
            }

            string s = str.ToString();
            str.Clear();

            for (int i = 0; i < s.Length; i += 16)
            {
                char ch = (char)Convert.ToInt32(s.Substring(i, 16), 2);
                str.Append(ch.ToString());
            }

            return str.ToString();
        }

        /// <summary>
        /// DES解密
        /// </summary>
        /// <param name="str">待解密字符串</param>
        /// <param name="key">解密密钥</param>
        /// <returns></returns>
        public static string DESDecode(string str, string key)
        {

            string value = string.Empty;
            str = str ?? string.Empty;

            try
            {
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                byte[] keyBytes = Encoding.UTF8.GetBytes(key.MD5().ToLower().Substring(8, 8));
                provider.Key = keyBytes;
                provider.IV = keyBytes;
                byte[] buffer = new byte[str.Length / 2];
                for (int i = 0; i < (str.Length / 2); i++)
                {
                    int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
                    buffer[i] = (byte)num2;
                }
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                stream.Close();
                value = Encoding.UTF8.GetString(stream.ToArray());
            }
            catch { }

            return value;
        }


        /// <summary>
        /// DES加密
        /// </summary>
        /// <param name="str">待加密字符串</param>
        /// <param name="key">加密密钥</param>
        /// <returns>加密后的代码</returns>        
        public static string DESEncode(string str, string key)
        {

            string value = string.Empty;

            try
            {
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                byte[] keyBytes = Encoding.UTF8.GetBytes(key.MD5().ToLower().Substring(8, 8));
                provider.Key = keyBytes;
                provider.IV = keyBytes;
                byte[] bytes = Encoding.UTF8.GetBytes(str);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                StringBuilder builder = new StringBuilder();
                foreach (byte num in stream.ToArray())
                {
                    builder.AppendFormat("{0:X2}", num);
                }
                stream.Close();
                value = builder.ToString();

            }
            catch
            { }
            return value;
        }

        /// <summary>
        /// 发送服务请求，返回对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="requestData_Json">请求的参数(Json格式)</param>
        /// <param name="defaultValue">获取失败默认值</param>
        /// <returns>T</returns>
        public static T GetServices<T>(string requestData_Json, T defaultValue = default(T))
        {
            T value = defaultValue;
            try
            {
                string urlData = HttpUtility.UrlEncode(requestData_Json);
                //string url = "http://napi.xxsy.net/services2?" + urlData;
                string url = "http://napi.xxsy.net/services?requestData=" + urlData;

                string service_back = WebHelper.QuickGet(url);

                HttpResponseModel<T> model = WebHelper.Json<HttpResponseModel<T>>(service_back);

                if(model.Code == 0)
                    value = model.Data;
            }
            catch { }
            return value;
        }


        /// <summary>
        /// Http响应结果 
        /// </summary>
        public partial class HttpResponseModel<T>
        {
            /// <summary>
            /// 响应Code
            /// </summary>
            public int Code = 0;
            /// <summary>
            /// 响应信息
            /// </summary>
            public string Message = string.Empty;
            /// <summary>
            /// 响应数据
            /// </summary>
            public T Data = default(T);
            /// <summary>
            /// 附加数据
            /// </summary>
            public object Attachments = default(Object);
        }

        /// <summary>
        /// 通用调用方法1
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <typeparam name="TAttach">TAttach</typeparam>
        /// <param name="httpParameters">Parameters参数字典</param>
        /// <param name="attach">Attements</param>
        /// <returns>T</returns>
        public static T InvokeService<T, TAttach>(Dictionary<string, object> httpParameters, out TAttach attach)
        {

            if (!httpParameters.ContainsKey("method"))
                throw new Exception("method");

            T value = default(T);
            attach = default(TAttach);

            string host = "http://napi.xxsy.net/services2?";
            StringBuilder sb = new StringBuilder();
            foreach (var k in httpParameters.Keys)
                sb.AppendFormat("{0}={1}&", k, HttpUtility.UrlEncode(httpParameters[k].To<string>(string.Empty)));

            string sign = (httpParameters["method"] + "vage~244@$9234sdfnsdf~!").MD5();
            sb.AppendFormat("sign={0}", sign);
            host += sb.ToString();
            sb.Clear();

            string responseData = WebHelper.QuickGet(host);
            var httpModel = WebHelper.Json<HttpResModel<T, TAttach>>(responseData);
            if (httpModel != null)
            {
                value = httpModel.Data;
                attach = httpModel.Attachments;
            }

            return value;
        }

        /// <summary>
        /// 通用调用方法2
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <param name="httpParameters">Parameters参数字典</param>
        /// <returns>T</returns>
        public static T InvokeService<T>(Dictionary<string, object> httpParameters)
        {
            Object attch;
            return InvokeService<T, Object>(httpParameters, out attch);
        }

        /// <summary>
        /// 过渡对象
        /// </summary>
        /// <typeparam name="T">T</typeparam>
        /// <typeparam name="TAttach">TAttach</typeparam>
        public class HttpResModel<T, TAttach>
        {
            /// <summary>
            /// 响应Code
            /// </summary>
            public int Code = 0;
            /// <summary>
            /// 响应信息
            /// </summary>
            public string Message = string.Empty;
            /// <summary>
            /// 响应数据
            /// </summary>
            public T Data = default(T);
            /// <summary>
            /// 附加数据
            /// </summary>
            public TAttach Attachments = default(TAttach);
        }
    }
}

<file_sep>/Mvc.Web.Android/Helper/SmsHelper.cs
﻿using NapiService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Security;

namespace Mvc.Web.Android.Helper
{
    /// <summary>
    /// 短信发送支持
    /// </summary>
    public static class SmsHelper
    {
        /// <summary>
        /// 短信接口路径
        /// </summary>
        private static string HOST = "http://link.xxsy.net/svc/sms.aspx?mobile={0}&message={1}&token={2}";

        /// <summary>
        /// 短信接口路径
        /// </summary>
        private static string HOST2 = "http://link.xxsy.net/svc/sms.aspx?mobile={0}&message={1}&token={2}&ip={3}&forwhat={4}";

        /// <summary>
        /// 发送信息
        /// </summary>
        /// <param name="mebile">手机号</param>
        /// <param name="message">发送内容(必须符合模板约定)</param>
        /// <returns>bool成功返回true否则false</returns>
        public static bool Send(string mobile, string message)
        {
            var value = false;

            var secret = "d6e3ea3679d28199c60b61dfeba204ac";
            var token = FormsAuthentication.HashPasswordForStoringInConfigFile(
                string.Format("xxsynet{0}{1}{2}", mobile, DateTime.Now.ToString("yyyyMMdd"), secret), "MD5").ToLower();

            using (var client = new WebClient())
            {

                var temp = client.DownloadString(string.Format(HOST, mobile, message, token));
                var res = 0;
                int.TryParse(temp, out res);
                value = (res > 0);
            }

            return value;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="message">信息</param>
        /// <param name="forwhat">用途</param>
        /// <returns>bool</returns>
        public static bool Send(string mobile, string message, string forwhat)
        {
            var value = false;

            var secret = "d6e3ea3679d28199c60b61dfeba204ac";
            var token = FormsAuthentication.HashPasswordForStoringInConfigFile(
                string.Format("xxsynet{0}{1}{2}", mobile, DateTime.Now.ToString("yyyyMMdd"), secret), "MD5").ToLower();

            using (var client = new WebClient())
            {
                var temp = client.DownloadString(string.Format(HOST2, mobile, HttpUtility.UrlEncode(message), token, WebHelper.IP(), HttpUtility.UrlEncode(forwhat)));
                var res = 0;
                int.TryParse(temp, out res);
                value = (res > 0);
            }

            return value;
        }
    }
}<file_sep>/Mvc.Web.Android/Models/HttpRequestArgsModel.cs
﻿using Mvc.Web.Android.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mvc.Web.Android.Models
{

    /// <summary>
    /// Http请求对象
    /// </summary>
    public class HttpRequestArgsModel
    {
        /// <summary>
        /// 创建HttpRequestArgsModel
        /// </summary>
        public HttpRequestArgsModel()
        {
            this.Method = string.Empty;
            this.Parameters = new NxpDictionary<string, object>();
            this.Date = DateTime.Now;
        }

        /// <summary>
        /// 请求方法
        /// </summary>
        public string Method { get; set; }

        /// <summary>
        /// 请求参数
        /// </summary>
        public NxpDictionary<string, object> Parameters { get; set; }

        /// <summary>
        /// 请求时间
        /// </summary>
        public DateTime Date { get; set; }

    }
}<file_sep>/Mvc.Web.Android/Models/MemberTagsModel.cs
﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace Mvc.Web.Android.Models
{
    /// <summary>
    /// MemberTags
    /// </summary>
    ///子类并不映射到任何数据库，加上一个不映射的属性[NotMapped]
    [NotMapped]
    public partial class MemberTagsModel : BaseModel
    {
        [Display(Name = "登录名", Description = "4-20个字符")]
        [Required(ErrorMessage = "×")]
        [StringLength(20, MinimumLength = 4, ErrorMessage = "×")]
        public string Name { get; set; }

        [Display(Name = "密码", Description = "6-20个字符")]
        [Required(ErrorMessage = "×")]
        [StringLength(20, MinimumLength = 6, ErrorMessage = "×")]
        public string Password { get; set; }
    }
}<file_sep>/Mvc.Web.Android/Script/tiyanbi.js
﻿/// <reference path="JX.js" />

function showTiyanbiAds(isNew) {
    if (isNew == 1) {
        var showed = Util.CookieValue('showtiyanbiads');
        if (showed == '') {
            var s = [
                '<div class="tiyanbi">',
                '    <div class="tiyanbi_cover"></div>',
                '    <div class="tiyanbi_ads">',
                '        <div class="tiyanbi_main">',
                '            <img src="http://images.xxsy.net/mxxsynet/tiyanbi_ads.png" />',
                '            <a class="tiyanbi_button" href="Chongzhi.aspx">去充值</a>',
                '            <a class="tiyanbi_help" href="MyTiyanbiMark.aspx">体验币的秘密，你造吗？</a>',
                '        </div>',     
                '    </div>',
                '</div>'
            ];

            $('.tiyanbi').remove();
            $(s.join('')).appendTo('body');
            Util.CookieWrite('showtiyanbiads', '1', 60 * 24);

            $('.tiyanbi_main img').load(function () {
                $('.tiyanbi_cover').height($(document).height()).click(function () { $('.tiyanbi').remove(); });
                var box = $('.tiyanbi_ads');
                var top = ($(window).height() - box.height()) * 0.5 - 20;
                if (top < 0) top = 0;
                box.css({top: top + 'px' });
            });
        }
    }
}<file_sep>/Mvc.Web.Android/Controllers/Info_OLDController.cs
﻿using Mvc.Web.Android.Helper;
using NapiService;
using NapiService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class Info_OLDController : BaseController
    {
        /// <summary>
        /// 详情数据
        /// </summary>
        public InfoDetail Detail = new InfoDetail();

        NapiService.BookService _bookService = new NapiService.BookService();
        NapiService.BookcaseService _bookcaseService = new NapiService.BookcaseService();
        NapiService.ChapterService _bookChapterService = new NapiService.ChapterService();

        /// <summary>
        /// 页面主入口
        /// </summary>
        public ActionResult Index(int bookid = 0)
        {
            ViewBag.BID = bookid;

            if (bookid == 0)
                return RedirectToAction("NotFound", "Error", new { err = "该作品不存在或者已暂时被下架" });

            if (bookid != 0)
            {
                ViewBag.IsKeep = _bookcaseService.Exists(ViewBag.User.ID, bookid);
            }

            Detail = GetInfoDetail(bookid);

            if (Detail.Book.Id != bookid || Detail.Book.Check != 0)
                return RedirectToAction("NotFound", "Error", new { err = "该作品不存在或者已暂时被下架" });

            if (Detail.Book.SpecialOffer > 0)
            {

                ViewBag.Tejia_Class = "group g2";
                ViewBag.Tejia_InnerHtml = string.Format(
                        "<li><a href=\"javascript:XiaoXiangJS.download({1},'{3}')\" class=\"button color1 r3\">下载到本地离线阅读</a></li><li><a href=\"javascript:;\" onclick=\"Site.showQuanbenrSubscribebox({0},{1})\" class=\"button color3 r3\">{2}元特价</a></li>"
                        , ViewBag.UserID, Detail.Book.Id, Detail.Book.SpecialOffer / 100, Detail.Book.Title);

                //判断是否包月
                if (ViewBag.User.ID > 0)
                {
                    DateTime baoyueTime = _memberService.GetMonthlyEndTime(ViewBag.User.ID);
                    if (baoyueTime > DateTime.Now)
                    {
                        if (Detail.Book.IsMonthly == 1)
                        {
                            ViewBag.Tejia_Class = "group g1";
                            ViewBag.Tejia_InnerHtml = string.Format(
                                "<li><a href=\"javascript:XiaoXiangJS.download({0},'{1}')\" class=\"button color1 r3\">下载到本地离线阅读</a></li>"
                                , Detail.Book.Id, Detail.Book.Title);
                        }
                    }
                }

            }
            else
            {
                ViewBag.Tejia_Class = "group g1";
                ViewBag.Tejia_InnerHtml = string.Format(
                        "<li><a href=\"javascript:XiaoXiangJS.download({0},'{1}')\" class=\"button color1 r3\">下载到本地离线阅读</a></li>"
                        , Detail.Book.Id, Detail.Book.Title);
            }

            return View(Detail);
        }

        /// <summary>
        /// 获取详情数据
        /// </summary>
        InfoDetail GetInfoDetail(int bookid)
        {
            var detail = new InfoDetail();

            var book = _bookService.Get(bookid);

            var lastChapterTags = _bookChapterService.GetLast(bookid);

            if (book != null)
            {
                detail.Book = book;
                //获取最新的5条评论
                //detail.Revies.AddRange(_bookReviewService.GetReviews(bookid, 0, 5, 0, out iTotal));
                //获取同类推荐
                //detail.SimilarBooks.AddRange(_cacheManager.Get<List<Nxp.Framework.Model.Books.Booksearch>>(string.Format("TongleiTuijian_{0}", book.ClassId), 180, () => { return _bookSearchService.SameRecommendtion(bookid, 5, 50); }));
                //获取作者其他
                //detail.AuthorOtherBooks.AddRange(_bookSearchService.GetAuthorOtherBooks(bookid));
                //获取最新章节
                detail.LastChapterTags = lastChapterTags;
            }
            return detail;
        }

        public class InfoDetail
        {
            public Book Book = new Book();
            public Bookgift Props = new Bookgift();
            public List<Bookreview> Revies = new List<Bookreview>();
            public List<Booksearch> AuthorOtherBooks = new List<Booksearch>();
            public List<Booksearch> SimilarBooks = new List<Booksearch>();
            public Chapter LastChapterTags = new Chapter();
        }
    }
}
<file_sep>/Mvc.Web.Android/Controllers/ServicesController.cs
﻿using Mvc.Web.Android.Helper;
using Mvc.Web.Android.Models;
using Mvc.Web.Android.Settings;
using NapiService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class ServicesController : BaseController
    {
        #region MyRegion

        //private MemberService _memberService;

        public ServicesController()
        {
            //_memberService = new MemberService();
        }
        #endregion

        /// <summary>
        /// 回调函数名
        /// </summary>
        string _NxpCallback = string.Empty;

        /// <summary>
        /// 接口入口
        /// <para>@requestData：json字符串</para>
        /// <para>@nxpCallback：JSONP回调函数名</para>
        /// </summary>
        public ActionResult Index(string requestData = "", string nxpCallback = "")
        {
            this._NxpCallback = nxpCallback;
            if (!string.IsNullOrEmpty(requestData))
            {
                var data = WebHelper.Json<HttpRequestArgsModel>(requestData);
                if (data != null)
                {
                    switch (data.Method.ToLower())
                    {
                        #region 用户相关
                        //用户登陆
                        case "user_login": return Login(data.Parameters);
                        // 用户状态检测
                        case "user_check": return CheckUser(data.Parameters);
                        // 发送注册验证码
                        case "user_sendregistercode": return SendRegisterCode(data.Parameters);
                        // 发送找回密码验证码
                        case "user_sendfindpasswordcode": return SendFindPasswordCode(data.Parameters);
                        // 发送绑定手机验证码
                        case "user_sendbindingcode": return SendBindingCode(data.Parameters);
                        // 发送解绑手机验证码
                        case "user_sendunbindingcode": return SendUnBindingCode(data.Parameters);
                        // 找回密码
                        case "user_findpassword": return FindPassword(data.Parameters);
                        // 获取绑定信息
                        case "user_getbinding": return GetBinding(data.Parameters);
                        // 绑定手机号
                        case "user_binding": return MemberBinding(data.Parameters);
                        // 手机解除绑定
                        case "user_unbinding": return MemberUnbinding(data.Parameters);
                        #endregion
                    }
                }
            }
            return View();
        }

        /// <summary>
        /// 发送解绑手机验证码
        /// <para>@mobile:手机号</para>
        /// <para>@rv:验证码</para>
        /// </summary>
        private ActionResult SendUnBindingCode(NxpDictionary<string, object> nxpDictionary)
        {
            var mobile = nxpDictionary.GetString("mobile", string.Empty);
            var userid = nxpDictionary.GetInt32("userid", 0);

            var member = _memberService.GetById(userid);
            if (member.Mobile != mobile)
            {
                return LogError("请输入正确的手机号");
            }

            if (string.IsNullOrWhiteSpace(member.Mobile))
            {
                return LogError("手机号已解除绑定");
            }

            var code = new Random().Next(1000, 9999);

            var res = _memberService.SendSmsUnbindingMobileMessage(mobile, code.To<string>());

            if (!res)
            {
                return LogError("发送失败或使用次数已满");
            }

            //验证码写入Session
            Session["UNBINDING_CODE_" + WebHelper.Md5(mobile)] = code;
            Session["UNBINDING_CODE_COUNT_" + WebHelper.Md5(mobile)] = 0;

            return ShowResult("验证码已发送");
        }

        /// <summary>
        /// 发送绑定手机验证码
        /// <para>@mobile:手机号</para>
        /// <para>@rv:验证码</para>
        /// </summary>
        private ActionResult SendBindingCode(NxpDictionary<string, object> nxpDictionary)
        {
            var mobile = nxpDictionary.GetString("mobile", string.Empty);

            var rv = nxpDictionary.GetString("rv", string.Empty);
            if (string.IsNullOrEmpty(rv) || rv != Session["VALIDATE_CODE"].To<string>(string.Empty))
            {
                return LogError("输入的答案不正确");
            }

            if (!Regex.IsMatch(mobile, "\\d{11}"))
            {
                return LogError("非法手机号");
            }

            if (_memberService.GetByMobile(mobile) != null)
            {
                return LogError("手机号已被绑定");
            }

            var code = new Random().Next(1000, 9999);

            var res = _memberService.SendSmsBindingMobileMessage(mobile, code.To<string>());

            if (!res)
            {
                return LogError("发送失败或使用次数已满");
            }

            //验证码写入Session
            Session["BINDING_CODE_" + WebHelper.Md5(mobile)] = code;
            Session["BINDING_CODE_COUNT_" + WebHelper.Md5(mobile)] = 0;

            return ShowResult("验证码已发送");
        }

        /// <summary>
        /// 手机解除绑定
        /// <para>@userid:用户Id</para>
        /// </summary>
        private ActionResult MemberUnbinding(NxpDictionary<string, object> nxpDictionary)
        {
            var userid = nxpDictionary.GetInt32("userid", 0);
            var code = nxpDictionary.GetString("code", string.Empty);
            var mobile = nxpDictionary.GetString("mobile", string.Empty);

            if (!Security(userid))
                return LogError("验证用户失败请重新登陆！", -1);

            int errorNumber = Session["UNBINDING_CODE_COUNT_" + WebHelper.Md5(mobile)].To<int>();
            if (errorNumber >= 3)
            {
                return LogError("验证码不正确");
            }

            var myCode = Session["UNBINDING_CODE_" + WebHelper.Md5(mobile)].To<string>("");
            if (code == "" || code != myCode)
            {
                Session["UNBINDING_CODE_COUNT_" + WebHelper.Md5(mobile)] = errorNumber++;
                return LogError("验证码不正确");
            }

            var member = _memberService.GetById(userid);
            if (member == null || member.Id == 0)
                return LogError("用户不存在");

            if (member.IsBindingMobile == 0)
            {
                return LogError("用户已解除绑定");
            }

            var httpModel = _memberService.UpdateMobileHttpModel(userid, mobile, 0);

            if (httpModel.Code == 0)
                return ShowResult(httpModel.Data, httpModel.Attachments);
            else
                return LogError(httpModel.Message);
        }

        /// <summary>
        /// 绑定手机号
        /// <para>@userid:用户Id</para>
        /// <para>@mobile:手机号</para>
        /// <para>@code:验证码</para>
        /// </summary>
        private ActionResult MemberBinding(NxpDictionary<string, object> nxpDictionary)
        {
            var userid = nxpDictionary.GetInt32("userid", 0);
            var mobile = nxpDictionary.GetString("mobile", string.Empty);
            var code = nxpDictionary.GetString("code", string.Empty);

            if (!Security(userid))
                return LogError("验证用户失败请重新登陆！", -1);

            int errorNumber = Session["BINDING_CODE_COUNT_" + WebHelper.Md5(mobile)].To<int>();
            if (errorNumber >= 3)
            {
                return LogError("验证码不正确");
            }

            var myCode = Session["BINDING_CODE_" + WebHelper.Md5(mobile)].To<string>("");
            if (code == "" || code != myCode)
            {
                Session["BINDING_CODE_COUNT_" + WebHelper.Md5(mobile)] = errorNumber++;
                return LogError("验证码不正确");
            }

            var member = _memberService.GetById(userid);

            if (member.IsBindingMobile == 1)
            {
                return LogError("用户已绑定");
            }

            var httpModel = _memberService.UpdateMobileHttpModel(userid, mobile, 1);

            if (httpModel.Code == 0)
                return ShowResult(httpModel.Data, httpModel.Attachments);
            else
                return LogError(httpModel.Message);
        }

        /// <summary>
        /// 获取绑定信息
        /// <para>@userid:用户Id</para>
        /// </summary>
        private ActionResult GetBinding(NxpDictionary<string, object> nxpDictionary)
        {
            var userid = nxpDictionary.GetInt32("userid", 0);
            if (!Security(userid))
                return LogError("验证用户失败请重新登陆！", -1);

            var member = _memberService.GetById(userid);

            return ShowResult(member.IsBindingMobile, !string.IsNullOrEmpty(member.Mobile)
                    ? string.Format("你已绑定手机号为：{0}***{1}", member.Mobile.Substring(0, 4), member.Mobile.Substring(member.Mobile.Length - 3))
                    : "");
        }

        /// <summary>
        /// 用户状态检测
        /// <para>@userid:用户Id</para>
        /// </summary>
        private ActionResult CheckUser(NxpDictionary<string, object> nxpDictionary)
        {
            int userid = nxpDictionary.GetInt32("userid", 0);
            var member = _memberService.GetById(userid);
            int value = 0;
            if(member != null)
                value = member.Status;

            return ShowResult(value);
        }

        /// <summary>
        /// 找回密码
        /// <para>@username:用户名</para>
        /// <para>@verifycode:验证码</para>
        /// <para>@userpass:用户密码</para>
        /// </summary>
        private ActionResult FindPassword(NxpDictionary<string, object> nxpDictionary)
        {
            var userName = nxpDictionary.GetString("username", string.Empty);
            var verifyCode = nxpDictionary.GetString("verifycode", string.Empty);
            var userPass = nxpDictionary.GetString("userpass", string.Empty);

            if (userPass.Length < 6)
            {
                return LogError("密码不能少于6个字符");
            }

            int errorNumber = Session["FINDPASSWORD_CODE_COUNT_" + WebHelper.Md5(userName)].To<int>();
            if (errorNumber >= 3)
            {
                return LogError("验证码不正确");
            }

            var myCode = Session["FINDPASSWORD_CODE_" + WebHelper.Md5(userName)].To<string>("");
            if (verifyCode == "" || verifyCode != myCode)
            {
                Session["FINDPASSWORD_CODE_COUNT_" + WebHelper.Md5(userName)] = errorNumber + 1;
                return LogError("验证码不正确");
            }

            var member = _memberService.GetByName(userName);
            if (member == null)
            {
                return LogError("用户名不存在或手机未绑定");
            }

            var httpModel = _memberService.UpdatePasswordHttpModel(userName, userPass);

            if (httpModel.Code == 0)
            {
                return Login(new NxpDictionary<string, object>
                {
                    {"username",userName},
                    {"userpassword",userPass}
                });
            }
            else
            {
                return LogError("修改密码失败");
            }
        }

        /// <summary>
        /// 发送找回密码验证码
        /// <para>@username:用户名</para>
        /// <para>@rv:验证码</para>
        /// </summary>
        private ActionResult SendFindPasswordCode(NxpDictionary<string, object> nxpDictionary)
        {
            var userName = nxpDictionary.GetString("username", string.Empty);

            var rv = nxpDictionary.GetString("rv", string.Empty);
            if (string.IsNullOrEmpty(rv) || rv != Session["VALIDATE_CODE"].To<string>(string.Empty))
            {
                return LogError("输入的答案不正确");
            }

            var member = _memberService.GetByName(userName);
            if (member == null)
            {
                return LogError("用户名不存在");
            }

            if (member.IsBindingMobile != 1)
            {
                return LogError("用户未绑定手机号");
            }

            if (member.Status != 0)
            {
                return LogError("用户账号被冻结");
            }

            var code = new Random().Next(1000, 9999);

            var res = _memberService.SendSmsRegisterMessage(member.Mobile, code.To<string>());

            if (!res)
            {
                return LogError("发送失败或使用次数已满");
            }

            //验证码写入Session
            Session["FINDPASSWORD_CODE_" + WebHelper.Md5(userName)] = code;
            Session["FINDPASSWORD_CODE_COUNT_" + WebHelper.Md5(userName)] = 0;

            return ShowResult("验证码已发送");
        }

        /// <summary>
        /// 发送注册验证码
        /// <para>@mobile:手机</para>
        /// <para>@rv:验证码</para>
        /// </summary>
        private ActionResult SendRegisterCode(NxpDictionary<string, object> nxpDictionary)
        {
            var mobile = nxpDictionary.GetString("mobile", string.Empty);;
            var rv = nxpDictionary.GetString("rv", string.Empty);

            if (string.IsNullOrEmpty(rv) || rv != Session["VALIDATE_CODE"].To<string>(string.Empty))
            {
                return LogError("输入的答案不正确");
            }

            if (!Regex.IsMatch(mobile, "\\d{11}"))
            {
                return LogError("非法手机号");
            }

            var member = _memberService.GetByName(mobile);
            if (member != null && member.Id > 0)
            {
                return LogError("手机号已存在");
            }

            var tempMember = _memberService.GetByMobile(mobile);
            if (tempMember != null && tempMember.Id > 0)
            {
                return LogError("该手机号已被其他账号绑定");
            }

            var code = new Random().Next(1000, 9999);

            var res = _memberService.SendSmsRegisterMessage(mobile, code.To<string>());

            if (!res)
            {
                return LogError("发送失败或使用次数已满");
            }

            //验证码写入Session
            Session["REGISTER_CODE_" + WebHelper.Md5(mobile)] = code;
            Session["REGISTER_CODE_COUNT_" + WebHelper.Md5(mobile)] = 0;

            return ShowResult("成功发送了验证码");
        }

        /// <summary>
        /// 用户登录
        /// <para>@username:用户名</para>
        /// <para>@userpassword:<PASSWORD></para>
        /// <para>@imei:设备号</para>
        /// <para>@devicetype:设备类型</para>
        /// </summary>
        private ActionResult Login(NxpDictionary<string, object> nxpDictionary)
        {
            var userName = nxpDictionary.GetString("username", string.Empty);
            var userPass = nxpDictionary.GetString("userpassword", string.Empty);

            var session = string.Empty;
            // 20140707添加
            var imei = nxpDictionary.GetString("imei", string.Empty);
            var deviceType = nxpDictionary.GetString("devicetype", string.Empty);

            var httpModel = _memberService.LoginHttpModel(userName, userPass, SiteSettings.SubscribeChannel);
            var member = httpModel.Data;

            if (httpModel.Code != 0)
            {
                return LogError(httpModel.Message);
            }

            string attachments = WebHelper.Json(new { Id = member.Id, Name = member.Name, Password = <PASSWORD> });
            attachments = WebHelper.Encrypt(attachments);

            int expires = 999 * 24 * 60;

            WebHelper.SetCookie("Session_Code", httpModel.Attachments, expires);
            WebHelper.SetCookie("USER_FLAG", attachments, expires);

            return ShowResult(member);

            //记录IMEI
            //imei = WebHelper.Decrypt(imei);
            //if (!string.IsNullOrEmpty(imei))
            //{
            //    _ingotService.InsertDevice(member.Id, imei, deviceType);
            //}
        }

        /// <summary>
        /// 检测安全性
        /// </summary>
        /// <returns></returns>
        private bool Security(int userid)
        {
            if (userid == 0)
                return false;
            var member = _memberService.GetById(userid);
            var value = (userid == ViewBag.User.ID && member.Password == <PASSWORD>);
            
            return value;
        }

        /// <summary>
        /// 返回结果（支持JSONP）
        /// </summary>
        /// <param name="data">结果对象</param>
        /// <param name="attachments">附加信息</param>
        private ActionResult ShowResult(object data, object attachments = null)
        {
            var model = new HttpResponseModel();
            model.Data = data;
            model.Attachments = attachments;
            if (string.IsNullOrEmpty(_NxpCallback))
                return Json(model);
            return Content(string.Format("{0}({1})", _NxpCallback, WebHelper.Json(model, "yyyy-MM-dd HH:mm:ss")));
        }

        /// <summary>
        /// 显示错误
        /// </summary>
        /// <param name="error">错误信息</param>
        /// <param name="code">错误代码</param>
        private ActionResult LogError(string error, int code = 1)
        {
            HttpResponseModel model = new Models.HttpResponseModel();
            model.Code = code;
            model.Message = error;
            if (string.IsNullOrEmpty(_NxpCallback))
                return Json(model);
            return Content(string.Format("{0}({1})", _NxpCallback, WebHelper.Json(model, "yyyy-MM-dd HH:mm:ss")));
        }
    }
}
<file_sep>/Mvc.Web.Android/Controllers/ErrorController.cs
﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mvc.Web.Android.Controllers
{
    public class ErrorController : Controller
    {
        public ActionResult Error(string errorUrl = "")
        {
            if (errorUrl.Length > 0)
            {
                //SmsManager.Send(errorUrl, string.Empty);
            }

            return View();
        }

        public ActionResult NotFound(string err = "")
        {
            ViewBag.NotFoundMessage = "您所访问的页面没找到！";
            if (!string.IsNullOrEmpty(err))
            {
                ViewBag.NotFoundMessage = err;
            }
            return View();
        }
    }
}
