/*
 * 仓库订单汇总
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询仓库订单汇总列表

        /// <summary>
        /// 仓库订单汇总列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(StoreMallOrderSummary data, string StoreNo, string StoreName, string AgentStoreNo, string AgentStoreName, string SettleStatusSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("CreateDate", "3"); //交易日期
            Fields.Add("BrandId", "1"); //品牌

            string condition = " and Status>-1";
            //仓库编号
            if (!string.IsNullOrEmpty(StoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + StoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForName where Name='" + StoreName + "')";
            }
            //代理分仓编号
            if (!string.IsNullOrEmpty(AgentStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + AgentStoreNo + "')";
            }
            //代理分仓名称
            if (!string.IsNullOrEmpty(AgentStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForName where Name='" + AgentStoreName + "')";
            }
            //结算状态
            if(!string.IsNullOrEmpty(SettleStatusSelect))
            {
                condition += " and SettleStatus=" + SettleStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreMallOrderSummary", 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)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));

                //仓库
                int StoreId = int.Parse(dic["StoreId"].ToString());
                StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new StoreHouse();
                dic["StoreNo"] = store.StoreNo;
                dic["StoreName"] = store.StoreName;

                //代理分仓
                int AgentStoreId = int.Parse(dic["AgentStoreId"].ToString());
                StoreHouse astore = db.StoreHouse.FirstOrDefault(m => m.Id == AgentStoreId) ?? new StoreHouse();
                dic["AgentStoreNo"] = astore.StoreNo;
                dic["AgentStoreName"] = astore.StoreName;

                //结算状态
                int SettleStatus = int.Parse(dic["SettleStatus"].ToString());
                if(SettleStatus == 0) dic["SettleStatus"] = "未结算";
                if(SettleStatus == 1) dic["SettleStatus"] = "已结算";
                
                //交易日期
                dic["CreateDate"] = string.IsNullOrEmpty(dic["CreateDate"].ToString()) ? "" : DateTime.Parse(dic["CreateDate"].ToString()).ToString("yyyy-MM-dd");
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            other.Add("OrderCount", 0);
            other.Add("OrderAmt", 0);
            other.Add("ReturnOrderCount", 0);
            other.Add("ReturnAmt", 0);
            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(StoreMallOrderSummary 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("StoreMallOrderSummary", Fields, 0);
            AddSysLog(data.Id.ToString(), "StoreMallOrderSummary", "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;


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

        #endregion

        #region 修改仓库订单汇总

        /// <summary>
        /// 增加或修改仓库订单汇总信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(StoreMallOrderSummary 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("StoreMallOrderSummary", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "StoreMallOrderSummary", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除仓库订单汇总信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(StoreMallOrderSummary data, string StoreNo, string StoreName, string AgentStoreNo, string AgentStoreName, string SettleStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("CreateDate", "3"); //交易日期
            Fields.Add("BrandId", "1"); //品牌

            string condition = " and Status>-1";
            //仓库编号
            if (!string.IsNullOrEmpty(StoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + StoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForName where Name='" + StoreName + "')";
            }
            //代理分仓编号
            if (!string.IsNullOrEmpty(AgentStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreForCode where Code='" + AgentStoreNo + "')";
            }
            //代理分仓名称
            if (!string.IsNullOrEmpty(AgentStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreForName where Name='" + AgentStoreName + "')";
            }
            //结算状态
            if(!string.IsNullOrEmpty(SettleStatusSelect))
            {
                condition += " and SettleStatus=" + SettleStatusSelect;
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("StoreMallOrderSummary", Fields, "Id desc", "0", 1, 20000, condition, "TradeMonth,StoreId,AgentStoreId,BrandId,UnitPrice,OrderNum,OrderAmt,RefundOrderNum,RefundAmt,SettleStatus,Remark", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));

                //仓库
                int StoreId = int.Parse(dic["StoreId"].ToString());
                StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == StoreId) ?? new StoreHouse();
                dic["StoreNo"] = store.StoreNo;
                dic["StoreName"] = store.StoreName;

                //代理分仓
                int AgentStoreId = int.Parse(dic["AgentStoreId"].ToString());
                StoreHouse astore = db.StoreHouse.FirstOrDefault(m => m.Id == AgentStoreId) ?? new StoreHouse();
                dic["AgentStoreNo"] = astore.StoreNo;
                dic["AgentStoreName"] = astore.StoreName;

                //结算状态
                int SettleStatus = int.Parse(dic["SettleStatus"].ToString());
                if(SettleStatus == 0) dic["SettleStatus"] = "未结算";
                if(SettleStatus == 1) dic["SettleStatus"] = "已结算";

                //交易日期
                dic["CreateDate"] = string.IsNullOrEmpty(dic["CreateDate"].ToString()) ? "" : DateTime.Parse(dic["CreateDate"].ToString()).ToString("yyyy-MM-dd");

                dic.Remove("StoreId");
                dic.Remove("AgentStoreId");
            }

            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("AgentStoreNo", "代理分仓编号");
            ReturnFields.Add("AgentStoreName", "代理分仓名称");
            ReturnFields.Add("BrandId", "产品类型");
            ReturnFields.Add("TradeMonth", "交易所在月份");
            ReturnFields.Add("CreateDate", "交易日期");
            ReturnFields.Add("UnitPrice", "单价(元)");
            ReturnFields.Add("OrderNum", "订单数量");
            ReturnFields.Add("OrderAmt", "订单金额(元)");
            ReturnFields.Add("RefundOrderNum", "退款订单数量");
            ReturnFields.Add("RefundAmt", "退款金额(元)");
            ReturnFields.Add("SettleStatus", "结算状态");
            ReturnFields.Add("Remark", "备注");
            ReturnFields.Add("UpdateMan", "操作人");
            ReturnFields.Add("UpdateDate", "操作时间");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "StoreMallOrderSummary", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
