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




        #region 首页-客小爽产品-机具管理-机具申请-申请记录
        [Authorize]
        public JsonResult ApplyRecords(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            List<Dictionary<string, object>> dataList = ApplyRecordsDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList });
        }
        public List<Dictionary<string, object>> ApplyRecordsDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].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>>();
            IQueryable<MachineApply> query = maindb.MachineApply.Where(m => m.UserId == UserId).OrderByDescending(m => m.Id);
            if (PageNum == 1)
            {
                query = query.Take(PageSize);
            }
            else
            {
                int skipNum = PageSize * (PageNum - 1);
                query = query.Skip(skipNum).Take(PageSize);
            }
            foreach (MachineApply subdata in query)
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("ApplyNo", subdata.ApplyNo); //申请单号
                curData.Add("Areas", function.CheckNull(subdata.Areas).Replace(",", "")); //收货所在地区
                curData.Add("Address", string.IsNullOrEmpty(subdata.Address) ? "上门自提" : subdata.Address); //收货详细地址
                curData.Add("ApplyDeviceNum", subdata.ApplyDeviceNum); //申请机具数量
                curData.Add("Id", subdata.Id); //Id
                curData.Add("CreateDate", subdata.CreateDate == null ? "" : subdata.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //CreateDate
                curData.Add("Status", RelationClass.GetMachineApplyStatusInfo(subdata.Status)); //Status
                dataList.Add(curData);
            }
            return dataList;
        }
        #endregion

        #region 首页-客小爽产品-机具管理-机具申请-申请记录详情
        [Authorize]
        public JsonResult ApplyDetail(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Obj = ApplyDetailDo(value);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = Obj });
        }
        public Dictionary<string, object> ApplyDetailDo(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()));
            MachineApply query = MachineApplyDbconn.Instance.Get(Id) ?? new MachineApply();
            StoreHouse store = StoreHouseDbconn.Instance.Get(query.StoreId) ?? new StoreHouse();
            Obj.Add("ApplyNo", query.ApplyNo); //申请单号
            Obj.Add("ProductName", query.ProductName); //产品名称
            Obj.Add("Areas", function.CheckNull(query.Areas).Replace(",", "")); //收货所在地区
            Obj.Add("Address", string.IsNullOrEmpty(query.Address) ? "上门自提" : query.Address); //收货详细地址
            Obj.Add("RealName", query.RealName); //收件人姓名
            Obj.Add("Mobile", query.Mobile); //收件人手机号
            Obj.Add("ApplyDeviceNum", query.ApplyDeviceNum); //申请机具数量
            Obj.Add("DeliveryType", query.DeliveryType); //提货类型
            if (store.UserId == 1)
            {
                Obj.Add("StoreManagerMobile", "19141324516"); //仓库联系人手机号
            }
            else
            {
                Obj.Add("StoreManagerMobile", query.StoreManagerMobile); //仓库联系人手机号
            }
            Obj.Add("StoreName", store.StoreName); //提货仓库
            Obj.Add("Status", RelationClass.GetMachineApplyStatusInfo(query.Status)); //状态
            Obj.Add("CreateDate", query.CreateDate == null ? "" : query.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss")); //创建时间
            string SwapSnExpand = query.SwapSnExpand;
            int Kind = 0;
            if (SwapSnExpand.StartsWith("02") || SwapSnExpand.StartsWith("03")) Kind = 2;
            else Kind = 1;
            List<string> list = new List<string>();
            if (!string.IsNullOrEmpty(SwapSnExpand))
            {
                list = SwapSnExpand.Split('\n').ToList();
            }
            Obj.Add("Kind", Kind); //申请类别:1-机具,2-兑换券
            Obj.Add("SnList", list); //机具SN/兑换码列表
            return Obj;
        }
        #endregion

        #region 首页-客小爽产品-机具管理-机具申请-确认申请
        [Authorize]
        public JsonResult ConfirmApply(string value)
        {
            value = DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = ConfirmApplyDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        public AppResultJson ConfirmApplyDo(string value)
        {
            function.WriteLog("\r\n\r\n" + DateTime.Now.ToString(), "机具申请-确认申请-V2");
            function.WriteLog(value, "机具申请-确认申请-V2");
            JsonData data = JsonMapper.ToObject(value);
            int UserId = int.Parse(function.CheckInt(data["UserId"].ToString())); //创客
            int Kind = int.Parse(function.CheckInt(data["Kind"].ToString())); //申请类型,1-机具SN,2-200兑换码,3-300券
            string SendSn = data["SendSn"].ToString(); //发货SN            
            string[] Sns = SendSn.Split(',');
            foreach (var item in Sns)
            {
                string checkOp = RedisDbconn.Instance.Get<string>("ConfirmApply:" + UserId + ":" + Kind + ":" + item);
                if (!string.IsNullOrEmpty(checkOp))
                {
                    return new AppResultJson() { Status = "-1", Info = "申请已提交,请勿重复提交" };
                }
                RedisDbconn.Instance.Set("ConfirmApply:"  + UserId + ":" + Kind + ":" + item, "1");
                RedisDbconn.Instance.SetExpire("ConfirmApply:"  + UserId + ":" + Kind + ":" + item, 30);
            }
            string ProductType = data["ProductType"].ToString(); //产品类型
            int StoreId = int.Parse(function.CheckInt(data["StoreId"].ToString())); //仓库
            var brand = maindb.KqProducts.ToList();
            string SnIdString = "";
            function.WriteLog("SnIdString:" + SnIdString, "机具申请-确认申请-V2");
            int DeliveryType = int.Parse(function.CheckInt(data["DeliveryType"].ToString())); //提货类型
            string Remark = data["Remark"].ToString(); //订单备注
            int AddressId = int.Parse(function.CheckInt(data["AddressId"].ToString()));  //收货地址Id
            if (StoreId == 0)
            {
                return new AppResultJson() { Status = "-1", Info = "请选择仓库" };
            }
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            int MachineCount = 0;
            if (Kind == 1)
            {
                if (!string.IsNullOrEmpty(SendSn))
                {
                    int OpId = 0;
                    string SwapSnExpand = "";
                    string[] SnIds = SendSn.Split(',');
                    foreach (string SnId in SnIds)
                    {
                        int SnIdNum = int.Parse(SnId);
                        PosMachinesTwo machine = maindb.PosMachinesTwo.FirstOrDefault(m => m.Status > -1 && m.Id == SnIdNum);
                        if (machine != null)
                        {
                            bool check = maindb.MachineApply.Any(m => m.SwapSnExpand.Contains(machine.PosSn) && m.Status > -1);
                            if (check)
                            {
                                return new AppResultJson() { Status = "-1", Info = "机具" + machine.PosSn + "已申请,请勿重复申请" };
                            }
                        }
                    }
                    foreach (string SnId in SnIds)
                    {
                        int SnIdNum = int.Parse(SnId);
                        PosMachinesTwo machine = maindb.PosMachinesTwo.FirstOrDefault(m => m.Status > -1 && m.Id == SnIdNum);
                        if (machine != null)
                        {
                            if (!SwapSnExpand.Contains(machine.PosSn))
                            {
                                machine.IsPurchase = 1;
                                maindb.SaveChanges();
                                SwapSnExpand += machine.PosSn + ":" + RelationClass.GetPosSnTypeInfo(machine.PosSnType) + "\n";
                                MachineCount += 1;
                                OpId = machine.OpId;
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(SwapSnExpand))
                    {
                        return new AppResultJson() { Status = "-1", Info = "请选择机具" };
                    }
                    function.WriteLog("Kind:" + Kind, "机具申请-确认申请-V2");
                    string ApplyNo = "BA" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                    int BrandId = int.Parse(function.CheckInt(ProductType));
                    KqProducts protype = KqProductsDbconn.Instance.GetList().FirstOrDefault(m => m.Id == BrandId) ?? new KqProducts();
                    Users user = UsersDbconn.Instance.Get(UserId) ?? new Users();
                    UserAddress address = UserAddressDbconn.Instance.Get(AddressId) ?? new UserAddress();
                    StoreHouse store = StoreHouseDbconn.Instance.Get(StoreId) ?? new StoreHouse();
                    Users manager = UsersDbconn.Instance.Get(store.ManageUserId) ?? new Users();
                    string OrderNo = "BM" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                    RedisDbconn.Instance.GetLock("MachineApply:" + UserId);
                    MachineApply query = maindb.MachineApply.Add(new MachineApply()
                    {
                        CreateDate = DateTime.Now,
                        ApplyNo = ApplyNo, //申请单号
                        UserId = UserId, //创客
                        BrandId = BrandId, //品牌
                        ProductName = protype.Name, //产品名称
                        Areas = address.Areas, //收货所在地区
                        Address = address.Address, //收货详细地址
                        RealName = address.RealName, //收件人姓名
                        Mobile = address.Mobile, //收件人手机号
                        ApplyDeviceName = protype.Name, //申请机具名称
                        ApplyDeviceNum = MachineCount, //申请机具数量
                        ApplyTime = DateTime.Now, //申请时间
                        DeliveryType = DeliveryType, //提货类型
                        SwapSnExpand = SwapSnExpand, //兑换机器SN来源
                        OrderExpand = SendSn,
                        StoreId = store.Id,
                        StoreUserId = store.UserId,
                        StoreAreas = store.Areas,
                        StoreAddress = store.Address,
                        StoreManager = manager.RealName,
                        StoreManagerMobile = store.ManageMobile,
                        TopUserId = PublicFunction.GetTopUserId(user.ParentNav), //顶级创客
                        OperateId = OpId,
                    }).Entity;
                    maindb.SaveChanges();
                    function.WriteLog("in", "机具申请-确认申请-V2");
                    function.WriteLog("applyid:" + query.Id, "首页-客小爽产品-机具管理-机具申请-确认申请");
                    RedisDbconn.Instance.ReleaseLock("MachineApply:" + UserId);
                    Products product = ProductsDbconn.Instance.Get(protype.QueryCount) ?? new Products();
                    Orders order = maindb.Orders.Add(new Orders()
                    {
                        OrderNo = OrderNo,
                        RealName = address.RealName,
                        Mobile = address.Mobile,
                        Areas = address.Areas,
                        Address = address.Address,
                        StoreContact = manager.RealName,
                        StoreContactMobile = store.ManageMobile,
                        StoreUserId = store.UserId,
                        StoreType = store.StoreType,
                        CreateDate = DateTime.Now, //创建时间
                        UserId = UserId, //创客
                        StoreId = StoreId, //仓库
                        TopUserId = PublicFunction.GetTopUserId(user.ParentNav), //顶级创客
                        DeliveryType = DeliveryType, //提货类型
                        BuyCount = MachineCount,
                        TotalPrice = 0, //订单总额
                        Remark = Remark, //订单备注
                        Status = 1,
                        PayStatus = 1,
                        PayDate = DateTime.Now,
                        QueryCount = 1, //申请循环机标记
                        Sort = query.Id,
                        OpId = OpId,
                    }).Entity;
                    maindb.SaveChanges();
                    function.WriteLog("in2", "机具申请-确认申请-V2");
                    function.WriteLog("orderid:" + order.Id, "首页-客小爽产品-机具管理-机具申请-确认申请");
                    MachineApply edit = maindb.MachineApply.FirstOrDefault(m => m.Id == query.Id);
                    if (edit != null)
                    {
                        edit.QueryCount = order.Id;
                        maindb.SaveChanges();
                    }
                    OrderProduct pro = maindb.OrderProduct.Add(new OrderProduct()
                    {
                        CreateDate = DateTime.Now, //创建时间
                        OrderId = order.Id,
                        ProductId = product.Id,
                        ProductCount = MachineCount,
                        ProductName = product.ProductName,
                        ProductPhoto = product.ListPicPath,
                        ProductPrice = 0,
                        TotalPrice = 0,
                        ProductCode = product.ProductCode,
                        UserId = UserId,
                        StoreId = StoreId,
                    }).Entity;
                    OrderForNo orderFor = maindb.OrderForNo.Add(new OrderForNo()
                    {
                        OrderNo = OrderNo,
                        OrderIds = order.Id.ToString(),
                    }).Entity;
                    maindb.SaveChanges();
                    function.WriteLog("2", "首页-客小爽产品-机具管理-机具申请-确认申请");
                    function.WriteLog("ok\r\n\r\n", "首页-客小爽产品-机具管理-机具申请-确认申请");
                    return new AppResultJson() { Status = "1", Info = "", Data = Obj };
                }
                return new AppResultJson() { Status = "-1", Info = "请选择机具", Data = Obj };
            }
            else
            {
                if (!string.IsNullOrEmpty(SendSn))
                {
                    int OpId = 0;
                    string SwapSnExpand = "";
                    string[] SnIds = SendSn.Split(',');
                    foreach (string SnId in SnIds)
                    {
                        int SnIdNum = int.Parse(SnId);
                        PosCoupons coupon = maindb.PosCoupons.FirstOrDefault(m => m.Id == SnIdNum);
                        if (coupon != null)
                        {
                            if (!SwapSnExpand.Contains(coupon.ExchangeCode))
                            {
                                coupon.IsLock = 1;
                                coupon.IsUse = 1;
                                coupon.UseDate = DateTime.Now;
                                SwapSnExpand += coupon.ExchangeCode + "\n";
                                MachineCount += 1;
                                OpId = coupon.OpId;
                            }
                        }
                    }
                    if (string.IsNullOrEmpty(SwapSnExpand))
                    {
                        return new AppResultJson() { Status = "-1", Info = "请选择兑换码" };
                    }
                    function.WriteLog("Kind:" + Kind, "机具申请-确认申请-V2");
                    string ApplyNo = "BA" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                    int BrandId = int.Parse(function.CheckInt(ProductType));
                    KqProducts protype = KqProductsDbconn.Instance.GetList().FirstOrDefault(m => m.Id == BrandId) ?? new KqProducts();
                    Users user = UsersDbconn.Instance.Get(UserId) ?? new Users();
                    UserAddress address = UserAddressDbconn.Instance.Get(AddressId) ?? new UserAddress();
                    StoreHouse store = StoreHouseDbconn.Instance.Get(StoreId) ?? new StoreHouse();
                    Users manager = UsersDbconn.Instance.Get(store.ManageUserId) ?? new Users();
                    string OrderNo = "C" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8);
                    bool check = maindb.MachineApply.Any(m => m.SwapSnExpand == SwapSnExpand && m.Status > -1);
                    if (check)
                    {
                        return new AppResultJson() { Status = "-1", Info = "申请已提交,请勿重复申请" };
                    }
                    RedisDbconn.Instance.GetLock("MachineApply:" + UserId);
                    MachineApply query = maindb.MachineApply.Add(new MachineApply()
                    {
                        CreateDate = DateTime.Now,
                        ApplyNo = ApplyNo, //申请单号
                        UserId = UserId, //创客
                        BrandId = BrandId, //品牌
                        ProductName = protype.Name, //产品名称
                        Areas = address.Areas, //收货所在地区
                        Address = address.Address, //收货详细地址
                        RealName = address.RealName, //收件人姓名
                        Mobile = address.Mobile, //收件人手机号
                        ApplyDeviceName = protype.Name, //申请机具名称
                        ApplyDeviceNum = MachineCount, //申请机具数量
                        ApplyTime = DateTime.Now, //申请时间
                        DeliveryType = DeliveryType, //提货类型
                        SwapSnExpand = SwapSnExpand, //兑换机器SN来源
                        OrderExpand = SendSn,
                        StoreId = store.Id,
                        StoreUserId = store.UserId,
                        StoreAreas = store.Areas,
                        StoreAddress = store.Address,
                        StoreManager = manager.RealName,
                        StoreManagerMobile = store.ManageMobile,
                        TopUserId = PublicFunction.GetTopUserId(user.ParentNav), //顶级创客
                        Sort = Kind, // 申请类型,1-机具SN,2-200兑换码,3-300券
                        OperateId = OpId,
                    }).Entity;
                    maindb.SaveChanges();
                    RedisDbconn.Instance.ReleaseLock("MachineApply:" + UserId);
                    function.WriteLog("in", "机具申请-确认申请-V2");
                    Products product = ProductsDbconn.Instance.Get(protype.Sort) ?? new Products();
                    Orders order = maindb.Orders.Add(new Orders()
                    {
                        OrderNo = OrderNo,
                        RealName = address.RealName,
                        Mobile = address.Mobile,
                        Areas = address.Areas,
                        Address = address.Address,
                        StoreContact = manager.RealName,
                        StoreContactMobile = store.ManageMobile,
                        StoreUserId = store.UserId,
                        StoreType = store.StoreType,
                        CreateDate = DateTime.Now, //创建时间
                        UserId = UserId, //创客
                        StoreId = StoreId, //仓库
                        TopUserId = PublicFunction.GetTopUserId(user.ParentNav), //顶级创客
                        DeliveryType = DeliveryType, //提货类型
                        BuyCount = MachineCount,
                        TotalPrice = 0, //订单总额
                        Remark = Remark, //订单备注
                        Status = 1,
                        PayStatus = 1,
                        PayDate = DateTime.Now,
                        Sort = query.Id,
                        OpId = OpId,
                    }).Entity;
                    maindb.SaveChanges();
                    function.WriteLog("in2", "机具申请-确认申请-V2");
                    MachineApply edit = maindb.MachineApply.FirstOrDefault(m => m.Id == query.Id);
                    if (edit != null)
                    {
                        edit.QueryCount = order.Id;
                        maindb.SaveChanges();
                    }
                    OrderProduct pro = maindb.OrderProduct.Add(new OrderProduct()
                    {
                        CreateDate = DateTime.Now, //创建时间
                        OrderId = order.Id,
                        ProductId = product.Id,
                        ProductCount = MachineCount,
                        ProductName = product.ProductName,
                        ProductPhoto = product.ListPicPath,
                        ProductPrice = 0,
                        TotalPrice = 0,
                        ProductCode = product.ProductCode,
                        UserId = UserId,
                        StoreId = StoreId,
                    }).Entity;
                    OrderForNo orderFor = maindb.OrderForNo.Add(new OrderForNo()
                    {
                        OrderNo = OrderNo,
                        OrderIds = order.Id.ToString(),
                    }).Entity;
                    maindb.SaveChanges();
                    return new AppResultJson() { Status = "1", Info = "", Data = Obj };
                }
                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

    }
}