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 PosCouponOrdersController : BaseController
    {
        public PosCouponOrdersController(IHttpContextAccessor accessor) : base(accessor)
        {
        }




        #region 创客-首页-客小爽产品-码牌管理-划拨记录
        // [Authorize]
        public JsonResult List(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            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.getItem("UserId").ToString())); //创客Id
            int ChangeKind = int.Parse(function.CheckInt(data.getItem("ChangeKind").ToString())); // 1-拨入，2-拨出
            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>>();
            IQueryable<PosCouponOrders> query = maindb.PosCouponOrders.Where(m=> m.ChangeKind == 1);
            if(ChangeKind == 1)
            {
                query = query.Where(m => m.ToUserId == UserId);
            }
            else
            {
                query = query.Where(m => m.FromUserId == UserId);
            }
            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("Id", subdata.Id);
                string RealName = "";
                string MakerCode = "";
                if(ChangeKind == 1)
                {
                    Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == subdata.FromUserId) ?? new Models.KxsMainModels.Users();
                    RealName = function.CheckNull(user.RealName);
                    MakerCode = function.CheckNull(user.MakerCode);
                    if(string.IsNullOrEmpty(RealName)) RealName = "成都总仓";
                }
                else
                {
                    Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == subdata.ToUserId) ?? new Models.KxsMainModels.Users();
                    RealName = function.CheckNull(user.RealName);
                    MakerCode = function.CheckNull(user.MakerCode);
                }
                if (RealName.Length > 2 && RealName != "成都总仓")
                {
                    RealName = RealName.Substring(0, 1) + "*" + RealName.Substring(RealName.Length - 1);
                }
                else if(!string.IsNullOrEmpty(RealName) && RealName != "成都总仓")
                { 
                    RealName = RealName.Substring(0, 1) + "*";
                }
                curData.Add("RealName", RealName); //真实姓名
                curData.Add("MakerCode", MakerCode); //创客编号
                curData.Add("ChangeCount", subdata.ChangeCount); //变更数量
                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>();
            if(PageNum == 1)
            {
                DataTable dt = CustomerSqlConn.dtable("select (select count(Id) from PosCouponOrders where FromUserId=" + UserId + "),(select count(Id) from PosCouponOrders where ToUserId=" + UserId + " and ChangeKind=1)", AppConfig.Base.SqlConnStr);
                if(dt.Rows.Count > 0)
                {
                    other.Add("FromTotalCount", dt.Rows[0][1].ToString());
                    other.Add("ToTotalCount", dt.Rows[0][0].ToString());
                }
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-客小爽产品-码牌管理-划拨记录-详情
        // [Authorize]
        public JsonResult Detail(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = DetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> DetailDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString()));
            int Id = int.Parse(function.CheckInt(data.getItem("Id").ToString()));
            PosCouponOrders query = maindb.PosCouponOrders.FirstOrDefault(m => m.Id == Id) ?? new PosCouponOrders();
            string OrderNo = query.OrderNo;
            Dictionary<string, object> UserInfo = new Dictionary<string, object>();
            string RealName = "";
            string MakerCode = "";
            string Mobile = "";
            if(query.ToUserId == UserId)
            {
                Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == query.FromUserId) ?? new Models.KxsMainModels.Users();
                RealName = function.CheckNull(user.RealName);
                MakerCode = function.CheckNull(user.MakerCode);
                Mobile = function.CheckNull(user.Mobile);
                if(string.IsNullOrEmpty(RealName)) RealName = "成都总仓";
            }
            else
            {
                Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == query.ToUserId) ?? new Models.KxsMainModels.Users();
                RealName = function.CheckNull(user.RealName);
                MakerCode = function.CheckNull(user.MakerCode);
                Mobile = function.CheckNull(user.Mobile);
            }
            if (RealName.Length > 2 && RealName != "成都总仓")
            {
                RealName = RealName.Substring(0, 1) + "*" + RealName.Substring(RealName.Length - 1);
            }
            else if(!string.IsNullOrEmpty(RealName) && RealName != "成都总仓")
            { 
                RealName = RealName.Substring(0, 1) + "*";
            }
            Obj.Add("RealName", RealName); //真实姓名
            Obj.Add("MakerCode", MakerCode); //创客编号
            Obj.Add("Mobile", Mobile); //手机号
            Obj.Add("ChangeCount", query.ChangeCount); //变更数量
            Obj.Add("ChangeKind", query.ChangeKind); //变更类型
            Obj.Add("CreateDate", query.CreateDate); //创建时间
            List<int> posids = maindb.PosCouponRecord.Where(m => m.OrderNo == query.OrderNo).ToList().Select(m => m.PosCouponId).ToList();
            List<string> list = main1db.PosMachinesTwo.Where(m => posids.Contains(m.Id)).ToList().Select(m => m.PosSn).ToList();
            Obj.Add("SnNoList", list); //机具券列表
            return Obj;
        }
        #endregion



        #region 创客-首页-客小爽产品-音响管理-划拨记录
        // [Authorize]
        public JsonResult List2(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = List2Do(value, out other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = other });
        }
        public List<Dictionary<string, object>> List2Do(string value, out Dictionary<string, object> other)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString())); //创客Id
            int ChangeKind = int.Parse(function.CheckInt(data.getItem("ChangeKind").ToString())); // 1-拨入，2-拨出
            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>>();
            IQueryable<PosCouponOrders> query = maindb.PosCouponOrders.Where(m=> m.ChangeKind == 2);
            if(ChangeKind == 1)
            {
                query = query.Where(m => m.ToUserId == UserId);
            }
            else
            {
                query = query.Where(m => m.FromUserId == UserId);
            }
            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("Id", subdata.Id);
                string RealName = "";
                string MakerCode = "";
                if(ChangeKind == 1)
                {
                    Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == subdata.FromUserId) ?? new Models.KxsMainModels.Users();
                    RealName = function.CheckNull(user.RealName);
                    MakerCode = function.CheckNull(user.MakerCode);
                    if(string.IsNullOrEmpty(RealName)) RealName = "成都总仓";
                }
                else
                {
                    Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == subdata.ToUserId) ?? new Models.KxsMainModels.Users();
                    RealName = function.CheckNull(user.RealName);
                    MakerCode = function.CheckNull(user.MakerCode);
                }
                if (RealName.Length > 2 && RealName != "成都总仓")
                {
                    RealName = RealName.Substring(0, 1) + "*" + RealName.Substring(RealName.Length - 1);
                }
                else if(!string.IsNullOrEmpty(RealName) && RealName != "成都总仓")
                { 
                    RealName = RealName.Substring(0, 1) + "*";
                }
                curData.Add("RealName", RealName); //真实姓名
                curData.Add("MakerCode", MakerCode); //创客编号
                curData.Add("ChangeCount", subdata.ChangeCount); //变更数量
                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>();
            if(PageNum == 1)
            {
                DataTable dt = CustomerSqlConn.dtable("select (select count(Id) from PosCouponOrders where FromUserId=" + UserId + "),(select count(Id) from PosCouponOrders where ToUserId=" + UserId + " and ChangeKind=2)", AppConfig.Base.SqlConnStr);
                if(dt.Rows.Count > 0)
                {
                    other.Add("FromTotalCount", dt.Rows[0][1].ToString());
                    other.Add("ToTotalCount", dt.Rows[0][0].ToString());
                }
            }
            return dataList;
        }
        #endregion



        #region 创客-首页-客小爽产品-音响管理-划拨记录-详情
        // [Authorize]
        public JsonResult Detail2(string value)
        {
            value = DesDecrypt(value);
            value = value.Replace("null", "\"\"");
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = Detail2Do(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> Detail2Do(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int UserId = int.Parse(function.CheckInt(data.getItem("UserId").ToString()));
            int Id = int.Parse(function.CheckInt(data.getItem("Id").ToString()));
            PosCouponOrders query = maindb.PosCouponOrders.FirstOrDefault(m => m.Id == Id) ?? new PosCouponOrders();
            string OrderNo = query.OrderNo;
            Dictionary<string, object> UserInfo = new Dictionary<string, object>();
            string RealName = "";
            string MakerCode = "";
            string Mobile = "";
            if(query.ToUserId == UserId)
            {
                Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == query.FromUserId) ?? new Models.KxsMainModels.Users();
                RealName = function.CheckNull(user.RealName);
                MakerCode = function.CheckNull(user.MakerCode);
                Mobile = function.CheckNull(user.Mobile);
                if(string.IsNullOrEmpty(RealName)) RealName = "成都总仓";
            }
            else
            {
                Models.KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == query.ToUserId) ?? new Models.KxsMainModels.Users();
                RealName = function.CheckNull(user.RealName);
                MakerCode = function.CheckNull(user.MakerCode);
                Mobile = function.CheckNull(user.Mobile);
            }
            if (RealName.Length > 2 && RealName != "成都总仓")
            {
                RealName = RealName.Substring(0, 1) + "*" + RealName.Substring(RealName.Length - 1);
            }
            else if(!string.IsNullOrEmpty(RealName) && RealName != "成都总仓")
            { 
                RealName = RealName.Substring(0, 1) + "*";
            }
            Obj.Add("RealName", RealName); //真实姓名
            Obj.Add("MakerCode", MakerCode); //创客编号
            Obj.Add("Mobile", Mobile); //手机号
            Obj.Add("ChangeCount", query.ChangeCount); //变更数量
            Obj.Add("ChangeKind", query.ChangeKind); //变更类型
            Obj.Add("CreateDate", query.CreateDate); //创建时间
            List<int> posids = maindb.PosCouponRecord.Where(m => m.OrderNo == query.OrderNo).ToList().Select(m => m.PosCouponId).ToList();
            List<string> list = main1db.PosMachines.Where(m => posids.Contains(m.Id)).ToList().Select(m => m.PosSn).ToList();
            Obj.Add("SnNoList", list); //机具券列表
            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

    }
}
