/*
 * 机具变动历史
 */

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 StoreChangeHistoryController : BaseController
    {
        public StoreChangeHistoryController(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(StoreChangeHistory data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询机具变动历史列表

        /// <summary>
        /// 机具变动历史列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(StoreChangeHistory data, string UserIdMakerCode, string UserIdRealName, string BrandIdSelect, string TransTypeSelect, string SnTypeSelect, string StockOpDirectSelect, string StoreIdStoreNo, string StoreIdStoreName, string CreateDateData, int page = 1, int limit = 30)
        {

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

            Fields.Add("SnNo", "1"); //SN编号


            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(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }
            //交易类型
            if (!string.IsNullOrEmpty(TransTypeSelect))
            {
                condition += " and TransType=" + TransTypeSelect;
            }
            //SN机具类型
            if (!string.IsNullOrEmpty(SnTypeSelect))
            {
                condition += " and SnType=" + SnTypeSelect;
            }
            //库存操作方向
            if (!string.IsNullOrEmpty(StockOpDirectSelect))
            {
                condition += " and StockOpDirect=" + StockOpDirectSelect;
            }
            //仓库编号
            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 StoreForName 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'";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreChangeHistory", 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["FromUserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                dic.Remove("UserId");
                //接收创客
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users tuserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["TUserIdMakerCode"] = tuserid_Users.MakerCode;
                dic["TUserIdRealName"] = tuserid_Users.RealName;
                dic.Remove("ToUserId");
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //交易类型
                int TransType = int.Parse(dic["TransType"].ToString());
                if (TransType == 1) dic["TransType"] = "调拨";
                if (TransType == 2) dic["TransType"] = "出货";
                if (TransType == 3) dic["TransType"] = "退货";
                if (TransType == 4) dic["TransType"] = "驳回";
                if (TransType == 5) dic["TransType"] = "回仓退款";
                if (TransType == 6) dic["TransType"] = "换机出仓";
                if (TransType == 7) dic["TransType"] = "换机回仓";
                if (TransType == 0) dic["TransType"] = "采购";
                //SN机具类型
                int SnType = int.Parse(dic["SnType"].ToString());
                if (SnType == 0) dic["SnType"] = "兑换机具";
                if (SnType == 1) dic["SnType"] = "循环机具";
                //库存操作方向
                int StockOpDirect = int.Parse(dic["StockOpDirect"].ToString());
                if (StockOpDirect == 0) dic["StockOpDirect"] = "入库";
                if (StockOpDirect == 1) dic["StockOpDirect"] = "出库";
                //创客收货仓库
                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");
                //仓库
                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");

            }
            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(StoreChangeHistory 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("StoreChangeHistory", Fields, 0);
            AddSysLog(data.Id.ToString(), "StoreChangeHistory", "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;


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

        #endregion

        #region 修改机具变动历史

        /// <summary>
        /// 增加或修改机具变动历史信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(StoreChangeHistory 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("StoreChangeHistory", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "StoreChangeHistory", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除机具变动历史信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(StoreChangeHistory data, string UserIdMakerCode, string UserIdRealName, string BrandIdSelect, string TransTypeSelect, string SnTypeSelect, string StockOpDirectSelect, string StoreIdStoreNo, string StoreIdStoreName)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("SnNo", "1"); //SN编号


            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(BrandIdSelect))
            {
                condition += " and BrandId=" + BrandIdSelect;
            }
            //交易类型
            if (!string.IsNullOrEmpty(TransTypeSelect))
            {
                condition += " and TransType=" + TransTypeSelect;
            }
            //SN机具类型
            if (!string.IsNullOrEmpty(SnTypeSelect))
            {
                condition += " and SnType=" + SnTypeSelect;
            }
            //库存操作方向
            if (!string.IsNullOrEmpty(StockOpDirectSelect))
            {
                condition += " and StockOpDirect=" + StockOpDirectSelect;
            }
            //仓库编号
            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 StoreForName where Name='" + StoreIdStoreName + "')";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreChangeHistory", Fields, "Id desc", "0", 1, 20000, condition, "", 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.Remove("UserId");
                //产品类型
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));
                //交易类型
                int TransType = int.Parse(dic["TransType"].ToString());
                if (TransType == 1) dic["TransType"] = "调拨";
                if (TransType == 2) dic["TransType"] = "出货";
                if (TransType == 3) dic["TransType"] = "退货";
                if (TransType == 0) dic["TransType"] = "采购";
                //SN机具类型
                int SnType = int.Parse(dic["SnType"].ToString());
                if (SnType == 0) dic["SnType"] = "兑换机具";
                if (SnType == 1) dic["SnType"] = "循环机具";
                //库存操作方向
                int StockOpDirect = int.Parse(dic["StockOpDirect"].ToString());
                if (StockOpDirect == 0) dic["StockOpDirect"] = "入库";
                if (StockOpDirect == 1) dic["StockOpDirect"] = "出库";
                //接收创客
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users tuserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["TUserIdMakerCode"] = tuserid_Users.MakerCode;
                dic["TUserIdRealName"] = tuserid_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");
                //仓库
                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");

            }

            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>();

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

        #endregion

    }
}
