using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.IO;
using System.Collections.Generic;
using LitJson;
using Library;
using System.Linq;
using System;
using MySystem.MainModels;
using System.Data;

namespace MySystem.Areas.Api.Controllers.v1
{
    public class RadioCardController : BaseController
    {
        public RadioCardController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }

        //测试
        // string apiKey = "12345678";

        //生产
        string apiKey = "n^ZbEjK%";

        #region 广电卡获取机构用户信息
        [HttpPost]
        [Route("/kxs/gdk/getuserinfo")]
        public Dictionary<string, object> GetUserInfo()
        {
            StreamReader sr = new StreamReader(Request.Body);
            string requestMes = sr.ReadToEnd();
            function.WriteLog(DateTime.Now.ToString() + ":" + requestMes, "广电卡获取机构用户信息");
            JsonData req = JsonMapper.ToObject(requestMes);
            string sign = req["sign"].ToString(); //接口签名
            string brhUserId = req["brhUserId"].ToString(); //机构用户编码

            string month = DateTime.Now.AddMonths(-1).ToString("yyyyMM");
            int UserId = int.Parse(function.CheckInt(dbconn.DesDecrypt(brhUserId, apiKey)));
            Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            Dictionary<string, object> obj = new Dictionary<string, object>();
            Dictionary<string, object> data = new Dictionary<string, object>();
            if(user.AuthFlag == 0)
            {
                obj.Add("resultCode", 0);
                obj.Add("errorCode", 40000);
                obj.Add("errorDesc", "用户暂未认证");
                obj.Add("data", data);
                return obj;
            }
            string timestamp = req["timestamp"].ToString(); //时间戳，精确到秒。签名用参数
            obj.Add("resultCode", 1);
            data.Add("name",user.RealName); //用户姓名
            data.Add("brhMobile",user.Mobile); //机构用户手机号
            data.Add("gender",int.Parse(function.CheckInt(user.CertId.Substring(16, 1))) % 2 == 0 ? "1" : "0"); //性别：0 男，1 女
            data.Add("idcardNo",user.CertId); //用户身份证号
            data.Add("brhUserRegTime",user.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //机构用户注册时间
            decimal SimTradeAmount = maindb.SimCardDaySummary.Where(m => m.UserId == UserId && m.SeoTitle == "team" && m.TradeMonth == month).Sum(m => m.TradeAmount);
            decimal SimTradeAmountResult = SimTradeAmount * 100;
            data.Add("paymentPerformance",SimTradeAmountResult.ToString("f0")); //用户上月业绩，单位:分
            int Percent = function.get_Random(1, 35);
            decimal SimProfit = SimTradeAmount * Percent;
            data.Add("paymentIncome",SimProfit.ToString("f0")); //用户上月分润收入，单位:分
            obj.Add("data", data);
            return obj;
        }
        #endregion

        #region 预扣款-添加预扣款
        [Route("/v1/kxsmain/tochargebackrecord/addtochargebackrecord")]
        public JsonResult AddToChargeBackRecord(string value)
        {
            // value = DesDecrypt(value);
            function.WriteLog(DateTime.Now.ToString() + "\n" + value + "\n\n", "预扣款-添加预扣款");
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = AddToChargeBackRecordDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson AddToChargeBackRecordDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string PosSn = data["PosSn"].ToString(); //机具SN
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            var pos = maindb.PosMachinesTwo.FirstOrDefault(m => m.PosSn == PosSn && m.Status > -1) ?? new PosMachinesTwo();
            if (pos.Id > 0)
            {
                bool check = maindb.ToChargeBackRecord.Any(m => m.Field1 == PosSn && m.ChargeType == 124);
                if(!check)
                {
                    var brand = maindb.KqProducts.FirstOrDefault(m => m.Id == pos.BrandId) ?? new KqProducts();
                    var amount = 0.00M;
                    if (brand.Kind == 1) amount = 200;
                    if (brand.Kind == 2) amount = 300;
                    var ToChargeBackRecord = maindb.ToChargeBackRecord.Add(new ToChargeBackRecord
                    {
                        CreateDate = DateTime.Now,
                        SeoTitle = SysUserName + "_" + SysRealName,
                        SeoDescription = "循环过期(" + PosSn + ")",
                        Remark = "循环过期(" + PosSn + ")",
                        Field1 = PosSn,
                        ChargeType = 124,
                        Kind = 0,
                        ChargeAmount = amount,
                        UserId = pos.BuyUserId,
                    }).Entity;
                    UserAccount account = maindb.UserAccount.FirstOrDefault(m => m.Id == pos.BuyUserId);
                    if(account != null)
                    {
                        account.ToChargeAmount += amount;
                    }
                    maindb.SaveChanges();
                }
                return new AppResultJson() { Status = "1", Info = "成功", Data = Obj };
            }
            else
            {
                return new AppResultJson() { Status = "-1", Info = "机具不存在", Data = Obj };
            }
        }
        #endregion

        #region 团队开机统计
        [Route("/v1/kxsmain/users/getteamopenposinfo")] // 团队开机统计
        public JsonResult GetTeamOpenPosInfo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString()));
            string StartTime = data["StartTime"].ToString(); //开始时间
            string EndTime = data["EndTime"].ToString(); //结束时间
            var SelfPosMerchantCount = 0; // 个人POS机激活商户
            var TeamPosMerchantCount = 0; // 团队POS机激活商户
            var SelfSimMerchantCount = 0; // 个人广电卡激活商户
            var TeamSimMerchantCount = 0; // 团队广电卡激活商户
            var SelfMpMerchantCount = 0; // 个人来客吧激活商户
            var TeamMpMerchantCount = 0; // 团队来客吧激活商户
            var SelfMpMerchantCount1 = 0; // 个人来客吧激活商户(直连)
            var TeamMpMerchantCount1 = 0; // 团队来客吧激活商户(直连)
            var SelfMpMerchantCount2 = 0; // 个人来客吧激活商户(银联)
            var TeamMpMerchantCount2 = 0; // 团队来客吧激活商户(银联)

            Dictionary<string, object> Obj = new Dictionary<string, object>();
            DataTable dt = CustomerSqlConn.dtable("SELECT a.teamPosAct,a.selfPosAct,b.teamSimAct,b.selfSimAct FROM(SELECT UserId,SUM(IF(SeoTitle='team',ActiveBuddyMerStatus,0)) teamPosAct,SUM(IF(SeoTitle='self',ActiveBuddyMerStatus,0)) selfPosAct from UserTradeMonthSummary WHERE BrandId!=14 AND UserId=" + UserId + " AND SeoKeyword>=" + StartTime + " AND SeoKeyword<=" + EndTime + ")a LEFT JOIN(SELECT UserId,SUM(IF(SeoTitle='team',ActiveBuddyMerStatus,0)) teamSimAct,SUM(IF(SeoTitle='self',ActiveBuddyMerStatus,0)) selfSimAct from UserTradeMonthSummary WHERE BrandId=14 AND UserId=" + UserId + " AND SeoKeyword>=" + StartTime + " AND SeoKeyword<=" + EndTime + ")b ON a.UserId=b.UserId;", AppConfig.Base.ReadSqlConn);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    SelfPosMerchantCount = int.Parse(function.CheckNum(dr["selfPosAct"].ToString()));
                    TeamPosMerchantCount = int.Parse(function.CheckNum(dr["teamPosAct"].ToString()));
                    SelfSimMerchantCount = int.Parse(function.CheckNum(dr["selfSimAct"].ToString()));
                    TeamSimMerchantCount = int.Parse(function.CheckNum(dr["teamSimAct"].ToString()));
                }
            }

            dt = CustomerSqlConn.dtable("SELECT SUM(IF(SeoTitle='team',ActiveBuddyMerStatus,0)) teamAct,SUM(IF(SeoTitle='self',ActiveBuddyMerStatus,0)) selfAct from UserTradeMonthSummary WHERE UserId=" + UserId + " AND SeoKeyword>=" + StartTime + " AND SeoKeyword<=" + EndTime + ";", AppConfig.Base.MpSqlConn);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    SelfMpMerchantCount1 = int.Parse(function.CheckNum(dr["selfAct"].ToString()));
                    TeamMpMerchantCount1 = int.Parse(function.CheckNum(dr["teamAct"].ToString()));
                }
            }

            dt = CustomerSqlConn.dtable("SELECT SUM(IF(SeoTitle='team',ActiveBuddyMerStatus,0)) teamAct,SUM(IF(SeoTitle='self',ActiveBuddyMerStatus,0)) selfAct from UserTradeMonthSummary WHERE UserId=" + UserId + " AND SeoKeyword>=" + StartTime + " AND SeoKeyword<=" + EndTime + ";", AppConfig.Base.MpSqlConn2);
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    SelfMpMerchantCount2 = int.Parse(function.CheckNum(dr["selfAct"].ToString()));
                    TeamMpMerchantCount2 = int.Parse(function.CheckNum(dr["teamAct"].ToString()));
                }
            }
            SelfMpMerchantCount = SelfMpMerchantCount1 + SelfMpMerchantCount2;
            TeamMpMerchantCount = TeamMpMerchantCount1 + TeamMpMerchantCount;

            Obj.Add("SelfPosMerchantCount", SelfPosMerchantCount); // 个人POS机激活商户
            Obj.Add("TeamPosMerchantCount", TeamPosMerchantCount); // 团队POS机激活商户
            Obj.Add("SelfSimMerchantCount", SelfSimMerchantCount); // 个人广电卡激活商户
            Obj.Add("TeamSimMerchantCount", TeamSimMerchantCount); // 团队广电卡激活商户
            Obj.Add("SelfMpMerchantCount", SelfMpMerchantCount); // 个人来客吧激活商户
            Obj.Add("TeamMpMerchantCount", TeamMpMerchantCount); // 团队来客吧激活商户

            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion

        #region 首页-股东大盘分红交易统计
        [Route("/Api/v1/UserTradeDaySummary/GetUserTradeAmout")]
        public JsonResult GetUserTradeAmout(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            string TradeMonthOrDate = data["TradeMonthOrDate"].ToString(); //月份或日期(yyyyMM yyyyMMdd)
            string Kind = data["Kind"].ToString(); //类别(个人 self 团队 team)
            if (string.IsNullOrEmpty(data["UserId"].ToString()))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "创客Id为空" });
            }
            if (string.IsNullOrEmpty(data["TradeMonthOrDate"].ToString()))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "月份或日期为空" });
            }
            if (string.IsNullOrEmpty(data["Kind"].ToString()))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "类别为空" });
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();

            Obj = GetUserTradeAmoutWd(UserId, TradeMonthOrDate, Kind);

            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        #endregion

        #region 获取创客稳定交易额
        /// <summary>
        /// 获取创客稳定交易额
        /// </summary>
        /// <param name="UserId">创客Id</param>
        /// <param name="Kind">类型(个人 self 团队 team)</param>
        /// <param name="TradeMonthOrDate">月份或日期(yyyyMM yyyyMMdd)</param>
        public static Dictionary<string, object> GetUserTradeAmoutWd(int UserId, string TradeMonthOrDate, string Kind)
        {
            using (WebCMSEntities maindb = new WebCMSEntities())
            {
                Dictionary<string, object> Obj = new Dictionary<string, object>();

                //POS机
                var TotalAmtwd = 0M; //刷卡交易总额(稳定期)
                var TotalAmtwdA = 0M; //刷卡交易总额(稳定期A)
                var TotalAmtwdB = 0M; //刷卡交易总额(稳定期B)
                var TotalPosAmt = 0M; //POS总交易额

                //来客吧码牌
                var MpAmtwd = 0M; //来客吧码牌交易总额

                //广电卡
                var SimAmtwd = 0M; //广电卡活动交易总额

                //POS机
                List<TradeDaySummary> query = new List<TradeDaySummary>();
                if (TradeMonthOrDate.Length == 6)
                {
                    bool check = maindb.TradeDaySummary.Any(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeMonth == TradeMonthOrDate);
                    if (check)
                    {
                        query = maindb.TradeDaySummary.Where(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeMonth == TradeMonthOrDate).ToList();
                    }
                }
                else if (TradeMonthOrDate.Length == 8)
                {
                    bool check = maindb.TradeDaySummary.Any(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeDate == TradeMonthOrDate);
                    if (check)
                    {
                        query = maindb.TradeDaySummary.Where(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeDate == TradeMonthOrDate).ToList();
                    }
                }

                List<TradeDaySummary2> query2 = new List<TradeDaySummary2>();
                if (TradeMonthOrDate.Length == 6)
                {
                    bool check = maindb.TradeDaySummary2.Any(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeMonth == TradeMonthOrDate);
                    if (check)
                    {
                        query2 = maindb.TradeDaySummary2.Where(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeMonth == TradeMonthOrDate).ToList();
                    }
                }
                else if (TradeMonthOrDate.Length == 8)
                {
                    bool check = maindb.TradeDaySummary2.Any(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeDate == TradeMonthOrDate);
                    if (check)
                    {
                        query2 = maindb.TradeDaySummary2.Where(m => m.SeoTitle == Kind && m.UserId == UserId && m.TradeDate == TradeMonthOrDate).ToList();
                    }
                }

                if (query.Count > 0)
                {
                    // //扶持期
                    // if (Kind == "team")
                    // {
                    //     TotalAmtfc = query.Sum(m => m.HelpNonDirectTradeAmt + m.HelpNonDirectDebitTradeAmt);
                    // }
                    // else
                    // {
                    //     TotalAmtfc = query.Sum(m => m.HelpDirectTradeAmt + m.HelpDirectDebitTradeAmt);
                    // }
                    //稳定期
                    if (Kind == "team")
                    {
                        TotalAmtwd = query.Sum(m => m.NotHelpNonDirectTradeAmt + m.NotHelpNonDirectDebitTradeAmt);
                    }
                    else
                    {
                        TotalAmtwd = query.Sum(m => m.NotHelpDirectTradeAmt + m.NotHelpDirectDebitTradeAmt);
                    }
                    //稳定期A
                    if (Kind == "team")
                    {
                        TotalAmtwdA = query.Sum(m => m.ProfitNonDirectTradeAmt + m.ProfitNonDirectDebitTradeAmt);
                    }
                    else
                    {
                        TotalAmtwdA = query.Sum(m => m.ProfitDirectTradeAmt + m.ProfitDirectDebitTradeAmt);
                    }
                }
                if (query2.Count > 0)
                {
                    //稳定期B
                    TotalAmtwdB = query2.Sum(m => m.ProfitTradeAmt + m.ProfitDebitTradeAmt);
                }

                TotalPosAmt = TotalAmtwd + TotalAmtwdA + TotalAmtwdB;

                //来客吧码牌
                decimal MpActTradeAmount = MpStatDbconn.Instance.GetTrade(UserId, TradeMonthOrDate, 1, "team");
                decimal MpUnActTradeAmount = MpStatDbconn.Instance.GetTrade(UserId, TradeMonthOrDate, 0, "team");

                MpAmtwd = MpActTradeAmount + MpUnActTradeAmount;

                //广电卡
                var SimActCount = UserDataDbconn.Instance.GetTeamBrandPosActCount(UserId, 14, TradeMonthOrDate);
                SimAmtwd = SimActCount * 10000M;

                // Obj.Add("TotalAmtwd", TotalAmtwd); //刷卡交易总额(稳定期)
                // Obj.Add("TotalAmtwdA", TotalAmtwdA); //刷卡交易总额(稳定期A)
                // Obj.Add("TotalAmtwdB", TotalAmtwdB); //刷卡交易总额(稳定期B)

                Obj.Add("TotalPosAmt", TotalPosAmt); //POS总交易额

                Obj.Add("MpAmtwd", MpAmtwd); //来客吧码牌交易总额

                Obj.Add("SimAmtwd", SimAmtwd); //广电卡活动交易总额

                return Obj;
            }
        }

        #endregion
    }
}
