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

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.OpModels;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class UserAccountRecordOperateController : BaseController
    {
        public UserAccountRecordOperateController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }

        #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();

            var 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 MakerCode, string OpCode, string CreateDateData, 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 = condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //运营中心编号
            if (!string.IsNullOrEmpty(OpCode))
            {
                condition += " and UserId in (select Id from SysAdmin where OpCode='" + OpCode + "')";
            }
            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/OpUsersAccountRecord/UsersAccountRecord.txt");
                    if (string.IsNullOrEmpty(Info.ToString()))
                    {
                        function.WritePage("/WritePage/OpUsersAccountRecord/", "UsersAccountRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else if (minId != int.Parse(Info))
                    {
                        function.WritePage("/WritePage/OpUsersAccountRecord/", "UsersAccountRecord.txt", minId.ToString());
                        condition += " and Id >=" + minId;
                    }
                    else
                    {
                        condition += " and Id >=" + Convert.ToInt32(Info);
                    }
                }
                else
                {
                    condition += " and Id =0";
                }
                
            }
            if (data.ChangeType > 0)
            {
                condition += " and ChangeType=" + data.ChangeType;
            }
            if (data.ProductType > 0)
            {
                condition += " and ProductType=" + data.ProductType;
            }
            if (!string.IsNullOrEmpty(data.TransRecordNo))
            {
                condition += " and TransRecordNo='" + data.TransRecordNo + "'";
            }

            Dictionary<string, object> obj = new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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());
                SysAdmin sysAdmin = opdb.SysAdmin.FirstOrDefault(m => m.Id == UId) ?? new SysAdmin();
                dic["OpCode"] = sysAdmin.OpCode;
                dic["MakerCode"] = sysAdmin.MakerCode;
                dic["MakerName"] = sysAdmin.MakerName;
                int ProductType = int.Parse(dic["ProductType"].ToString());
                dic["ProductTypeName"] = RelationClass.GetKqProductBrandInfo(ProductType);
                int ChangeType = int.Parse(dic["ChangeType"].ToString());
                dic["ChangeTypeName"] = RelationClassForConst.GetChangeTypeInfo(ChangeType);

                //获得盟主5元奖励的机具Sn
                int SnId = int.Parse(dic["QueryCount"].ToString());
                var pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == SnId) ?? new Models.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";
            DataTable dt = OtherMySqlConn.dtable("select sum(if(ChangeType=0, ChangeAmount, 0)),sum(if(ChangeType=1, 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, ChangeAmount, 0)),sum(if(ChangeType=60, ChangeAmount, 0)),sum(if(ChangeType=31, ChangeAmount, 0)),sum(if(ChangeType=3, ChangeAmount, 0)),sum(if(ChangeType=4, ChangeAmount, 0)),sum(if(ChangeType=5, 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();
            }
            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); //红包奖励
            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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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 = opdb.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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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 AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).Edit("UserAccountRecord", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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];

                opdb.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, string MakerCode, string OpCode, string RealName, int TopUserId, int UserId)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ChangeType", "1"); //交易类型
            Fields.Add("ProductType", "1"); //产品类型
            Fields.Add("TransRecordNo", "3"); //交易流水编号
            Fields.Add("CreateDate", "3"); //交易时间

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //运营中心编号
            if (!string.IsNullOrEmpty(OpCode))
            {
                condition += " and UserId in (select Id from SysAdmin where OpCode='" + OpCode + "')";
            }
            //创客名称
            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;
            }

            Dictionary<string, object> obj = new AdminContentByConn(_accessor.HttpContext, PublicFunction.OpTables, OpConn).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());
                SysAdmin sysAdmin = opdb.SysAdmin.FirstOrDefault(m => m.Id == UId) ?? new SysAdmin();
                dic["OpCode"] = sysAdmin.OpCode;
                dic["MakerCode"] = sysAdmin.MakerCode;
                dic["MakerName"] = sysAdmin.MakerName;
                int ProductType = int.Parse(dic["ProductType"].ToString());
                dic["ProductTypeName"] = RelationClass.GetKqProductBrandInfo(ProductType);
                int ChangeType = int.Parse(dic["ChangeType"].ToString());
                dic["ChangeTypeName"] = RelationClassForConst.GetChangeTypeInfo(ChangeType);
                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("OpCode", "运营中心编号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            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

    }
}
