/*
 * 创客
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

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

        #region 创客列表

        /// <summary>
        /// 根据条件查询创客列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(Users data, string right, int SelfId = 0, int ParentId = 0, string MakerCode = "")
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.SelfId = SelfId.ToString();
            ViewBag.ParentId = ParentId.ToString();
            ViewBag.MakerCode = MakerCode;

            List<Users> TopUsers = db.Users.Where(m => m.ParentUserId == 0).ToList();
            ViewBag.TopUsers = TopUsers;
            List<UserLevelSet> Levels = db.UserLevelSet.OrderBy(m => m.Id).ToList();
            ViewBag.Levels = Levels;
            return View();
        }

        #endregion

        #region 根据条件查询创客列表

        /// <summary>
        /// 创客列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(Users data, string ParentMakerCode, string ParentRealName, string AuthFlagSelect, string CreateDateData, int TopUserId, string RiskFlagSelect, string MerchantTypeSelect, int? sSettleAmount, int? eSettleAmount, int? sCashFreezeAmt, int? eCashFreezeAmt, int UserId, int SelfId = 0, int ParentId = 0, int page = 1, int limit = 30)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("MakerCode", "1"); //创客编号
            Fields.Add("RealName", "1"); //创客名称
            Fields.Add("Mobile", "1"); //手机号
            Fields.Add("CertId", "1"); //身份证号码
            Fields.Add("SettleAmount", "3"); //结算金额
            Fields.Add("CashFreezeAmt", "3"); //冻结金额
            Fields.Add("UserLevel", "0"); //创客等级

            string condition = " and Status>-1";
            string sort = "Id desc";
            //直属创客编号
            if (!string.IsNullOrEmpty(ParentMakerCode))
            {
                condition += " and ParentUserId in (select UserId from UserForMakerCode where MakerCode='" + ParentMakerCode + "')";
            }
            //直属创客名称
            if (!string.IsNullOrEmpty(ParentRealName))
            {
                condition += " and ParentUserId in (select UserId from UserForRealName where RealName='" + ParentRealName + "')";
            }
            //实名状态
            if (!string.IsNullOrEmpty(AuthFlagSelect))
            {
                condition += " and AuthFlag=" + AuthFlagSelect;
            }
            //顶级创客
            if (TopUserId > 0)
            {
                condition += " and ParentNav like '," + TopUserId + ",%'";
            }
            //风控标识
            if (!string.IsNullOrEmpty(RiskFlagSelect))
            {
                condition += " and RiskFlag=" + RiskFlagSelect;
            }
            //商户创客类型
            if (!string.IsNullOrEmpty(MerchantTypeSelect))
            {
                condition += " and MerchantType=" + MerchantTypeSelect;
            }
            if (sSettleAmount != null)
            {
                condition += " and SettleAmount>=" + sSettleAmount.Value;
            }
            if (eSettleAmount != null)
            {
                condition += " and SettleAmount<=" + eSettleAmount.Value;
            }
            if (sCashFreezeAmt != null)
            {
                condition += " and CashFreezeAmt>=" + sCashFreezeAmt.Value;
            }
            if (eCashFreezeAmt != null)
            {
                condition += " and CashFreezeAmt<=" + eCashFreezeAmt.Value;
            }
            if (SelfId > 0)
            {
                Users self = db.Users.FirstOrDefault(m => m.Id == SelfId);
                if (self != null)
                {
                    string ParentNav = function.CheckNull(self.ParentNav);
                    condition += " and Id in (" + ParentNav.Trim(',').Replace(",,", ",") + ")";
                    sort = "ParentNav asc";
                }
            }
            if (ParentId > 0)
            {
                condition += " and ParentUserId=" + ParentId;
            }
            if (UserId > 0)
            {
                condition += " and Id=" + UserId;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Users", Fields, sort, "True", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["AuthFlagName"] = dic["AuthFlag"].ToString() == "1" ? "已实名" : "未实名";
                dic["RiskFlagName"] = dic["RiskFlag"].ToString() == "1" ? "已风控" : "未风控";
                dic["UserLevel"] = RelationClass.GetUserLevelSetInfo(int.Parse(dic["UserLevel"].ToString()));
                dic["MerchantType"] = RelationClassForConst.GetMerchantTypeInfo(int.Parse(dic["MerchantType"].ToString()));
                int ParentUserId = int.Parse(dic["ParentUserId"].ToString());
                Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                dic["ParentMakerCode"] = puser.MakerCode;
                dic["ParentRealName"] = puser.RealName;
                string ParentNav = dic["ParentNav"].ToString();
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] list = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    if (list.Length > 1)
                    {
                        int TopId = int.Parse(function.CheckInt(list[1]));
                        Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                        dic["TopMakerCode"] = tuser.MakerCode;
                        dic["TopRealName"] = tuser.RealName;
                    }
                }
            }
            return Json(obj);
        }

        #endregion

        #region 增加创客

        /// <summary>
        /// 增加或修改创客信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 增加创客

        /// <summary>
        /// 增加或修改创客信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(Users data, string ParentMakerCode)
        {
            bool check = db.UserForMobile.Any(m => m.Mobile == data.Mobile);
            if (check)
            {
                return "手机号已存在，请重新输入";
            }
            check = db.UserForRealName.Any(m => m.RealName == data.RealName);
            if (check)
            {
                return "姓名已存在，请重新输入";
            }
            if (!string.IsNullOrEmpty(data.MakerCode))
            {
                check = db.UserForMakerCode.Any(m => m.MakerCode == data.MakerCode);
                if (check)
                {
                    return "创客编码已存在，请重新输入";
                }
            }
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("RealName", data.RealName); //真实姓名
            Fields.Add("CertId", data.CertId); //身份证号
            Fields.Add("Mobile", data.Mobile); //手机号
            Fields.Add("LoginPwd", function.MD532(data.LoginPwd)); //登录密码
            Fields.Add("SettleBankCardNo", data.SettleBankCardNo); //结算银行卡号
            if (!string.IsNullOrEmpty(ParentMakerCode))
            {
                UserForMakerCode userFor = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == ParentMakerCode) ?? new UserForMakerCode();
                Users puser = db.Users.FirstOrDefault(m => m.Id == userFor.UserId) ?? new Users();
                Fields.Add("ParentUserId", userFor.UserId);
                Fields.Add("ParentNav", puser.ParentNav + "," + userFor.UserId + ",");
            }
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("Users", Fields, 0);
            if (string.IsNullOrEmpty(ParentMakerCode))
            {
                string MakerCode = Id.ToString();
                for (int i = 0; i < 7 - Id.ToString().Length; i++)
                {
                    MakerCode = "0" + MakerCode;
                }
                MakerCode = "K" + MakerCode;
                Fields = new Dictionary<string, object>();
                Fields.Add("MakerCode", MakerCode); //编号
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, Id);
            }

            db.UserDetail.Add(new UserDetail() { Id = Id });
            db.UserData.Add(new UserData() { UserId = Id });

            AddSysLog(data.Id.ToString(), "Users", "add");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改创客

        /// <summary>
        /// 增加或修改创客信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.data = editData;

            return View();
        }

        #endregion

        #region 修改创客

        /// <summary>
        /// 增加或修改创客信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(Users data, UserDetail userdetail, UserData userdata)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("RealName", data.RealName); //真实姓名
            Fields.Add("CertId", data.CertId); //身份证号
            Fields.Add("Mobile", data.Mobile); //手机号
            Fields.Add("SettleBankName", data.SettleBankName); //结算银行名称
            Fields.Add("SettleBankCardNo", data.SettleBankCardNo); //结算银行卡号
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, data.Id);

            AddSysLog(data.Id.ToString(), "Users", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改结算金额

        public IActionResult EditSettleAmount(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改结算金额

        [HttpPost]
        public string EditSettleAmount(Users data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("SettleAmount", data.SettleAmount);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "Users", "EditSettleAmount");
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 修改账户金额

        public IActionResult EditCashFreezeAmt(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改账户金额

        [HttpPost]
        public string EditCashFreezeAmt(Users data, string Note, int Kind)
        {
            int UserId = data.Id;
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == UserId);
            if (account == null)
            {
                account = db.UserAccount.Add(new UserAccount()
                {
                    Id = UserId,
                    UserId = UserId,
                }).Entity;
                db.SaveChanges();
            }
            if ((Kind == 1 || Kind == 3) && data.CashFreezeAmt > account.BalanceAmount)
            {
                return "账号余额不足";
            }
            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
            int ChangeType = 0;
            if (Kind == 1 && data.CashFreezeAmt <= account.BalanceAmount)
            {
                account.BalanceAmount -= data.CashFreezeAmt;
                account.FreezeAmount += data.CashFreezeAmt;
                ChangeType = 61;
            }
            else if (Kind == 1 && data.CashFreezeAmt > account.BalanceAmount)
            {
                return "冻结金额大于余额";
            }
            else if (Kind == 2 && data.CashFreezeAmt <= account.FreezeAmount)
            {
                account.BalanceAmount += data.CashFreezeAmt;
                account.FreezeAmount -= data.CashFreezeAmt;
                ChangeType = 62;
            }
            else if (Kind == 2 && data.CashFreezeAmt > account.FreezeAmount)
            {
                return "解冻金额大于冻结金额";
            }
            else if (Kind == 3 && data.CashFreezeAmt <= account.BalanceAmount)
            {
                account.TotalAmount -= data.CashFreezeAmt;
                account.BalanceAmount -= data.CashFreezeAmt;
                ChangeType = 63;
            }
            else if (Kind == 3 && data.CashFreezeAmt > account.BalanceAmount)
            {
                return "扣减金额大于余额";
            }
            else if (Kind == 4)
            {
                account.TotalAmount += data.CashFreezeAmt;
                account.BalanceAmount += data.CashFreezeAmt;
                ChangeType = 64;
            }
            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
            {
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now,
                UserId = UserId, //创客
                ChangeType = ChangeType, //变动类型
                ChangeAmount = data.CashFreezeAmt, //变更金额
                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                Remark = Note,
            }).Entity;
            db.SaveChanges();
            RedisDbconn.Instance.Set("UserAccount:" + UserId, account);
            AddSysLog(data.Id.ToString(), "Users", "EditCashFreezeAmt");
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 账户操作

        public IActionResult EditBalance(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.data = editData;

            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == Id) ?? new UserAccount();
            ViewBag.account = account;
            return View();
        }

        #endregion

        #region 账户操作

        [HttpPost]
        public string EditBalance(UserAccount data)
        {
            UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == data.Id);
            if (account != null)
            {
                decimal amount = data.BalanceAmount - account.BalanceAmount;
                if (amount != 0)
                {
                    account.BalanceAmount += amount;
                    account.TotalAmount += amount;
                    AddSysLog(data.Id.ToString(), "UserAccount", "EditBalance");
                    db.SaveChanges();
                }
            }
            return "success";
        }

        #endregion

        #region 详情

        public IActionResult Detail(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.AuthDate = editData.AuthDate == null ? "" : editData.AuthDate.Value.ToString("yyyy-MM-dd HH:mm:ss");

            string Age = "";
            if (!string.IsNullOrEmpty(editData.CertId))
            {
                int year = DateTime.Now.Year - int.Parse(editData.CertId.Substring(6, 4));
                Age = year.ToString();
            }
            ViewBag.Age = Age;

            ViewBag.QrCode = string.IsNullOrEmpty(editData.ReferenceQrCode) ? defaultImage : SourceHost + editData.ReferenceQrCode;

            return View();
        }

        #endregion

        #region 三/四要素验证

        public IActionResult ThreeElement(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            return View();
        }

        #endregion

        #region 三/四要素验证

        [HttpPost]
        public string ThreeElement(string Name, string CertId, string CardNo, string Mobile)
        {

            return "success";
        }

        #endregion

        #region 删除创客信息

        /// <summary>
        /// 删除创客信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Users", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Users", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Users", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion


        #region 一键企业创客

        /// <summary>
        /// 一键企业创客
        /// </summary>
        /// <returns></returns>
        public string OpenEnterpriseMaker(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Users", "OpenEnterpriseMaker");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("BusinessFlag", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭企业创客

        /// <summary>
        /// 关闭企业创客
        /// </summary>
        /// <returns></returns>
        public string CloseEnterpriseMaker(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Users", "CloseEnterpriseMaker");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("BusinessFlag", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion


        #region 风控

        public IActionResult Risk(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 风控

        [HttpPost]
        public string Risk(Users data)
        {
            Users user = db.Users.FirstOrDefault(m => m.Id == data.Id);
            if (user != null)
            {
                user.RiskFlag = data.RiskFlag;
                user.RiskRemark = data.RiskRemark;
                db.SaveChanges();
            }
            return "success";
        }

        #endregion

        #region 解除风控

        public string UnRisk(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "Users", "UnRisk");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("RiskFlag", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 重置密码

        public string ResetPwd(int Id)
        {
            string NewPwd = function.get_Random(6);
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("LoginPwd", function.MD532(NewPwd));
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("Users", Fields, Id);
            AddSysLog(Id, "Users", "ResetPwd");
            RedisDbconn.Instance.Clear("Users:" + Id);
            return "success|" + NewPwd;
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Sort("Users", Sort, Id);

            AddSysLog(Id.ToString(), "Users", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData, int Kind = 0)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            if (Kind == 1)
            {
                for (int i = 1; i < list.Count; i++)
                {
                    JsonData dr = list[i];
                    string MakerCode = dr[0].ToString();
                    string SettleAmount = dr[2].ToString();
                    UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                    if (UserCode != null)
                    {
                        Users User = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId);
                        if (User != null)
                        {
                            User.SettleAmount = decimal.Parse(function.CheckInt(SettleAmount));
                        }
                    }
                }
                db.SaveChanges();
            }
            else if (Kind == 2)
            {
                for (int i = 1; i < list.Count; i++)
                {
                    JsonData dr = list[i];
                    string MakerCode = dr[0].ToString();
                    string CashFreezeAmt = dr[2].ToString();
                    UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                    if (UserCode != null)
                    {
                        Users User = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId);
                        if (User != null)
                        {
                            User.CashFreezeAmt = decimal.Parse(function.CheckInt(CashFreezeAmt));
                        }
                    }
                }
                db.SaveChanges();
            }
            else if (Kind == 3)
            {
                for (int i = 1; i < list.Count; i++)
                {
                    JsonData dr = list[i];
                    string MakerCode = dr[0].ToString();
                    string RiskFlag = dr[2].ToString();
                    string RiskNote = dr[3].ToString();
                    UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                    if (UserCode != null)
                    {
                        Users User = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId);
                        if (User != null)
                        {
                            User.RiskFlag = ulong.Parse(function.CheckInt(RiskFlag));
                            User.RiskRemark = RiskNote;
                        }
                    }
                }
                db.SaveChanges();
            }
            else if (Kind == 4)
            {
                string error = "";
                for (int i = 1; i < list.Count; i++)
                {
                    JsonData dr = list[i];
                    string MakerCode = dr[0].ToString();
                    string OperationAmt = dr[2].ToString();//操作金额
                    string OperationType = dr[3].ToString();//操作类型

                    UserForMakerCode UserCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                    if (UserCode != null)
                    {
                        Users User = db.Users.FirstOrDefault(m => m.Id == UserCode.UserId);
                        UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == User.Id);
                        if (account == null)
                        {
                            account = db.UserAccount.Add(new UserAccount()
                            {
                                Id = User.Id,
                                UserId = User.Id,
                            }).Entity;
                            db.SaveChanges();
                        }
                        if (User != null)
                        {

                            decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                            decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                            decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                            int ChangeType = 0;
                            if (OperationType == "1" && Convert.ToDecimal(OperationAmt) <= account.BalanceAmount)
                            {
                                account.BalanceAmount -= Convert.ToDecimal(OperationAmt);
                                account.FreezeAmount += Convert.ToDecimal(OperationAmt);
                                ChangeType = 61;
                            }
                            else if (OperationType == "1" && Convert.ToDecimal(OperationAmt) > account.BalanceAmount)
                            {
                                error += "以下操作失败" + User.MakerCode + ',' + User.RealName + "冻结金额大于余额" + '|' + '\n';
                            }
                            else if (OperationType == "2" && Convert.ToDecimal(OperationAmt) <= account.FreezeAmount)
                            {
                                account.BalanceAmount += Convert.ToDecimal(OperationAmt);
                                account.FreezeAmount -= Convert.ToDecimal(OperationAmt);
                                ChangeType = 62;
                            }
                            else if (OperationType == "2" && Convert.ToDecimal(OperationAmt) > account.FreezeAmount)
                            {
                                error += "以下操作失败" + User.MakerCode + ',' + User.RealName + "解冻金额大于冻结金额" + '|' + '\n';
                            }
                            else if (OperationType == "3" && Convert.ToDecimal(OperationAmt) <= account.BalanceAmount)
                            {
                                account.TotalAmount -= Convert.ToDecimal(OperationAmt);
                                account.BalanceAmount -= Convert.ToDecimal(OperationAmt);
                                ChangeType = 63;
                            }
                            else if (OperationType == "3" && Convert.ToDecimal(OperationAmt) > account.BalanceAmount)
                            {
                                error += "以下操作失败" + User.MakerCode + ',' + User.RealName + "扣减金额大于余额" + '|' + '\n';
                            }
                            else if (OperationType == "4")
                            {
                                account.TotalAmount += Convert.ToDecimal(OperationAmt);
                                account.BalanceAmount += Convert.ToDecimal(OperationAmt);
                                ChangeType = 64;
                            }
                            decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                            decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                            decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                            UserAccountRecord userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord()
                            {
                                CreateDate = DateTime.Now,
                                UpdateDate = DateTime.Now,
                                UserId = User.Id, //创客
                                ChangeType = ChangeType, //变动类型
                                ChangeAmount = Convert.ToDecimal(OperationAmt), //变更金额
                                BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                Remark = dr[4].ToString(),
                            }).Entity;
                            db.SaveChanges();
                            AddSysLog(User.Id.ToString(), "Users", "ChangeCashFreezeAmts");
                            db.SaveChanges();

                        }
                    }
                }
                db.SaveChanges();
                return "warning" + error;
            }
            AddSysLog("0", "Users", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(Users data, string CreateDate, string ParentMakerCode, string ParentRealName, string AuthFlagSelect, int TopUserId, string RiskFlagSelect, string MerchantTypeSelect, int SelfId = 0, int ParentId = 0)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("MakerCode", "1"); //创客编号
            Fields.Add("RealName", "1"); //创客名称
            Fields.Add("Mobile", "1"); //手机号
            Fields.Add("CertId", "1"); //身份证号码
            Fields.Add("CreateDate", "3"); //注册时间
            Fields.Add("SettleAmount", "3"); //结算金额
            Fields.Add("CashFreezeAmt", "3"); //冻结金额
            Fields.Add("UserLevel", "0"); //创客等级

            string condition = " and Status>-1";
            //直属创客编号
            if (!string.IsNullOrEmpty(ParentMakerCode))
            {
                condition += " and Id in (select UserId from UserForMakerCode where MakerCode='" + ParentMakerCode + "')";
            }
            //直属创客名称
            if (!string.IsNullOrEmpty(ParentRealName))
            {
                condition += " and Id in (select UserId from UserForRealName where RealName='" + ParentRealName + "')";
            }
            //实名状态
            if (!string.IsNullOrEmpty(AuthFlagSelect))
            {
                condition += " and AuthFlag=" + AuthFlagSelect;
            }
            //顶级创客
            if (TopUserId > 0)
            {
                condition += " and ParentNav like '," + TopUserId + ",%'";
            }
            //风控标识
            if (!string.IsNullOrEmpty(RiskFlagSelect))
            {
                condition += " and RiskFlag=" + RiskFlagSelect;
            }
            //商户创客类型
            if (!string.IsNullOrEmpty(MerchantTypeSelect))
            {
                condition += " and MerchantType=" + MerchantTypeSelect;
            }
            if (SelfId > 0)
            {
                Users self = db.Users.FirstOrDefault(m => m.Id == SelfId);
                if (self != null)
                {
                    string ParentNav = function.CheckNull(self.ParentNav);
                    condition += " and Id in (" + ParentNav.Trim(',').Replace(",,", ",") + ")";
                }
            }
            if (ParentId > 0)
            {
                condition += " and ParentUserId=" + ParentId;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Users", Fields, "Id desc", "True", 1, 20000, condition, "ParentUserId,ParentNav,UserLevel,SettleAmount,CashFreezeAmt,CertId,Mobile,MerchantType,MerchantDate,AuthFlag,RiskFlag,CreateDate", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["AuthFlag"] = dic["AuthFlag"].ToString() == "1" ? "已实名" : "未实名";
                dic["RiskFlag"] = dic["RiskFlag"].ToString() == "1" ? "已风控" : "未风控";
                dic["UserLevel"] = RelationClass.GetUserLevelSetInfo(int.Parse(dic["UserLevel"].ToString()));
                dic["MerchantType"] = RelationClassForConst.GetMerchantTypeInfo(int.Parse(dic["MerchantType"].ToString()));
                int ParentUserId = int.Parse(dic["ParentUserId"].ToString());
                Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                dic["ParentMakerCode"] = puser.MakerCode;
                dic["ParentRealName"] = puser.RealName;
                string ParentNav = dic["ParentNav"].ToString();
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    string[] list = ParentNav.Trim(',').Replace(",,", ",").Split(',');
                    if (list.Length > 1)
                    {
                        int TopId = int.Parse(function.CheckInt(list[1]));
                        Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                        dic["TopMakerCode"] = tuser.MakerCode;
                        dic["TopRealName"] = tuser.RealName;
                    }
                }
                dic.Remove("ParentUserId");
                dic.Remove("ParentNav");
            }
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();

            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("UserLevel", "创客等级");
            ReturnFields.Add("SettleAmount", "提现金额(元)");
            ReturnFields.Add("CashFreezeAmt", "冻结金额(元)");
            ReturnFields.Add("CertId", "身份证号");
            ReturnFields.Add("Mobile", "联系手机");
            ReturnFields.Add("MerchantType", "商户创客类型");
            ReturnFields.Add("MerchantDate", "成为商户创客时间");
            ReturnFields.Add("ParentMakerCode", "直属创客编号");
            ReturnFields.Add("ParentRealName", "直属创客名称");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("AuthFlag", "实名状态");
            ReturnFields.Add("RiskFlag", "风控状态");
            ReturnFields.Add("CreateDate", "注册时间");

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "Users", "ExportExcel");
            return Json(result);
        }

        #endregion

        #region 同步数据

        /// <summary>
        /// 同步数据
        /// </summary>
        /// <returns></returns>
        public string SycnData(int Id = 0)
        {
            var Brands = db.KqProducts.Where(m => m.Status == 1).ToList();
            foreach (var Brand in Brands)
            {
                PublicFunction.SycnMachineCount(Id, Brand.Id);
                // RedisDbconn.Instance.Set("UserMachineData:" + IdBrand, machineData);
                // RedisDbconn.Instance.SetExpire("UserMachineData:" + IdBrand, function.get_Random(1800, 5400));
            }
            AddSysLog(Id, "Users", "SycnData");
            db.SaveChanges();
            return "success";
        }

        #endregion


        #region 同步交易额

        public IActionResult SycnTradeAmount(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            Users editData = db.Users.FirstOrDefault(m => m.Id == Id) ?? new Users();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 同步交易额

        [HttpPost]
        public string SycnTradeAmountDo(DateTime sdate, DateTime edate, int UserId, int BrandId)
        {
            if (sdate.AddMonths(1) < edate)
            {
                return "时间间隔不能超过1个月";
            }
            if (edate >= DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00"))
            {
                return "结束时间只能是今天之前";
            }
            string check = RedisDbconn.Instance.Get<string>("ResetUserTradeQueue:" + UserId + ":" + BrandId);
            if (!string.IsNullOrEmpty(check))
            {
                return "请稍后再试";
            }
            try
            {
                RedisDbconn.Instance.AddList("ResetUserTradeQueue", UserId + "#cut#" + sdate.ToString("yyyy-MM-dd HH:mm:ss") + "#cut#" + edate.ToString("yyyy-MM-dd HH:mm:ss") + "#cut#" + BrandId);
                RedisDbconn.Instance.Set("ResetUserTradeQueue:" + UserId + ":" + BrandId, "wait");
                RedisDbconn.Instance.SetExpire("ResetUserTradeQueue:" + UserId + ":" + BrandId, 3600);
            }
            catch (Exception ex)
            {
                function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString(), "统计创客的交易额异常");
                return "同步异常";
            }
            return "success";
        }

        #endregion




        #region 创客展业城市

        public IActionResult City(Users data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            List<Users> TopUsers = db.Users.Where(m => m.ParentUserId == 0).ToList();
            ViewBag.TopUsers = TopUsers;
            return View();
        }

        #endregion

        #region 根据条件查询创客展业城市

        public JsonResult CityData(Users data, string ParentMakerCode, string ParentRealName, int TopUserId, string Areas, int page = 1, int limit = 30)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("MakerCode", "1"); //创客编号
            Fields.Add("RealName", "1"); //创客名称
            Fields.Add("CitySetDate", "3"); //创建时间
            Fields.Add("Areas", "2"); //省市

            string condition = " and Status>-1";
            //直属创客编号
            if (!string.IsNullOrEmpty(ParentMakerCode))
            {
                condition += " and Id in (select UserId from UserForMakerCode where MakerCode='" + ParentMakerCode + "')";
            }
            //直属创客名称
            if (!string.IsNullOrEmpty(ParentRealName))
            {
                condition += " and Id in (select UserId from UserForRealName where RealName='" + ParentRealName + "')";
            }
            //顶级创客
            if (TopUserId > 0)
            {
                condition += " and ParentNav like '," + TopUserId + ",%'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Users", Fields, "Id desc", "True", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int ParentUserId = int.Parse(dic["ParentUserId"].ToString());
                Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                dic["ParentMakerCode"] = puser.MakerCode;
                dic["ParentRealName"] = puser.RealName;
                string ParentNav = dic["ParentNav"].ToString();
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    int TopId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                    dic["TopMakerCode"] = tuser.MakerCode;
                    dic["TopRealName"] = tuser.RealName;
                }
            }
            return Json(obj);
        }

        #endregion

        #region 导出展业城市

        public JsonResult ExportCity(Users data, string CreateDate, string ParentMakerCode, string ParentRealName, string AuthFlagSelect, int TopUserId, string RiskFlagSelect, string MerchantTypeSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("MakerCode", "1"); //创客编号
            Fields.Add("RealName", "1"); //创客名称
            Fields.Add("Mobile", "1"); //手机号
            Fields.Add("CertId", "1"); //身份证号码
            Fields.Add("CreateDate", "3"); //注册时间
            Fields.Add("SettleAmount", "3"); //结算金额
            Fields.Add("CashFreezeAmt", "3"); //冻结金额
            Fields.Add("UserLevel", "0"); //创客等级

            string condition = " and Status>-1";
            //直属创客编号
            if (!string.IsNullOrEmpty(ParentMakerCode))
            {
                condition += " and Id in (select UserId from UserForMakerCode where MakerCode='" + ParentMakerCode + "')";
            }
            //直属创客名称
            if (!string.IsNullOrEmpty(ParentRealName))
            {
                condition += " and Id in (select UserId from UserForRealName where RealName='" + ParentRealName + "')";
            }
            //实名状态
            if (!string.IsNullOrEmpty(AuthFlagSelect))
            {
                condition += " and AuthFlag=" + AuthFlagSelect;
            }
            //顶级创客
            if (TopUserId > 0)
            {
                condition += " and ParentNav like '," + TopUserId + ",%'";
            }
            //风控标识
            if (!string.IsNullOrEmpty(RiskFlagSelect))
            {
                condition += " and RiskFlag=" + RiskFlagSelect;
            }
            //商户创客类型
            if (!string.IsNullOrEmpty(MerchantTypeSelect))
            {
                condition += " and MerchantType=" + MerchantTypeSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Users", Fields, "Id desc", "True", 1, 20000, condition, "ParentUserId,ParentNav,UserLevel,SettleAmount,CashFreezeAmt,CertId,Mobile,MerchantType,MerchantDate,AuthFlag,RiskFlag,CreateDate", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["AuthFlag"] = dic["AuthFlag"].ToString() == "1" ? "已实名" : "未实名";
                dic["RiskFlag"] = dic["RiskFlag"].ToString() == "1" ? "已风控" : "未风控";
                dic["UserLevel"] = RelationClass.GetUserLevelSetInfo(int.Parse(dic["UserLevel"].ToString()));
                dic["MerchantType"] = RelationClassForConst.GetMerchantTypeInfo(int.Parse(dic["MerchantType"].ToString()));
                int ParentUserId = int.Parse(dic["ParentUserId"].ToString());
                Users puser = db.Users.FirstOrDefault(m => m.Id == ParentUserId) ?? new Users();
                dic["ParentMakerCode"] = puser.MakerCode;
                dic["ParentRealName"] = puser.RealName;
                string ParentNav = dic["ParentNav"].ToString();
                if (!string.IsNullOrEmpty(ParentNav))
                {
                    int TopId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                    dic["TopMakerCode"] = tuser.MakerCode;
                    dic["TopRealName"] = tuser.RealName;
                }
                dic.Remove("ParentUserId");
                dic.Remove("ParentNav");
            }
            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();

            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("UserLevel", "创客等级");
            ReturnFields.Add("SettleAmount", "提现金额(元)");
            ReturnFields.Add("CashFreezeAmt", "冻结金额(元)");
            ReturnFields.Add("CertId", "身份证号");
            ReturnFields.Add("Mobile", "联系手机");
            ReturnFields.Add("MerchantType", "商户创客类型");
            ReturnFields.Add("MerchantDate", "成为商户创客时间");
            ReturnFields.Add("ParentMakerCode", "直属创客编号");
            ReturnFields.Add("ParentRealName", "直属创客名称");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("AuthFlag", "实名状态");
            ReturnFields.Add("RiskFlag", "风控状态");
            ReturnFields.Add("CreateDate", "注册时间");

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "Users", "ExportExcel");
            return Json(result);
        }

        #endregion


        #region 根据条件查询直属创客交易额列表

        /// <summary>
        /// 直属创客交易额列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Children(Users data, string right, int ParentId = 0, string MakerCode = "")
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.ParentId = ParentId.ToString();
            ViewBag.MakerCode = MakerCode;

            List<Users> TopUsers = db.Users.Where(m => m.ParentUserId == 0).ToList();
            ViewBag.TopUsers = TopUsers;
            List<UserLevelSet> Levels = db.UserLevelSet.OrderBy(m => m.Id).ToList();
            ViewBag.Levels = Levels;
            List<KqProducts> Brands = db.KqProducts.OrderBy(m => m.Id).ToList();
            ViewBag.Brands = Brands;
            return View();
        }

        #endregion

        #region 根据条件查询直属创客交易额列表

        /// <summary>
        /// 直属创客交易额列表
        /// </summary>
        /// <returns></returns>
        public JsonResult ChildrenData(Users data, int BrandSelect, string MakerCode, string CreateDateData, int ParentId = 0, int page = 1, int limit = 30)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("MakerCode", "1"); //创客编号

            int BrandId = BrandSelect;
            string start = "";
            string end = "";

            string condition = " and Status>-1";
            string sort = "Id desc";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and Id in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            if (ParentId > 0)
            {
                condition += " and ParentUserId=" + ParentId + " or Id=" + ParentId;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                start = datelist[0].Replace("-", "");
                end = datelist[1].Replace("-", "");
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Users", Fields, sort, "True", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int UId = int.Parse(dic["Id"].ToString());
                var Info = GetMonthTradeForBrand(UId, start, end, BrandId);

                dic["TotalAmtfc"] = Convert.ToDecimal(Info["TotalAmtfc"].ToString()) + Convert.ToDecimal(Info["YAmtfc"].ToString());
                dic["DAmtfc"] = Convert.ToDecimal(Info["DAmtfc"].ToString());
                dic["JAmtfc"] = Convert.ToDecimal(Info["JAmtfc"].ToString());
                dic["JfAmtfc"] = Convert.ToDecimal(Info["JfAmtfc"].ToString());
                dic["JCountfc"] = Convert.ToInt32(Info["JCountfc"].ToString());
                dic["YAmtfc"] = Convert.ToDecimal(Info["YAmtfc"].ToString());

                dic["TotalAmtwd"] = Convert.ToDecimal(Info["TotalAmtwd"].ToString()) + Convert.ToDecimal(Info["YAmtwd"].ToString());
                dic["DAmtwd"] = Convert.ToDecimal(Info["DAmtwd"].ToString());
                dic["JAmtwd"] = Convert.ToDecimal(Info["JAmtwd"].ToString());
                dic["JfAmtwd"] = Convert.ToDecimal(Info["JfAmtwd"].ToString());
                dic["JCountwd"] = Convert.ToInt32(Info["JCountwd"].ToString());
                dic["YAmtwd"] = Convert.ToDecimal(Info["YAmtwd"].ToString());

                dic["BCount"] = Info["BCount"].ToString();
                dic["ACount"] = Info["ACount"].ToString();

            }

            //扶持期
            decimal TotalAmtfc = 0;
            decimal DAmtfc = 0;
            decimal JAmtfc = 0;
            decimal JfAmtfc = 0;
            int JCountfc = 0;
            decimal YAmtfc = 0;

            //稳定期
            decimal TotalAmtwd = 0;
            decimal DAmtwd = 0;
            decimal JAmtwd = 0;
            decimal JfAmtwd = 0;
            int JCountwd = 0;
            decimal YAmtwd = 0;

            int BCount = 0;
            int ACount = 0;

            WebCMSEntities db = new WebCMSEntities();
            Dictionary<string, object> other = new Dictionary<string, object>();
            DataTable dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectTradeAmt + HelpNonDirectDebitTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                TotalAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                DAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectDebitTradeAmt),Sum(HelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                JAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString())) - Convert.ToDecimal(function.CheckNum(dt.Rows[0][1].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                JfAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpDirectDebitCapNum) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                JCountfc = Convert.ToInt32(function.CheckInt(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=1 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                YAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }

            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectTradeAmt + NotHelpNonDirectDebitTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                TotalAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                DAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectDebitTradeAmt),Sum(NotHelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                JAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString())) - Convert.ToDecimal(function.CheckNum(dt.Rows[0][1].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                JfAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpDirectDebitCapNum) from TradeDaySummary where QueryCount=0 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                JCountwd = Convert.ToInt32(function.CheckInt(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=1 and SeoTitle='self' and UserId= '"+ParentId+"' and TradeDate >= '"+start+"' and TradeDate <= '"+end+"'");
            if (dt.Rows.Count > 0)
            {
                YAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }

            other.Add("TotalAmtfc", TotalAmtfc);
            other.Add("DAmtfc", DAmtfc);
            other.Add("JAmtfc", JAmtfc);
            other.Add("JfAmtfc", JfAmtfc);
            other.Add("JCountfc", JCountfc);
            other.Add("YAmtfc", YAmtfc);

            other.Add("TotalAmtwd", TotalAmtwd);
            other.Add("DAmtwd", DAmtwd);
            other.Add("JAmtwd", JAmtwd);
            other.Add("JfAmtwd", JfAmtwd);
            other.Add("JCountwd", JCountwd);
            other.Add("YAmtwd", YAmtwd);

            other.Add("BCount", BCount);
            other.Add("ACount", ACount);
            db.Dispose();
            obj.Add("other", other);

            return Json(obj);
        }

        public Dictionary<string, object> GetMonthTradeForBrand(int UserId, string sTradeDate, string eTradeDate, int BrandId)
        {
            string condition = " and Status>-1";

            //产品类型
            if (!string.IsNullOrEmpty(BrandId.ToString()) && BrandId > 0)
            {
                condition += " and BrandId =" + BrandId;
            }
            //创客Id
            if (!string.IsNullOrEmpty(UserId.ToString()))
            {
                condition += " and UserId =" + UserId;
            }
            //开始时间
            if (!string.IsNullOrEmpty(sTradeDate))
            {
                condition += " and TradeDate >=" + Convert.ToInt32(sTradeDate);
            }
            //结束时间
            if (!string.IsNullOrEmpty(eTradeDate))
            {
                condition += " and TradeDate <=" + Convert.ToInt32(eTradeDate);
            }

            //扶持期
            decimal TotalAmtfc = 0;
            decimal DAmtfc = 0;
            decimal JAmtfc = 0;
            decimal JfAmtfc = 0;
            int JCountfc = 0;
            decimal YAmtfc = 0;

            //稳定期
            decimal TotalAmtwd = 0;
            decimal DAmtwd = 0;
            decimal JAmtwd = 0;
            decimal JfAmtwd = 0;
            int JCountwd = 0;
            decimal YAmtwd = 0;

            int BCount = 0;
            int ACount = 0;

            WebCMSEntities db = new WebCMSEntities();
            Dictionary<string, object> obj = new Dictionary<string, object>();
            DataTable dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectTradeAmt + HelpNonDirectDebitTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                TotalAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                DAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectDebitTradeAmt),Sum(HelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                JAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString())) - Convert.ToDecimal(function.CheckNum(dt.Rows[0][1].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                JfAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpDirectDebitCapNum) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                JCountfc = Convert.ToInt32(function.CheckInt(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(HelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=1 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                YAmtfc = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }

            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectTradeAmt + NotHelpNonDirectDebitTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                TotalAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                DAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectDebitTradeAmt),Sum(NotHelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                JAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString())) - Convert.ToDecimal(function.CheckNum(dt.Rows[0][1].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpDirectDebitCapTradeAmt) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                JfAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpDirectDebitCapNum) from TradeDaySummary where QueryCount=0 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                JCountwd = Convert.ToInt32(function.CheckInt(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select Sum(NotHelpNonDirectTradeAmt) from TradeDaySummary where QueryCount=1 and SeoTitle='team'"+ condition);
            if (dt.Rows.Count > 0)
            {
                YAmtwd = Convert.ToDecimal(function.CheckNum(dt.Rows[0][0].ToString()));
            }

            obj.Add("TotalAmtfc", TotalAmtfc);
            obj.Add("DAmtfc", DAmtfc);
            obj.Add("JAmtfc", JAmtfc);
            obj.Add("JfAmtfc", JfAmtfc);
            obj.Add("JCountfc", JCountfc);
            obj.Add("YAmtfc", YAmtfc);

            obj.Add("TotalAmtwd", TotalAmtwd);
            obj.Add("DAmtwd", DAmtwd);
            obj.Add("JAmtwd", JAmtwd);
            obj.Add("JfAmtwd", JfAmtwd);
            obj.Add("JCountwd", JCountwd);
            obj.Add("YAmtwd", YAmtwd);

            obj.Add("BCount", BCount);
            obj.Add("ACount", ACount);
            db.Dispose();
            return obj;
        }

        #endregion
    }
}
