/*
 * 仓库库存变动信息
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询仓库库存变动信息列表

        /// <summary>
        /// 仓库库存变动信息列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(StoreBalance data, string StoreIdStoreNo, string StoreIdStoreName, string TransTypeSelect, string CreateDateData, string BrandIdSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("TransRecordNo", "1"); //交易流水编号


            string condition = " and Status>-1";
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + StoreIdStoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForStoreName where Name='" + StoreIdStoreName + "')";
            }
            //操作时间
            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(TransTypeSelect))
            {
                condition += " and TransType=" + TransTypeSelect;
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreBalance", 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()));
                StoreHouse storeid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new StoreHouse();
                dic["StoreIdStoreNo"] = storeid_StoreHouse.StoreNo;
                dic["StoreIdStoreName"] = storeid_StoreHouse.StoreName;
                dic.Remove("StoreId");
                //交易类型
                int TransType = int.Parse(dic["TransType"].ToString());
                if (TransType == 0) dic["TransType"] = "入库";
                if (TransType == 1) dic["TransType"] = "调拨";
                if (TransType == 2) dic["TransType"] = "出货";
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //操作符
                string OpSymbol = dic["OpSymbol"].ToString();
                if (OpSymbol == "1") dic["OpSymbol"] = "增加";
                if (OpSymbol == "2") dic["OpSymbol"] = "减少";
                if (OpSymbol == "") dic["OpSymbol"] = "";

            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            int InCount = 0;//入库
            int MoveInCount = 0;//调拨入库
            int MoveOutCount = 0;//调拨出库
            int OutCount = 0;//出库
            DataTable dt = OtherMySqlConn.dtable("select sum(OpStoreNum) from StoreBalance where TransType=0" + condition);
            if (dt.Rows.Count > 0)
            {
                InCount = int.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select sum(OpStoreNum) from StoreBalance where TransType=1 and OpSymbol='+'" + condition);
            if (dt.Rows.Count > 0)
            {
                MoveInCount = int.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select sum(OpStoreNum) from StoreBalance where TransType=1 and OpSymbol='-'" + condition);
            if (dt.Rows.Count > 0)
            {
                MoveOutCount = int.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            dt = OtherMySqlConn.dtable("select sum(OpStoreNum) from StoreBalance where TransType=2" + condition);
            if (dt.Rows.Count > 0)
            {
                OutCount = int.Parse(function.CheckNum(dt.Rows[0][0].ToString()));
            }
            other.Add("InCount", InCount);
            other.Add("MoveInCount", MoveInCount);
            other.Add("MoveOutCount", MoveOutCount);
            other.Add("OutCount", OutCount);
            obj.Add("other", other);
            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(StoreBalance data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


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

            return "success";
        }

        #endregion

        #region 修改仓库库存变动信息

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


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

        #endregion

        #region 修改仓库库存变动信息

        /// <summary>
        /// 增加或修改仓库库存变动信息信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(StoreBalance data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


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

            return "success";
        }

        #endregion

        #region 删除仓库库存变动信息信息

        /// <summary>
        /// 删除仓库库存变动信息信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "StoreBalance", "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("StoreBalance", 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, "StoreBalance", "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("StoreBalance", 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, "StoreBalance", "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("StoreBalance", 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("StoreBalance", Sort, Id);

            AddSysLog(Id.ToString(), "StoreBalance", "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.StoreBalance.Add(new StoreBalance()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(StoreBalance data, string StoreIdStoreNo, string StoreIdStoreName, string TransTypeSelect, string BrandIdSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("TransRecordNo", "1"); //交易流水编号


            string condition = " and Status>-1";
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForStoreNo where StoreNo='" + StoreIdStoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForStoreName where StoreName='" + StoreIdStoreName + "')";
            }
            //交易类型
            if (!string.IsNullOrEmpty(TransTypeSelect))
            {
                condition += " and TransType=" + TransTypeSelect;
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreBalance", Fields, "Id desc", "0", 1, 20000, condition, "StoreId,TransRecordNo,TransType,BrandId,OpStoreNum,OpSymbol,BeforeTotalNum,AfterTotalNum,BeforeLaveNum,AfterLaveNum,BeforeOutNum,AfterOutNum", 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()));
                StoreHouse storeid_StoreHouse = db.StoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new StoreHouse();
                dic["StoreIdStoreNo"] = storeid_StoreHouse.StoreNo;
                dic["StoreIdStoreName"] = storeid_StoreHouse.StoreName;
                dic.Remove("StoreId");
                //交易类型
                int TransType = int.Parse(dic["TransType"].ToString());
                if (TransType == 0) dic["TransType"] = "入库";
                if (TransType == 1) dic["TransType"] = "调拨";
                if (TransType == 2) dic["TransType"] = "出货";
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //操作符
                string OpSymbol = dic["OpSymbol"].ToString();
                if (OpSymbol == "1") dic["OpSymbol"] = "增加";
                if (OpSymbol == "2") dic["OpSymbol"] = "减少";
                if (OpSymbol == "") dic["OpSymbol"] = "";

            }

            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("StoreIdStoreNo", "仓库编号");
            ReturnFields.Add("StoreIdStoreName", "仓库名称");
            ReturnFields.Add("TransRecordNo", "交易流水编号");
            ReturnFields.Add("TransType", "交易类型");
            ReturnFields.Add("BrandId", "产品类型");
            ReturnFields.Add("OpStoreNum", "操作库存数");
            ReturnFields.Add("OpSymbol", "操作符");
            ReturnFields.Add("BeforeTotalNum", "操作前总库存数");
            ReturnFields.Add("AfterTotalNum", "操作后总库存数");
            ReturnFields.Add("BeforeLaveNum", "操作前剩余库存数");
            ReturnFields.Add("AfterLaveNum", "操作后剩余库存数");
            ReturnFields.Add("BeforeOutNum", "操作前出库数");
            ReturnFields.Add("AfterOutNum", "操作后出库数");

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

        #endregion



        #region 快捷导出Excel
        public IActionResult QuickExportExcel(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(string StoreIdStoreNo, string StoreIdStoreName, string TransTypeSelect, string CreateDateData, string BrandIdSelect, string TransRecordNo)
        {

            string condition = " WhERE 1=1 and a.Status>-1";
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and a.StoreId in (select StoreId from StoreForCode where Code='" + StoreIdStoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and a.StoreId in (select StoreId from StoreForStoreName where Name='" + StoreIdStoreName + "')";
            }
            //操作时间
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and a.CreateDate>='" + start + " 00:00:00' and a.CreateDate<='" + end + " 23:59:59'";
            }
            //交易类型
            if (!string.IsNullOrEmpty(TransTypeSelect))
            {
                condition += " and a.TransType=" + TransTypeSelect;
            }
            //产品类型
            if (!string.IsNullOrEmpty(BrandIdSelect))
            {
                condition += " and a.BrandId=" + BrandIdSelect;
            }
            var Sql = "SELECT b.StoreNo '仓库编号',b.StoreName '仓库名称',a.TransRecordNo '交易流水编号',(CASE WHEN a.TransType=0 THEN '入库' WHEN a.TransType=1 THEN '调拨' WHEN a.TransType=2 THEN '出货' ELSE '' end) '交易类型',c.`Name` '产品类型',a.OpStoreNum '操作库存数',a.OpSymbol '操作符',a.BeforeTotalNum '操作前总库存数',a.AfterTotalNum '操作后总库存数',a.BeforeLaveNum '操作前剩余库存数',a.AfterLaveNum '操作后剩余库存数',a.BeforeOutNum '操作前出库数',a.AfterOutNum '操作后出库数' FROM StoreBalance a LEFT JOIN StoreHouse b ON a.StoreId=b.Id LEFT JOIN KqProducts c ON a.BrandId=c.Id" + condition + "";
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "仓库库存变动记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion

    }
}
