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.pos
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class PosCouponRecordController : BaseController
    {
        public PosCouponRecordController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
        }




        #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 });
        }
        int[] ToUserIds = { 1, 76922 };
        public AppResultJson AddDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int ToUserId = int.Parse(function.CheckInt(data["ToUserId"].ToString())); //目标创客
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客Id
            string SnIds = data["SnIds"].ToString(); //码牌列表返回的Id集合
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            bool checkUser = kxsdb.Users.Any(m => m.Id == ToUserId);
            if (!checkUser)
            {
                return new AppResultJson() { Status = "-1", Info = "请输入正确的创客编号", Data = Obj };
            }
            KxsMainModels.Users user = kxsdb.Users.FirstOrDefault(m => m.Id == UserId) ?? new KxsMainModels.Users();
            KxsMainModels.Users touser = kxsdb.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new KxsMainModels.Users();
            if (!ToUserIds.Contains(UserId))
            {
                if (!function.CheckNull(touser.ParentNav).Contains("," + UserId + ",") || function.CheckNull(user.ParentNav).Contains("," + ToUserId + ","))
                {
                    return new AppResultJson() { Status = "-1", Info = "划拨对象不在您的权限范围", Data = Obj };
                }
            }
            if (!string.IsNullOrEmpty(SnIds))
            {
                string ChangeRecordNo = "SC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                string[] SnIdList = SnIds.Split(',');
                foreach (string SnId in SnIdList)
                {
                    int SnIdNum = int.Parse(SnId);
                    PosMachinesTwo pos = maindb.PosMachinesTwo.FirstOrDefault(m => m.Id == SnIdNum) ?? new PosMachinesTwo();
                    if (pos.BuyUserId != UserId)
                    {
                        return new AppResultJson() { Status = "-1", Info = pos.PosSn + "已划拨，请勿重复划拨", Data = Obj };
                    }
                    if(pos.BindingState == 1)
                    {
                        return new AppResultJson() { Status = "-1", Info = pos.PosSn + "已绑定，无法划拨", Data = Obj };
                    }
                    PosCouponRecord query = maindb.PosCouponRecord.Add(new PosCouponRecord()
                    {
                        CreateDate = DateTime.Now,
                        OrderNo = ChangeRecordNo,
                        ToUserId = ToUserId,
                        FromUserId = UserId,
                        PosCouponId = SnIdNum,
                    }).Entity;
                    pos.BuyUserId = ToUserId;
                    pos.UserId = ToUserId;
                }
                maindb.SaveChanges();
                int SnCount = SnIdList.Length;
                PosCouponOrders tostat = maindb.PosCouponOrders.Add(new PosCouponOrders()
                {
                    CreateDate = DateTime.Now,
                    ChangeCount = SnCount,
                    OrderNo = ChangeRecordNo,
                    ToUserId = ToUserId,
                    FromUserId = UserId,
                }).Entity;
                
                PublicFunction.StatUserMachineData(UserId, 0, -SnCount);
                PublicFunction.StatUserMachineData(ToUserId, 0, SnCount);

                maindb.SaveChanges();
            }
            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

    }
}
