using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Authorization;
using System.Web;
using MySystem.Models.Main;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1.pos
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class ActiveRewardController : BaseController
    {
        public ActiveRewardController(IHttpContextAccessor accessor) : base(accessor)
        {
            OtherMySqlConn.connstr = Library.ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        }

        #region 首页-客小爽产品-收益查看-达标奖励
        // [Authorize]
        public JsonResult StatList(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = StatListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> StatListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString())); //创客
            string TradeMonth = data.getItem("TradeMonth").ToString();
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("PageNum").ToString()));
            int Kind = int.Parse(function.CheckInt(data.getItem("Kind").ToString()));
            string Date = Kind == 1 ? "%Y%m%d" : "%Y%m";
            string TradeMonthCondi = "";
            if (Kind == 2)
            {
                string StartTradeMonth = TradeMonth + "-01 00:00:00";
                string EndTradeMonth = DateTime.Parse(StartTradeMonth).AddMonths(1).ToString("yyyy-MM-dd HH:mm:ss");
                TradeMonthCondi = " and CreateDate>='" + StartTradeMonth + "' and CreateDate>='" + EndTradeMonth + "'";
            }
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            string PageCondition = PageSize.ToString();
            if (PageNum > 1)
            {
                int skipNum = PageSize * (PageNum - 1);
                PageCondition = skipNum + "," + PageSize;
            }
            DataTable dt = CustomerSqlConn.dtable("select DATE_FORMAT(CreateDate,'" + Date + "'),sum(RewardAmount) from ActiveReward where UserId=" + UserId + TradeMonthCondi + " group by DATE_FORMAT(CreateDate,'" + Date + "') order by DATE_FORMAT(CreateDate,'" + Date + "') desc limit " + PageCondition, AppConfig.Base.SqlConnStr);
            foreach (DataRow dr in dt.Rows)
            {
                string subdata = dr[0].ToString();
                decimal RewardAmount = decimal.Parse(dr[1].ToString());
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("RewardAmount", RewardAmount); //奖励金额
                if (Kind == 1)
                {
                    curData.Add("ActDate", subdata.Substring(0, 4) + "年" + subdata.Substring(4, 2) + "月" + subdata.Substring(6, 2) + "日"); //激活时间
                }
                else
                {
                    curData.Add("ActDate", subdata.Substring(0, 4) + "年" + subdata.Substring(4, 2) + "月"); //激活时间
                }
                curData.Add("ActDateValue", subdata); //激活时间值
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion


        #region 首页-客小爽产品-收益查看-达标奖励-明细
        // [Authorize]
        public JsonResult StatDetail(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = StatDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> StatDetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString())); //创客
            string ActDate = data.getItem("ActDate").ToString(); //激活时间
            int PageSize = int.Parse(function.CheckInt(data.getItem("PageSize").ToString()));
            int PageNum = int.Parse(function.CheckInt(data.getItem("PageNum").ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            DateTime start = DateTime.Parse(ActDate + " 00:00:00");
            DateTime end = DateTime.Parse(ActDate + " 23:59:59");
            IQueryable<ActiveReward> query = maindb.ActiveReward.Where(m => m.UserId == UserId && m.CreateDate >= start && m.CreateDate <= end);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (var subdata in query.ToList())
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                PosMerchantInfo merchant = PosMerchantInfoDbconn.Instance.Get(subdata.MerchantId) ?? new PosMerchantInfo();
                curData.Add("SnNo", subdata.KqSnNo);
                curData.Add("MerchantName", merchant.MerchantName); //商户名称
                curData.Add("RewardAmount", subdata.RewardAmount); //奖励金额
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 检查签名是否合法，合法返回1，不合法返回提示信息

        /// <summary>
        /// 检查签名是否合法，合法返回1，不合法返回提示信息
        /// </summary>
        /// <param name="value">请求的参数(json字符串)</param>
        /// <param name="signField">要签名的字段</param>
        /// <returns></returns>
        private string CheckSign(string value, string[] signField)
        {
            JsonData json = JsonMapper.ToObject(value);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < signField.Length; i++)
            {
                dic.Add(signField[i], json[signField[i]].ToString());
            }
            string sign = json["sign"].ToString(); //客户端签名字符串
            return new Sign().sign(dic, sign);
        }

        #endregion

    }
}
