/*
 * 创客账户变动记录
 */

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 UserAccountRecordController : BaseController
    {
        public UserAccountRecordController(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(UserAccountRecord data, string right, int UserId = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.UserId = UserId.ToString();

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

            return View();
        }

        #endregion

        #region 根据条件查询创客账户变动记录列表

        /// <summary>
        /// 创客账户变动记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(UserAccountRecord data, string ChangeType, int ProductType, string TransRecordNo, string MakerCode, string RealName, int TopUserId, string CreateDateData, int UserId = 0, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            // Fields.Add("ChangeType", "1"); //交易类型
            // Fields.Add("ProductType", "1"); //产品类型
            // Fields.Add("TransRecordNo", "3"); //交易流水编号

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //顶级创客
            if (TopUserId > 0)
            {
                condition += " and UserId in (select Id from Users where ParentNav like '," + TopUserId + ",%')";
            }
            if (UserId > 0)
            {
                condition += " and UserId=" + UserId;
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = Convert.ToDateTime(Convert.ToDateTime(datelist[0]).ToString("yyyy-MM-dd"));
                var end = Convert.ToDateTime(Convert.ToDateTime(datelist[1]).ToString("yyyy-MM-dd") + " 23:59:59");
                var check = db.UserAccountRecord.Any(m => m.CreateDate >= start);
                var checks = db.UserAccountRecord.Any(m => m.CreateDate <= end);
                if (check)
                {
                    var sId = db.UserAccountRecord.Where(m => m.CreateDate >= start).Min(m => m.Id);
                    condition += "  and Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.UserAccountRecord.Where(m => m.CreateDate <= end).Max(m => m.Id);
                    condition += " and Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.UserAccountRecord.Any(m => m.CreateDate >= start);
                if (check)
                {
                    var minId = db.UserAccountRecord.Where(m => m.CreateDate >= start).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/UsersAccountRecord/UsersAccountRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/UsersAccountRecord/", "UsersAccountRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/UsersAccountRecord/", "UsersAccountRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }

            }
            if (!string.IsNullOrEmpty(ChangeType))
            {
                if (int.Parse(ChangeType) > 0)
                {
                    // if (ChangeType == 0)
                    // {
                    //     condition += " and ChangeType in(0,12)";
                    // }
                    if (int.Parse(ChangeType) == 1)
                    {
                        condition += " and (ChangeType=" + int.Parse(ChangeType) + " or (ChangeType in(112,1) and ProductType=101))";
                    }
                    else if (int.Parse(ChangeType) == 30)
                    {
                        condition += " and ChangeType=31 and Remark='开机抢红包活动'";
                    }
                    else if (int.Parse(ChangeType) == 31)
                    {
                        condition += " and (ChangeType=" + int.Parse(ChangeType) + " and (Remark!='开机抢红包活动' or Remark IS NULL))";
                    }
                    else if (int.Parse(ChangeType) == 112)
                    {
                        condition += " and ChangeType=112 and ProductType=0";
                    }
                    else
                    {
                        condition += " and ChangeType=" + int.Parse(ChangeType);
                    }
                }
                if (int.Parse(ChangeType) == 0)
                {
                    condition += " and ChangeType in(0,12)";
                }
            }
            if (ProductType > 0)
            {
                condition += " and ProductType=" + ProductType;
            }
            if (!string.IsNullOrEmpty(TransRecordNo))
            {
                condition += " and TransRecordNo='" + TransRecordNo + "'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserAccountRecord", Fields, "Id desc", "0", 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["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                if (!string.IsNullOrEmpty(user.ParentNav))
                {
                    int TopId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                    dic["TopMakerCode"] = tuser.MakerCode;
                    dic["TopRealName"] = tuser.RealName;
                }
                int ProductTypes = int.Parse(dic["ProductType"].ToString());
                dic["ProductTypeName"] = RelationClass.GetKqProductBrandInfo(ProductTypes);
                int ChangeTypes = int.Parse(dic["ChangeType"].ToString());
                dic["ChangeTypeName"] = RelationClassForConst.GetChangeTypeInfo(ChangeTypes);

                //获得盟主5元奖励的机具Sn
                int SnId = int.Parse(dic["QueryCount"].ToString());
                PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == SnId) ?? new PosMachinesTwo();
                dic["PosSn"] = pos.PosSn;
            }
            Dictionary<string, object> other = new Dictionary<string, object>();

            // string ChangeTypeAmount0 = "0.00", ChangeTypeAmount1 = "0.00", ChangeTypeAmount2 = "0.00", ChangeTypeAmount3 = "0.00", ChangeTypeAmount4 = "0.00", ChangeTypeAmount5 = "0.00", ChangeTypeAmount6 = "0.00", ChangeTypeAmount61 = "0.00", ChangeTypeAmount62 = "0.00", ChangeTypeAmount63 = "0.00", ChangeTypeAmount64 = "0.00", ChangeTypeAmount50 = "0.00", ChangeTypeAmount111 = "0.00", ChangeTypeAmount112 = "0.00", ChangeTypeAmount60 = "0.00", ChangeTypeAmount31 = "0.00", ChangeTypeAmount31s = "0.00", ChangeTypeAmount124 = "0.00", ChangeTypeAmount125 = "0.00";
            // DataTable dt = OtherMySqlConn.dtable("select sum(if(ChangeType=0, ChangeAmount, 0)),sum(if(ChangeType=1 and ProductType!=101, ChangeAmount, 0)) + sum(if(ChangeType in(112,1) and ProductType=101, ChangeAmount, 0)),sum(if(ChangeType=2, ChangeAmount, 0)),sum(if(ChangeType=6, ChangeAmount, 0)),sum(if(ChangeType=61, ChangeAmount, 0)),sum(if(ChangeType=62, ChangeAmount, 0)),sum(if(ChangeType=63, ChangeAmount, 0)),sum(if(ChangeType=64, ChangeAmount, 0)),sum(if(ChangeType=50, ChangeAmount, 0)),sum(if(ChangeType=111, ChangeAmount, 0)),sum(if(ChangeType=112  and ProductType!=101, ChangeAmount, 0)),sum(if(ChangeType=60, ChangeAmount, 0)),sum(if(ChangeType=31 and Remark='开机抢红包活动', ChangeAmount, 0)),sum(if(ChangeType=3, ChangeAmount, 0)),sum(if(ChangeType=4, ChangeAmount, 0)),sum(if(ChangeType=5, ChangeAmount, 0)),sum(if(ChangeType=124, ChangeAmount, 0)),sum(if(ChangeType=125, ChangeAmount, 0)),sum(if(ChangeType=31 and (Remark!='开机抢红包活动' or Remark IS NULL), ChangeAmount, 0)) from UserAccountRecord where 1=1" + condition);
            // if (dt.Rows.Count > 0)
            // {
            //     ChangeTypeAmount0 = dt.Rows[0][0].ToString();
            //     ChangeTypeAmount1 = dt.Rows[0][1].ToString();
            //     ChangeTypeAmount2 = dt.Rows[0][2].ToString();
            //     ChangeTypeAmount3 = dt.Rows[0][13].ToString();
            //     ChangeTypeAmount4 = dt.Rows[0][14].ToString();
            //     ChangeTypeAmount5 = dt.Rows[0][15].ToString();
            //     ChangeTypeAmount6 = dt.Rows[0][3].ToString();
            //     ChangeTypeAmount61 = dt.Rows[0][4].ToString();
            //     ChangeTypeAmount62 = dt.Rows[0][5].ToString();
            //     ChangeTypeAmount63 = dt.Rows[0][6].ToString();
            //     ChangeTypeAmount64 = dt.Rows[0][7].ToString();
            //     ChangeTypeAmount50 = dt.Rows[0][8].ToString();
            //     ChangeTypeAmount111 = dt.Rows[0][9].ToString();
            //     ChangeTypeAmount112 = dt.Rows[0][10].ToString();
            //     ChangeTypeAmount60 = dt.Rows[0][11].ToString();
            //     ChangeTypeAmount31 = dt.Rows[0][12].ToString();
            //     ChangeTypeAmount124 = dt.Rows[0][16].ToString();
            //     ChangeTypeAmount125 = dt.Rows[0][17].ToString();
            //     ChangeTypeAmount31s = dt.Rows[0][18].ToString();
            // }
            // other.Add("ChangeTypeAmount0", ChangeTypeAmount0); //激活奖励
            // other.Add("ChangeTypeAmount1", ChangeTypeAmount1); //交易分润
            // other.Add("ChangeTypeAmount2", ChangeTypeAmount2); //提现申请
            // other.Add("ChangeTypeAmount3", ChangeTypeAmount3); //提现代付
            // other.Add("ChangeTypeAmount4", ChangeTypeAmount4); //提现手续费
            // other.Add("ChangeTypeAmount5", ChangeTypeAmount5); //提现税点扣除
            // other.Add("ChangeTypeAmount6", ChangeTypeAmount6); //提现失败，解冻
            // other.Add("ChangeTypeAmount61", ChangeTypeAmount61); //人工冻结
            // other.Add("ChangeTypeAmount62", ChangeTypeAmount62); //人工解冻
            // other.Add("ChangeTypeAmount63", ChangeTypeAmount63); //人工扣减
            // other.Add("ChangeTypeAmount64", ChangeTypeAmount64); //人工增加
            // other.Add("ChangeTypeAmount50", ChangeTypeAmount50); //开机奖励
            // other.Add("ChangeTypeAmount111", ChangeTypeAmount111); //分润补贴
            // other.Add("ChangeTypeAmount112", ChangeTypeAmount112); //推荐奖励
            // other.Add("ChangeTypeAmount60", ChangeTypeAmount60); //流量卡分佣
            // other.Add("ChangeTypeAmount31", ChangeTypeAmount31); //红包奖励
            // other.Add("ChangeTypeAmount31s", ChangeTypeAmount31s); //活动奖励
            // other.Add("ChangeTypeAmount124", ChangeTypeAmount124); //机具过期
            // other.Add("ChangeTypeAmount125", ChangeTypeAmount125); //软件服务费

            string ChangeTypeAmount0 = "0.00", ChangeTypeAmount1 = "0.00", ChangeTypeAmount2 = "0.00", ChangeTypeAmount3 = "0.00", ChangeTypeAmount4 = "0.00", ChangeTypeAmount5 = "0.00", ChangeTypeAmount6 = "0.00", ChangeTypeAmount12 = "0.00", ChangeTypeAmount20 = "0.00", ChangeTypeAmount31 = "0.00", ChangeTypeAmount50 = "0.00", ChangeTypeAmount60 = "0.00", ChangeTypeAmount61 = "0.00", ChangeTypeAmount62 = "0.00", ChangeTypeAmount63 = "0.00", ChangeTypeAmount64 = "0.00", ChangeTypeAmount111 = "0.00", ChangeTypeAmount112 = "0.00", ChangeTypeAmount114 = "0.00", ChangeTypeAmount115 = "0.00", ChangeTypeAmount116 = "0.00", ChangeTypeAmount119 = "0.00", ChangeTypeAmount121 = "0.00", ChangeTypeAmount122 = "0.00", ChangeTypeAmount123 = "0.00", ChangeTypeAmount118And120And128 = "0.00", ChangeTypeAmount124 = "0.00", ChangeTypeAmount125 = "0.00", ChangeTypeAmount126 = "0.00", ChangeTypeAmount127 = "0.00", ChangeTypeAmount202 = "0.00", ChangeTypeAmount30 = "0.00";
            DataTable dt = OtherMySqlConn.dtable("select sum(if(ChangeType=0, ChangeAmount, 0)) + sum(if(ChangeType=12, ChangeAmount, 0)) + sum(if(ChangeType=133, ChangeAmount, 0)),sum(if(ChangeType=1 and ProductType!=101, ChangeAmount, 0)) + sum(if(ChangeType in(112,1) and ProductType=101, ChangeAmount, 0)),sum(if(ChangeType=2, ChangeAmount, 0)),sum(if(ChangeType=3, ChangeAmount, 0)),sum(if(ChangeType=4, ChangeAmount, 0)),sum(if(ChangeType=5, ChangeAmount, 0)),sum(if(ChangeType=6, ChangeAmount, 0)),sum(if(ChangeType=12, ChangeAmount, 0)),sum(if(ChangeType=20, ChangeAmount, 0)),sum(if(ChangeType=31 and (Remark!='开机抢红包活动' or Remark IS NULL), ChangeAmount, 0)),sum(if(ChangeType=50, ChangeAmount, 0)),sum(if(ChangeType=60, ChangeAmount, 0)),sum(if(ChangeType=61, ChangeAmount, 0)),sum(if(ChangeType=62, ChangeAmount, 0)),sum(if(ChangeType=63, ChangeAmount, 0)),sum(if(ChangeType=64, ChangeAmount, 0)),sum(if(ChangeType=111, ChangeAmount, 0)),sum(if(ChangeType=112  and ProductType=0, ChangeAmount, 0)),sum(if(ChangeType=114, ChangeAmount, 0)),sum(if(ChangeType=115, ChangeAmount, 0)),sum(if(ChangeType=116, ChangeAmount, 0)),sum(if(ChangeType=119, ChangeAmount, 0)),sum(if(ChangeType=121, ChangeAmount, 0)),sum(if(ChangeType=122, ChangeAmount, 0)),sum(if(ChangeType=123, ChangeAmount, 0)),sum(if(ChangeType in(118,120,128), ChangeAmount, 0)),sum(if(ChangeType=124, ChangeAmount, 0)),sum(if(ChangeType=125, ChangeAmount, 0)),sum(if(ChangeType=126, ChangeAmount, 0)),sum(if(ChangeType=127, ChangeAmount, 0)),sum(if(ChangeType=202, ChangeAmount, 0)),sum(if(ChangeType=31 and Remark='开机抢红包活动', ChangeAmount, 0)) from UserAccountRecord where 1=1" + condition);
            if (dt.Rows.Count > 0)
            {
                ChangeTypeAmount0 = dt.Rows[0][0].ToString();
                ChangeTypeAmount1 = dt.Rows[0][1].ToString();
                ChangeTypeAmount2 = dt.Rows[0][2].ToString();
                ChangeTypeAmount3 = dt.Rows[0][3].ToString();
                ChangeTypeAmount4 = dt.Rows[0][4].ToString();
                ChangeTypeAmount5 = dt.Rows[0][5].ToString();
                ChangeTypeAmount6 = dt.Rows[0][6].ToString();
                ChangeTypeAmount12 = dt.Rows[0][7].ToString();
                ChangeTypeAmount20 = dt.Rows[0][8].ToString();
                ChangeTypeAmount31 = dt.Rows[0][9].ToString();
                ChangeTypeAmount50 = dt.Rows[0][10].ToString();
                ChangeTypeAmount60 = dt.Rows[0][11].ToString();
                ChangeTypeAmount61 = dt.Rows[0][12].ToString();
                ChangeTypeAmount62 = dt.Rows[0][13].ToString();
                ChangeTypeAmount63 = dt.Rows[0][14].ToString();
                ChangeTypeAmount64 = dt.Rows[0][15].ToString();
                ChangeTypeAmount111 = dt.Rows[0][16].ToString();
                ChangeTypeAmount112 = dt.Rows[0][17].ToString();
                ChangeTypeAmount114 = dt.Rows[0][18].ToString();
                ChangeTypeAmount115 = dt.Rows[0][19].ToString();
                ChangeTypeAmount116 = dt.Rows[0][20].ToString();
                ChangeTypeAmount119 = dt.Rows[0][21].ToString();
                ChangeTypeAmount121 = dt.Rows[0][22].ToString();
                ChangeTypeAmount122 = dt.Rows[0][23].ToString();
                ChangeTypeAmount123 = dt.Rows[0][24].ToString();
                ChangeTypeAmount118And120And128 = dt.Rows[0][25].ToString();
                ChangeTypeAmount124 = dt.Rows[0][26].ToString();
                ChangeTypeAmount125 = dt.Rows[0][27].ToString();
                ChangeTypeAmount126 = dt.Rows[0][28].ToString();
                ChangeTypeAmount127 = dt.Rows[0][29].ToString();
                ChangeTypeAmount202 = dt.Rows[0][30].ToString();
                ChangeTypeAmount30 = dt.Rows[0][31].ToString();
            }
            other.Add("ChangeTypeAmount0", ChangeTypeAmount0); //激活奖励
            other.Add("ChangeTypeAmount1", ChangeTypeAmount1); //交易分润
            other.Add("ChangeTypeAmount2", ChangeTypeAmount2); //提现申请
            other.Add("ChangeTypeAmount3", ChangeTypeAmount3); //提现代付
            other.Add("ChangeTypeAmount4", ChangeTypeAmount4); //提现手续费
            other.Add("ChangeTypeAmount5", ChangeTypeAmount5); //提现税点扣除
            other.Add("ChangeTypeAmount6", ChangeTypeAmount6); //提现失败，解冻
            other.Add("ChangeTypeAmount12", ChangeTypeAmount12); //交易奖励
            other.Add("ChangeTypeAmount20", ChangeTypeAmount20); //余额支付
            other.Add("ChangeTypeAmount31", ChangeTypeAmount31); //活动奖励
            other.Add("ChangeTypeAmount50", ChangeTypeAmount50); //开机奖励
            other.Add("ChangeTypeAmount60", ChangeTypeAmount60); //流量卡分佣
            other.Add("ChangeTypeAmount61", ChangeTypeAmount61); //人工冻结
            other.Add("ChangeTypeAmount62", ChangeTypeAmount62); //人工解冻
            other.Add("ChangeTypeAmount63", ChangeTypeAmount63); //系统扣减(人工扣减)
            other.Add("ChangeTypeAmount64", ChangeTypeAmount64); //系统奖励(人工增加)
            other.Add("ChangeTypeAmount111", ChangeTypeAmount111); //分润补贴
            other.Add("ChangeTypeAmount112", ChangeTypeAmount112); //推荐奖励
            other.Add("ChangeTypeAmount114", ChangeTypeAmount114); //私董会分红
            other.Add("ChangeTypeAmount115", ChangeTypeAmount115); //分仓奖励
            other.Add("ChangeTypeAmount116", ChangeTypeAmount116); //大盟主奖励
            other.Add("ChangeTypeAmount119", ChangeTypeAmount119); //分仓临时额度退还
            other.Add("ChangeTypeAmount121", ChangeTypeAmount121); //运营中心奖励
            other.Add("ChangeTypeAmount122", ChangeTypeAmount122); //推荐大盟主奖励
            other.Add("ChangeTypeAmount123", ChangeTypeAmount123); //推荐小盟主奖励
            other.Add("ChangeTypeAmount118And120", ChangeTypeAmount118And120And128); //购机奖励(118盟主奖励(购机奖励) 120运营中心(购机奖励) 128合伙人(购机奖励))
            other.Add("ChangeTypeAmount124", ChangeTypeAmount124); //扣机具货款
            other.Add("ChangeTypeAmount125", ChangeTypeAmount125); //软件服务费
            other.Add("ChangeTypeAmount126", ChangeTypeAmount126); //机具货款退还
            other.Add("ChangeTypeAmount127", ChangeTypeAmount127); //运营中心分仓奖励
            other.Add("ChangeTypeAmount202", ChangeTypeAmount202); //创客预扣款
            other.Add("ChangeTypeAmount30", ChangeTypeAmount30); //红包奖励
            obj.Add("other", other);
            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(UserAccountRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("UserAccountRecord", Fields, 0);
            AddSysLog(data.Id.ToString(), "UserAccountRecord", "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;


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

        #endregion

        #region 修改创客账户变动记录

        /// <summary>
        /// 增加或修改创客账户变动记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(UserAccountRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("UserAccountRecord", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "UserAccountRecord", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除创客账户变动记录信息

        /// <summary>
        /// 删除创客账户变动记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserAccountRecord", "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("UserAccountRecord", 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, "UserAccountRecord", "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("UserAccountRecord", 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, "UserAccountRecord", "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("UserAccountRecord", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

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

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

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                db.UserAccountRecord.Add(new UserAccountRecord()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                db.SaveChanges();
            }
            AddSysLog("0", "UserAccountRecord", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(UserAccountRecord data, int ChangeType, int ProductType, string TransRecordNo, string MakerCode, string RealName, string CreateDateData, int TopUserId, int UserId)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            // Fields.Add("ChangeType", "1"); //交易类型
            // Fields.Add("ProductType", "1"); //产品类型
            // Fields.Add("TransRecordNo", "3"); //交易流水编号

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //顶级创客
            if (TopUserId > 0)
            {
                condition += " and UserId in (select Id from Users where ParentNav like '," + TopUserId + ",%')";
            }
            if (UserId > 0)
            {
                condition += " and UserId=" + UserId;
            }
            if (ChangeType > 0)
            {
                if (ChangeType == 1)
                {
                    condition += " and (ChangeType=" + ChangeType + " or (ChangeType in(112,1) and ProductType=101))";
                }
                else if (ChangeType == 30)
                {
                    condition += " and ChangeType=31 and Remark='开机抢红包活动'";
                }
                else if (ChangeType == 31)
                {
                    condition += " and (ChangeType=" + ChangeType + " and (Remark!='开机抢红包活动' or Remark IS NULL))";
                }
                else
                {
                    condition += " and ChangeType=" + ChangeType;
                }
            }
            if (ProductType > 0)
            {
                condition += " and ProductType=" + ProductType;
            }
            if (!string.IsNullOrEmpty(TransRecordNo))
            {
                condition += " and TransRecordNo='" + TransRecordNo + "'";
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = Convert.ToDateTime(Convert.ToDateTime(datelist[0]).ToString("yyyy-MM-dd"));
                var end = Convert.ToDateTime(Convert.ToDateTime(datelist[1]).ToString("yyyy-MM-dd") + " 23:59:59");
                var check = db.UserAccountRecord.Any(m => m.CreateDate >= start);
                var checks = db.UserAccountRecord.Any(m => m.CreateDate <= end);
                if (check)
                {
                    var sId = db.UserAccountRecord.Where(m => m.CreateDate >= start).Min(m => m.Id);
                    condition += "  and Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.UserAccountRecord.Where(m => m.CreateDate <= end).Max(m => m.Id);
                    condition += " and Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.UserAccountRecord.Any(m => m.CreateDate >= start);
                if (check)
                {
                    var minId = db.UserAccountRecord.Where(m => m.CreateDate >= start).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/UsersAccountRecord/UsersAccountRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/UsersAccountRecord/", "UsersAccountRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserAccountRecord", Fields, "Id desc", "0", 1, 20000, condition, "UserId,ProductType,TransRecordNo,ChangeType,ChangeAmount,Remark,BeforeTotalAmount,AfterTotalAmount,BeforeFreezeAmount,AfterFreezeAmount,BeforeBalanceAmount,AfterBalanceAmount,CreateDate", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int UId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                if (!string.IsNullOrEmpty(user.ParentNav))
                {
                    int TopId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
                    Users tuser = db.Users.FirstOrDefault(m => m.Id == TopId) ?? new Users();
                    dic["TopMakerCode"] = tuser.MakerCode;
                    dic["TopRealName"] = tuser.RealName;
                }
                int ProductTypes = int.Parse(dic["ProductType"].ToString());
                dic["ProductTypeName"] = RelationClass.GetKqProductBrandInfo(ProductTypes);
                int ChangeTypes = int.Parse(dic["ChangeType"].ToString());
                string Remark = dic["Remark"].ToString();
                if (ChangeTypes == 31 && (Remark == "开机抢红包活动" || string.IsNullOrEmpty(Remark)))
                {
                    dic["ChangeTypeName"] = "红包奖励";
                }
                else
                {
                    dic["ChangeTypeName"] = RelationClassForConst.GetChangeTypeInfo(ChangeTypes);
                }
                dic.Remove("UserId");
                dic.Remove("ChangeType");
                dic.Remove("ProductType");
            }

            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("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("ProductTypeName", "产品类型");
            ReturnFields.Add("TransRecordNo", "交易流水编号");
            ReturnFields.Add("ChangeTypeName", "交易类型");
            ReturnFields.Add("ChangeAmount", "交易金额");
            ReturnFields.Add("Remark", "备注");
            ReturnFields.Add("BeforeTotalAmount", "交易前总金额");
            ReturnFields.Add("AfterTotalAmount", "交易后总金额");
            ReturnFields.Add("BeforeFreezeAmount", "交易前冻结金额");
            ReturnFields.Add("AfterFreezeAmount", "交易后冻结金额");
            ReturnFields.Add("BeforeBalanceAmount", "交易前余额");
            ReturnFields.Add("AfterBalanceAmount", "交易后余额");
            ReturnFields.Add("CreateDate", "交易时间");

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

        #endregion


        #region 快捷导出Excel
        public IActionResult QuickExportExcel(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(int ChangeType, int ProductType, string TransRecordNo, string MakerCode, string RealName, string CreateDateData)
        {

            string SqlString = " and a.Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                SqlString += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                SqlString += " and a.UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            if (ChangeType > 0)
            {
                // if (ChangeType == 1)
                // {
                //     SqlString += " and (a.ChangeType=" + ChangeType + " or (a.ChangeType in(112,1) and a.ProductType=101))";
                // }
                // else if (ChangeType == 30)
                // {
                //     SqlString += " and a.ChangeType=31 and a.Remark='开机抢红包活动'";
                // }
                // else if (ChangeType == 31)
                // {
                //     SqlString += " and (a.ChangeType=" + ChangeType + " and (a.Remark!='开机抢红包活动' or a.Remark IS NULL))";
                // }
                // else
                // {
                //     SqlString += " and a.ChangeType=" + ChangeType;
                // }

                if (ChangeType > 0)
                {
                    if (ChangeType == 1)
                    {
                        SqlString += " and (a.ChangeType=" + ChangeType + " or (a.ChangeType in(112,1) and a.ProductType=101))";
                    }
                    else if (ChangeType == 112)
                    {
                        SqlString += " and a.ChangeType=112 and a.ProductType=0";
                    }
                    else
                    {
                        SqlString += " and a.ChangeType=" + ChangeType;
                    }
                }
                if (ChangeType == 0)
                {
                    SqlString += " and a.ChangeType in(0,12)";
                }
            }
            if (ProductType > 0)
            {
                SqlString += " and a.ProductType=" + ProductType;
            }
            if (!string.IsNullOrEmpty(TransRecordNo))
            {
                SqlString += " and a.TransRecordNo='" + TransRecordNo + "'";
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                var start = Convert.ToDateTime(Convert.ToDateTime(datelist[0]).ToString("yyyy-MM-dd"));
                var end = Convert.ToDateTime(Convert.ToDateTime(datelist[1]).ToString("yyyy-MM-dd") + " 23:59:59");
                var check = db.UserAccountRecord.Any(m => m.CreateDate >= start);
                var checks = db.UserAccountRecord.Any(m => m.CreateDate <= end);
                if (check)
                {
                    var sId = db.UserAccountRecord.Where(m => m.CreateDate >= start).Min(m => m.Id);
                    SqlString += "  and a.Id >=" + sId;
                }
                if (checks)
                {
                    var eId = db.UserAccountRecord.Where(m => m.CreateDate <= end).Max(m => m.Id);
                    SqlString += " and a.Id <=" + eId;
                }
            }
            else
            {
                var start = Convert.ToDateTime(DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-01");
                var check = db.UserAccountRecord.Any(m => m.CreateDate >= start);
                if (check)
                {
                    var minId = db.UserAccountRecord.Where(m => m.CreateDate >= start).Min(m => m.Id);
                    var Info = function.ReadInstance("/WritePage/UsersAccountRecord/UsersAccountRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/UsersAccountRecord/", "UsersAccountRecord.txt", minId.ToString());
                        SqlString += " and a.Id >=" + minId;
                    }
                    else
                    {
                        SqlString += " and a.Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    SqlString += " and a.Id =0";
                }
            }
            var Sql = "SELECT e.MakerCode '创客编号',e.RealName '创客姓名',f.MakerCode '顶级创客编号',f.RealName '顶级创客名称',e.`Name` '产品类型',e.TransRecordNo '交易流水编号',e.ChangeTypeName '交易类型',e.ChangeAmount '交易金额',e.Remark '备注',e.BeforeTotalAmount '交易前总金额',e.AfterTotalAmount '交易后总金额',e.BeforeFreezeAmount '交易前冻结金额',e.AfterFreezeAmount '交易后冻结金额',e.BeforeBalanceAmount '交易前余额',e.AfterBalanceAmount '交易后余额',DATE_FORMAT(e.CreateDate,'%Y-%m-%d %H:%i:%s') '交易时间' FROM (SELECT b.MakerCode,b.RealName,SUBSTRING_INDEX(SUBSTRING_INDEX(b.ParentNav,',',4),',',-1) topId,c.`Name`,a.TransRecordNo,d.`Name` ChangeTypeName,a.ChangeAmount,a.Remark,a.BeforeTotalAmount,a.AfterTotalAmount,a.BeforeFreezeAmount,a.AfterFreezeAmount,a.BeforeBalanceAmount,a.AfterBalanceAmount,a.CreateDate FROM UserAccountRecord a LEFT JOIN Users b ON a.UserId=b.Id LEFT JOIN KqProducts c ON a.ProductType=c.Id LEFT JOIN ChangeTypes d ON a.ChangeType=d.Id WHERE 1=1 " + SqlString + ") e LEFT JOIN Users f ON e.topId=f.Id";
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "创客账户变动记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion

    }
}
