/*
 * 流量分佣汇总
 */

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 FluxProfitSummaryController : BaseController
    {
        public FluxProfitSummaryController(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(FluxProfitSummary data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询流量分佣汇总列表

        /// <summary>
        /// 流量分佣汇总列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(FluxProfitSummary data, string MakerCode, string RealName, string TopMakerCode, string TopRealName, string TradeMonthSelect, string CheckStatusSelect, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();

            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 (!string.IsNullOrEmpty(TopMakerCode))
            {
                condition += " and TopUserId in (select UserId from UserForMakerCode where MakerCode='" + TopMakerCode + "')";
            }
            //顶级创客名称
            if (!string.IsNullOrEmpty(TopRealName))
            {
                condition += " and TopUserId in (select UserId from UserForRealName where RealName='" + TopRealName + "')";
            }
            //交易月份
            if(!string.IsNullOrEmpty(TradeMonthSelect))
            {
                condition += " and TradeMonth=" + TradeMonthSelect.Replace("-", "");
            }
            //是否验证
            if(!string.IsNullOrEmpty(CheckStatusSelect))
            {
                condition += " and CheckStatus=" + CheckStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("FluxProfitSummary", 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(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;

                int TopUserId = int.Parse(dic["TopUserId"].ToString());
                Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopMakerCode"] = tuser.MakerCode;
                dic["TopRealName"] = tuser.RealName;

                int MerUserType = int.Parse(dic["MerUserType"].ToString());
                if (MerUserType == 0) dic["MerUserType"] = "非商户型创客";
                if (MerUserType == 1) dic["MerUserType"] = "商户型创客";

                int CheckStatus = int.Parse(dic["CheckStatus"].ToString());
                if (CheckStatus == 0) dic["CheckStatus"] = "初始";
                if (CheckStatus == 1) dic["CheckStatus"] = "已验证和同步";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string TradeCount = "0.00";//流量费交易笔数
            string FluxProfit = "0.00";//分佣总金额
            DataTable dt = OtherMySqlConn.dtable("select count(0) from FluxProfitSummary where BrandId=3 or BrandId=5" + condition);
            if (dt.Rows.Count > 0)
            {
                TradeCount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            dt = OtherMySqlConn.dtable("select sum(FluxProfitAmt) from FluxProfitSummary where BrandId=3 or BrandId=5" + condition);
            if (dt.Rows.Count > 0)
            {
                FluxProfit = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            other.Add("TradeCount", TradeCount);
            other.Add("FluxProfit", FluxProfit);
            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(FluxProfitSummary 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("FluxProfitSummary", Fields, 0);
            AddSysLog(data.Id.ToString(), "FluxProfitSummary", "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;


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

        #endregion

        #region 修改流量分佣汇总

        /// <summary>
        /// 增加或修改流量分佣汇总信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(FluxProfitSummary 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("FluxProfitSummary", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "FluxProfitSummary", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除流量分佣汇总信息

        /// <summary>
        /// 删除流量分佣汇总信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "FluxProfitSummary", "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("FluxProfitSummary", 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, "FluxProfitSummary", "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("FluxProfitSummary", 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, "FluxProfitSummary", "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("FluxProfitSummary", 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("FluxProfitSummary", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(FluxProfitSummary data, string MakerCode, string RealName, string TopMakerCode, string TopRealName, string TradeMonthSelect, string CheckStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            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 (!string.IsNullOrEmpty(TopMakerCode))
            {
                condition += " and TopUserId in (select UserId from UserForMakerCode where MakerCode='" + TopMakerCode + "')";
            }
            //顶级创客名称
            if (!string.IsNullOrEmpty(TopRealName))
            {
                condition += " and TopUserId in (select UserId from UserForRealName where RealName='" + TopRealName + "')";
            }
            //交易月份
            if(!string.IsNullOrEmpty(TradeMonthSelect))
            {
                condition += " and TradeMonth=" + TradeMonthSelect.Replace("-", "");
            }
            //是否验证
            if(!string.IsNullOrEmpty(CheckStatusSelect))
            {
                condition += " and CheckStatus=" + CheckStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("FluxProfitSummary", Fields, "Id desc", "0", 1, 20000, condition, "UserId,TopUserId,TradeMonth,MerUserType,FluxProfitAmt,FluxTradeNum,CheckStatus", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;

                int TopUserId = int.Parse(dic["TopUserId"].ToString());
                Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopMakerCode"] = tuser.MakerCode;
                dic["TopRealName"] = tuser.RealName;

                int MerUserType = int.Parse(dic["MerUserType"].ToString());
                if (MerUserType == 0) dic["MerUserType"] = "非商户型创客";
                if (MerUserType == 1) dic["MerUserType"] = "商户型创客";

                int CheckStatus = int.Parse(dic["CheckStatus"].ToString());
                if (CheckStatus == 0) dic["CheckStatus"] = "初始";
                if (CheckStatus == 1) dic["CheckStatus"] = "已验证和同步";

                dic.Remove("UserId");
                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>();
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客姓名");
            ReturnFields.Add("TradeMonth", "交易月");
            ReturnFields.Add("MerUserType", "商户创客类型");
            ReturnFields.Add("FluxProfitAmt", "流量分润总金额(元)");
            ReturnFields.Add("FluxTradeNum", "流量卡交易分佣笔数");
            ReturnFields.Add("CheckStatus", "同步账户状态");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "FluxProfitSummary", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
