/*
 * 仓库
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
using System.Threading;
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 StoreHouseController : BaseController
    {
        public StoreHouseController(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(StoreHouse data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询仓库列表

        /// <summary>
        /// 仓库列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(StoreHouse data, string UserIdMakerCode, string UserIdRealName, string ManageUserIdRealName, string ManageUserIdMobile, string ManageUserIdMakerCode, string StoreStatusSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("StoreNo", "1"); //仓库编号
            Fields.Add("StoreName", "1"); //仓库名称
            Fields.Add("ManagerEmail", "1"); //管理者邮箱


            string condition = " and Status>-1";
            //仓库归属人创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //仓库归属人真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + UserIdRealName + "')";
            }
            //仓库管理员真实姓名
            if (!string.IsNullOrEmpty(ManageUserIdRealName))
            {
                condition += " and ManageUserId in (select ManageUserId from UserForRealName where RealName='" + ManageUserIdRealName + "')";
            }
            //仓库管理员手机号
            if (!string.IsNullOrEmpty(ManageUserIdMobile))
            {
                condition += " and ManageUserId in (select ManageUserId from UserForMobile where Mobile='" + ManageUserIdMobile + "')";
            }
            //仓库管理员创客编号
            if (!string.IsNullOrEmpty(ManageUserIdMakerCode))
            {
                condition += " and ManageUserId in (select ManageUserId from UserForMakerCode where MakerCode='" + ManageUserIdMakerCode + "')";
            }
            //仓库状态
            if (!string.IsNullOrEmpty(StoreStatusSelect))
            {
                condition += " and StoreStatus=" + StoreStatusSelect;
            }
            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'";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreHouse", 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 UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandList(dic["BrandId"].ToString());
                //仓库管理员
                int ManageUserId = int.Parse(function.CheckInt(dic["ManageUserId"].ToString()));
                Users manageuserid_Users = db.Users.FirstOrDefault(m => m.Id == ManageUserId) ?? new Users();
                dic["ManageUserIdRealName"] = manageuserid_Users.RealName;
                dic["ManageUserIdMobile"] = manageuserid_Users.Mobile;
                dic["ManageUserIdMakerCode"] = manageuserid_Users.MakerCode;
                //仓库类型
                int StoreType = int.Parse(dic["StoreType"].ToString());
                if (StoreType == 0) dic["StoreType"] = "实体仓";
                if (StoreType == 1) dic["StoreType"] = "虚拟仓";
                //仓库状态
                int StoreStatus = int.Parse(dic["StoreStatus"].ToString());
                if (StoreStatus == 1) dic["StoreStatus"] = "启用";
                if (StoreStatus == 0) dic["StoreStatus"] = "禁用";
                //仓库归属类型
                int StoreKind = int.Parse(dic["StoreKind"].ToString());
                if (StoreKind == 0) dic["StoreKind"] = "分仓";
                if (StoreKind == 1) dic["StoreKind"] = "总仓";

            }
            return Json(obj);
        }

        #endregion

        #region 增加仓库

        /// <summary>
        /// 增加或修改仓库信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 增加仓库

        /// <summary>
        /// 增加或修改仓库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(StoreHouse data, string ManageMakerCode, string MakerCode)
        {
            string BrandIdString = data.BrandId;
            if (!string.IsNullOrEmpty(BrandIdString))
            {
                string[] BrandIdList = BrandIdString.Split(',');
                foreach (string BrandId in BrandIdList)
                {
                    Dictionary<string, object> Fields = new Dictionary<string, object>();
                    Fields.Add("CreateMan", SysUserName); //创建人
                    Fields.Add("StoreName", data.StoreName); //仓库名称
                    UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
                    if (user == null)
                    {
                        return "您输入的仓库归属创客编号不存在，请重新输入正确的仓库归属创客编号";
                    }
                    Fields.Add("UserId", user.UserId); //仓库归属人
                    Fields.Add("Areas", data.Areas); //所属地区
                    Fields.Add("Address", data.Address); //仓库地址
                    UserForMakerCode manage = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == ManageMakerCode);
                    if (manage == null)
                    {
                        return "您输入的仓库负责人编号不存在，请重新输入正确的仓库负责人编号";
                    }
                    Fields.Add("ManageUserId", manage.UserId); //仓库管理员
                    Fields.Add("ManagerEmail", data.ManagerEmail); //管理者邮箱
                    Fields.Add("ManageMobile", data.ManageMobile);
                    Fields.Add("Remark", data.Remark); //备注
                    Fields.Add("LimitTopUserId", data.LimitTopUserId); //限制创客特殊仓库
                    Fields.Add("StoreKind", data.StoreKind); //仓库归属类型
                    int bid = int.Parse(BrandId);
                    KqProducts pro = db.KqProducts.FirstOrDefault(m => m.Id == bid) ?? new KqProducts();
                    Fields.Add("BrandId", BrandId);
                    Fields.Add("ProductName", pro.Name);
                    Fields.Add("StoreStatus", 1);
                    Fields.Add("Status", 1);

                    int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("StoreHouse", Fields, 0);
                    StoreHouse edit = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
                    if (edit != null)
                    {
                        string No = Id.ToString();
                        for (int i = 0; i < 7 - Id.ToString().Length; i++)
                        {
                            No = "0" + No;
                        }
                        No = "S" + No;
                        edit.StoreNo = No;
                        db.StoreForCode.Add(new StoreForCode()
                        {
                            Code = No,
                            StoreId = Id,
                        });
                        RedisDbconn.Instance.Set("StoreForCode:" + No, Id);
                    }
                    db.StoreForName.Add(new StoreForName()
                    {
                        Name = data.StoreName,
                        StoreId = Id,
                    });
                    RedisDbconn.Instance.Set("StoreForName:" + data.StoreName, Id);
                    AddSysLog(data.Id.ToString(), "StoreHouse", "add");
                    db.SaveChanges();

                    SetRedis(Id, user.UserId);
                }
            }
            return "success";
        }

        #endregion

        #region 修改仓库

        /// <summary>
        /// 增加或修改仓库信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            StoreHouse editData = db.StoreHouse.FirstOrDefault(m => m.Id == Id) ?? new StoreHouse();
            ViewBag.data = editData;

            Users manage = db.Users.FirstOrDefault(m => m.Id == editData.ManageUserId) ?? new Users();
            ViewBag.ManageMakerCode = manage.MakerCode;
            ViewBag.ManageRealName = manage.RealName;

            Users user = db.Users.FirstOrDefault(m => m.Id == editData.ManageUserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            return View();
        }

        #endregion

        #region 修改仓库

        /// <summary>
        /// 增加或修改仓库信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(StoreHouse data, string ManageMakerCode, string MakerCode)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("CreateMan", SysUserName); //创建人
            Fields.Add("StoreName", data.StoreName); //仓库名称
            UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
            if (user == null)
            {
                return "您输入的仓库归属创客编号不存在，请重新输入正确的仓库归属创客编号";
            }
            Fields.Add("UserId", user.UserId); //仓库归属人
            Fields.Add("Areas", data.Areas); //所属地区
            Fields.Add("Address", data.Address); //仓库地址
            UserForMakerCode manage = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == ManageMakerCode);
            if (manage == null)
            {
                return "您输入的仓库负责人编号不存在，请重新输入正确的仓库负责人编号";
            }
            Fields.Add("ManageUserId", manage.UserId); //仓库管理员
            Fields.Add("ManagerEmail", data.ManagerEmail); //管理者邮箱
            Fields.Add("ManageMobile", data.ManageMobile);
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("LimitTopUserId", data.LimitTopUserId); //限制创客特殊仓库
            Fields.Add("StoreKind", data.StoreKind); //仓库归属类型
            Fields.Add("Status", data.Status);
            Fields.Add("StoreStatus", data.Status);

            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("StoreHouse", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "StoreHouse", "update");
            db.SaveChanges();

            SetRedis(data.Id, user.UserId);

            return "success";
        }

        #endregion


        #region 一键添加仓库

        /// <summary>
        /// 一件添加仓库
        /// </summary>
        /// <returns></returns>
        public IActionResult Edits(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            StoreHouse editData = db.StoreHouse.FirstOrDefault(m => m.Id == Id) ?? new StoreHouse();
            ViewBag.data = editData;

            Users manage = db.Users.FirstOrDefault(m => m.Id == editData.ManageUserId) ?? new Users();
            ViewBag.ManageMakerCode = manage.MakerCode;
            ViewBag.ManageRealName = manage.RealName;

            Users user = db.Users.FirstOrDefault(m => m.Id == editData.ManageUserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            return View();
        }

        #endregion

        #region 一键添加仓库

        /// <summary>
        /// 一键添加仓库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edits(StoreHouse data, string ManageMakerCode, string MakerCode)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            StoreHouse storeHouse = db.StoreHouse.FirstOrDefault(m => m.Id == data.Id);
            var brand = db.StoreHouse.FirstOrDefault(m => m.UserId == storeHouse.UserId && m.BrandId == data.BrandId);
            if (brand != null)
            {
                return "您已有该品牌类型的仓库，请重新选择";
            }
            var name = db.StoreHouse.FirstOrDefault(m => m.UserId == storeHouse.UserId && m.StoreName == data.StoreName);
            if (name != null)
            {
                return "您的仓库名重复，请重新填写";
            }
            Fields.Add("StoreName", data.StoreName); //仓库名称
            UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
            if (user == null)
            {
                return "您输入的仓库归属创客编号不存在，请重新输入正确的仓库归属创客编号";
            }
            Fields.Add("UserId", user.UserId); //仓库归属人
            Fields.Add("Areas", data.Areas); //所属地区
            Fields.Add("Address", data.Address); //仓库地址
            UserForMakerCode manage = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == ManageMakerCode);
            if (manage == null)
            {
                return "您输入的仓库负责人编号不存在，请重新输入正确的仓库负责人编号";
            }
            Fields.Add("CreateMan", SysUserName); //创建人
            Fields.Add("ManageUserId", manage.UserId); //仓库管理员
            Fields.Add("ManagerEmail", data.ManagerEmail); //管理者邮箱
            Fields.Add("ManageMobile", data.ManageMobile);
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("LimitTopUserId", data.LimitTopUserId); //限制创客特殊仓库
            Fields.Add("StoreKind", data.StoreKind); //仓库归属类型
            int bid = Convert.ToInt32(data.BrandId);
            KqProducts pro = db.KqProducts.FirstOrDefault(m => m.Id == bid) ?? new KqProducts();
            Fields.Add("BrandId", data.BrandId);
            Fields.Add("ProductName", pro.Name);
            Fields.Add("StoreStatus", 1);
            Fields.Add("Status", 1);

            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("StoreHouse", Fields, 0);
            StoreHouse edit = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
            if (edit != null)
            {
                string No = Id.ToString();
                for (int i = 0; i < 7 - Id.ToString().Length; i++)
                {
                    No = "0" + No;
                }
                No = "S" + No;
                edit.StoreNo = No;
                db.StoreForCode.Add(new StoreForCode()
                {
                    Code = No,
                    StoreId = Id,
                });
                RedisDbconn.Instance.Set("StoreForCode:" + No, Id);
            }
            db.StoreForName.Add(new StoreForName()
            {
                Name = data.StoreName,
                StoreId = Id,
            });
            RedisDbconn.Instance.Set("StoreForName:" + data.StoreName, Id);
            AddSysLog(data.Id.ToString(), "StoreHouse", "add");
            db.SaveChanges();

            SetRedis(Id, user.UserId);
            return "success";
        }

        #endregion


        #region 删除仓库信息

        /// <summary>
        /// 删除仓库信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "StoreHouse", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                StoreHouse edit = db.StoreHouse.FirstOrDefault(m => m.Id == id);
                if (edit != null)
                {
                    StoreForCode code = db.StoreForCode.FirstOrDefault(m => m.Code == edit.StoreNo);
                    if (code != null)
                    {
                        db.StoreForCode.Remove(code);
                    }
                    StoreForName name = db.StoreForName.FirstOrDefault(m => m.Name == edit.StoreName);
                    if (name != null)
                    {
                        db.StoreForName.Remove(name);
                    }
                }
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("StoreHouse", 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, "StoreHouse", "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("StoreHouse", 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, "StoreHouse", "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("StoreHouse", 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("StoreHouse", Sort, Id);

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

        #region 导入数据

        public IActionResult Import(string right, string ExcelKind)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.ExcelKind = ExcelKind;
            return View();
        }
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        [HttpPost]
        public string ImportPost(string ExcelPath, int Kind = 0)
        {
            // RedisDbconn.Instance.AddList("ExcelImport", ExcelPath + "#cut#" + Kind);
            string key = function.MD5_16(Guid.NewGuid().ToString());
            RedisDbconn.Instance.AddList("ExcelImportV2", ExcelPath + "#cut#" + Kind + "#cut#" + key + "#cut#" + SysUserName);
            return "success|" + key;
        }

        // [HttpPost]
        // public Dictionary<string, object> ImportPostV2(string ExcelPath, int Kind = 0)
        // {
        //     Dictionary<string, object> Obj = new Dictionary<string, object>();
        //     string key = function.MD5_16(Guid.NewGuid().ToString());
        //     RedisDbconn.Instance.AddList("ExcelImportV2", ExcelPath + "#cut#" + Kind + "#cut#" + key);
        //     Obj.Add("status", "success");
        //     Obj.Add("key", key);
        //     Obj.Add("errlist", RedisDbconn.Instance.GetList<string>("ErrList" + key));
        //     return Obj;
        // }
        public string CheckImport(string key)
        {
            string result = RedisDbconn.Instance.Get<string>("CheckImport:" + key);
            if (!string.IsNullOrEmpty(result))
            {
                string[] datalist = result.Split('|');
                if (datalist[0] == "success")
                {
                    return result;
                }
                return datalist[0];
            }
            return "0";
        }
        public Dictionary<string, object> CheckImportV2(string key)
        {
            Dictionary<string, object> Obj = new Dictionary<string, object>();
            string result = RedisDbconn.Instance.Get<string>("CheckImport:" + key);
            if (!string.IsNullOrEmpty(result))
            {
                string[] datalist = result.Split('|');
                if (datalist[0] == "success")
                {
                    List<string> errList = RedisDbconn.Instance.GetList<string>("ErrList" + key);
                    if (errList.Count > 0)
                    {
                        Obj.Add("status", 2);
                        Obj.Add("errList", errList);
                    }
                    else
                    {
                        Obj.Add("status", 1);
                        Obj.Add("data", result);
                    }
                    return Obj;
                }
                Obj.Add("status", 0);
                Obj.Add("data", datalist[0]);
                return Obj;
            }
            Obj.Add("status", -1);
            Obj.Add("data", "执行中...");
            return Obj;
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(StoreHouse data, string UserIdMakerCode, string UserIdRealName, string ManageUserIdRealName, string ManageUserIdMobile, string ManageUserIdMakerCode, string StoreStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("StoreNo", "1"); //仓库编号
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("StoreName", "1"); //仓库名称
            Fields.Add("ManagerEmail", "1"); //管理者邮箱


            string condition = " and Status>-1";
            //仓库归属人创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //仓库归属人真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + UserIdRealName + "')";
            }
            //仓库管理员真实姓名
            if (!string.IsNullOrEmpty(ManageUserIdRealName))
            {
                condition += " and ManageUserId in (select ManageUserId from UserForRealName where RealName='" + ManageUserIdRealName + "')";
            }
            //仓库管理员手机号
            if (!string.IsNullOrEmpty(ManageUserIdMobile))
            {
                condition += " and ManageUserId in (select ManageUserId from UserForMobile where Mobile='" + ManageUserIdMobile + "')";
            }
            //仓库管理员创客编号
            if (!string.IsNullOrEmpty(ManageUserIdMakerCode))
            {
                condition += " and ManageUserId in (select ManageUserId from UserForMakerCode where MakerCode='" + ManageUserIdMakerCode + "')";
            }
            //仓库状态
            if (!string.IsNullOrEmpty(StoreStatusSelect))
            {
                condition += " and StoreStatus=" + StoreStatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreHouse", Fields, "Id desc", "0", 1, 20000, condition, "StoreNo,StoreName,UserId,BrandId,Address,ManageUserId,ManagerEmail,StoreType,TotalNum,LaveNum,OutNum,LimitTopUserId,StoreStatus,StoreKind", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //仓库归属人
                int UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandList(dic["BrandId"].ToString());
                //仓库管理员
                int ManageUserId = int.Parse(function.CheckInt(dic["ManageUserId"].ToString()));
                Users manageuserid_Users = db.Users.FirstOrDefault(m => m.Id == ManageUserId) ?? new Users();
                dic["ManageUserIdRealName"] = manageuserid_Users.RealName;
                dic["ManageUserIdMobile"] = manageuserid_Users.Mobile;
                dic["ManageUserIdMakerCode"] = manageuserid_Users.MakerCode;
                //仓库类型
                int StoreType = int.Parse(dic["StoreType"].ToString());
                if (StoreType == 0) dic["StoreType"] = "实体仓";
                if (StoreType == 1) dic["StoreType"] = "虚拟仓";
                //仓库状态
                int StoreStatus = int.Parse(dic["StoreStatus"].ToString());
                if (StoreStatus == 1) dic["StoreStatus"] = "启用";
                if (StoreStatus == 0) dic["StoreStatus"] = "禁用";
                //仓库归属类型
                int StoreKind = int.Parse(dic["StoreKind"].ToString());
                if (StoreKind == 0) dic["StoreKind"] = "分仓";
                if (StoreKind == 1) dic["StoreKind"] = "总仓";

            }

            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("StoreNo", "仓库编号");
            ReturnFields.Add("StoreName", "仓库名称");
            ReturnFields.Add("UserIdMakerCode", "仓库归属人创客编号");
            ReturnFields.Add("UserIdRealName", "仓库归属人真实姓名");
            ReturnFields.Add("BrandId", "产品类型");
            ReturnFields.Add("Address", "仓库地址");
            ReturnFields.Add("ManageUserIdRealName", "仓库管理员真实姓名");
            ReturnFields.Add("ManageUserIdMobile", "仓库管理员手机号");
            ReturnFields.Add("ManageUserIdMakerCode", "仓库管理员创客编号");
            ReturnFields.Add("ManagerEmail", "管理者邮箱");
            ReturnFields.Add("StoreType", "仓库类型");
            ReturnFields.Add("TotalNum", "总库存数");
            ReturnFields.Add("LaveNum", "剩余库存数");
            ReturnFields.Add("OutNum", "出库数");
            ReturnFields.Add("LimitTopUserId", "限制创客特殊仓库");
            ReturnFields.Add("StoreStatus", "仓库状态");
            ReturnFields.Add("StoreKind", "仓库归属类型");

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

        #endregion





        #region 仓库列表

        /// <summary>
        /// 根据条件查询仓库列表
        /// </summary>
        /// <returns></returns>
        public IActionResult Stat(StoreHouse data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询仓库列表

        /// <summary>
        /// 仓库列表
        /// </summary>
        /// <returns></returns>
        public JsonResult StatDo(string CreateDateData, int page = 1, int limit = 30)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["StatSqlConnStr"].ToString();
            string sCreateDate = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
            string eCreateDate = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                sCreateDate = datelist[0] + " 00:00:00";
                eCreateDate = datelist[1] + " 23:59:59";
            }
            else
            {
                Dictionary<string, object> nodata = new Dictionary<string, object>();
                nodata.Add("code", 0);
                nodata.Add("msg", "");
                nodata.Add("count", 0);
                nodata.Add("data", new List<Dictionary<string, object>>());

                return Json(nodata);
            }
            string minId = "0";
            string maxId = "0";
            string minPosId = "0";
            string maxPosId = "0";
            DataTable startDt = OtherMySqlConn.dtable("select min(Id) from StoreStockChange where CreateDate>='" + sCreateDate + "'");
            if (startDt.Rows.Count > 0)
            {
                minId = function.CheckInt(startDt.Rows[0][0].ToString());
                if (minId == "0")
                {
                    startDt = OtherMySqlConn.dtable("select max(Id) from StoreStockChange");
                    if (startDt.Rows.Count > 0)
                    {
                        minId = function.CheckInt(startDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable endDt = OtherMySqlConn.dtable("select max(Id) from StoreStockChange where CreateDate>='" + sCreateDate + "'");
            if (endDt.Rows.Count > 0)
            {
                maxId = function.CheckInt(endDt.Rows[0][0].ToString());
                if (minId == "0")
                {
                    endDt = OtherMySqlConn.dtable("select max(Id) from StoreStockChange");
                    if (endDt.Rows.Count > 0)
                    {
                        maxId = function.CheckInt(endDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable startPosDt = OtherMySqlConn.dtable("select min(Id) from PosMachinesTwo where ActivationTime>='" + sCreateDate + "'");
            if (startPosDt.Rows.Count > 0)
            {
                minPosId = function.CheckInt(startPosDt.Rows[0][0].ToString());
                if (minPosId == "0")
                {
                    startPosDt = OtherMySqlConn.dtable("select max(Id) from PosMachinesTwo");
                    if (startPosDt.Rows.Count > 0)
                    {
                        minPosId = function.CheckInt(startPosDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable endPosDt = OtherMySqlConn.dtable("select max(Id) from PosMachinesTwo where ActivationTime>='" + sCreateDate + "'");
            if (endPosDt.Rows.Count > 0)
            {
                maxPosId = function.CheckInt(endPosDt.Rows[0][0].ToString());
                if (maxPosId == "0")
                {
                    endPosDt = OtherMySqlConn.dtable("select max(Id) from PosMachinesTwo");
                    if (endPosDt.Rows.Count > 0)
                    {
                        maxPosId = function.CheckInt(endPosDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable list = OtherMySqlConn.dtable("select * from (select s.StoreName,s.StoreNo,u.RealName,u.Mobile,k.Name,s.LaveNum,(select count(Id) from StoreStockChange where Id>=" + minId + " and Id<=" + maxId + " and CreateDate>='" + sCreateDate + "' and CreateDate<='" + eCreateDate + "' and StoreId=s.Id and TransType=1) as c1,(select count(Id) from StoreStockChange where Id>=" + minId + " and Id<=" + maxId + " and CreateDate>='" + sCreateDate + "' and CreateDate<='" + eCreateDate + "' and StoreId=s.Id and TransType in (10,11,2)) as c2,(select count(Id) from PosMachinesTwo where Id>=" + minPosId + " and Id<=" + maxPosId + " and ActivationState=1 and ActivationTime>='" + sCreateDate + "' and ActivationTime<='" + eCreateDate + "' and StoreId=s.Id) as c3 from StoreHouse s left join Users u on s.BrandId>0 and s.UserId=u.Id left join KqProducts k on s.BrandId=k.Id) tb where c1>0 or c2>0 or c3>0");

            int recordcount = list.Rows.Count;
            List<Dictionary<string, object>> diclist = new List<Dictionary<string, object>>();
            foreach (DataRow sub in list.Rows)
            {
                Dictionary<string, object> row = new Dictionary<string, object>();
                row.Add("StoreName", sub["StoreName"].ToString());
                row.Add("StoreNo", sub["StoreNo"].ToString());
                row.Add("Mobile", sub["Mobile"].ToString());
                row.Add("RealName", sub["RealName"].ToString());
                row.Add("Name", sub["Name"].ToString());
                row.Add("LaveNum", sub["LaveNum"].ToString());
                row.Add("c1", sub["c1"].ToString());
                row.Add("c2", sub["c2"].ToString());
                row.Add("c3", sub["c3"].ToString());
                diclist.Add(row);
            }

            Dictionary<string, object> obj = new Dictionary<string, object>();
            obj.Add("code", 0);
            obj.Add("msg", "");
            obj.Add("count", recordcount);
            obj.Add("data", diclist);

            return Json(obj);
        }

        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult StatExportExcel(string CreateDateData)
        {
            OtherMySqlConn.connstr = ConfigurationManager.AppSettings["StatSqlConnStr"].ToString();
            string sCreateDate = DateTime.Now.ToString("yyyy-MM-dd") + " 00:00:00";
            string eCreateDate = DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59";
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                sCreateDate = datelist[0] + " 00:00:00";
                eCreateDate = datelist[1] + " 23:59:59";
            }
            else
            {
                Dictionary<string, object> nodata = new Dictionary<string, object>();
                nodata.Add("Status", "1");
                nodata.Add("Info", "分仓统计数据报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
                nodata.Add("Obj", new List<Dictionary<string, object>>());
                Dictionary<string, object> NoDataReturnFields = new Dictionary<string, object>();
                NoDataReturnFields.Add("StoreName", "仓库名称");
                NoDataReturnFields.Add("StoreNo", "仓库编号");
                NoDataReturnFields.Add("Mobile", "仓库所属人手机号");
                NoDataReturnFields.Add("RealName", "仓库所属人名称");
                NoDataReturnFields.Add("Name", "品牌");
                NoDataReturnFields.Add("LaveNum", "当前库存");
                NoDataReturnFields.Add("c1", "出库(调拨)量");
                NoDataReturnFields.Add("c2", "出货(发货到创客)量");
                NoDataReturnFields.Add("c3", "激活量");
                nodata.Add("Fields", NoDataReturnFields);
                return Json(nodata);
            }
            string minId = "0";
            string maxId = "0";
            string minPosId = "0";
            string maxPosId = "0";
            DataTable startDt = OtherMySqlConn.dtable("select min(Id) from StoreStockChange where CreateDate>='" + sCreateDate + "'");
            if (startDt.Rows.Count > 0)
            {
                minId = function.CheckInt(startDt.Rows[0][0].ToString());
                if (minId == "0")
                {
                    startDt = OtherMySqlConn.dtable("select max(Id) from StoreStockChange");
                    if (startDt.Rows.Count > 0)
                    {
                        minId = function.CheckInt(startDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable endDt = OtherMySqlConn.dtable("select max(Id) from StoreStockChange where CreateDate>='" + sCreateDate + "'");
            if (endDt.Rows.Count > 0)
            {
                maxId = function.CheckInt(endDt.Rows[0][0].ToString());
                if (minId == "0")
                {
                    endDt = OtherMySqlConn.dtable("select max(Id) from StoreStockChange");
                    if (endDt.Rows.Count > 0)
                    {
                        maxId = function.CheckInt(endDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable startPosDt = OtherMySqlConn.dtable("select min(Id) from PosMachinesTwo where ActivationTime>='" + sCreateDate + "'");
            if (startPosDt.Rows.Count > 0)
            {
                minPosId = function.CheckInt(startPosDt.Rows[0][0].ToString());
                if (minPosId == "0")
                {
                    startPosDt = OtherMySqlConn.dtable("select max(Id) from PosMachinesTwo");
                    if (startPosDt.Rows.Count > 0)
                    {
                        minPosId = function.CheckInt(startPosDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable endPosDt = OtherMySqlConn.dtable("select max(Id) from PosMachinesTwo where ActivationTime>='" + sCreateDate + "'");
            if (endPosDt.Rows.Count > 0)
            {
                maxPosId = function.CheckInt(endPosDt.Rows[0][0].ToString());
                if (maxPosId == "0")
                {
                    endPosDt = OtherMySqlConn.dtable("select max(Id) from PosMachinesTwo");
                    if (endPosDt.Rows.Count > 0)
                    {
                        maxPosId = function.CheckInt(endPosDt.Rows[0][0].ToString());
                    }
                }
            }
            DataTable list = OtherMySqlConn.dtable("select * from (select s.StoreName,s.StoreNo,u.RealName,u.Mobile,k.Name,s.LaveNum,(select count(Id) from StoreStockChange where Id>=" + minId + " and Id<=" + maxId + " and CreateDate>='" + sCreateDate + "' and CreateDate<='" + eCreateDate + "' and StoreId=s.Id and TransType=1) as c1,(select count(Id) from StoreStockChange where Id>=" + minId + " and Id<=" + maxId + " and CreateDate>='" + sCreateDate + "' and CreateDate<='" + eCreateDate + "' and StoreId=s.Id and TransType in (10,11,2)) as c2,(select count(Id) from PosMachinesTwo where Id>=" + minPosId + " and Id<=" + maxPosId + " and ActivationState=1 and ActivationTime>='" + sCreateDate + "' and ActivationTime<='" + eCreateDate + "' and StoreId=s.Id) as c3 from StoreHouse s left join Users u on s.BrandId>0 and s.UserId=u.Id left join KqProducts k on s.BrandId=k.Id) tb where c1>0 or c2>0 or c3>0");

            int recordcount = list.Rows.Count;
            List<Dictionary<string, object>> diclist = new List<Dictionary<string, object>>();
            foreach (DataRow sub in list.Rows)
            {
                Dictionary<string, object> row = new Dictionary<string, object>();
                row.Add("StoreName", sub["StoreName"].ToString());
                row.Add("StoreNo", sub["StoreNo"].ToString());
                row.Add("Mobile", sub["Mobile"].ToString());
                row.Add("RealName", sub["RealName"].ToString());
                row.Add("Name", sub["Name"].ToString());
                row.Add("LaveNum", sub["LaveNum"].ToString());
                row.Add("c1", sub["c1"].ToString());
                row.Add("c2", sub["c2"].ToString());
                row.Add("c3", sub["c3"].ToString());
                diclist.Add(row);
            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "分仓统计数据报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();
            ReturnFields.Add("StoreName", "仓库名称");
            ReturnFields.Add("StoreNo", "仓库编号");
            ReturnFields.Add("Mobile", "仓库所属人手机号");
            ReturnFields.Add("RealName", "仓库所属人名称");
            ReturnFields.Add("Name", "品牌");
            ReturnFields.Add("LaveNum", "当前库存");
            ReturnFields.Add("c1", "出库(调拨)量");
            ReturnFields.Add("c2", "出货(发货到创客)量");
            ReturnFields.Add("c3", "激活量");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "StoreHouse", "StatExportExcel");
            return Json(result);
        }

        #endregion


        #region 同步数据

        /// <summary>
        /// 同步数据
        /// </summary>
        /// <returns></returns>
        public string SycnData(int Id = 0)
        {
            if (Id > 0)
            {
                DataTable dt = OtherMySqlConn.dtable("select Id,(select count(Id) from PosMachinesTwo where StoreId=s.Id and UserId=0 and PreUserId=0 and Status>-1) as CurLaveNum from StoreHouse s where Id=" + Id);
                if (dt.Rows.Count > 0)
                {
                    int CurLaveNum = int.Parse(function.CheckInt(dt.Rows[0]["CurLaveNum"].ToString()));
                    StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
                    if (store != null)
                    {
                        store.LaveNum = CurLaveNum;
                        db.SaveChanges();
                    }
                }
            }
            else
            {
                DataTable dt = OtherMySqlConn.dtable("select s.Id,LaveNum,count(p.Id) as CurLaveNum from StoreHouse s left join PosMachinesTwo p on s.Id=p.StoreId and s.BrandId=p.BrandId and p.UserId=0 and p.PreUserId=0 and p.Status>-1 group by s.Id HAVING LaveNum!=count(p.Id)");
                foreach (DataRow dr in dt.Rows)
                {
                    int StoreId = int.Parse(function.CheckInt(dr["Id"].ToString()));
                    int CurLaveNum = int.Parse(function.CheckInt(dr["CurLaveNum"].ToString()));
                    StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == StoreId);
                    if (store != null)
                    {
                        store.LaveNum = CurLaveNum;
                        db.SaveChanges();
                    }
                }
            }
            AddSysLog(Id, "StoreHouse", "SycnData");
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 设置缓存

        private void SetRedis(int Id, int UserId)
        {
            if (UserId > 0)
            {
                RedisDbconn.Instance.Clear("StoreHouseList:" + UserId);
                List<StoreHouse> stores = db.StoreHouse.Where(m => m.Status > -1 && m.UserId == UserId).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();

                RedisDbconn.Instance.Clear("StoreHouse");
                stores = db.StoreHouse.Where(m => m.Status > -1).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();
            }
            if (Id > 0)
            {
                StoreHouse edit = db.StoreHouse.FirstOrDefault(m => m.Id == Id);
                if (edit != null)
                {
                    RedisDbconn.Instance.Clear("StoreHouse:" + Id);
                }
            }
        }

        #endregion

    }
}
