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 UserCardRecordController : BaseController
    {
        public UserCardRecordController(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);
            List<Dictionary<string, object>> dataList = ListDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            string SearchKey = data["SearchKey"].ToString(); //查询关键词
            string Sort = data["Sort"].ToString(); //排序，0-默认，1-最近消费降序，2-最近加入会员降序，3-累计消费次数降序，4-累计消费金额降序，5-近7日消费金额降序
            ulong CardFlag = ulong.Parse(function.CheckInt(data["CardFlag"].ToString()));
            int ConsumerFlag = int.Parse(function.CheckInt(data["ConsumerFlag"].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>>();
            string condition = "";
            if (!string.IsNullOrEmpty(data["SearchKey"].ToString()))
            {
                condition += " and NickName like '%" + SearchKey + "%'";
            }
            if (!string.IsNullOrEmpty(data["CardFlag"].ToString()))
            {
                condition += " and CardFlag=" + CardFlag;
            }
            if (!string.IsNullOrEmpty(data["ConsumerFlag"].ToString()))
            {
                string check = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd") + "00:00:00";
                if (ConsumerFlag == 1)
                {
                    condition += " and LastConsumDate>='" + check + "'";
                }
                else if (ConsumerFlag == 0)
                { 
                    condition += " and LastConsumDate<'" + check + "'";
                }
            }
            string OrderBy = "Id desc";
            if (!string.IsNullOrEmpty(data["Sort"].ToString()))
            {
                if (Sort == "1")
                {
                    OrderBy = "LastConsumDate desc";
                }
                else if (Sort == "2")
                {
                    OrderBy = "Id desc";
                }
                else if (Sort == "3")
                {
                    OrderBy = "TotalConsumCount desc";
                }
                else if (Sort == "4")
                {
                    OrderBy = "TotalAmount desc";
                }
            }
            else
            { 
                OrderBy = "Id desc";
            }
            List<Dictionary<string, object>> query = new ConsumersService().List(new List<FieldItem>() , condition, PageNum, PageSize, OrderBy);
            foreach (var ConsumersData in query)
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("ConsumerId", RelationClass.GetConsumersInfo(int.Parse(ConsumersData["Id"].ToString()))); //消费者
                Dictionary<string, object> Consumer = new Dictionary<string, object>();
                Consumer.Add("NickName", ConsumersData["NickName"].ToString()); //昵称
                Consumer.Add("HeadPhoto", ConsumersData["HeadPhoto"].ToString()); //头像
                Consumer.Add("CurIntgegral", ConsumersData["CurIntgegral"].ToString()); //当前积分
                Consumer.Add("TotalAmount", ConsumersData["TotalAmount"].ToString()); //累计消费金额
                Consumer.Add("TotalConsumCount", ConsumersData["TotalConsumCount"].ToString()); //累计消费次数
                Consumer.Add("LastConsumDate", ConsumersData["LastConsumDate"].ToString()); //最近消费时间
                curData.Add("Consumer", Consumer);

                curData.Add("CreateDate", ConsumersData["CreateDate"].ToString()); //CreateDate
                int ConsumeCount = 0;
                for (int i = 0; i < 7; i++)
                {
                    string Date = DateTime.Now.AddDays(-i).ToString("yyyyMMdd");
                }
                curData.Add("ConsumeCount", ConsumeCount); //近7日消费次数
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion



        #region 消费者-发放会员卡
        [Authorize]
        public JsonResult Add(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = AddDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson AddDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int ConsumerId = int.Parse(function.CheckInt(data["ConsumerId"].ToString())); //消费者
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            UserCardForWeChat card = new UserCardForWeChatService().Query(MerchantId);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            UserCardRecord query = new UserCardRecord()
            {
                CreateDate = DateTime.Now, //创建时间
                UpdateDate = DateTime.Now, //修改时间
                ConsumerId = ConsumerId, //消费者
                MerchantId = MerchantId, //商户
                CardId = card.Id, 
            };
            return new AppResultJson() { Status = "1", Info = "", Data = Obj };
        }
        #endregion


        #region 消费者-获取会员卡
        [Authorize]
        public JsonResult GetCardList(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = GetCardListDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson GetCardListDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int MerchantId = int.Parse(function.CheckInt(data["MerchantId"].ToString())); //商户
            UserCardForWeChat card = new UserCardForWeChatService().Query(MerchantId);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            Dictionary<string, object> cardExt = new WeChatFunction(_accessor.HttpContext).GetUserCard(MerchantId);
            Obj.Add("CardId", card.Id);
            Obj.Add("CardExt", cardExt);
            return new AppResultJson() { Status = "1", Info = "", Data = 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

    }
}
