/*
 * 预发货库存明细
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class PreSendStockDetailController : BaseController
    {
        public PreSendStockDetailController(IHttpContextAccessor accessor, ILogger<BaseController> logger, IOptions<Setting> setting) : base(accessor, logger, setting)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["SqlConnStr"].ToString();
        }

        #region 预发货库存明细列表

        /// <summary>
        /// 根据条件查询预发货库存明细列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Index(PreSendStockDetail data, string right, string StoreId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.StoreId = StoreId;


            return View();
        }

        #endregion

        #region 根据条件查询预发货库存明细列表

        /// <summary>
        /// 预发货库存明细列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(PreSendStockDetail data, string StoreIdStoreName, string StoreIdStoreNo, string CreateDateData, string ApplyDateData, string BrandIdSelect, string ToUserIdMakerCode, string ToUserIdRealName, string ToStoreIdStoreNo, string ToStoreIdStoreName, string SourceStoreIdStoreNo, string SourceStoreIdStoreName, string FromUserIdMakerCode, string FromUserIdRealName, string FromStoreIdStoreNo, string FromStoreIdStoreName, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("StoreId", "1");
            Fields.Add("SnNo", "1"); //SN编号


            string condition = " and Status>-1";
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForName where Name='" + StoreIdStoreName + "')";
            }
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + StoreIdStoreNo + "')";
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }
            if (!string.IsNullOrEmpty(ApplyDateData))
            {
                string[] datelist = ApplyDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and ApplyDate>='" + start + " 00:00:00' and ApplyDate<='" + end + " 23:59:59'";
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }
            //收货人创客编号
            if (!string.IsNullOrEmpty(ToUserIdMakerCode))
            {
                condition += " and ToUserId in (select UserId from UserForMakerCode where MakerCode='" + ToUserIdMakerCode + "')";
            }
            //收货人真实姓名
            if (!string.IsNullOrEmpty(ToUserIdRealName))
            {
                condition += " and ToUserId in (select UserId from UserForRealName where RealName='" + ToUserIdRealName + "')";
            }
            //收货仓库编号
            if (!string.IsNullOrEmpty(ToStoreIdStoreNo))
            {
                condition += " and ToStoreId in (select StoreId from StoreForCode where Code='" + ToStoreIdStoreNo + "')";
            }
            //收货仓库名称
            if (!string.IsNullOrEmpty(ToStoreIdStoreName))
            {
                condition += " and ToStoreId in (select StoreId from StoreForName where Name='" + ToStoreIdStoreName + "')";
            }
            //源仓库编号仓库编号
            if (!string.IsNullOrEmpty(SourceStoreIdStoreNo))
            {
                condition += " and SourceStoreId in (select StoreId from StoreForCode where Code='" + SourceStoreIdStoreNo + "')";
            }
            //源仓库编号仓库名称
            if (!string.IsNullOrEmpty(SourceStoreIdStoreName))
            {
                condition += " and SourceStoreId in (select StoreId from StoreForName where Name=='" + SourceStoreIdStoreName + "')";
            }
            //出货创客编号
            if (!string.IsNullOrEmpty(FromUserIdMakerCode))
            {
                condition += " and FromUserId in (select UserId from UserForMakerCode where MakerCode='" + FromUserIdMakerCode + "')";
            }
            //出货创客真实姓名
            if (!string.IsNullOrEmpty(FromUserIdRealName))
            {
                condition += " and FromUserId in (select UserId from UserForRealName where RealName='" + FromUserIdRealName + "')";
            }
            //出货仓库编号
            if (!string.IsNullOrEmpty(FromStoreIdStoreNo))
            {
                condition += " and FromStoreId in (select StoreId from StoreForCode where Code='" + FromStoreIdStoreNo + "')";
            }
            //出货仓库名称
            if (!string.IsNullOrEmpty(FromStoreIdStoreName))
            {
                condition += " and FromStoreId in (select StoreId from StoreForName where Name='" + FromStoreIdStoreName + "')";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreSendStockDetail", Fields, "Id desc", "0", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //仓库
                int StoreId = int.Parse(function.CheckInt(dic["StoreId"].ToString()));
                SmallStoreHouse storeid_SmallStoreHouse = db.SmallStoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new SmallStoreHouse();
                dic["StoreIdStoreName"] = storeid_SmallStoreHouse.StoreName;
                dic["StoreIdStoreNo"] = storeid_SmallStoreHouse.StoreNo;
                dic.Remove("StoreId");
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //SNID
                dic["SnId"] = RelationClass.GetPosMachinesTwoInfo(int.Parse(dic["SnId"].ToString()));
                //收货人
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users touserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["ToUserIdMakerCode"] = touserid_Users.MakerCode;
                dic["ToUserIdRealName"] = touserid_Users.RealName;
                dic.Remove("ToUserId");
                //收货仓库
                int ToStoreId = int.Parse(function.CheckInt(dic["ToStoreId"].ToString()));
                StoreHouse tostoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == ToStoreId) ?? new StoreHouse();
                dic["ToStoreIdStoreNo"] = tostoreid_StoreHouse.StoreNo;
                dic["ToStoreIdStoreName"] = tostoreid_StoreHouse.StoreName;
                dic.Remove("ToStoreId");
                //源仓库编号
                int SourceStoreId = int.Parse(function.CheckInt(dic["SourceStoreId"].ToString()));
                StoreHouse sourcestoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == SourceStoreId) ?? new StoreHouse();
                dic["SourceStoreIdStoreNo"] = sourcestoreid_StoreHouse.StoreNo;
                dic["SourceStoreIdStoreName"] = sourcestoreid_StoreHouse.StoreName;
                dic.Remove("SourceStoreId");
                dic["ApplyFlagName"] = dic["ApplyFlag"].ToString() == "1" ? "是" : "否";
                //出货创客
                int FromUserId = int.Parse(function.CheckInt(dic["FromUserId"].ToString()));
                Users fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == FromUserId) ?? new Users();
                dic["FromUserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["FromUserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("FromUserId");
                //出货仓库
                int FromStoreId = int.Parse(function.CheckInt(dic["FromStoreId"].ToString()));
                StoreHouse fromstoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == FromStoreId) ?? new StoreHouse();
                dic["FromStoreIdStoreNo"] = fromstoreid_StoreHouse.StoreNo;
                dic["FromStoreIdStoreName"] = fromstoreid_StoreHouse.StoreName;
                dic.Remove("FromStoreId");
                dic["CancelFlagName"] = dic["CancelFlag"].ToString() == "1" ? "是" : "否";
                //是否占用额度
                int AuthFlag = int.Parse(function.CheckInt(dic["AuthFlag"].ToString()));
                if (AuthFlag == 0) dic["PayMode"] = "否";
                if (AuthFlag == 1) dic["PayMode"] = "是";
                //是否预扣标记
                int WithholdFlag = int.Parse(function.CheckInt(dic["WithholdFlag"].ToString()));
                if (WithholdFlag == 0) dic["WithholdFlagName"] = "否";
                if (WithholdFlag == 1) dic["WithholdFlagName"] = "是";

            }
            return Json(obj);
        }

        #endregion

        #region 增加预发货库存明细

        /// <summary>
        /// 增加或修改预发货库存明细信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right, string StoreId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.StoreId = StoreId;


            return View();
        }

        #endregion

        #region 增加预发货库存明细

        /// <summary>
        /// 增加或修改预发货库存明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(PreSendStockDetail data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("StoreId", data.StoreId);

            Fields.Add("StoreId", data.StoreId); //仓库
            Fields.Add("BrandId", data.BrandId); //产品类型
            Fields.Add("SnId", data.SnId); //SNID
            Fields.Add("ToUserId", data.ToUserId); //收货人
            Fields.Add("ToStoreId", data.ToStoreId); //收货仓库
            Fields.Add("SourceStoreId", data.SourceStoreId); //源仓库编号
            Fields.Add("ApplyFlag", data.ApplyFlag); //申请标记
            Fields.Add("ApplyDate", data.ApplyDate); //申请时间
            Fields.Add("FromUserId", data.FromUserId); //出货创客
            Fields.Add("FromStoreId", data.FromStoreId); //出货仓库
            Fields.Add("CancelFlag", data.CancelFlag); //撤回标记
            Fields.Add("CancelDate", data.CancelDate); //撤回时间

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("PreSendStockDetail", Fields, 0);
            AddSysLog(data.Id.ToString(), "PreSendStockDetail", "add");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改预发货库存明细

        /// <summary>
        /// 增加或修改预发货库存明细信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, string StoreId, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.StoreId = StoreId;


            PreSendStockDetail editData = db.PreSendStockDetail.FirstOrDefault(m => m.Id == Id) ?? new PreSendStockDetail();
            ViewBag.data = editData;
            return View();
        }

        #endregion

        #region 修改预发货库存明细

        /// <summary>
        /// 增加或修改预发货库存明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(PreSendStockDetail data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("StoreId", data.StoreId);

            Fields.Add("StoreId", data.StoreId); //仓库
            Fields.Add("BrandId", data.BrandId); //产品类型
            Fields.Add("SnId", data.SnId); //SNID
            Fields.Add("ToUserId", data.ToUserId); //收货人
            Fields.Add("ToStoreId", data.ToStoreId); //收货仓库
            Fields.Add("SourceStoreId", data.SourceStoreId); //源仓库编号
            Fields.Add("ApplyFlag", data.ApplyFlag); //申请标记
            Fields.Add("ApplyDate", data.ApplyDate); //申请时间
            Fields.Add("FromUserId", data.FromUserId); //出货创客
            Fields.Add("FromStoreId", data.FromStoreId); //出货仓库
            Fields.Add("CancelFlag", data.CancelFlag); //撤回标记
            Fields.Add("CancelDate", data.CancelDate); //撤回时间

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("PreSendStockDetail", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "PreSendStockDetail", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除预发货库存明细信息

        /// <summary>
        /// 删除预发货库存明细信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PreSendStockDetail", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("PreSendStockDetail", Fields, id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PreSendStockDetail", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("PreSendStockDetail", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 关闭

        /// <summary>
        /// 关闭
        /// </summary>
        /// <returns></returns>
        public string Close(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PreSendStockDetail", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("PreSendStockDetail", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 排序
        /// <summary>
        /// 排序
        /// </summary>
        /// <param name="Id"></param>
        public string Sort(int Id, int Sort)
        {
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Sort("PreSendStockDetail", Sort, Id);

            AddSysLog(Id.ToString(), "PreSendStockDetail", "sort");
            return "success";
        }
        #endregion

        #region 导入数据
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];

                db.PreSendStockDetail.Add(new PreSendStockDetail()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

                });
                db.SaveChanges();
            }
            AddSysLog("0", "PreSendStockDetail", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(PreSendStockDetail data, string StoreIdStoreName, string StoreIdStoreNo, string BrandIdSelect, string ToUserIdMakerCode, string ToUserIdRealName, string ToStoreIdStoreNo, string ToStoreIdStoreName, string SourceStoreIdStoreNo, string SourceStoreIdStoreName, string FromUserIdMakerCode, string FromUserIdRealName, string FromStoreIdStoreNo, string FromStoreIdStoreName)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("SnNo", "1"); //SN编号
            Fields.Add("ApplyDate", "3"); //申请时间


            string condition = " and Status>-1";
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from SmallStoreHouseForStoreName where StoreName='" + StoreIdStoreName + "')";
            }
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from SmallStoreHouseForStoreNo where StoreNo='" + StoreIdStoreNo + "')";
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }
            //收货人创客编号
            if (!string.IsNullOrEmpty(ToUserIdMakerCode))
            {
                condition += " and ToUserId in (select ToUserId from UserForMakerCode where MakerCode='" + ToUserIdMakerCode + "')";
            }
            //收货人真实姓名
            if (!string.IsNullOrEmpty(ToUserIdRealName))
            {
                condition += " and ToUserId in (select ToUserId from UserForRealName where RealName='" + ToUserIdRealName + "')";
            }
            //收货仓库编号
            if (!string.IsNullOrEmpty(ToStoreIdStoreNo))
            {
                condition += " and ToStoreId in (select ToStoreId from StoreHouseForStoreNo where StoreNo='" + ToStoreIdStoreNo + "')";
            }
            //收货仓库名称
            if (!string.IsNullOrEmpty(ToStoreIdStoreName))
            {
                condition += " and ToStoreId in (select ToStoreId from StoreHouseForStoreName where StoreName='" + ToStoreIdStoreName + "')";
            }
            //源仓库编号仓库编号
            if (!string.IsNullOrEmpty(SourceStoreIdStoreNo))
            {
                condition += " and SourceStoreId in (select SourceStoreId from StoreHouseForStoreNo where StoreNo='" + SourceStoreIdStoreNo + "')";
            }
            //源仓库编号仓库名称
            if (!string.IsNullOrEmpty(SourceStoreIdStoreName))
            {
                condition += " and SourceStoreId in (select SourceStoreId from StoreHouseForStoreName where StoreName='" + SourceStoreIdStoreName + "')";
            }
            //出货创客编号
            if (!string.IsNullOrEmpty(FromUserIdMakerCode))
            {
                condition += " and FromUserId in (select FromUserId from UserForMakerCode where MakerCode='" + FromUserIdMakerCode + "')";
            }
            //出货创客真实姓名
            if (!string.IsNullOrEmpty(FromUserIdRealName))
            {
                condition += " and FromUserId in (select FromUserId from UserForRealName where RealName='" + FromUserIdRealName + "')";
            }
            //出货仓库编号
            if (!string.IsNullOrEmpty(FromStoreIdStoreNo))
            {
                condition += " and FromStoreId in (select FromStoreId from StoreHouseForStoreNo where StoreNo='" + FromStoreIdStoreNo + "')";
            }
            //出货仓库名称
            if (!string.IsNullOrEmpty(FromStoreIdStoreName))
            {
                condition += " and FromStoreId in (select FromStoreId from StoreHouseForStoreName where StoreName='" + FromStoreIdStoreName + "')";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreSendStockDetail", Fields, "Id desc", "0", 1, 20000, condition, "StoreId,BrandId,SnNo,SnId,ToUserId,ToStoreId,SourceStoreId,ApplyFlag,ApplyDate,FromUserId,FromStoreId,CancelFlag,CancelDate", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //仓库
                int StoreId = int.Parse(function.CheckInt(dic["StoreId"].ToString()));
                SmallStoreHouse storeid_SmallStoreHouse = db.SmallStoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new SmallStoreHouse();
                dic["StoreIdStoreName"] = storeid_SmallStoreHouse.StoreName;
                dic["StoreIdStoreNo"] = storeid_SmallStoreHouse.StoreNo;
                dic.Remove("StoreId");
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //SNID
                dic["SnId"] = RelationClass.GetPosMachinesTwoInfo(int.Parse(dic["SnId"].ToString()));
                //收货人
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users touserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["ToUserIdMakerCode"] = touserid_Users.MakerCode;
                dic["ToUserIdRealName"] = touserid_Users.RealName;
                dic.Remove("ToUserId");
                //收货仓库
                int ToStoreId = int.Parse(function.CheckInt(dic["ToStoreId"].ToString()));
                StoreHouse tostoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == ToStoreId) ?? new StoreHouse();
                dic["ToStoreIdStoreNo"] = tostoreid_StoreHouse.StoreNo;
                dic["ToStoreIdStoreName"] = tostoreid_StoreHouse.StoreName;
                dic.Remove("ToStoreId");
                //源仓库编号
                int SourceStoreId = int.Parse(function.CheckInt(dic["SourceStoreId"].ToString()));
                StoreHouse sourcestoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == SourceStoreId) ?? new StoreHouse();
                dic["SourceStoreIdStoreNo"] = sourcestoreid_StoreHouse.StoreNo;
                dic["SourceStoreIdStoreName"] = sourcestoreid_StoreHouse.StoreName;
                dic.Remove("SourceStoreId");
                dic["ApplyFlagName"] = dic["ApplyFlag"].ToString() == "1" ? "是" : "否";
                //出货创客
                int FromUserId = int.Parse(function.CheckInt(dic["FromUserId"].ToString()));
                Users fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == FromUserId) ?? new Users();
                dic["FromUserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["FromUserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("FromUserId");
                //出货仓库
                int FromStoreId = int.Parse(function.CheckInt(dic["FromStoreId"].ToString()));
                StoreHouse fromstoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == FromStoreId) ?? new StoreHouse();
                dic["FromStoreIdStoreNo"] = fromstoreid_StoreHouse.StoreNo;
                dic["FromStoreIdStoreName"] = fromstoreid_StoreHouse.StoreName;
                dic.Remove("FromStoreId");
                dic["CancelFlagName"] = dic["CancelFlag"].ToString() == "1" ? "是" : "否";

            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();
            ReturnFields.Add("StoreIdStoreName", "仓库名称");
            ReturnFields.Add("StoreIdStoreNo", "仓库编号");
            ReturnFields.Add("BrandId", "产品类型");
            ReturnFields.Add("SnNo", "SN编号");
            ReturnFields.Add("SnId", "SNID");
            ReturnFields.Add("ToUserIdMakerCode", "收货人创客编号");
            ReturnFields.Add("ToUserIdRealName", "收货人真实姓名");
            ReturnFields.Add("ToStoreIdStoreNo", "收货仓库编号");
            ReturnFields.Add("ToStoreIdStoreName", "收货仓库名称");
            ReturnFields.Add("SourceStoreIdStoreNo", "源仓库编号仓库编号");
            ReturnFields.Add("SourceStoreIdStoreName", "源仓库编号仓库名称");
            ReturnFields.Add("ApplyFlag", "申请标记");
            ReturnFields.Add("ApplyDate", "申请时间");
            ReturnFields.Add("FromUserIdMakerCode", "出货创客编号");
            ReturnFields.Add("FromUserIdRealName", "出货创客真实姓名");
            ReturnFields.Add("FromStoreIdStoreNo", "出货仓库编号");
            ReturnFields.Add("FromStoreIdStoreName", "出货仓库名称");
            ReturnFields.Add("CancelFlag", "撤回标记");
            ReturnFields.Add("CancelDate", "撤回时间");

            result.Add("Fields", ReturnFields);
            AddSysLog("0", "PreSendStockDetail", "ExportExcel");
            return Json(result);
        }

        #endregion


        #region 预发机撤回

        /// <summary>
        /// 预发机撤回
        /// </summary>
        /// <returns></returns>
        public string Cancle(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PreSendStockDetail", "cancle");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("PreSendStockDetail", Fields, id);

                string check = RedisDbconn.Instance.Get<string>("HTSmallStoreCancel:" + id);
                if (!string.IsNullOrEmpty(check))
                {
                    return "请勿频繁操作，稍后再试";
                }
                RedisDbconn.Instance.Set("HTSmallStoreCancel:" + id, "wait");
                RedisDbconn.Instance.SetExpire("HTSmallStoreCancel:" + id, 3);
                var query = db.PreSendStockDetail.FirstOrDefault(m => m.Id == id);
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == query.FromUserId) ?? new UserAccount();
                var tuserAccount = db.UserAccount.FirstOrDefault(m => m.Id == query.ToUserId) ?? new UserAccount();
                KqProducts kqProducts = db.KqProducts.FirstOrDefault(m => m.Id == query.BrandId);
                var date = DateTime.Now.AddDays(-30);
                var amount = 0;
                if (query != null)
                {
                    PosMachinesTwo posMachinesTwo = db.PosMachinesTwo.FirstOrDefault(m => m.Id == query.SnId) ?? new PosMachinesTwo();
                    StoreHouse storeHouse = db.StoreHouse.FirstOrDefault(m => m.Id == query.FromStoreId) ?? new StoreHouse();
                    PosMachinesTwo pm = db.PosMachinesTwo.FirstOrDefault(m => m.Id == query.SnId);
                    var brandInfo = db.KqProducts.FirstOrDefault(m => m.Id == posMachinesTwo.BrandId);
                    if (brandInfo.Name.Contains("电签"))
                    {
                        amount = 200;
                    }
                    if (brandInfo.Name.Contains("大POS"))
                    {
                        amount = 300;
                    }
                    if (pm != null)
                    {
                        // if (pm.BindingState == 1)
                        // {
                        //     return "机具已绑定，不可撤回！请创客申请机具后补录！";
                        // }
                        SmallStoreHouse smallStoreHouse = db.SmallStoreHouse.FirstOrDefault(m => m.UserId == query.ToUserId);
                        posMachinesTwo.PreUserId = 0;
                        query.UpdateDate = DateTime.Now;
                        query.Status = -1;
                        query.CancelFlag = 1;
                        storeHouse.LaveNum += 1;
                        smallStoreHouse.UpdateDate = DateTime.Now;
                        smallStoreHouse.LaveNum += 1;
                        smallStoreHouse.TotalNum -= 1;
                        if (query.CreateDate <= date)
                        {
                            //撤回占用小分仓额度的增加接收创客的小分仓可用额度
                            if (query.AuthFlag == 1 && tuserAccount.SmallStoreDeposit >= amount)
                            {
                                userAccount.ValidAmount -= amount;//扣减分仓可用额度
                                tuserAccount.SmallStoreDeposit -= amount;
                                tuserAccount.ValidPreAmount += amount;//增加小分仓可用额度
                                var add = db.UserAccountRecord.Add(new UserAccountRecord()
                                {
                                    CreateDate = DateTime.Now,
                                    Remark = "小分仓押金退还",
                                    ChangeType = 66,
                                    BeforeBalanceAmount = tuserAccount.SmallStoreDeposit + amount, //变更前小分仓押金
                                    AfterBalanceAmount = tuserAccount.SmallStoreDeposit, //变更后小分仓押金
                                    ChangeAmount = amount,//变动金额
                                    UserId = tuserAccount.Id,
                                }).Entity;
                                db.SaveChanges();
                            }
                        }
                        else
                        {
                            //撤回占用小分仓额度的增加接收创客的小分仓可用额度
                            if (query.AuthFlag == 1)
                            {
                                tuserAccount.ValidPreAmount += amount;//增加小分仓可用额度
                                userAccount.ValidAmount -= amount;//扣减分仓可用额度
                            }
                        }
                        
                        RedisDbconn.Instance.AddList("PreWithholdQueue", "{\"UserId\":\"" + query.ToUserId + "\",\"SnNo\":\"" + query.SnNo + "\"}");

                        string text = string.Format("创客-首页-仓库管理-小分仓-撤回，UserId: '" + query.FromUserId + "'，ToUserId: '" + smallStoreHouse.UserId + "'，LaveNum：'" + smallStoreHouse.LaveNum + "'，TotalNum：'" + smallStoreHouse.TotalNum + "'，ChangeCount：'" + 1 + "'，Time'" + DateTime.Now + "'");
                        function.WriteLog(text, "smallstorehouse");//小分仓记录日志
                        if (smallStoreHouse.LaveNum > 10 || smallStoreHouse.TotalNum < 0)
                        {
                            return "*库存已重置，不可撤回！";
                        }
                        db.SaveChanges();
                        RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                        {
                            UserId = query.ToUserId, //收货创客
                            Title = "预发机撤回通知", //标题
                            Content = "<div class='f16'>您的预发机 SN:<br/>" + query.SnNo + "<br/>已被" + storeHouse.StoreName + " 撤回！</div>", //内容
                            Summary = "您的预发机: " + kqProducts.Name + "  sn:" + query.SnNo + "已被 " + storeHouse.StoreName + " 撤回！",
                            CreateDate = DateTime.Now,

                        }));

                        var toUser = db.Users.FirstOrDefault(m => m.Id == query.ToUserId);
                        RedisDbconn.Instance.AddList("MsgPersonalQueue", Newtonsoft.Json.JsonConvert.SerializeObject(new MsgPersonal()
                        {
                            UserId = query.FromUserId, //收货创客
                            Title = "预发机撤回通知", //标题
                            Content = "<div class='f16'>已撤回创客：" + toUser.MakerCode + " " + toUser.RealName + " 的预发机 SN：<br/>" + query.SnNo + "</div>", //内容
                            Summary = "已撤回创客：" + toUser.MakerCode + " " + toUser.RealName + " 的预发机 SN：" + query.SnNo + "",
                            CreateDate = DateTime.Now,

                        }));

                        //删除预发机过期提醒
                        List<Dictionary<string, string>> result = RedisDbconn.Instance.GetList<Dictionary<string, string>>("PrePosRing:" + DateTime.Now.ToString("yyyyMMdd") + ":" + query.ToUserId);
                        if (result.Count > 0)
                        {
                            foreach (Dictionary<string, string> item in result)
                            {
                                if (item["SnNo"] == pm.PosSn)
                                {
                                    RedisDbconn.Instance.DelFromList("PrePosRing:" + DateTime.Now.ToString("yyyyMMdd") + ":" + query.ToUserId, item);
                                }
                            }
                        }
                        result = RedisDbconn.Instance.GetList<Dictionary<string, string>>("PrePosRingForExpired:" + DateTime.Now.ToString("yyyyMMdd") + ":" + query.ToUserId);
                        if (result.Count > 0)
                        {
                            foreach (Dictionary<string, string> item in result)
                            {
                                if (item["SnNo"] == pm.PosSn)
                                {
                                    RedisDbconn.Instance.DelFromList("PrePosRingForExpired:" + DateTime.Now.ToString("yyyyMMdd") + ":" + query.ToUserId, item);
                                }
                            }
                        }
                    }
                }
                RedisDbconn.Instance.SetExpire("HTSmallStoreCancel:" + id, 1);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion


        #region 预发货库存明细列表(占额度超过30天未兑换)

        /// <summary>
        /// 根据条件查询预发货库存明细列表(占额度超过30天未兑换)
        /// </summary>
        /// <returns></returns>
        public IActionResult Indexs(PreSendStockDetail data, string right, string StoreId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.StoreId = StoreId;


            return View();
        }

        #endregion

        #region 根据条件查询预发货库存明细列表(占额度超过30天未兑换)

        /// <summary>
        /// 根据条件查询预发货库存明细列表(占额度超过30天未兑换)
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexsData(PreSendStockDetail data, string StoreIdStoreName, string StoreIdStoreNo, string CreateDateData, string ApplyDateData, string BrandIdSelect, string ToUserIdMakerCode, string ToUserIdRealName, string ToStoreIdStoreNo, string ToStoreIdStoreName, string SourceStoreIdStoreNo, string SourceStoreIdStoreName, string FromUserIdMakerCode, string FromUserIdRealName, string FromStoreIdStoreNo, string FromStoreIdStoreName, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("StoreId", "1");
            Fields.Add("SnNo", "1"); //SN编号


            string condition = " and Status=1 and DATE_SUB(CURDATE(), INTERVAL 30 DAY) >= date(CreateDate) and ApplyFlag =0";
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForName where Name='" + StoreIdStoreName + "')";
            }
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + StoreIdStoreNo + "')";
            }
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }
            if (!string.IsNullOrEmpty(ApplyDateData))
            {
                string[] datelist = ApplyDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and ApplyDate>='" + start + " 00:00:00' and ApplyDate<='" + end + " 23:59:59'";
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }
            //收货人创客编号
            if (!string.IsNullOrEmpty(ToUserIdMakerCode))
            {
                condition += " and ToUserId in (select UserId from UserForMakerCode where MakerCode='" + ToUserIdMakerCode + "')";
            }
            //收货人真实姓名
            if (!string.IsNullOrEmpty(ToUserIdRealName))
            {
                condition += " and ToUserId in (select UserId from UserForRealName where RealName='" + ToUserIdRealName + "')";
            }
            //收货仓库编号
            if (!string.IsNullOrEmpty(ToStoreIdStoreNo))
            {
                condition += " and ToStoreId in (select StoreId from StoreForCode where Code='" + ToStoreIdStoreNo + "')";
            }
            //收货仓库名称
            if (!string.IsNullOrEmpty(ToStoreIdStoreName))
            {
                condition += " and ToStoreId in (select StoreId from StoreForName where Name='" + ToStoreIdStoreName + "')";
            }
            //源仓库编号仓库编号
            if (!string.IsNullOrEmpty(SourceStoreIdStoreNo))
            {
                condition += " and SourceStoreId in (select StoreId from StoreForCode where Code='" + SourceStoreIdStoreNo + "')";
            }
            //源仓库编号仓库名称
            if (!string.IsNullOrEmpty(SourceStoreIdStoreName))
            {
                condition += " and SourceStoreId in (select StoreId from StoreForName where Name=='" + SourceStoreIdStoreName + "')";
            }
            //出货创客编号
            if (!string.IsNullOrEmpty(FromUserIdMakerCode))
            {
                condition += " and FromUserId in (select UserId from UserForMakerCode where MakerCode='" + FromUserIdMakerCode + "')";
            }
            //出货创客真实姓名
            if (!string.IsNullOrEmpty(FromUserIdRealName))
            {
                condition += " and FromUserId in (select UserId from UserForRealName where RealName='" + FromUserIdRealName + "')";
            }
            //出货仓库编号
            if (!string.IsNullOrEmpty(FromStoreIdStoreNo))
            {
                condition += " and FromStoreId in (select StoreId from StoreForCode where Code='" + FromStoreIdStoreNo + "')";
            }
            //出货仓库名称
            if (!string.IsNullOrEmpty(FromStoreIdStoreName))
            {
                condition += " and FromStoreId in (select StoreId from StoreForName where Name='" + FromStoreIdStoreName + "')";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PreSendStockDetail", Fields, "Id desc", "0", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //仓库
                int StoreId = int.Parse(function.CheckInt(dic["StoreId"].ToString()));
                SmallStoreHouse storeid_SmallStoreHouse = db.SmallStoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new SmallStoreHouse();
                dic["StoreIdStoreName"] = storeid_SmallStoreHouse.StoreName;
                dic["StoreIdStoreNo"] = storeid_SmallStoreHouse.StoreNo;
                dic.Remove("StoreId");
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //收货人
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users touserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["ToUserIdMakerCode"] = touserid_Users.MakerCode;
                dic["ToUserIdRealName"] = touserid_Users.RealName;
                dic.Remove("ToUserId");
                //收货仓库
                int ToStoreId = int.Parse(function.CheckInt(dic["ToStoreId"].ToString()));
                StoreHouse tostoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == ToStoreId) ?? new StoreHouse();
                dic["ToStoreIdStoreNo"] = tostoreid_StoreHouse.StoreNo;
                dic["ToStoreIdStoreName"] = tostoreid_StoreHouse.StoreName;
                dic.Remove("ToStoreId");
                //源仓库编号
                int SourceStoreId = int.Parse(function.CheckInt(dic["SourceStoreId"].ToString()));
                StoreHouse sourcestoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == SourceStoreId) ?? new StoreHouse();
                dic["SourceStoreIdStoreNo"] = sourcestoreid_StoreHouse.StoreNo;
                dic["SourceStoreIdStoreName"] = sourcestoreid_StoreHouse.StoreName;
                dic.Remove("SourceStoreId");
                dic["ApplyFlagName"] = dic["ApplyFlag"].ToString() == "1" ? "是" : "否";
                //出货创客
                int FromUserId = int.Parse(function.CheckInt(dic["FromUserId"].ToString()));
                Users fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == FromUserId) ?? new Users();
                dic["FromUserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["FromUserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("FromUserId");
                //出货仓库
                int FromStoreId = int.Parse(function.CheckInt(dic["FromStoreId"].ToString()));
                StoreHouse fromstoreid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == FromStoreId) ?? new StoreHouse();
                dic["FromStoreIdStoreNo"] = fromstoreid_StoreHouse.StoreNo;
                dic["FromStoreIdStoreName"] = fromstoreid_StoreHouse.StoreName;
                dic.Remove("FromStoreId");
                dic["CancelFlagName"] = dic["CancelFlag"].ToString() == "1" ? "是" : "否";
                //是否占用额度
                int AuthFlag = int.Parse(function.CheckInt(dic["AuthFlag"].ToString()));
                if (AuthFlag == 0) dic["PayMode"] = "否";
                if (AuthFlag == 1) dic["PayMode"] = "是";

            }
            return Json(obj);
        }

        #endregion

    }
}
