using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using System.Web;
using MySystem.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class UsersController : BaseController
    {
        public UsersController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        }




        #region 创客-我的-个人资料
        [Authorize]
        public JsonResult PersonalInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = PersonalInfoDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> PersonalInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            KxsMainModels.Users query = kxsdb.Users.FirstOrDefault(m => m.Id == Id) ?? new KxsMainModels.Users();
            string IdString = Id.ToString();
            Obj.Add("RealName", query.RealName); //真实姓名
            Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
            // Obj.Add("UserLevel", query.UserLevel); //创客实际等级
            DateTime now = DateTime.Now;
            UserRankWhite rank = maindb.UserRankWhite.FirstOrDefault(m => m.Id == Id && m.UpdateDate > now) ?? new UserRankWhite();
            if (rank.Id > 0 && rank.Rank > query.UserLevel)
            {
                Obj.Add("UserLevel", rank.Rank); //创客当前等级
            }
            else
            {
                Obj.Add("UserLevel", query.UserLevel); //创客当前等级
            }
            Obj.Add("Mobile", query.Mobile); //手机号
            Obj.Add("AuthFlag", query.AuthFlag); //实名标识
            Obj.Add("AuthDate", query.AuthDate == null ? "" : query.AuthDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //实名时间
            Obj.Add("MakerCode", query.MakerCode); //创客编号
            var str = function.CheckNull(query.ParentNav).Replace(",,", ",").Trim(',');
            Obj.Add("ParentNav", str); //创客组
            Obj.Add("LeaderLevel", query.LeaderLevel); //盟主标记(0 否 1 小盟主 2 大盟主)
            var storeHouse = maindb.StoreHouse.Any(m => m.UserId == Id && m.AuthFlag == 1);
            if (storeHouse)
            {
                Obj.Add("AuthFlags", 1); //认证分仓标记(0 否 1 是)
            }
            else
            {
                Obj.Add("AuthFlags", 0); //认证分仓标记
            }
            Users invite = UsersDbconn.Instance.Get(query.ParentUserId) ?? new Users();
            if (invite.Id > 0)
            {
                Obj.Add("InviteName", invite.RealName); //推荐人名称
                Obj.Add("InviteMobile", invite.Mobile); //推荐人手机号
            }
            else
            {
                Obj.Add("InviteName", query.RealName); //推荐人名称
                Obj.Add("InviteMobile", query.Mobile); //推荐人手机号
            }
            Obj.Add("CreateDate", query.CreateDate == null ? "" : query.CreateDate.Value.ToString("yyyy-MM-dd")); //创建时间
            Obj.Add("UserType", query.UserType); // 1-运营中心
            Obj.Add("AgentAreas", query.AgentAreas); //展业地区
            List<string> RightList = new List<string>();
            if (!string.IsNullOrEmpty(query.SeoDescription))
            {
                RightList = query.SeoDescription.Split(',').ToList();
            }
            Obj.Add("RightList", RightList);
            return Obj;
        }
        #endregion



        #region 创客-我的-主界面创客信息
        [Authorize]
        public JsonResult MyInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyInfoDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = UsersDbconn.Instance.Get(Id) ?? new Users();
            Obj.Add("RealName", DefaultRealName(query)); //真实姓名
            Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
            Obj.Add("UserLevel", query.UserLevel); //创客等级
            Obj.Add("MakerCode", query.MakerCode); //创客编号
            Obj.Add("Id", query.Id); //Id
            return Obj;
        }
        #endregion



        #region 创客-我的-忘记密码
        // [Authorize]
        public JsonResult ForgetPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ForgetPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ForgetPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string Mobile = data["Mobile"].ToString(); //手机号
            string LoginPwd = data["LoginPwd"].ToString(); //登录密码
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            string RealName = ""; //姓名
            if (value.Contains("\"RealName\""))
            {
                RealName = data["RealName"].ToString(); //姓名
            }
            string MakerCode = ""; //创客ID
            if (value.Contains("\"MakerCode\""))
            {
                MakerCode = data["MakerCode"].ToString(); //创客ID
                MakerCode = MakerCode.ToUpper();
            }
            if (string.IsNullOrEmpty(data["Mobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["Mobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["Mobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Mobile == Mobile);
            if (query != null)
            {
                query.UpdateDate = DateTime.Now; //修改时间
                query.LoginPwd = function.MD532(LoginPwd); //登录密码
                maindb.SaveChanges();
                UserForMobile mobilefor = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
                if (mobilefor == null)
                {
                    mobilefor = maindb.UserForMobile.Add(new UserForMobile()
                    {
                        Mobile = Mobile,
                        UserId = query.Id,
                    }).Entity;
                    maindb.SaveChanges();
                }
            }
            else
            {
                return new AppResultJson() { Status = "-1", Info = "此手机号不存在" };
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-我的推荐人
        [Authorize]
        public JsonResult MyInviter(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyInviterDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyInviterDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = new Users();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = maindb.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            Obj.Add("RealName", query.RealName); //真实姓名
            Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
            Obj.Add("Mobile", query.Mobile); //手机号
            Obj.Add("ReferenceCode", DefaultPic(query.ReferenceCode)); //推荐码
            return Obj;
        }
        #endregion



        #region 创客-我的-注册
        // [Authorize]
        public JsonResult Register(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = RegisterDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson RegisterDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string Mobile = data["Mobile"].ToString(); //手机号
            string LoginPwd = data["LoginPwd"].ToString(); //登录密码
            string ReferenceCode = data["ReferenceCode"].ToString(); //推荐码
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            string OpenId = data["OpenId"].ToString(); //短信验证码
            if (string.IsNullOrEmpty(data["Mobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["Mobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["Mobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            UserForMobile checkmobile = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
            if (checkmobile != null)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号已经被注册，请更换手机号" };
            }
            UserForMakerCode userfor = maindb.UserForMakerCode.FirstOrDefault(m => m.MakerCode == ReferenceCode);
            if (userfor == null)
            {
                return new AppResultJson() { Status = "-1", Info = "推荐码有误，请核对后重新填写" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Users inviteUser = maindb.Users.FirstOrDefault(m => m.Id == userfor.UserId) ?? new Users();
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.Add(new Users()
            {
                CreateDate = DateTime.Now, //创建时间
                Mobile = Mobile, //手机号
                LoginPwd = function.MD532(LoginPwd), //登录密码
                ReferenceCode = ReferenceCode, //推荐码
                // MakerCode = MakerCode,
                ParentUserId = userfor.UserId,
                ParentNav = inviteUser.ParentNav + "," + inviteUser.Id + ",",
                OpenId = OpenId,
                UserLevel = 1,
            }).Entity;
            maindb.SaveChanges();
            string MakerCode = "K";
            int UserId = query.Id;
            string UserIdString = UserId.ToString();
            for (int i = 0; i < 8 - UserId.ToString().Length; i++)
            {
                UserIdString = "0" + UserIdString;
            }
            MakerCode += UserIdString;
            bool checkMakerCode = maindb.UserForMakerCode.Any(m => m.MakerCode == MakerCode);
            if (checkMakerCode)
            {
                MakerCode += "D";
            }
            query.MakerCode = MakerCode;
            maindb.SaveChanges();
            UserForMobile userformobile = maindb.UserForMobile.Add(new UserForMobile()
            {
                Mobile = Mobile,
                UserId = query.Id,
            }).Entity;
            UserForMakerCode userforcode = maindb.UserForMakerCode.Add(new UserForMakerCode()
            {
                MakerCode = MakerCode,
                UserId = query.Id,
            }).Entity;
            maindb.SaveChanges();
            if (value.Contains("\"SnId\":"))
            {
                int SnId = int.Parse(function.CheckInt(data["SnId"].ToString()));
                PosMachinesTwo pos = maindb.PosMachinesTwo.FirstOrDefault(m => m.Status > -1 && m.Id == SnId);
                if (pos != null)
                {
                    if (function.CheckNull(query.ParentNav).Contains("," + pos.BuyUserId + ","))
                    {
                        pos.UserId = query.Id;
                        query.MerchantType = 1;
                        string MerNo = "";
                        PosMerchantInfo merchant = maindb.PosMerchantInfo.FirstOrDefault(m => m.Id == pos.BindMerchantId);
                        if (merchant != null)
                        {
                            merchant.UserId = query.Id;
                            merchant.MerUserType = 1;
                            MerNo = merchant.MerchantName;
                        }
                        pos.SeoTitle = query.Id.ToString(); // 记录商户型创客的Id
                        maindb.SetMerchantTypeRecord.Add(new SetMerchantTypeRecord()
                        {
                            CreateDate = DateTime.Now,
                            IsRecyc = (ulong)pos.IsPurchase,
                            CreditAmount = pos.CreditTrade,
                            PosSnType = pos.PosSnType,
                            ActDate = pos.ActivationTime,
                            BindDate = pos.BindingTime,
                            ActStatus = (ulong)pos.ActivationState,
                            BindStatus = (ulong)pos.BindingState,
                            MerNo = MerNo,
                            PosSn = pos.PosSn,
                            Note = "设置商户型创客2",
                            ToUserId = query.Id,
                            FromUserId = pos.BuyUserId,
                        });
                        maindb.SaveChanges();
                        if (System.IO.File.Exists(function.getPath("/static/MerQrCode/" + function.MD5_16(SnId.ToString()) + ".png")))
                        {
                            System.IO.File.Delete(function.getPath("/static/MerQrCode/" + function.MD5_16(SnId.ToString()) + ".png"));
                        }
                    }
                }
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-登录
        public JsonResult Login(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string Mobile = data["Mobile"].ToString(); //手机号
            string NickName = data["NickName"].ToString();
            string HeadPhoto = data["HeadPhoto"].ToString();
            string MakerCode = data["MakerCode"].ToString();
            string KxsOpenId = data["KxsOpenId"].ToString();
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            MiniModels.UserForProject miniuser = minidb.UserForProject.FirstOrDefault(m => m.OpenId == KxsOpenId) ?? new MiniModels.UserForProject();
            Users user = maindb.Users.FirstOrDefault(m => m.Id == miniuser.PlateformUserId && m.Tags == KxsOpenId);
            if (user == null)
            {
                user = maindb.Users.Add(new Users()
                {
                    Id = miniuser.PlateformUserId,
                    CreateDate = DateTime.Now,
                    Tags = KxsOpenId,
                    NickName = NickName,
                    HeadPhoto = HeadPhoto,
                    Mobile = Mobile,
                    MakerCode = MakerCode,
                }).Entity;
                maindb.SaveChanges();
            }
            else
            {
                user.UpdateDate = DateTime.Now;
                user.NickName = NickName;
                user.HeadPhoto = HeadPhoto;
                user.MakerCode = MakerCode;
                user.Mobile = Mobile;
                maindb.SaveChanges();
            }
            UserForMobile query = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
            if (query == null)
            {
                query = maindb.UserForMobile.Add(new UserForMobile()
                {
                    Mobile = Mobile,
                    UserId = user.Id,
                }).Entity;
                maindb.SaveChanges();
            }
            else
            {
                query.UserId = user.Id;
                maindb.SaveChanges();
            }
            Obj.Add("Id", user.Id);
            Obj.Add("Token", PublicFunction.AppToken(user.Id, JwtSecret, JwtIss));
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 创客-我的-注销
        // 1、未实名创客；
        // 2、已实名创客，无开通商户；
        // 3、近7天未在商城下单过商品；
        // 4、名下无未绑定机具、机具券，无未申请的循环机；
        [Authorize]
        public JsonResult Delete(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString()));
            string Mobile = data["Mobile"].ToString();
            // string MobileCode = data["MobileCode"].ToString(); //短信验证码
            // MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            // if (mobilecheck == null)
            // {
            //     return Json(new AppResultJson() { Status = "-1", Info = "短信验证码不正确" });
            // }
            // if (mobilecheck.CheckCode != MobileCode)
            // {
            //     return Json(new AppResultJson() { Status = "-1", Info = "短信验证码不正确" });
            // }
            // RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId && m.Mobile == Mobile);
            if (user != null)
            {
                if (user.AuthFlag == 1)
                {
                    bool check = maindb.PosMachinesTwo.Any(m => m.BuyUserId == user.Id && m.BindingState == 1);
                    if (check)
                    {
                        return Json(new AppResultJson() { Status = "-1", Info = "注销失败，未满足条件：已实名创客，无开通商户。如有疑问，请联系客服" });
                    }
                    DateTime checkDate = DateTime.Now.AddDays(-7);
                    check = maindb.Orders.Any(m => m.CreateDate >= checkDate && m.Status > 0 && m.UserId == user.Id);
                    if (check)
                    {
                        return Json(new AppResultJson() { Status = "-1", Info = "注销失败，未满足条件：近7天未在商城下单过商品。如有疑问，请联系客服" });
                    }
                    check = maindb.PosMachinesTwo.Any(m => m.BuyUserId == user.Id && m.IsPurchase == 0);
                    if (check)
                    {
                        return Json(new AppResultJson() { Status = "-1", Info = "注销失败，未满足条件：名下无未绑定机具、机具券，无未申请的循环机。如有疑问，请联系客服" });
                    }
                    check = maindb.PosCoupons.Any(m => m.UserId == user.Id && m.IsUse == 0);
                    if (check)
                    {
                        return Json(new AppResultJson() { Status = "-1", Info = "注销失败，未满足条件：名下无未绑定机具、机具券，无未申请的循环机。如有疑问，请联系客服" });
                    }
                    UserForMobile forMobile = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
                    if (forMobile != null)
                    {
                        maindb.Remove(forMobile);
                    }
                    user.Status = -1;
                    user.Mobile += "d";
                    user.CertId += "d";
                }
                else
                {
                    UserForMobile forMobile = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
                    if (forMobile != null)
                    {
                        maindb.Remove(forMobile);
                    }
                    user.Status = -1;
                    user.Mobile += "d";
                    user.CertId += "d";
                }
                function.WriteLog(user.Id + "于" + DateTime.Now.ToString() + "注销账号", "创客注销日志");
                // TODO: 每月扫描一次注销的创客，把注销创客伞下创客全部挂到注销创客的上级
                // TODO: 清除token,token登录返回
                maindb.SaveChanges();
                return Json(new AppResultJson() { Status = "1", Info = "" });
            }
            return Json(new AppResultJson() { Status = "-1", Info = "手机号不正确" });
        }
        #endregion



        #region 创客-我的-个人资料-上传头像
        [Authorize]
        public JsonResult UploadHeadPhoto(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = UploadHeadPhotoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson UploadHeadPhotoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string HeadPhoto = data["HeadPhoto"].ToString(); //头像
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.HeadPhoto = HeadPhoto; //头像
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-提现-绑定银行卡信息
        [Authorize]
        public JsonResult BindBankInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = BindBankInfoDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> BindBankInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = UsersDbconn.Instance.Get(Id) ?? new Users();
            Obj.Add("SettleBankCardNo", query.SettleBankCardNo); //结算银行卡号
            Obj.Add("BankName", query.SettleBankName); //银行名称
            return Obj;
        }
        #endregion



        #region 创客-我的-设置-修改支付密码
        [Authorize]
        public JsonResult ModifyPayPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ModifyPayPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ModifyPayPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string PayPwd = data["PayPwd"].ToString(); //支付密码
            string NewPayPwd = data["NewPayPwd"].ToString(); //新支付密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                if (query.PayPwd != function.MD532(PayPwd))
                {
                    return new AppResultJson() { Status = "1", Info = "原支付密码不正确，请重试", Data = Obj };
                }
                query.PayPwd = function.MD532(NewPayPwd); //支付密码
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-修改登录密码
        [Authorize]
        public JsonResult ModifyLoginPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ModifyLoginPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ModifyLoginPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string LoginPwd = data["LoginPwd"].ToString(); //登录密码
            string NewLoginPwd = data["NewLoginPwd"].ToString(); //新登录密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                if (function.MD532(LoginPwd) != query.LoginPwd)
                {
                    return new AppResultJson() { Status = "-1", Info = "原登录密码不正确，请重试" };
                }
                query.LoginPwd = function.MD532(NewLoginPwd); //登录密码
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-修改登录手机号
        [Authorize]
        public JsonResult ModifyMobile(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ModifyMobileDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ModifyMobileDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string Mobile = data["Mobile"].ToString(); //手机号
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            if (string.IsNullOrEmpty(data["Mobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["Mobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["Mobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            UserForMobile userfor = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile) ?? new UserForMobile();
            if (userfor.UserId != Id && userfor.UserId > 0)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号已被占用，请重新填写" };
            }
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                string oldMobile = query.Mobile;
                query.Mobile = Mobile; //手机号
                UserForMobile userFor = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == Mobile);
                if (userFor == null)
                {
                    userFor = maindb.UserForMobile.Add(new UserForMobile()
                    {
                        Mobile = Mobile,
                        UserId = Id,
                    }).Entity;
                    maindb.SaveChanges();
                }
                UserForMobile oldUserFor = maindb.UserForMobile.FirstOrDefault(m => m.Mobile == oldMobile);
                if (oldUserFor != null)
                {
                    maindb.Remove(oldUserFor);
                    maindb.SaveChanges();
                }
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-判断是否设置支付密码
        [Authorize]
        public JsonResult ExistPayPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            if (string.IsNullOrEmpty(query.PayPwd))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "", Data = Obj });
            }
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 创客-我的-设置-变更结算卡
        [Authorize]
        public JsonResult ChangeBankCard(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ChangeBankCardDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ChangeBankCardDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            string Mobile = data["Mobile"].ToString();
            string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string BankCardPositiveImage = data["BankCardPositiveImage"].ToString(); //银行卡正面照
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.SeoTitle = BankName;
                query.SettleBankName = SettleBankName;
                query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                query.BankCardPositiveImage = BankCardPositiveImage; //银行卡正面照
                UserAuthRecord auth = maindb.UserAuthRecord.FirstOrDefault(m => m.UserId == Id);
                if (auth != null)
                {
                    auth.BankCardAccount = SettleBankCardNo; //银行卡账号
                }
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }


        // 提交代付签约
        [Authorize]
        public JsonResult ChangeBankCardCheck(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            string Mobile = data["Mobile"].ToString();
            string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string BankCardPositiveImage = data["BankCardPositiveImage"].ToString(); //银行卡正面照
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            if (mobilecheck == null)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "短信验证码不正确" });
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "短信验证码不正确" });
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.SeoTitle = BankName;
                query.SettleBankName = SettleBankName;
                query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                query.BankCardPositiveImage = BankCardPositiveImage; //银行卡正面照
                maindb.SaveChanges();
                return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
            }
            return Json(new AppResultJson() { Status = "-1", Info = "认证失败，请重试", Data = Obj });
        }

        [Authorize]
        public JsonResult ChangeBankCard2(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ChangeBankCard2Do(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ChangeBankCard2Do(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            string Mobile = data["Mobile"].ToString();
            string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string BankCardPositiveImage = data["BankCardPositiveImage"].ToString(); //银行卡正面照
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.SeoTitle = BankName;
                query.SettleBankName = SettleBankName;
                query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                query.BankCardPositiveImage = BankCardPositiveImage; //银行卡正面照
                UserAuthRecord auth = maindb.UserAuthRecord.FirstOrDefault(m => m.UserId == Id);
                if (auth != null)
                {
                    auth.BankCardAccount = SettleBankCardNo; //银行卡账号
                }
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-安全退出
        [Authorize]
        public JsonResult Logout(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = LogoutDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson LogoutDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string UserId = data["UserId"].ToString(); //创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            // TODO:退出登录需要处理的逻辑，待定
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-忘记支付密码验证
        [Authorize]
        public JsonResult CheckForgetPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = CheckForgetPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson CheckForgetPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string RealName = data["RealName"].ToString(); //真实姓名
            string CertId = data["CertId"].ToString(); //身份证号
            string Mobile = data["Mobile"].ToString(); //手机号
            string MobileCode = data["MobileCode"].ToString(); //短信验证码
            if (string.IsNullOrEmpty(data["Mobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["Mobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["Mobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            MobileCodeCheck mobilecheck = RedisDbconn.Instance.Get<MobileCodeCheck>("MobileCodeCheck:" + Mobile);
            if (mobilecheck == null)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            if (mobilecheck.CheckCode != MobileCode)
            {
                return new AppResultJson() { Status = "-1", Info = "短信验证码不正确" };
            }
            RedisDbconn.Instance.Clear("MobileCodeCheck:" + Mobile);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            // TODO:验证接口，待定
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-提交实名认证资料
        [Authorize]
        public JsonResult PostAuth(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = PostAuthDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson PostAuthDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string RealName = data["RealName"].ToString(); //真实姓名
            string CertId = data["CertId"].ToString(); //身份证号
            string Areas = data["Areas"].ToString(); //所在地区
            string Mobile = data["Mobile"].ToString(); //手机号
            string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string CertFrontImage = data["CertFrontImage"].ToString(); //身份证正面照
            string CertReverseImage = data["CertReverseImage"].ToString(); //身份证反面照
            string HandCertImage = data["HandCertImage"].ToString(); //手持身份证
            string BankCardPositiveImage = data["BankCardPositiveImage"].ToString(); //银行卡正面照
            string BankMobile = data["BankMobile"].ToString(); //银行预留手机号
            string Distribute = "";
            if (value.Contains("\"Distribute\""))
            {
                Distribute = data["Distribute"].ToString();
            }
            if (string.IsNullOrEmpty(data["BankMobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["BankMobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["BankMobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            bool checkCertId = maindb.Users.Any(m => m.CertId == CertId);
            if (checkCertId)
            {
                return new AppResultJson() { Status = "-1", Info = "您输入的身份证号已经认证过了，请更换身份证" };
            }
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                string result = BankCardCheckForThree.Instance.Do(SettleBankCardNo, CertId, RealName);
                JsonData jsonObj = JsonMapper.ToObject(result);
                if (jsonObj["code"].ToString() == "200")
                {
                    if (jsonObj["data"]["result"].ToString() == "0")
                    {
                        query.AuthFlag = 1;
                        query.AuthDate = DateTime.Now;
                        query.RealName = RealName; //真实姓名
                        query.CertId = CertId; //身份证号
                        query.Areas = Areas; //所在地区
                        query.SeoTitle = BankName;
                        query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                        query.SettleBankName = SettleBankName; //结算银行名称
                        query.CertFrontImage = CertFrontImage; //身份证正面照
                        query.CertReverseImage = CertReverseImage; //身份证反面照
                        query.HandCertImage = HandCertImage; //手持身份证
                        query.BankCardPositiveImage = BankCardPositiveImage; //银行卡正面照
                        maindb.SaveChanges();
                        UserAuthRecord auth = maindb.UserAuthRecord.Add(new UserAuthRecord()
                        {
                            CreateDate = DateTime.Now,
                            UserId = Id, //创客
                            RealName = RealName, //真实姓名
                            IdcardNo = CertId, //身份证号码
                            BankCardAccount = SettleBankCardNo, //银行卡账号
                            BankMobile = BankMobile, //银行预留手机号码
                        }).Entity;
                        maindb.SaveChanges();

                        //实名认证成功后消息推送
                        Users users = maindb.Users.FirstOrDefault(m => m.Id == query.ParentUserId);
                        RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                        {
                            UserId = users.Id, //创客Id
                            MsgType = 2,
                            Title = "来新人啦", //标题
                            Summary = "您的码牌系统有新人加入了，请进入码牌-我的创客中查看！",//简介
                            CreateDate = DateTime.Now,

                        }));
                        return new AppResultJson() { Status = "1", Info = "", Data = Obj };
                    }
                    else
                    {
                        return new AppResultJson() { Status = "-1", Info = jsonObj["data"]["desc"].ToString() };
                    }
                }
                else
                {
                    return new AppResultJson() { Status = "-1", Info = jsonObj["msg"].ToString() };
                }
            }
            return new AppResultJson() { Status = "-1", Info = "认证失败，请重试" };
        }


        [Authorize]
        public JsonResult PostAuth2(string value, string CertFrontBase64, string CertReverseBase64)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = PostAuth2Do(value, CertFrontBase64, CertReverseBase64);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson PostAuth2Do(string value, string CertFrontBase64, string CertReverseBase64)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string RealName = data["RealName"].ToString(); //真实姓名
            string CertId = data["CertId"].ToString(); //身份证号
            string Areas = data["Areas"].ToString(); //所在地区
            string Mobile = data["Mobile"].ToString(); //手机号
            string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string CertFrontImage = data["CertFrontImage"].ToString(); //身份证正面照
            string CertReverseImage = data["CertReverseImage"].ToString(); //身份证反面照
            // string CertFrontBase64 = data["CertFrontBase64"].ToString(); //身份证正面照
            // string CertReverseBase64 = data["CertReverseBase64"].ToString(); //身份证反面照
            string HandCertImage = data["HandCertImage"].ToString(); //手持身份证
            string BankCardPositiveImage = data["BankCardPositiveImage"].ToString(); //银行卡正面照
            string BankMobile = data["BankMobile"].ToString(); //银行预留手机号
            string Distribute = "";
            if (value.Contains("\"Distribute\""))
            {
                Distribute = data["Distribute"].ToString();
            }
            if (string.IsNullOrEmpty(data["BankMobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["BankMobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["BankMobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            bool checkCertId = maindb.Users.Any(m => m.CertId == CertId);
            if (checkCertId)
            {
                return new AppResultJson() { Status = "-1", Info = "您输入的身份证号已经认证过了，请更换身份证" };
            }
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                string result = BankCardCheckForThree.Instance.Do(SettleBankCardNo, CertId, RealName);
                JsonData jsonObj = JsonMapper.ToObject(result);
                if (jsonObj["code"].ToString() == "200")
                {
                    if (jsonObj["data"]["result"].ToString() == "0")
                    {
                        query.AuthFlag = 1;
                        query.AuthDate = DateTime.Now;
                        query.RealName = RealName; //真实姓名
                        query.CertId = CertId; //身份证号
                        query.Areas = Areas; //所在地区
                        query.SeoTitle = BankName;
                        query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                        query.SettleBankName = SettleBankName; //结算银行名称
                        query.CertFrontImage = CertFrontImage; //身份证正面照
                        query.CertReverseImage = CertReverseImage; //身份证反面照
                        query.HandCertImage = HandCertImage; //手持身份证
                        query.BankCardPositiveImage = BankCardPositiveImage; //银行卡正面照
                        maindb.SaveChanges();
                        UserAuthRecord auth = maindb.UserAuthRecord.Add(new UserAuthRecord()
                        {
                            CreateDate = DateTime.Now,
                            UserId = Id, //创客
                            RealName = RealName, //真实姓名
                            IdcardNo = CertId, //身份证号码
                            BankCardAccount = SettleBankCardNo, //银行卡账号
                            BankMobile = BankMobile, //银行预留手机号码
                        }).Entity;
                        maindb.SaveChanges();

                        //实名认证成功后消息推送
                        Users users = maindb.Users.FirstOrDefault(m => m.Id == query.ParentUserId);
                        RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                        {
                            UserId = users.Id, //创客Id
                            MsgType = 2,
                            Title = "来新人啦", //标题
                            Summary = "您的码牌系统有新人加入了，请进入码牌-我的创客中查看！",//简介
                            CreateDate = DateTime.Now,

                        }));

                        return new AppResultJson() { Status = "1", Info = "", Data = Obj };
                    }
                    else
                    {
                        return new AppResultJson() { Status = "-1", Info = jsonObj["data"]["desc"].ToString() };
                    }
                }
                else
                {
                    return new AppResultJson() { Status = "-1", Info = jsonObj["msg"].ToString() };
                }
            }
            return new AppResultJson() { Status = "-1", Info = "认证失败，请重试" };
        }

        #endregion



        #region 创客-我的-提现实名认证资料
        [Authorize]
        public JsonResult CashAuth(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = CashAuthDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson CashAuthDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string CertFrontImage = data["CertFrontImage"].ToString(); //身份证正面照
            string CertReverseImage = data["CertReverseImage"].ToString(); //身份证反面照
            // string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string BankMobile = data["BankMobile"].ToString(); //银行预留手机号
            if (string.IsNullOrEmpty(data["BankMobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["BankMobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["BankMobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string check = RedisDbconn.Instance.Get<string>("CashAuth:" + Id);
            if (!string.IsNullOrEmpty(check))
            {
                return new AppResultJson() { Status = "-1", Info = "资料审核中, 请稍后再试" };
            }
            RedisDbconn.Instance.Set("CashAuth:" + Id, "1");
            RedisDbconn.Instance.SetExpire("CashAuth:" + Id, 300);
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                query.SettleBankName = SettleBankName; //结算银行名称
                query.CertFrontImage = CertFrontImage; //身份证正面照
                query.CertReverseImage = CertReverseImage; //身份证反面照
                UserAuthRecord auth = maindb.UserAuthRecord.FirstOrDefault(m => m.UserId == Id);
                if (auth != null)
                {
                    auth.BankCardAccount = SettleBankCardNo; //银行卡账号
                    auth.BankMobile = BankMobile; //银行预留手机号码
                }
                maindb.SaveChanges();
                return new AppResultJson() { Status = "1", Info = "", Data = Obj };
            }
            return new AppResultJson() { Status = "-1", Info = "认证失败，请重试" };
        }


        [Authorize]
        public JsonResult CashAuth2(string value, string CertFrontBase64, string CertReverseBase64)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = CashAuth2Do(value, CertFrontBase64, CertReverseBase64);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson CashAuth2Do(string value, string CertFrontBase64, string CertReverseBase64)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string CertFrontImage = data["CertFrontImage"].ToString(); //身份证正面照
            string CertReverseImage = data["CertReverseImage"].ToString(); //身份证反面照
            // string CertFrontBase64 = data["CertFrontBase64"].ToString(); //身份证正面照
            // string CertReverseBase64 = data["CertReverseBase64"].ToString(); //身份证反面照
            // string BankName = data["BankName"].ToString(); //开户行全称
            string SettleBankName = data["SettleBankName"].ToString(); //结算银行名称
            string SettleBankCardNo = data["SettleBankCardNo"].ToString(); //结算银行卡号
            string BankMobile = data["BankMobile"].ToString(); //银行预留手机号
            if (string.IsNullOrEmpty(data["BankMobile"].ToString()))
            {
                return new AppResultJson() { Status = "-1", Info = "请填写手机号" };
            }
            if (data["BankMobile"].ToString().Length > 11)
            {
                return new AppResultJson() { Status = "-1", Info = "手机号最多11个字符" };
            }
            if (function.CheckMobile(data["BankMobile"].ToString()) == "")
            {
                return new AppResultJson() { Status = "-1", Info = "请填写正确的手机号" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string check = RedisDbconn.Instance.Get<string>("CashAuth:" + Id);
            if (!string.IsNullOrEmpty(check))
            {
                return new AppResultJson() { Status = "-1", Info = "资料审核中, 请稍后再试" };
            }
            RedisDbconn.Instance.Set("CashAuth:" + Id, "1", 600);
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.SettleBankCardNo = SettleBankCardNo; //结算银行卡号
                query.SettleBankName = SettleBankName; //结算银行名称
                query.CertFrontImage = CertFrontImage; //身份证正面照
                query.CertReverseImage = CertReverseImage; //身份证反面照
                UserAuthRecord auth = maindb.UserAuthRecord.FirstOrDefault(m => m.UserId == Id);
                if (auth != null)
                {
                    auth.BankCardAccount = SettleBankCardNo; //银行卡账号
                    auth.BankMobile = BankMobile; //银行预留手机号码
                }
                maindb.SaveChanges();
                return new AppResultJson() { Status = "1", Info = "", Data = Obj };
            }
            return new AppResultJson() { Status = "-1", Info = "认证失败，请重试" };
        }

        #endregion

        #region 创客-我的-获取提现认证失败原因
        [Authorize]
        public JsonResult CashAuthFailInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = UsersDbconn.Instance.Get(Id) ?? new Users();
            string Remark = function.CheckNull(query.Remark);
            if (Remark.StartsWith("代付失败原因："))
            {
                return Json(new AppResultJson() { Status = "-1", Info = Remark.Replace("代付失败原因：", "") });
            }
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 创客-我的-设置-提交忘记支付密码
        [Authorize]
        public JsonResult ForgetPayPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ForgetPayPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ForgetPayPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string PayPwd = data["PayPwd"].ToString(); //支付密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = new Users();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.PayPwd = function.MD532(PayPwd); //支付密码
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-设置支付密码
        [Authorize]
        public JsonResult SetPayPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = SetPayPwdDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson SetPayPwdDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string PayPwd = data["PayPwd"].ToString(); //支付密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.UpdateDate = DateTime.Now; //修改时间
                query.PayPwd = function.MD532(PayPwd); //支付密码\
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-我的-设置-验证原支付密码
        [Authorize]
        public JsonResult CheckPayPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string PayPwd = data["PayPwd"].ToString(); //支付密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            if (string.IsNullOrEmpty(query.PayPwd))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "请设置支付密码" });
            }
            if (query.PayPwd != function.MD532(PayPwd))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "原支付密码不正确" });
            }
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 创客-我的-设置-验证登录密码
        [Authorize]
        public JsonResult CheckLoginPwd(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string LoginPwd = data["LoginPwd"].ToString(); //支付密码
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = new Users();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = UsersDbconn.Instance.Get(Id) ?? new Users();
            if (query.LoginPwd != function.MD532(LoginPwd))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "登录密码不正确" });
            }
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 我的-设置-获取实名认证四要素
        [Authorize]
        public JsonResult AuthInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = AuthInfoDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> AuthInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = UsersDbconn.Instance.Get(Id) ?? new Users();
            Obj.Add("RealName", DefaultRealName(query)); //真实姓名
            Obj.Add("CertId", query.CertId); //身份证号
            Obj.Add("Mobile", query.Mobile); //手机号
            Obj.Add("SettleBankCardNo", query.SettleBankCardNo); //结算银行卡号
            Obj.Add("SettleBankName", query.SettleBankName); //结算银行卡名称
            Obj.Add("BankName", query.SeoTitle); //开户行全称
            return Obj;
        }
        #endregion



        #region 创客-首页-交易分析-个人业绩-趋势图
        [Authorize]
        public JsonResult PersonalPerformanceTrend(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = PersonalPerformanceTrendDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> PersonalPerformanceTrendDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string UserId = data["UserId"].ToString(); //创客Id
            string Kind = data["Kind"].ToString(); //查询类别
            Dictionary<string, object> Obj = new Dictionary<string, object>();

            //总交易趋势数据   
            List<Dictionary<string, object>> MainTradeList = new List<Dictionary<string, object>>();
            if (Kind == "1")
            {
                for (int i = 7; i >= 1; i--)
                {
                    DateTime Date = DateTime.Now.AddDays(-i);
                    var date = Date.ToString("yyyyMMdd");
                    decimal HelpAmount = 0;
                    DataTable dt = OtherMySqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId=" + UserId + ") AND TradeDate=" + date + "");
                    foreach (DataRow items in dt.Rows)
                    {
                        HelpAmount = decimal.Parse(function.CheckNum(items["TradeAmount"].ToString()));
                    }
                    var amount = UserTradeDaySummaryDbconn.Instance.GetDateTrade(int.Parse(UserId), Date.ToString("yyyyMMdd"));
                    var total = amount + HelpAmount;
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Date.ToString("MMdd")); //日期/月份
                    item.Add("TradeAmt", UserTradeDaySummaryDbconn.Instance.GetDateTrade(int.Parse(UserId), Date.ToString("yyyyMMdd"))); //交易额
                    MainTradeList.Add(item);
                }
            }
            else
            {
                for (int i = 6; i >= 1; i--)
                {
                    DateTime Month = DateTime.Now.AddMonths(-i);
                    var month = Month.ToString("yyyyMM");
                    decimal HelpAmount = 0;
                    DataTable dt = OtherMySqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId=" + UserId + ") AND TradeMonth=" + month + "");
                    foreach (DataRow items in dt.Rows)
                    {
                        HelpAmount = decimal.Parse(function.CheckNum(items["TradeAmount"].ToString()));
                    }
                    var amount = UserTradeDaySummaryDbconn.Instance.GetMonthTrade(int.Parse(UserId), Month.ToString("yyyyMM"));
                    var total = amount + HelpAmount;
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Month.ToString("yyyyMM")); //日期/月份
                    item.Add("TradeAmt", total); //交易额
                    MainTradeList.Add(item);
                }
            }
            Obj.Add("MainTrade", MainTradeList);

            //新增创客总数趋势数据
            List<Dictionary<string, object>> AddMakerList = new List<Dictionary<string, object>>();
            if (Kind == "1")
            {
                for (int i = 7; i >= 1; i--)
                {
                    DateTime Date = DateTime.Now.AddDays(-i);
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Date.ToString("MMdd")); //日期/月份
                    item.Add("Count", UsersDbconn.Instance.GetNewUserCount(int.Parse(UserId), Date.ToString("yyyyMMdd"))); //交易额
                    AddMakerList.Add(item);
                }
            }
            else
            {
                for (int i = 6; i >= 1; i--)
                {
                    DateTime Month = DateTime.Now.AddMonths(-i);
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Month.ToString("yyyyMM")); //日期/月份
                    item.Add("Count", UsersDbconn.Instance.GetNewUserCount(int.Parse(UserId), Month.ToString("yyyyMM"))); //交易额
                    AddMakerList.Add(item);
                }
            }
            Obj.Add("AddMaker", AddMakerList);

            //新增激活商户总数趋势数据
            List<Dictionary<string, object>> AddActMerchantList = new List<Dictionary<string, object>>();
            for (int i = 7; i >= 1; i--)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                if (Kind == "1")
                {
                    DateTime time = DateTime.Now.AddDays(-i);
                    string Date = time.ToString("MMdd");
                    item.Add("Time", Date); //日期/月份
                    item.Add("Count", UserDataDbconn.Instance.GetPosActCount(int.Parse(UserId), time.ToString("yyyyMMdd"))); //数量
                }
                else
                {
                    string Month = DateTime.Now.AddMonths(-i).ToString("yyyyMM");
                    item.Add("Time", Month); //日期/月份
                    item.Add("Count", UserDataDbconn.Instance.GetPosActCount(int.Parse(UserId), Month)); //数量
                }
                AddActMerchantList.Add(item);
            }
            Obj.Add("AddActMerchant", AddActMerchantList);
            return Obj;
        }
        #endregion


        #region 创客-首页-交易分析-团队业绩-趋势图
        [Authorize]
        public JsonResult TeamPerformanceTrend(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = TeamPerformanceTrendDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> TeamPerformanceTrendDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string UserId = data["UserId"].ToString(); //创客Id
            string Kind = data["Kind"].ToString(); //查询类别
            Dictionary<string, object> Obj = new Dictionary<string, object>();

            //总交易趋势数据
            List<Dictionary<string, object>> MainTradeList = new List<Dictionary<string, object>>();
            if (Kind == "1")
            {
                for (int i = 7; i >= 1; i--)
                {
                    DateTime Date = DateTime.Now.AddDays(-i);
                    var date = Date.ToString("yyyyMMdd");
                    decimal HelpAmount = 0;
                    DataTable dt = OtherMySqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId IN(SELECT Id from Users WHERE ParentNav like '%," + UserId + ",%' OR Id=" + UserId + ")) AND TradeDate=" + date + "");
                    foreach (DataRow items in dt.Rows)
                    {
                        HelpAmount = decimal.Parse(function.CheckNum(items["TradeAmount"].ToString()));
                    }
                    var amount = UserTradeDaySummaryDbconn.Instance.GetDateTrade(int.Parse(UserId), Date.ToString("yyyyMMdd"), "team");
                    var total = amount + HelpAmount;
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Date.ToString("MMdd")); //日期/月份
                    item.Add("TradeAmt", total); //交易额
                    MainTradeList.Add(item);
                }
            }
            else
            {
                for (int i = 6; i >= 1; i--)
                {
                    DateTime Month = DateTime.Now.AddMonths(-i);
                    var month = Month.ToString("yyyyMM");
                    decimal HelpAmount = 0;
                    DataTable dt = OtherMySqlConn.dtable("SELECT SUM(TradeAmount) TradeAmount FROM HelpProfitMerTradeSummay WHERE MerchantId IN(SELECT MerchantId FROM HelpProfitMerIds WHERE UserId IN(SELECT Id from Users WHERE ParentNav like '%," + UserId + ",%' OR Id=" + UserId + ")) AND TradeMonth=" + month + "");
                    foreach (DataRow items in dt.Rows)
                    {
                        HelpAmount = decimal.Parse(function.CheckNum(items["TradeAmount"].ToString()));
                    }
                    var amount = UserTradeDaySummaryDbconn.Instance.GetMonthTrade(int.Parse(UserId), Month.ToString("yyyyMM"), "team");
                    var total = amount + HelpAmount;
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Month.ToString("yyyyMM")); //日期/月份
                    item.Add("TradeAmt", total); //交易额
                    MainTradeList.Add(item);
                }
            }
            Obj.Add("MainTrade", MainTradeList);

            //新增创客总数趋势数据
            List<Dictionary<string, object>> AddMakerList = new List<Dictionary<string, object>>();
            if (Kind == "1")
            {
                for (int i = 7; i >= 1; i--)
                {
                    DateTime Date = DateTime.Now.AddDays(-i);
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Date.ToString("MMdd")); //日期/月份
                    item.Add("Count", UsersDbconn.Instance.GetTeamNewUserCount(int.Parse(UserId), Date.ToString("yyyyMMdd"))); //交易额
                    AddMakerList.Add(item);
                }
            }
            else
            {
                for (int i = 6; i >= 1; i--)
                {
                    DateTime Month = DateTime.Now.AddMonths(-i);
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item.Add("Time", Month.ToString("yyyyMM")); //日期/月份
                    item.Add("Count", UsersDbconn.Instance.GetTeamNewUserCount(int.Parse(UserId), Month.ToString("yyyyMM"))); //交易额
                    AddMakerList.Add(item);
                }
            }
            Obj.Add("AddMaker", AddMakerList);

            //新增激活商户总数趋势数据
            List<Dictionary<string, object>> AddActMerchantList = new List<Dictionary<string, object>>();
            if (Kind == "1")
            {
                for (int i = 7; i >= 1; i--)
                {
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    DateTime time = DateTime.Now.AddDays(-i);
                    string Date = time.ToString("MMdd");
                    item.Add("Time", Date); //日期/月份
                    item.Add("Count", UserDataDbconn.Instance.GetTeamPosActCount(int.Parse(UserId), time.ToString("yyyyMMdd"))); //数量
                    AddActMerchantList.Add(item);
                }
            }
            else
            {
                for (int i = 6; i >= 1; i--)
                {
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    string Month = DateTime.Now.AddMonths(-i).ToString("yyyyMM");
                    item.Add("Time", Month); //日期/月份
                    item.Add("Count", UserDataDbconn.Instance.GetTeamPosActCount(int.Parse(UserId), Month)); //数量
                    AddActMerchantList.Add(item);
                }
            }
            Obj.Add("AddActMerchant", AddActMerchantList);
            return Obj;
        }
        #endregion


        #region 创客-首页-我的创客-主界面创客列表
        [Authorize]
        public JsonResult MyMakerList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = MyMakerListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> MyMakerListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string RealName = data["RealName"].ToString(); //真实姓名
            int UserLevel = int.Parse(function.CheckInt(data["UserLevel"].ToString())); //创客等级
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            string Sort = data["Sort"].ToString(); //排序方式
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<Users> query = maindb.Users.Where(m => m.ParentUserId == UserId && m.AuthFlag == 1 && !m.Mobile.EndsWith("d"));
            if (!string.IsNullOrEmpty(RealName))
            {
                query = query.Where(m => (m.RealName == RealName || m.MakerCode == RealName));
            }
            if (Sort == "ThisMonthTrade")
            {
                query = query.OrderByDescending(m => m.ThisMonthTrade);
            }
            if (Sort == "AuthDate")
            {
                query = query.OrderByDescending(m => m.AuthDate);
            }
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("RealName", DefaultRealName(subdata)); //真实姓名
                curData.Add("HeadPhoto", DefaultPic(subdata.HeadPhoto)); //头像
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.AuthDate == null ? "" : subdata.AuthDate.Value.ToString("yyyy-MM-dd")); //CreateDate
                curData.Add("ThisMonthTrade", subdata.ThisMonthTrade); //本月交易额
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion


        #region 创客-首页-我的创客-搜索创客列表
        [Authorize]
        public JsonResult SearchMakerList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = SearchMakerListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> SearchMakerListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string RealName = data["RealName"].ToString(); //真实姓名
            int UserLevel = int.Parse(function.CheckInt(data["UserLevel"].ToString())); //创客等级
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            string Sort = data["Sort"].ToString(); //排序方式
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            string UserIdString = "," + UserId + ",";
            IQueryable<Users> query = maindb.Users.Where(m => m.ParentNav.Contains(UserIdString) && m.AuthFlag == 1);
            if (!string.IsNullOrEmpty(RealName))
            {
                query = query.Where(m => (m.RealName == RealName || m.MakerCode == RealName));
            }
            // if (UserLevel > 0)
            // {
            //     query = query.Where(m => m.UserLevel == UserLevel);
            // }
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                // Users subdata = UsersDbconn.Instance.Get(item.UserId) ?? new Users();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("RealName", DefaultRealName(subdata)); //真实姓名
                curData.Add("HeadPhoto", DefaultPic(subdata.HeadPhoto)); //头像
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd")); //CreateDate
                curData.Add("ThisMonthTrade", UserTradeDaySummaryDbconn.Instance.GetMonthTrade(subdata.Id, DateTime.Now.ToString("yyyyMM"), "team")); //本月交易额
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 首页-我的创客-未实名创客
        [Authorize]
        public JsonResult MyMakerForNotAuth(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            long TotalCount = 0;
            List<Dictionary<string, object>> dataList = MyMakerForNotAuthDo(value, out TotalCount);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            Other.Add("TotalCount", TotalCount);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        public List<Dictionary<string, object>> MyMakerForNotAuthDo(string value, out long TotalCount)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<Users> query = maindb.Users.Where(m => m.ParentUserId == UserId && m.AuthFlag == 0);
            TotalCount = query.Count();
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                // Users subdata = UsersDbconn.Instance.Get(item.UserId) ?? new Users();
                Dictionary<string, object> curData = new Dictionary<string, object>();
                string RealName = DefaultRealName(subdata);
                if (string.IsNullOrEmpty(RealName))
                {
                    RealName = subdata.SeoTitle;
                }
                curData.Add("RealName", RealName); //真实姓名
                curData.Add("HeadPhoto", DefaultPic(subdata.HeadPhoto)); //头像
                curData.Add("Mobile", subdata.Mobile); //手机号
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion


        #region 创客-首页-我的创客-主界面数据
        [Authorize]
        public JsonResult MyMakerData(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyMakerDataDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyMakerDataDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int MakerTotal = maindb.Users.Count(m => m.ParentUserId == UserId);
            int AuthCount = maindb.Users.Count(m => m.ParentUserId == UserId && m.AuthFlag == 1);
            int NotAuthCount = MakerTotal - AuthCount;
            DateTime start = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00");
            int ThisMonthCount = maindb.Users.Count(m => m.ParentUserId == UserId && m.AuthFlag == 1 && m.AuthDate >= start);
            Obj.Add("MakerTotal", MakerTotal); //创客总数
            Obj.Add("AuthCount", AuthCount); //已实名总数
            Obj.Add("NotAuthCount", NotAuthCount); //未实名总数
            Obj.Add("ThisMonthCount", ThisMonthCount); //当月新增
            return Obj;
        }
        #endregion


        #region 创客-我的-个人资料-我的名片
        [Authorize]
        public JsonResult MyCard(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyCardDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyCardDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            string filename = function.MD5_16(Id + "2022");
            string filepath = "/static/ReferenceQrCode/";
            if (!System.IO.File.Exists(function.getPath(filepath + filename + ".png")))
            {
                string path = function.CreateQRCode2(ConfigurationManager.AppSettings["SourceHost"].ToString() + "/p/user-inviteregist-1?Id=" + Id, filename, filepath);
                path = path.Replace("//", "/");
                query.ReferenceQrCode = filepath + filename + ".png";
                maindb.SaveChanges();
            }
            Obj.Add("RealName", DefaultRealName(query)); //真实姓名
            Obj.Add("HeadPhoto", DefaultPic(query.HeadPhoto)); //头像
            Obj.Add("ReferenceQrCode", Host + filepath.TrimStart('/') + filename + ".png"); //推广二维码地址
            Obj.Add("MakerCode", query.MakerCode); //创客编号
            Obj.Add("InvitePhoto", Host + filepath.TrimStart('/') + filename + ".png"); //DefaultPic(query.SignImgUrl)); //邀请图片
            return Obj;
        }
        #endregion


        #region 创客-首页-检测是否有级别
        [Authorize]
        public JsonResult CheckUserLevel(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserRank rank = maindb.UserRank.FirstOrDefault(m => m.UserId == UserId && m.Status == 0);
            if (rank != null)
            {
                Obj.Add("BeforeLevel", rank.WhiteRank);
                Obj.Add("AfterLevel", rank.Rank);
                rank.Status = 1;
                maindb.SaveChanges();
                return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
            }
            return Json(new AppResultJson() { Status = "-1", Info = "" });
        }
        #endregion


        #region 创客-我的-盟主中心-盟主信息详情
        [Authorize]
        public JsonResult LeaderInfo(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = LeaderInfoDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> LeaderInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            UserAccount account = maindb.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new UserAccount();
            Obj.Add("LeaderLevel", query.LeaderLevel); //盟主等级(0 无 1 小盟主 2 大盟主)
            Obj.Add("LeaderReserve", account.LeaderReserve); //盟主储备金
            Obj.Add("LeaderBalanceAmount", account.LeaderBalanceAmount); //可提现金额
            return Obj;
        }
        #endregion









        #region 创客-提交签名图片
        [Authorize]
        public JsonResult UploadSignPic(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = UploadSignPicDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson UploadSignPicDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string SignPic = data["SignPic"].ToString(); //签名图片
            if(string.IsNullOrEmpty(SignPic))
            {
                return new AppResultJson() { Status = "-1", Info = "签名图片不能为空" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id);
            if (query != null)
            {
                query.IsSign = 1;
                query.SignDate = DateTime.Now;
                query.SignPic = SignPic; //签名图片
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 创客-是否签名
        [Authorize]
        public JsonResult SignCheck(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = SignCheckDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> SignCheckDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            Users query = maindb.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            Obj.Add("IsSign", query.IsSign); //是否签名
            return Obj;
        }
        #endregion





        #region 通用-通过创客编号查询
        [Authorize]
        public JsonResult ForCode(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            string MakerCode = data["MakerCode"].ToString(); //创客编号
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            KxsMainModels.UserForMakerCode userfor = kxsdb.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new KxsMainModels.UserForMakerCode();
            KxsMainModels.Users query = kxsdb.Users.FirstOrDefault(m => m.Id == userfor.UserId) ?? new KxsMainModels.Users();
            if (query.AuthFlag != 1)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "创客未认证" });
            }
            Obj.Add("Id", query.Id); //创客Id
            Obj.Add("RealName", query.RealName); //真实姓名
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion



        #region 通用-灰度测试UserId集合
        [Authorize]
        public JsonResult UserIdForGrayTest(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<string> Obj = UserIdForGrayTestDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public List<string> UserIdForGrayTestDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            List<string> Obj = new List<string>();
            SystemSet set = maindb.SystemSet.FirstOrDefault() ?? new SystemSet();
            if (!string.IsNullOrEmpty(set.RightInfo))
            {
                string[] RightInfos = set.RightInfo.Split('\n');
                foreach (string sub in RightInfos)
                {
                    UserForMakerCode code = maindb.UserForMakerCode.FirstOrDefault(m => m.MakerCode == sub);
                    if (code != null)
                    {
                        Obj.Add(code.UserId.ToString());
                    }
                }
            }
            return Obj;
        }
        #endregion



        #region 企业创客-个人中心主界面
        [Authorize]
        public JsonResult BusinessMain(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = BusinessMainDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> BusinessMainDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string PartnerCount = data["PartnerCount"].ToString(); //伙伴总数
            string ThisMonthTrade = data["ThisMonthTrade"].ToString(); //本月交易额
            string ThisMonthAct = data["ThisMonthAct"].ToString(); //本月激活商户
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = new Users();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            query = maindb.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            return Obj;
        }
        #endregion


        #region 创客-我的-添加展业地区
        [Authorize]
        public JsonResult AddAgentAreas(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = AddAgentAreasDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson AddAgentAreasDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString()));
            string AgentAreas = data["AgentAreas"].ToString(); //展业地区
            if(string.IsNullOrEmpty(AgentAreas))
            {
                return new AppResultJson() { Status = "-1", Info = "展业地区不能为空" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Users query = maindb.Users.FirstOrDefault(m => m.Id == UserId);
            if (query != null)
            {
                query.UpdateDate = DateTime.Now;
                query.AgentAreas = AgentAreas; //展业地区
                maindb.SaveChanges();
            }
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}