/*
 * 创客账户
 */

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 UserAccountController : BaseController
    {
        public UserAccountController(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(UserAccount 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;

            return View();
        }

        #endregion

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

        /// <summary>
        /// 创客账户列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(UserAccount data, string CreateDate, string MakerCode, string RealName, int TopUserId, string AccountStatusSelect, string CreateDateData, int? sTotalAmount, int? eTotalAmount, int UserId = 0, int ShowFlag = 0, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //创建时间
            Fields.Add("sTotalAmount", "31"); //账户总金额
            Fields.Add("eTotalAmount", "32"); //账户总金额
            if (ShowFlag == 0)
            {
                Dictionary<string, object> objs = new Dictionary<string, object>();
                Dictionary<string, object> others = new Dictionary<string, object>();
                others.Add("TotalAmount", 0);
                others.Add("FreezeAmount", 0);
                others.Add("BalanceAmount", 0);
                objs.Add("other", others);
                return Json(objs);
            }

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

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserAccount", 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 Id = int.Parse(dic["Id"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == Id) ?? 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;
                }
                dic["AccountStatusName"] = dic["AccountStatus"].ToString() == "0" ? "有效" : "冻结";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            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'";
            }
            if (sTotalAmount != null)
            {
                condition += " and BalanceAmount>=" + sTotalAmount.Value;
            }
            if (eTotalAmount != null)
            {
                condition += " and BalanceAmount<=" + eTotalAmount.Value;
            }
            string TotalAmount = "0.00", FreezeAmount = "0.00", BalanceAmount = "0.00";
            DataTable dt = OtherMySqlConn.dtable("select sum(TotalAmount),sum(FreezeAmount),sum(BalanceAmount) from UserAccount where 1=1" + condition);
            if (dt.Rows.Count > 0)
            {
                TotalAmount = dt.Rows[0][0].ToString();
                FreezeAmount = dt.Rows[0][1].ToString();
                BalanceAmount = dt.Rows[0][2].ToString();
            }
            other.Add("TotalAmount", TotalAmount);
            other.Add("FreezeAmount", FreezeAmount);
            other.Add("BalanceAmount", BalanceAmount);
            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(UserAccount data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("UserId", data.UserId); //创客
            Fields.Add("UserType", data.UserType); //创客类型
            Fields.Add("UserProperty", data.UserProperty); //创客属性
            Fields.Add("TotalAmount", data.TotalAmount); //总金额
            Fields.Add("FreezeAmount", data.FreezeAmount); //冻结金额
            Fields.Add("BalanceAmount", data.BalanceAmount); //余额
            Fields.Add("AccountStatus", data.AccountStatus); //账户状态
            Fields.Add("LockStatus", data.LockStatus); //锁定状态

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


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

        #endregion

        #region 修改创客账户

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

            Fields.Add("UserId", data.UserId); //创客
            Fields.Add("UserType", data.UserType); //创客类型
            Fields.Add("UserProperty", data.UserProperty); //创客属性
            Fields.Add("TotalAmount", data.TotalAmount); //总金额
            Fields.Add("FreezeAmount", data.FreezeAmount); //冻结金额
            Fields.Add("BalanceAmount", data.BalanceAmount); //余额
            Fields.Add("AccountStatus", data.AccountStatus); //账户状态
            Fields.Add("LockStatus", data.LockStatus); //锁定状态

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

            return "success";
        }

        #endregion

        #region 冻结创客账户添加备注

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


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

        #endregion

        #region 冻结创客账户添加备注

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

            Fields.Add("UserId", data.UserId); //创客
            Fields.Add("AccountStatus", 1); //账户状态
            Fields.Add("UpdateMan", SysUserName + '-' + SysRealName + "操作冻结该账户"); //操作人信息
            Fields.Add("SeoDescription", data.SeoDescription); //冻结备注
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("UserAccount", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "UserAccount", "CloseRemark");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除创客账户信息

        /// <summary>
        /// 删除创客账户信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserAccount", "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("UserAccount", 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, "UserAccount", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("UpdateMan", SysUserName + '-' + SysRealName + "操作解冻该账户"); //操作人信息
                Fields.Add("AccountStatus", 0);
                Fields.Add("SeoDescription", "");
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("UserAccount", 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, "UserAccount", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("AccountStatus", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("UserAccount", 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("UserAccount", Sort, Id);

            AddSysLog(Id.ToString(), "UserAccount", "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.UserAccount.Add(new UserAccount()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(UserAccount data, decimal? sTotalAmount, decimal? eTotalAmount)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("sTotalAmount", "31"); //总金额上限
            Fields.Add("eTotalAmount", "32"); //总金额下限
            Fields.Add("AccountStatus", "1"); //账户状态

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserAccount", Fields, "Id desc", "0", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["UserId"] = RelationClass.GetUsersInfo(int.Parse(dic["UserId"].ToString()));

            }

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

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

        #endregion

    }
}
