using System;
using System.Collections.Generic;
using System.Linq;
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.MainModels;
using LitJson;
using Library;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class UserAccountRecordController : BaseController
    {
        public UserAccountRecordController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 我的-常用工具-收支明细
        [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = ListDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        public List<Dictionary<string, object>> ListDo(string value, out Dictionary<string, object> Other)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            string TradeMonth = data["TradeMonth"].ToString(); //月份
            if (TradeMonth.Contains("-"))
            {
                string day = TradeMonth.Substring(TradeMonth.IndexOf("-") + 1);
                if (day.Length == 1)
                {
                    day = "0" + day;
                }
                TradeMonth = TradeMonth.Substring(0, TradeMonth.IndexOf("-")) + day;
            }
            string Kind = data["Kind"].ToString(); //类型
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            DateTime start = DateTime.Parse(TradeMonth.Substring(0, 4) + "-" + TradeMonth.Substring(4, 2) + "-01 00:00:00");
            DateTime end = start.AddMonths(1);
            IQueryable<UserAccountRecord> query = maindb.UserAccountRecord;
            List<int> ChangeTypes = new List<int>();
            if (Kind == "1")
            {
                ChangeTypes = PublicFunction.IncomeTypes();
            }
            else
            {
                ChangeTypes = PublicFunction.ExpendTypes();
            }
            query = query.Where(m => m.UserId == UserId && m.CreateDate >= start && m.CreateDate < end && ChangeTypes.Contains(m.ChangeType));
            query = query.OrderByDescending(m => m.Id);
            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>();
                curData.Add("ChangeType", subdata.ChangeType);
                curData.Add("ChangeAmount", subdata.ChangeAmount); //变更金额
                if (subdata.ProductType == 0)
                {
                    string Note = RelationClass.GetChangeTypeInfo(subdata.ChangeType);
                    if (subdata.ChangeType == 20 || subdata.ChangeType == 31 || subdata.ChangeType == 63 || subdata.ChangeType == 64 || subdata.ChangeType == 65 || subdata.ChangeType == 66 || subdata.ChangeType == 114 || subdata.ChangeType == 115)
                    {
                        Note += "\n" + subdata.Remark;
                    }
                    curData.Add("Remark", Note); //账户变动明细备注信息
                }
                else if (subdata.ProductType == 101)
                {
                    string Note = "助利宝(交易分润)\n" + subdata.Remark;
                    curData.Add("Remark", Note); //账户变动明细备注信息
                }
                else
                {
                    string Note = RelationClass.GetKqProductBrandInfo(subdata.ProductType) + "(" + RelationClass.GetChangeTypeInfo(subdata.ChangeType) + ")";
                    if (subdata.ChangeType == 1)
                    {
                        Note += "\n" + subdata.Remark;
                    }
                    curData.Add("Remark", Note); //账户变动明细备注信息
                }
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                dataList.Add(curData);
            }
            Other = new Dictionary<string, object>();
            Other.Add("Income", UserAccountDbconn.Instance.GetIncome(UserId, TradeMonth));
            Other.Add("Expend", UserAccountDbconn.Instance.GetExpend(UserId, TradeMonth));
            return dataList;
        }
        #endregion


        #region 收支明细盟主贮蓄金记录
        [Authorize]
        public JsonResult Lists(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ListsDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListsDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            string Kind = data["Kind"].ToString(); //类型
            int PageSize = int.Parse(function.CheckInt(data["PageSize"].ToString()));
            int PageNum = int.Parse(function.CheckInt(data["PageNum"].ToString()));
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            IQueryable<UserAccountRecord> query = maindb.UserAccountRecord;
            List<int> ChangeTypes = new List<int>();
            if (Kind == "1")
            {
                ChangeTypes = PublicFunction.IncomeTypes();
            }
            else
            {
                ChangeTypes = PublicFunction.ExpendTypes();
            }
            query = query.Where(m => m.UserId == UserId && ChangeTypes.Contains(m.ChangeType)).OrderByDescending(m => m.CreateDate);            
            query = query.OrderByDescending(m => m.Id);
            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>();
                curData.Add("ChangeType", subdata.ChangeType);
                curData.Add("ChangeAmount", subdata.ChangeAmount); //变更金额
                if (subdata.ProductType == 0)
                {
                    string Note = RelationClass.GetChangeTypeInfo(subdata.ChangeType);
                    if (subdata.ChangeType == 20 || subdata.ChangeType == 31 || subdata.ChangeType == 63 || subdata.ChangeType == 64 || subdata.ChangeType == 114 || subdata.ChangeType == 115)
                    {
                        Note += "\n" + subdata.Remark;
                    }
                    curData.Add("Remark", Note); //账户变动明细备注信息
                }
                else
                {
                    string Note = RelationClass.GetKqProductBrandInfo(subdata.ProductType) + "(" + RelationClass.GetChangeTypeInfo(subdata.ChangeType) + ")";
                    if (subdata.ChangeType == 1)
                    {
                        Note += "\n" + subdata.Remark;
                    }
                    curData.Add("Remark", Note); //账户变动明细备注信息
                }
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                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

    }
}
