/*
 * 流量分佣明细
 */

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

            List<KqProducts> Brands = db.KqProducts.OrderBy(m => m.Id).ToList();
            ViewBag.Brands = Brands;

            return View();
        }

        #endregion

        #region 根据条件查询流量分佣明细列表

        /// <summary>
        /// 流量分佣明细列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(FluxProfitDetail data, string MakerCode, string RealName, string TopMakerCode, string TopRealName, string CreateDateData, string MerUserTypeSelect, string ProfitTypeSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("MerNo", "1"); //渠道商户编号
            Fields.Add("SnNo", "1"); //渠道SN号
            Fields.Add("BrandId", "1"); //渠道SN号
            Fields.Add("FluxOrderNo", "1"); //流量扣费单号
            Fields.Add("TradeOrderNo", "1"); //交易流水号

            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 (data.BrandId > 0)
            { 
                condition += " and BrandId=" + data.BrandId;
            }
            //顶级创客编号
            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(MerUserTypeSelect))
            {
                condition += " and MerUserType=" + MerUserTypeSelect;
            }
            //分润类型
            if (!string.IsNullOrEmpty(ProfitTypeSelect))
            {
                condition += " and ProfitType=" + ProfitTypeSelect;
            }
            //交易时间
            if(!string.IsNullOrEmpty(CreateDateData))
            {
               string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0].Replace("-", "");
                string end = datelist[1].Replace("-", "");
                condition += " and TradeDate >= '" + start + "' and TradeDate <= '" + end + "' ";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("FluxProfitDetail", 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 BrandId = int.Parse(dic["BrandId"].ToString());
                dic["BrandName"] = RelationClass.GetKqProductBrandInfo(BrandId);

                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantMobile"] = merchant.Mobile;

                int MerUserType = int.Parse(dic["MerUserType"].ToString());
                if (MerUserType == 0) dic["MerUserType"] = "非商户型创客";
                if (MerUserType == 1) dic["MerUserType"] = "商户型创客";
                
                int ProfitType = int.Parse(dic["ProfitType"].ToString());
                if (ProfitType == 0) dic["ProfitType"] = "直属分佣";
                if (ProfitType == 1) dic["ProfitType"] = "顶级交易分润";
                if (ProfitType == 2) dic["ProfitType"] = "上级交易分佣";

            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string ProfitAmt = "0.00";//分佣总金额
            DataTable dt = OtherMySqlConn.dtable("select sum(FluxProfitAmt) from FluxProfitDetail where 1=1" + condition);
            if(dt.Rows.Count > 0)
            {
                ProfitAmt = dt.Rows[0][0].ToString();
            }
            other.Add("ProfitAmt", ProfitAmt);
            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(FluxProfitDetail 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("FluxProfitDetail", Fields, 0);
            AddSysLog(data.Id.ToString(), "FluxProfitDetail", "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;


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

        #endregion

        #region 修改流量分佣明细

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

            return "success";
        }

        #endregion

        #region 删除流量分佣明细信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(FluxProfitDetail data, string MakerCode, string RealName, string TopMakerCode, string TopRealName, string MerUserTypeSelect, string ProfitTypeSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("TradeDate", "2"); //交易日期
            Fields.Add("MerNo", "2"); //渠道商户编号
            Fields.Add("SnNo", "2"); //渠道SN号
            Fields.Add("ProfitType", "1"); //分润类型
            Fields.Add("FluxOrderNo", "2"); //流量扣费单号
            Fields.Add("TradeOrderNo", "2"); //交易流水号

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("FluxProfitDetail", Fields, "Id desc", "0", 1, 20000, "", "TradeDate,UserId,TopUserId,MerchantId,MerNo,SnNo,ProfitType,FluxOrderNo,TradeOrderNo,TradeAmt,FluxFeeAmt,FluxStartDate,FluxEndDate,FluxProfitAmt,MerUserType", 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 MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantMobile"] = merchant.Mobile;

                int MerUserType = int.Parse(dic["MerUserType"].ToString());
                if (MerUserType == 0) dic["MerUserType"] = "非商户型创客";
                if (MerUserType == 1) dic["MerUserType"] = "商户型创客";
                
                int ProfitType = int.Parse(dic["ProfitType"].ToString());
                if (ProfitType == 0) dic["ProfitType"] = "直属分佣";
                if (ProfitType == 1) dic["ProfitType"] = "顶级交易分润";
                if (ProfitType == 2) dic["ProfitType"] = "上级交易分佣";

                dic.Remove("UserId");
                dic.Remove("TopUserId");
                dic.Remove("MerchantId");
            }

            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("TradeDate", "交易日期");
            ReturnFields.Add("MerUserType", "商户创客类型");
            ReturnFields.Add("MerchantMobile", "商户手机号");
            ReturnFields.Add("MerNo", "快钱商户编号");
            ReturnFields.Add("SnNo", "快钱SN号");
            ReturnFields.Add("ProfitType", "分润类型");
            ReturnFields.Add("FluxOrderNo", "流量扣费单号");
            ReturnFields.Add("TradeOrderNo", "交易流水号");
            ReturnFields.Add("TradeAmt", "商户交易额元)'");
            ReturnFields.Add("FluxFeeAmt", "流量费元)'");
            ReturnFields.Add("FluxProfitAmt", "流量分润总金额元)'");
            ReturnFields.Add("FluxStartDate", "流量扣费开始日期");
            ReturnFields.Add("FluxEndDate", "流量扣费结束日期");

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

        #endregion

    }
}
