/*
 * 分润补贴明细
 */

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 ProfitSubsidyDetailController : BaseController
    {
        public ProfitSubsidyDetailController(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(ProfitSubsidyDetail 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(ProfitSubsidyDetail data, string MerchantNo, string MerchantName, string MakerCode, string RealName, string TradeMonthSelect, string BrandIdSelect, string SubsidyTypeSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("BrandId", "1"); //品牌
            Fields.Add("MerNo", "2"); //渠道商户编号
            Fields.Add("SnNo", "2"); //渠道SN号

            string condition = " and Status>-1";
            //商户编号
            if (!string.IsNullOrEmpty(MerchantNo))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForCode where Code='" + MerchantNo + "')";
            }
            //商户名称
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForName where Name='" + MerchantName + "')";
            }
            //补贴创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and SubsidyUserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //补贴创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and SubsidyUserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //分润补贴类型
            if (!string.IsNullOrEmpty(SubsidyTypeSelect))
            {
                condition += " and SubsidyType=" + SubsidyTypeSelect;
            }
            if (!string.IsNullOrEmpty(TradeMonthSelect))
            {
                string[] datelist = TradeMonthSelect.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                condition += " and TradeMonth=" + start;
            }
            else
            {
                var start = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
                condition += " and TradeMonth>=" + start;
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ProfitSubsidyDetail", 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)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                int SubsidyUserId = int.Parse(dic["SubsidyUserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == SubsidyUserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo mer = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = mer.Name;
                int SubsidyType = int.Parse(dic["SubsidyType"].ToString());
                if (SubsidyType == 0) dic["SubsidyType"] = "直营商户交易分润补贴";
                if (SubsidyType == 1) dic["SubsidyType"] = "下级商户交易分润补贴";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string SubsidyProfit = "0.00";//分润补贴金额
            DataTable dt = OtherMySqlConn.dtable("select sum(SubsidyProfit) from ProfitSubsidyDetail where 1=1" + condition);
            if (dt.Rows.Count > 0)
            {
                SubsidyProfit = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            other.Add("SubsidyProfit", SubsidyProfit);
            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(ProfitSubsidyDetail data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("Remark", data.Remark); //备注

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


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

        #endregion

        #region 修改分润补贴明细

        /// <summary>
        /// 增加或修改分润补贴明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(ProfitSubsidyDetail data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("Remark", data.Remark); //备注

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

            return "success";
        }

        #endregion

        #region 删除分润补贴明细信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(ProfitSubsidyDetail data, string MerchantNo, string MerchantName, string MakerCode, string RealName, string TradeMonthSelect, string SubsidyTypeSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("BrandId", "1"); //品牌
            Fields.Add("MerNo", "2"); //渠道商户编号
            Fields.Add("SnNo", "2"); //渠道SN号

            string condition = " and Status>-1";
            //商户编号
            if (!string.IsNullOrEmpty(MerchantNo))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForCode where Code='" + MerchantNo + "')";
            }
            //商户名称
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForName where Name='" + MerchantName + "')";
            }
            //补贴创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and SubsidyUserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //补贴创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and SubsidyUserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //分润补贴类型
            if (!string.IsNullOrEmpty(SubsidyTypeSelect))
            {
                condition += " and SubsidyType=" + SubsidyTypeSelect;
            }
            //交易月份
            if (!string.IsNullOrEmpty(TradeMonthSelect))
            {
                condition += " and TradeMonth=" + TradeMonthSelect.Replace("-", "");
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ProfitSubsidyDetail", Fields, "Id desc", "0", 1, 20000, condition, "BrandId,MerchantId,MerNo,SnNo,MerRegTime,MerStandardDate,SubsidyUserId,SubsidyType,CreditTradeAmt,QrCreditTradeAmt,NonQrCreditTradeAmt,CreditProfitRate,SubsidyProfitRate,SubsidyProfit", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                int SubsidyUserId = int.Parse(dic["SubsidyUserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == SubsidyUserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo mer = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = mer.Name;
                int SubsidyType = int.Parse(dic["SubsidyType"].ToString());
                if (SubsidyType == 0) dic["SubsidyType"] = "直营商户交易分润补贴";
                if (SubsidyType == 1) dic["SubsidyType"] = "下级商户交易分润补贴";
                dic.Remove("SubsidyUserId");
                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("BrandId", "品牌");
            ReturnFields.Add("MerchantId", "商户");
            ReturnFields.Add("MerNo", "渠道商户编号");
            ReturnFields.Add("SnNo", "渠道SN号");
            ReturnFields.Add("MerRegTime", "渠道注册时间");
            ReturnFields.Add("MerStandardDate", "商户激活时间");
            ReturnFields.Add("SubsidyUserId", "补贴人");
            ReturnFields.Add("SubsidyType", "分润补贴类型");
            ReturnFields.Add("CreditTradeAmt", "商户贷记卡交易总金额");
            ReturnFields.Add("QrCreditTradeAmt", "商户(云闪付)贷记卡交易总金额");
            ReturnFields.Add("NonQrCreditTradeAmt", "商户(非云闪付)贷记卡交易总金额");
            ReturnFields.Add("CreditProfitRate", "(非云闪付)贷记卡交易分润比例");
            ReturnFields.Add("SubsidyProfitRate", "创客活动期内直营商户分润万分之十");
            ReturnFields.Add("SubsidyProfit", "商户(非云闪付)贷记卡交易分润补贴金额");

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

        #endregion

    }
}
