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




        #region 首页-客小爽产品-机具管理-未绑定-划拨
        [Authorize]
        public JsonResult Transfer(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = TransferDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson TransferDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            int BrandId = int.Parse(function.CheckInt(data["BrandId"].ToString())); //产品类型
            string SnIds = data["SnIds"].ToString(); //SN列表返回的Id
            int ToUserId = int.Parse(function.CheckInt(data["ToUserId"].ToString())); //划拨对象创客Id
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            bool checkUser = maindb.Users.Any(m => m.Id == ToUserId);
            if (!checkUser)
            { 
                return new AppResultJson() { Status = "-1", Info = "请输入正确的创客编号", Data = Obj };
            }
            Users user = maindb.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
            Users touser = maindb.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();            
            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[] SnIdList = SnIds.Split(',');
                foreach (string SnId in SnIdList)
                {
                    int SnIdNum = int.Parse(SnId);
                    PosMachinesTwo pos = maindb.PosMachinesTwo.FirstOrDefault(m => m.Status > -1 && m.Id == SnIdNum) ?? new PosMachinesTwo();
                    if (pos.PosSnType == 1)
                    {
                        return new AppResultJson() { Status = "-1", Info = "机具" + pos.PosSn + "是循环机,请勿划拨", Data = Obj };
                    }
                    StoreHouse store = StoreHouseDbconn.Instance.Get(pos.StoreId) ?? new StoreHouse();
                    string ChangeRecordNo = "SC" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                    UserStoreChange query = maindb.UserStoreChange.Add(new UserStoreChange()
                    {
                        CreateDate = DateTime.Now,
                        UserId = UserId, //创客
                        BrandId = BrandId, //产品类型
                        ChangeRecordNo = ChangeRecordNo, //变更记录单号
                        TransType = 11, //交易类型
                        SnNo = pos.PosSn, //SN编号
                        SnType = pos.PosSnType, //SN机具类型
                        StockOpDirect = 1, //库存操作方向
                        ToUserId = ToUserId, //收货创客
                        SnStatus = 0, //SN状态
                        BindStatus = (int)pos.BindingState, //绑定状态
                        BindMerchantId = pos.BindMerchantId, //绑定商户
                        ActiveStatus = (int)pos.ActivationState, //激活状态
                        FromUserId = UserId, //出货创客
                    }).Entity;
                    maindb.SaveChanges();
                    StoreChangeHistory history = maindb.StoreChangeHistory.Add(new StoreChangeHistory()
                    {
                        CreateDate = DateTime.Now,
                        UserId = UserId, //创客
                        BrandId = BrandId, //产品类型
                        ChangeRecordNo = ChangeRecordNo, //变更记录单号
                        TransType = 2, //交易类型
                        SnNo = pos.PosSn, //SN编号
                        SnType = pos.PosSnType, //SN机具类型
                        StockOpDirect = 1, //库存操作方向
                        DeviceVendor = pos.DeviceName, //设备厂商
                        DeviceModel = pos.DeviceKind, //设备型号
                        DeviceType = pos.DeviceType, //设备类型
                        ToUserId = ToUserId, //收货创客
                        FromUserId = store.UserId, //出货创客
                        FromDate = DateTime.Now, //出库时间
                        SourceStoreId = pos.SourceStoreId, //源仓库
                        StoreId = store.Id, //仓库
                    }).Entity;
                    maindb.SaveChanges();
                    StoreChangeItem item = new StoreChangeItem()
                    {
                        SnNo = pos.PosSn,
                        SnType = pos.PosSnType,
                        FromDate = DateTime.Now,
                        Id = query.Id,
                        UserId = ToUserId,
                    };
                    string IdBrand = UserId + "_" + BrandId;
                    PublicFunction.StatUserMachineData(UserId, BrandId, -1);
                    PublicFunction.StatUserMachineData(ToUserId, BrandId, 1);

                    pos.BuyUserId = ToUserId;
                    pos.UserId = ToUserId;
                    pos.TransferTime = DateTime.Now;
                    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

    }
}