/*
 * 创客分润规则
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
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 UserProfitController : BaseController
    {
        public UserProfitController(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(UserProfit data, string right, string UserId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.UserId = UserId;

            return View();
        }

        #endregion

        #region 根据条件查询创客分润规则列表

        /// <summary>
        /// 创客分润规则列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(UserProfit data, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("UserId", "1");



            string condition = " and Status>-1";


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserProfit", 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 UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                dic.Remove("UserId");
                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserIdMakerCode"] = topuserid_Users.MakerCode;
                dic["TopUserIdRealName"] = topuserid_Users.RealName;
                dic.Remove("TopUserId");

            }
            return Json(obj);
        }

        #endregion

        #region 增加创客分润规则

        /// <summary>
        /// 增加或修改创客分润规则信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right, int UserId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.UserId = UserId.ToString();

            Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            ViewBag.RealName = user.RealName;
            int TopUserId = 0;
            if (!string.IsNullOrEmpty(user.ParentNav))
            { 
                TopUserId = int.Parse(user.ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
            }
            Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
            ViewBag.TopMakerCode = tuser.MakerCode;
            ViewBag.TopRealName = tuser.RealName;
            return View();
        }

        #endregion

        #region 增加创客分润规则

        /// <summary>
        /// 增加或修改创客分润规则信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(UserProfit data)
        {
            Users user = db.Users.FirstOrDefault(m => m.Id == data.UserId) ?? new Users();
            string ParentNav = user.ParentNav;
            int TopUserId = 0;
            if (!string.IsNullOrEmpty(ParentNav))
            {
                TopUserId = int.Parse(ParentNav.Trim(',').Replace(",,", ",").Split(',')[0]);
            }
            string[] CardTypes = data.CardType.Split(',');
            foreach (string CardType in CardTypes)
            {
                bool op = db.UserProfit.Any(m => m.CardType == CardType && m.BrandId == data.BrandId);
                if (op)
                {
                    string BrandName = RelationClass.GetKqProductBrandInfo(data.BrandId);
                    string CardTypeName = CardType == "1" ? "贷记卡" : "借记卡";
                    return "已添加了" + BrandName + CardTypeName + "的分润规则，请勿重复添加";
                }
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("UserId", data.UserId);

                Fields.Add("TopUserId", TopUserId);
                Fields.Add("BrandId", data.BrandId); //品牌
                Fields.Add("CardType", CardType); //交易卡类型
                Fields.Add("ProfitRate", data.ProfitRate); //创客预设分润比例
                Fields.Add("ProfitPercent", data.ProfitPercent); //创客预设分润百分比
                Fields.Add("AddOrSubRate", data.AddOrSubRate); //浮动空间
                Fields.Add("ProfitRateBase", data.ProfitRateBase); //分润比例基数
                Fields.Add("Remark", data.Remark); //备注
                Fields.Add("HelpAddOrSubRate", data.HelpAddOrSubRate); //扶持期浮动空间
                Fields.Add("HelpProfitPercent", data.HelpProfitPercent); //扶持期创客预设分润百分比
                Fields.Add("HelpProfitRate", data.HelpProfitRate); //扶持期创客预设分润比例
                Fields.Add("HelpProfitRateBase", data.HelpProfitRateBase); //扶持期分润比例基数

                int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("UserProfit", Fields, 0);
                AddSysLog(data.Id.ToString(), "UserProfit", "add");
                db.UserProfitSet.Add(new UserProfitSet()
                {
                    CreateDate = DateTime.Now,
                    Remark = data.Remark,
                    ProfitRateBase = data.ProfitRateBase,
                    AddOrSubRate = data.AddOrSubRate,
                    ProfitPercent = data.ProfitPercent,
                    ProfitRate = data.ProfitRate,
                    HelpFlag = 0,
                    CardType = int.Parse(CardType),
                    BrandId = data.BrandId,
                    UserId = data.UserId,
                    TopUserId = TopUserId,
                });
                db.UserProfitSet.Add(new UserProfitSet()
                {
                    CreateDate = DateTime.Now,
                    Remark = data.Remark,
                    ProfitRateBase = data.HelpProfitRateBase,
                    AddOrSubRate = data.HelpAddOrSubRate,
                    ProfitPercent = data.HelpProfitPercent,
                    ProfitRate = data.HelpProfitRate,
                    HelpFlag = 1,
                    CardType = int.Parse(CardType),
                    BrandId = data.BrandId,
                    UserId = data.UserId,
                    TopUserId = TopUserId,
                });
                db.SaveChanges();
            }

            return "success";
        }

        #endregion

        #region 修改创客分润规则

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


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

        #endregion

        #region 修改创客分润规则

        /// <summary>
        /// 增加或修改创客分润规则信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(UserProfit data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("ProfitPercent", data.ProfitPercent); //创客预设分润百分比
            Fields.Add("AddOrSubRate", data.AddOrSubRate); //浮动空间
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("HelpAddOrSubRate", data.HelpAddOrSubRate); //扶持期浮动空间
            Fields.Add("HelpProfitPercent", data.HelpProfitPercent); //扶持期创客预设分润百分比

            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("UserProfit", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "UserProfit", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除创客分润规则信息

        /// <summary>
        /// 删除创客分润规则信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "UserProfit", "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("UserProfit", 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, "UserProfit", "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("UserProfit", 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, "UserProfit", "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("UserProfit", 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("UserProfit", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(UserProfit data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();


            string condition = " and Status>-1";


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("UserProfit", Fields, "Id desc", "0", 1, 20000, condition, "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //创客
                int UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                dic.Remove("UserId");
                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserIdMakerCode"] = topuserid_Users.MakerCode;
                dic["TopUserIdRealName"] = topuserid_Users.RealName;
                dic.Remove("TopUserId");

            }

            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", "UserProfit", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
