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 UserAccountController : BaseController
    {
        public UserAccountController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #region 创客-我的-账户信息
        [Authorize]
        public JsonResult MyAccount(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyAccountDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyAccountDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserAccount query = UserAccountDbconn.Instance.Get(UserId) ?? new UserAccount();
            Obj.Add("TotalAmount", query.TotalAmount); //总金额
            Obj.Add("BalanceAmount", query.BalanceAmount); //余额
            Obj.Add("ToChargeAmount", query.ToChargeAmount); //预扣款额度
            Obj.Add("WithdrawAmount", query.WithdrawAmount); //已提现金额
            Obj.Add("LeaderReserve", query.LeaderReserve); //盟主储蓄金
            Obj.Add("WithdrawFlag", query.QueryCount); //提现标记，1-已提现，0-未提现
            Obj.Add("SmallStoreDeposit", query.SmallStoreDeposit); //小分仓押金
            return Obj;
        }
        #endregion



        #region 创客-首页-统计数据
        [Authorize]
        public JsonResult MyStatData(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyStatDataDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyStatDataDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int Id = int.Parse(function.CheckInt(data["Id"].ToString()));
            string TradeMonth = DateTime.Now.ToString("yyyyMM"); //交易月
            // Obj.Add("TotalProfit", UserTradeDaySummaryDbconn.Instance.GetMonthTrade(UserId, TradeMonth, "team")); //总收益
            // Obj.Add("TeamTradeAmount", UserTradeDaySummaryDbconn.Instance.GetMonthTrade(UserId, TradeMonth, "team")); //团队交易额
            // Obj.Add("MerchantCount", UsersDbconn.Instance.GetTeamNewUserCount(UserId, TradeMonth)); //新增创客
            // Obj.Add("TeamMemberCount", UserDataDbconn.Instance.GetPosActCount(UserId, TradeMonth)); //累计激活POS机商户
            return Obj;
        }
        #endregion





        #region 创客-首页-仓库管理-申请机具-我的额度
        [Authorize]
        public JsonResult MyAmount(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = MyAmountDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> MyAmountDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            List<Dictionary<string, object>> listStoreHouse = new List<Dictionary<string, object>>();
            UserAccount query = maindb.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new UserAccount();
            var check = maindb.StoreHouseAmountPromiss.Any(m => m.ToUserId == UserId);
            decimal amount = 0;
            if (check)
            {
                amount = maindb.StoreHouseAmountPromiss.Where(m => m.Status == 1 && m.ToUserId == UserId).Sum(m => m.PromissAmount);
            }

            Obj.Add("Amount", query.ValidAmount); //可用总额度
            Obj.Add("TotalAmount", query.FixedAmount + query.TempAmount + query.TempAmountForBalance); //总额度
            Obj.Add("FixedAmount", query.FixedAmount); //固定额度
            Obj.Add("TempAmount", query.TempAmount + query.TempAmountForBalance); //临时额度
            Obj.Add("LeaderBalanceAmount", amount); //保证金额度
            var a = query.ValidAmount - amount;
            if (query.ValidAmount - amount >= query.TempAmount + query.TempAmountForBalance)
            {
                Obj.Add("OkTempAmount", query.TempAmount + query.TempAmountForBalance); //可用临时额度(可调低总临时额度金额)
                Obj.Add("cardLeast", query.TempAmount); //可用真实充值临时额度
                Obj.Add("balanceLeast", query.TempAmountForBalance); //可用余额充值临时额度
            }
            else if (query.ValidAmount - amount <= 0)
            {
                Obj.Add("OkTempAmount", 0); //可用临时额度(可调总低临时额度金额)
                Obj.Add("cardLeast", 0); //可用真实充值临时额度
                Obj.Add("balanceLeast", 0); //可用余额充值临时额度
            }
            else if (0 < query.ValidAmount - amount && query.ValidAmount - amount < query.TempAmount + query.TempAmountForBalance)
            {
                Obj.Add("OkTempAmount", query.ValidAmount - amount); //可用临时额度(可调低总临时额度金额)
                if (query.ValidAmount - amount <= query.TempAmount)
                {
                    Obj.Add("cardLeast", query.ValidAmount - amount); //可用真实充值临时额度
                }
                if (query.ValidAmount - amount > query.TempAmount)
                {
                    Obj.Add("cardLeast", query.TempAmount); //可用真实充值临时额度
                }
                if ( query.ValidAmount - amount <= query.TempAmountForBalance)
                {
                    Obj.Add("balanceLeast", query.ValidAmount - amount); //可用余额充值临时额度
                }
                if ( query.ValidAmount - amount > query.TempAmountForBalance)
                {
                    Obj.Add("balanceLeast", query.TempAmountForBalance); //可用余额充值临时额度
                }
            }
            return Obj;
        }
        #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

    }
}