/*
 * 创客订单
 */

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;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.Util;

namespace MySystem.Areas.Admin.Controllers
{
    [Area("Admin")]
    [Route("Admin/[controller]/[action]")]
    public class OrdersController : BaseController
    {
        public OrdersController(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(Orders data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询创客订单列表

        /// <summary>
        /// 创客订单列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(Orders data, string OrderNo, string TradeNo, string RealName, string Mobile, string StoreContact, string ErpCode, string SnNos, string PayDateData, string CreateDateData, string SendDateData, string UserIdMakerCode, string UserIdRealName, string PayModeSelect, string StoreIdStoreNo, string StoreIdStoreName, string StatusSelect, string RefundStatusSelect, string DeliveryTypeSelect, string SendStatusSelect, string ProductIdSelect, string StoreTypeSelect, string StoreUserIdMakerCode, string StoreUserIdRealName, string PayStatusSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("OrderNo", "1"); //订单号
            Fields.Add("RealName", "1"); //姓名
            Fields.Add("Mobile", "1"); //手机号
            Fields.Add("ErpCode", "1"); //运单号
            Fields.Add("TradeNo", "1"); //支付交易号
            Fields.Add("StoreContact", "1"); //仓库联系人
            Fields.Add("SnNos", "2"); //SN编号
            Fields.Add("TopUserId", "0");


            // string condition = " and Status>=-1 and  Status<4";
            string condition = " and Status>=-1 and Sort=0";
            //平台订单号
            if (!string.IsNullOrEmpty(OrderNo))
            {
                condition += " and OrderNo like '" + OrderNo + "'";
            }
            //渠道订单号
            if (!string.IsNullOrEmpty(TradeNo))
            {
                condition += " and TradeNo=" + TradeNo;
            }
            //收件人姓名
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and RealName=" + RealName;
            }
            //收件人电话
            if (!string.IsNullOrEmpty(Mobile))
            {
                condition += " and Mobile=" + Mobile;
            }

            //创客编号
            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(PayModeSelect))
            {
                condition += " and PayMode=" + PayModeSelect;
            }
            //仓库编号
            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(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }

            //仓库归属创客编号
            if (!string.IsNullOrEmpty(StoreUserIdMakerCode))
            {
                condition += " and StoreUserId in (select StoreUserId from UserForMakerCode where MakerCode='" + StoreUserIdMakerCode + "')";
            }
            //仓库归属创客真实姓名
            if (!string.IsNullOrEmpty(StoreUserIdRealName))
            {
                condition += " and StoreUserId in (select StoreUserId from UserForRealName where RealName='" + StoreUserIdRealName + "')";
            }
            //快递单号
            if (!string.IsNullOrEmpty(ErpCode))
            {
                condition += " and ErpCode=" + ErpCode;
            }
            //SN
            if (!string.IsNullOrEmpty(SnNos))
            {
                condition += " and SnNos=" + SnNos;
            }
            //支付时间
            if (!string.IsNullOrEmpty(PayDateData))
            {
                string[] datelist = PayDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and PayDate>='" + start + " 00:00:00' and PayDate<='" + end + " 23:59:59'";
            }
            //下单时间
            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(SendDateData))
            {
                string[] datelist = SendDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and SendDate>='" + start + " 00:00:00' and SendDate<='" + end + " 23:59:59'";
            }
            //订单状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //退款状态
            if (!string.IsNullOrEmpty(RefundStatusSelect))
            {
                condition += " and RefundStatus=" + RefundStatusSelect;
            }
            //提货类型
            if (!string.IsNullOrEmpty(DeliveryTypeSelect))
            {
                condition += " and DeliveryType=" + DeliveryTypeSelect;
            }
            //发货状态
            if (!string.IsNullOrEmpty(SendStatusSelect))
            {
                condition += " and SendStatus=" + SendStatusSelect;
            }
            //商品类型名称
            if (!string.IsNullOrEmpty(ProductIdSelect))
            {
                condition += " and Id in (select OrderId from OrderProduct where ProductId=" + ProductIdSelect + ")";//表数据量过大时不适用
            }
            //仓库类型
            if (!string.IsNullOrEmpty(StoreTypeSelect))
            {
                condition += " and StoreType=" + StoreTypeSelect;
            }
            //支付状态
            if (!string.IsNullOrEmpty(PayStatusSelect))
            {
                condition += " and PayStatus=" + PayStatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Orders", 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["OrderNo"] = dic["OrderNo"].ToString() + "<br />" + dic["TradeNo"].ToString();
                dic["StoreContact"] = dic["StoreContact"].ToString() + "<br />" + dic["StoreContactMobile"].ToString();
                dic["Address"] = dic["Areas"].ToString() + dic["Address"].ToString();
                dic["RecieveInfo"] = dic["RealName"].ToString() + "<br />" + dic["Mobile"].ToString();
                dic["ErpInfo"] = dic["ErpCode"].ToString() + "<br />" + dic["ErpName"].ToString();

                //创客
                int UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserInfo"] = userid_Users.MakerCode + "<br />" + userid_Users.RealName;
                dic.Remove("UserId");

                //订单状态
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == -1) dic["StatusName"] = "已取消";
                if (Status == 1) dic["StatusName"] = "待发货";
                if (Status == 2) dic["StatusName"] = "已完成";
                if (Status == 3) dic["StatusName"] = "已发货";
                if (Status == 4) dic["StatusName"] = "已退款";

                //物流名称
                dic["ErpName"] = RelationClass.GetErpCompanysInfo(dic["ErpName"].ToString());

                //支付方式
                int PayMode = int.Parse(dic["PayMode"].ToString());
                if (PayMode == 1) dic["PayMode"] = "支付宝";
                if (PayMode == 2) dic["PayMode"] = "微信";
                if (PayMode == 3) dic["PayMode"] = "账户余额";
                if (PayMode == 0) dic["PayMode"] = "";

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

                //仓库类型
                int StoreType = int.Parse(dic["StoreType"].ToString());
                if (StoreType == 0) dic["StoreType"] = "总仓";
                if (StoreType == 1) dic["StoreType"] = "分仓";
                dic["Store"] = storeid_StoreHouse.StoreNo + "<br />" + dic["StoreType"].ToString();
                dic.Remove("StoreId");

                // //退款状态
                // int RefundStatus = int.Parse(dic["RefundStatus"].ToString());
                // if (RefundStatus == 0) dic["RefundStatusName"] = "未退款";
                // if (RefundStatus == 1) dic["RefundStatusName"] = "已退款";

                //提货类型
                int DeliveryType = int.Parse(dic["DeliveryType"].ToString());
                if (DeliveryType == 1) dic["DeliveryType"] = "邮寄到付";
                if (DeliveryType == 2) dic["DeliveryType"] = "上门自提";
                if (DeliveryType == 0) dic["DeliveryType"] = "";

                // //发货状态
                // int SendStatus = int.Parse(dic["SendStatus"].ToString());
                // if (SendStatus == -1) dic["SendStatusName"] = "已驳回";
                // if (SendStatus == 0) dic["SendStatusName"] = "未发货";
                // if (SendStatus == 1) dic["SendStatusName"] = "已发货";
                // if (SendStatus == 2) dic["SendStatusName"] = "已退货";
                // if (SendStatus == 0)
                // {
                //     dic["SendInfo"] = dic["SendStatusName"];
                // }
                // else
                // {
                //     dic["SendInfo"] = dic["SendStatusName"].ToString() + "<br />" + dic["SendDate"].ToString();
                // }
                //商品名称
                dic["ProductId"] = RelationClass.GetProductsInfo(int.Parse(dic["ProductId"].ToString()));

                //商品名称
                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                OrderProduct orderProducts = db.OrderProduct.FirstOrDefault(m => m.OrderId == Id) ?? new OrderProduct();
                var product = db.Products.FirstOrDefault(m => m.Id == orderProducts.ProductId) ?? new Products();
                dic["ProductName"] = orderProducts.ProductName;
                if (product.ProductKind == 1) dic["ProductKind"] = "实物商品";
                if (product.ProductKind == 2) dic["ProductKind"] = "虚拟商品";

                //退款时间
                var orderRefund = db.OrderRefund.FirstOrDefault(m => m.OrderId == Id) ?? new OrderRefund();
                dic["RefundDate"] = "";
                if (orderRefund.Id > 0)
                {
                    dic["RefundDate"] = orderRefund.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss");
                }

                //仓库归属创客
                int StoreUserId = int.Parse(function.CheckInt(dic["StoreUserId"].ToString()));
                Users storeuserid_Users = db.Users.FirstOrDefault(m => m.Id == StoreUserId) ?? new Users();
                dic["StoreFrom"] = storeuserid_Users.MakerCode + "<br />" + storeid_StoreHouse.StoreName;
                dic.Remove("StoreUserId");

                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserInfo"] = topuserid_Users.MakerCode + "<br />" + topuserid_Users.RealName;
                dic.Remove("TopUserId");

                // //支付状态
                // int PayStatus = int.Parse(dic["PayStatus"].ToString());
                // if (PayStatus == 0) dic["PayStatusName"] = "未支付";
                // if (PayStatus == 1) dic["PayStatusName"] = "支付成功";
                // if (PayStatus == 2) dic["PayStatusName"] = "支付失败";
                // if (PayStatus == 3) dic["PayStatusName"] = "支付锁定中";
                // if (PayStatus == 4) dic["PayStatusName"] = "支付处理中";

            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string SuccessAmount = "0.00";//支付成功总金额
            string FailAmount = "0.00";//支付失败总金额
            DataTable dt = OtherMySqlConn.dtable("select sum(TotalPrice) from Orders where PayStatus=1 and Status>-1" + condition);
            if (dt.Rows.Count > 0)
            {
                SuccessAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            dt = OtherMySqlConn.dtable("select sum(TotalPrice) from Orders where PayStatus=2 and Status>-1" + condition);
            if (dt.Rows.Count > 0)
            {
                FailAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
            }
            other.Add("SuccessAmount", SuccessAmount);
            other.Add("FailAmount", FailAmount);
            obj.Add("other", other);
            return Json(obj);
        }
        #endregion


        #region 创客退货订单列表

        /// <summary>
        /// 根据条件查询创客退货订单列表
        /// </summary>
        /// <returns></returns>
        public IActionResult IndexRefund(Orders data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion

        #region 根据条件查询创客退货订单列表

        /// <summary>
        /// 创客退货订单列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexRefundData(Orders data, string OrderNo, string CreateDateData, string UserIdMakerCode, string UserIdRealName, string PayModeSelect, string ProductIdSelect, int page = 1, int limit = 30)
        {

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

            string condition = " and Status in(4,5)";
            //平台订单号
            if (!string.IsNullOrEmpty(OrderNo))
            {
                condition += " and OrderNo like '" + OrderNo + "'";
            }

            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //支付方式
            if (!string.IsNullOrEmpty(PayModeSelect))
            {
                condition += " and PayMode=" + PayModeSelect;
            }
            //商品类型名称
            if (!string.IsNullOrEmpty(ProductIdSelect))
            {
                condition += " and Id in (select OrderId from OrderProduct where ProductId=" + ProductIdSelect + ")";//表数据量过大时不适用
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Orders", 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["OrderNo"] = dic["OrderNo"].ToString() + "<br />" + dic["TradeNo"].ToString();
                //状态
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 4) dic["StatusName"] = "已退款";
                // if (Status == 5) dic["StatusName"] = "已退货";
                //创客
                int UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserInfo"] = userid_Users.MakerCode + "<br />" + userid_Users.RealName;
                dic.Remove("UserId");
                //支付方式
                int PayMode = int.Parse(dic["PayMode"].ToString());
                if (PayMode == 1) dic["PayMode"] = "支付宝";
                if (PayMode == 2) dic["PayMode"] = "微信";
                if (PayMode == 3) dic["PayMode"] = "账户余额";
                if (PayMode == 0) dic["PayMode"] = "";
                //商品名称
                dic["ProductId"] = RelationClass.GetProductsInfo(int.Parse(dic["ProductId"].ToString()));

                //商品名称
                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                OrderProduct orderProducts = db.OrderProduct.FirstOrDefault(m => m.OrderId == Id) ?? new OrderProduct();
                dic["ProductName"] = orderProducts.ProductName;

                //退款时间
                var info = db.OrderRefund.FirstOrDefault(m => m.OrderId == Id) ?? new OrderRefund();
                dic["ReturnDate"] = info.CreateDate == null ? "" : info.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss");

            }
            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(Orders data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("RealName", data.RealName); //姓名
            Fields.Add("ErpName", data.ErpName); //物流名称
            Fields.Add("ErpCode", data.ErpCode); //运单号
            Fields.Add("StoreId", data.StoreId); //仓库
            Fields.Add("SnNos", data.SnNos); //SN编号

            Fields.Add("SeoTitle", data.SeoTitle);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("Orders", Fields, 0);
            AddSysLog(data.Id.ToString(), "Orders", "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;


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

        #endregion

        #region 修改创客订单

        /// <summary>
        /// 增加或修改创客订单信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(Orders data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("RealName", data.RealName); //姓名
            Fields.Add("ErpName", data.ErpName); //物流名称
            Fields.Add("ErpCode", data.ErpCode); //运单号
            Fields.Add("StoreId", data.StoreId); //仓库
            Fields.Add("SnNos", data.SnNos); //SN编号

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

            return "success";
        }

        #endregion

        #region 发货

        public IActionResult Send(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

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

            Users user = db.Users.FirstOrDefault(m => m.Id == editData.UserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            ViewBag.RealName = user.RealName;

            StoreHouse store = db.StoreHouse.FirstOrDefault(m => m.Id == editData.StoreId) ?? new StoreHouse();
            ViewBag.StoreName = store.StoreName;

            List<OrderProduct> products = db.OrderProduct.Where(m => m.OrderId == editData.Id).ToList();
            ViewBag.products = products;
            var orderProduct = db.OrderProduct.FirstOrDefault(m => m.OrderId == editData.Id);
            ViewBag.productId = orderProduct.ProductId;
            return View();
        }

        #endregion

        #region 发货

        [HttpPost]
        public string Send(Orders data, string IdList, string SnNosList)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("ErpName", data.ErpName); //物流名称
            Fields.Add("ErpCode", data.ErpCode); //运单号
            Fields.Add("SnNos", SnNosList); //SN编号
            Fields.Add("SendStatus", 1); //发货状态
            Fields.Add("Status", 3); //状态
            Fields.Add("SendDate", DateTime.Now); //发货时间

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

            return "success";
        }

        #endregion

        #region 退货

        public IActionResult Return(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


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

        #endregion

        #region 退货

        [HttpPost]
        public string Return(Orders data)
        {
            AddSysLog(data.Id.ToString(), "Orders", "Return");
            Orders order = db.Orders.FirstOrDefault(m => m.Id == data.Id);
            if (order != null)
            {
                if (order.TotalPrice <= 0)
                {
                    return "该订单不符合退货规则！";
                }
                else if (order.TotalPrice < decimal.Parse(data.RefundActAmount.ToString()) || decimal.Parse(data.RefundActAmount.ToString()) <= 0)
                {
                    return "退款金额和订单金额不符！";
                }
                else
                {
                    // order.UpdateDate = DateTime.Now;
                    order.Status = 4;
                    order.RefundStatus = 1;
                    order.UpdateMan = SysUserName + "_" + SysRealName;
                    order.RefundReason = data.RefundReason;
                    order.RefundActAmount = data.RefundActAmount;
                    db.SaveChanges();
                    var Remark = "";
                    var orderProduct = db.OrderProduct.FirstOrDefault(m => m.OrderId == order.Id) ?? new OrderProduct();
                    Remark = orderProduct.ProductName + "退款至余额";
                    // string SendData = "{\"OrderId\":\"" + data.Id + "\",\"Operator\":\"" + SysUserName + "_" + SysRealName + "\",\"Amount\":\"" + data.RefundActAmount + "\",\"Remark\":\"" + Remark + "\"}";
                    // RedisDbconn.Instance.AddList("RefundQueue", SendData);

                    bool op = true;
                    decimal TotalPrice = order.TotalPrice;
                    decimal Amount = data.RefundActAmount;
                    if(order.PayMode == 1)
                    {
                        PublicAccountSet set = db.PublicAccountSet.FirstOrDefault() ?? new PublicAccountSet();
                        string result = new Alipay.AlipayPublicClass(_accessor.HttpContext).Refund(set.AlipayAppId, set.AlipayPrivateKey, set.AlipayPublicKey, order.OrderNo, Amount);
                    }
                    else if(order.PayMode == 3)
                    {
                        UserAccount user = db.UserAccount.FirstOrDefault(m => m.Id == order.UserId);
                        if (user == null)
                        {
                            user = db.UserAccount.Add(new UserAccount()
                            {
                                Id = order.UserId,
                                UserId = order.UserId,
                            }).Entity;
                            db.SaveChanges();
                        }
                        decimal BeforeTotalAmount = user.TotalAmount; //变更前总金额
                        decimal BeforeFreezeAmount = user.FreezeAmount; //变更前冻结金额
                        decimal BeforeBalanceAmount = user.BalanceAmount; //变更前余额
                        user.BalanceAmount += Amount;
                        decimal AfterTotalAmount = user.TotalAmount; //变更后总金额
                        decimal AfterFreezeAmount = user.FreezeAmount; //变更后冻结金额
                        decimal AfterBalanceAmount = user.BalanceAmount; //变更后余额
                        db.UserAccountRecord.Add(new UserAccountRecord()
                        {
                            CreateDate = DateTime.Now,
                            UpdateDate = DateTime.Now,
                            UserId = order.UserId, //创客
                            ChangeType = 21, //变动类型
                            ChangeAmount = Amount, //变更金额
                            BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                            AfterTotalAmount = AfterTotalAmount, //变更后总金额
                            BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                            AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                            BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                            AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                            QueryCount = order.Id,
                            Remark = Remark,
                        });
                    }
                    if(op)
                    {
                        order.RefundStatus = 1;
                        order.RefundActAmount = Amount;
                        db.OrderRefund.Add(new OrderRefund()
                        {
                            CreateDate = DateTime.Now,
                            Mobile = order.Mobile,
                            Amount = Amount,
                            SeoDescription = Remark,
                            ProductId = order.ProductId.ToString(),
                            OrderId = order.Id,
                            UserId = order.UserId,
                        });
                    }
                    else
                    {
                        order.RefundStatus = 0;
                        order.RefundReason = null;
                        order.RefundActAmount = 0;
                    }
                    db.SaveChanges();
                }
            }
            return "success";
        }

        #endregion

        #region 订单详情

        public IActionResult Detail(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

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

            Users user = db.Users.FirstOrDefault(m => m.Id == editData.UserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            ViewBag.RealName = user.RealName;

            //支付状态
            int PayStatus = editData.PayStatus;
            if (PayStatus == 0) ViewBag.PayStatus = "未支付";
            if (PayStatus == 1) ViewBag.PayStatus = "支付成功";
            if (PayStatus == 2) ViewBag.PayStatus = "支付失败";
            if (PayStatus == 3) ViewBag.PayStatus = "支付锁定中";
            if (PayStatus == 4) ViewBag.PayStatus = "支付处理中";

            //支付方式
            int PayMode = editData.PayMode;
            if (PayMode == 1)
            {
                ViewBag.PayMode = "支付宝支付";
                ViewBag.PayModeCode = "Alipay";
            }
            if (PayMode == 2)
            {
                ViewBag.PayMode = "微信支付";
                ViewBag.PayModeCode = "WeChat";
            }
            if (PayMode == 3)
            {
                ViewBag.PayMode = "账户余额支付";
                ViewBag.PayModeCode = "AccBalancePay";
            }

            //发货状态
            int SendStatus = editData.SendStatus;
            if (SendStatus == 0) ViewBag.SendStatus = "未发货";
            if (SendStatus == 1) ViewBag.SendStatus = "已发货";
            if (SendStatus == 2) ViewBag.SendStatus = "已退货";

            //提货类型
            int DeliveryType = editData.DeliveryType;
            if (DeliveryType == 1) ViewBag.DeliveryType = "邮寄到付";
            if (DeliveryType == 2) ViewBag.DeliveryType = "上门自提";

            List<OrderProduct> products = db.OrderProduct.Where(m => m.OrderId == editData.Id).ToList();
            List<Dictionary<string, object>> ProductList = new List<Dictionary<string, object>>();
            foreach (OrderProduct product in products)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                item.Add("ProductCode", product.ProductCode);  //商品编号
                item.Add("ProductName", product.ProductName);  //商品名称
                item.Add("ProductCount", product.ProductCount);  //商品数量
                item.Add("ProductPrice", product.ProductPrice);  //商品单价
                item.Add("SeoKeyword", product.SeoKeyword);  //商品简介
                item.Add("SeoDescription", product.SeoDescription);  //备注
                item.Add("ProductPhoto", SourceHost + product.ProductPhoto);  //商品小图
                item.Add("NormDetail", product.NormDetail);  //商品规格
                ProductList.Add(item);
            }
            ViewBag.ProductList = ProductList;

            return View();
        }

        #endregion

        #region 删除创客订单信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public string ExportExcel(Orders data, string UserIdMakerCode, string UserIdRealName, string PayModeSelect, string StoreIdStoreNo, string StoreIdStoreName, string RefundStatusSelect, string DeliveryTypeSelect, string SendStatusSelect, string ProductIdSelect, string StoreTypeSelect, string StoreUserIdMakerCode, string StoreUserIdRealName, string PayStatusSelect, string RedisKey = "ExportKey")
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("OrderNo", "1"); //订单号
            Fields.Add("RealName", "1"); //姓名
            Fields.Add("Mobile", "1"); //手机号
            Fields.Add("ErpCode", "1"); //运单号
            Fields.Add("SendDate", "3"); //发货时间
            Fields.Add("TradeNo", "1"); //支付交易号
            Fields.Add("StoreContact", "1"); //仓库联系人
            Fields.Add("SnNos", "2"); //SN编号
            Fields.Add("TopUserId", "0");

            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(PayModeSelect))
            {
                condition += " and PayMode=" + PayModeSelect;
            }
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreHouseForStoreNo where StoreNo='" + StoreIdStoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreHouseForStoreName where StoreName='" + StoreIdStoreName + "')";
            }
            //退款状态
            if (!string.IsNullOrEmpty(RefundStatusSelect))
            {
                condition += " and RefundStatus=" + RefundStatusSelect;
            }
            //提货类型
            if (!string.IsNullOrEmpty(DeliveryTypeSelect))
            {
                condition += " and DeliveryType=" + DeliveryTypeSelect;
            }
            //发货状态
            if (!string.IsNullOrEmpty(SendStatusSelect))
            {
                condition += " and SendStatus=" + SendStatusSelect;
            }
            //商品名称
            if (!string.IsNullOrEmpty(ProductIdSelect))
            {
                condition += " and ProductId=" + ProductIdSelect;
            }
            //仓库类型
            if (!string.IsNullOrEmpty(StoreTypeSelect))
            {
                condition += " and StoreType=" + StoreTypeSelect;
            }
            //仓库归属创客编号
            if (!string.IsNullOrEmpty(StoreUserIdMakerCode))
            {
                condition += " and StoreUserId in (select StoreUserId from UserForMakerCode where MakerCode='" + StoreUserIdMakerCode + "')";
            }
            //仓库归属创客真实姓名
            if (!string.IsNullOrEmpty(StoreUserIdRealName))
            {
                condition += " and StoreUserId in (select StoreUserId from UserForRealName where RealName='" + StoreUserIdRealName + "')";
            }
            //支付状态
            if (!string.IsNullOrEmpty(PayStatusSelect))
            {
                condition += " and PayStatus=" + PayStatusSelect;
            }
            //创建工作薄
            var workbook = new XSSFWorkbook();
            //创建表
            var table = workbook.CreateSheet("Sheet1");
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Orders", Fields, "Id desc", "0", 1, 20000, condition, "UserId,OrderNo,RealName,Mobile,TotalPrice,Areas,Address,ErpName,ErpCode,SendDate,PayMode,TradeNo,StoreId,RefundStatus,DeliveryType,SendStatus,ProductId,StoreContact,StoreType,StoreUserId,TopUserId,PayStatus,BuyCount,Remark,Id", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();
            ReturnFields.Add("UserIdMakerCode", "创客编号");
            ReturnFields.Add("UserIdRealName", "创客真实姓名");
            ReturnFields.Add("OrderNo", "订单号");
            ReturnFields.Add("RealName", "姓名");
            ReturnFields.Add("Mobile", "手机号");
            ReturnFields.Add("TotalPrice", "总价");
            ReturnFields.Add("Areas", "所在地区");
            ReturnFields.Add("Address", "详细地址");
            ReturnFields.Add("ErpName", "物流名称");
            ReturnFields.Add("ErpCode", "运单号");
            ReturnFields.Add("SendDate", "发货时间");
            ReturnFields.Add("PayMode", "支付方式");
            ReturnFields.Add("TradeNo", "支付交易号");
            ReturnFields.Add("StoreIdStoreNo", "仓库编号");
            ReturnFields.Add("StoreIdStoreName", "仓库名称");
            ReturnFields.Add("RefundStatus", "退款状态");
            ReturnFields.Add("DeliveryType", "提货类型");
            ReturnFields.Add("SendStatus", "发货状态");
            ReturnFields.Add("ProductId", "商品名称");
            ReturnFields.Add("StoreContact", "仓库联系人");
            ReturnFields.Add("StoreType", "仓库类型");
            ReturnFields.Add("StoreUserIdMakerCode", "仓库归属创客编号");
            ReturnFields.Add("StoreUserIdRealName", "仓库归属创客姓名");
            ReturnFields.Add("TopUserIdMakerCode", "顶级创客编号");
            ReturnFields.Add("TopUserIdRealName", "顶级创客姓名");
            ReturnFields.Add("PayStatus", "支付状态");
            ReturnFields.Add("BuyCount", "下单数量");
            ReturnFields.Add("Remark", "订单备注");
            int i = 0;
            foreach (Dictionary<string, object> dic in diclist)
            {
                i += 1;
                //创客
                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["ErpName"] = RelationClass.GetErpCompanysInfo(dic["ErpName"].ToString());
                //支付方式
                int PayMode = int.Parse(dic["PayMode"].ToString());
                if (PayMode == 1) dic["PayMode"] = "支付宝";
                if (PayMode == 2) dic["PayMode"] = "微信";
                if (PayMode == 3) dic["PayMode"] = "账户余额";
                if (PayMode == 0) dic["PayMode"] = "";
                //仓库
                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 RefundStatus = int.Parse(dic["RefundStatus"].ToString());
                if (RefundStatus == 0) dic["RefundStatus"] = "未退款";
                if (RefundStatus == 1) dic["RefundStatus"] = "已退款";
                //提货类型
                int DeliveryType = int.Parse(dic["DeliveryType"].ToString());
                if (DeliveryType == 1) dic["DeliveryType"] = "邮寄到付";
                if (DeliveryType == 2) dic["DeliveryType"] = "上门自提";
                if (DeliveryType == 0) dic["DeliveryType"] = "";
                //发货状态
                int SendStatus = int.Parse(dic["SendStatus"].ToString());
                if (SendStatus == 0) dic["SendStatus"] = "未发货";
                if (SendStatus == 1) dic["SendStatus"] = "已发货";
                if (SendStatus == 2) dic["SendStatus"] = "已退货";
                //商品名称
                dic["ProductId"] = RelationClass.GetProductsInfo(int.Parse(dic["ProductId"].ToString()));
                //仓库类型
                int StoreType = int.Parse(dic["StoreType"].ToString());
                if (StoreType == 0) dic["StoreType"] = "总仓";
                if (StoreType == 1) dic["StoreType"] = "分仓";
                //仓库归属创客
                int StoreUserId = int.Parse(function.CheckInt(dic["StoreUserId"].ToString()));
                Users storeuserid_Users = db.Users.FirstOrDefault(m => m.Id == StoreUserId) ?? new Users();
                dic["StoreUserIdMakerCode"] = storeuserid_Users.MakerCode;
                dic["StoreUserIdRealName"] = storeuserid_Users.RealName;
                dic.Remove("StoreUserId");
                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserIdMakerCode"] = topuserid_Users.MakerCode;
                dic["TopUserIdRealName"] = topuserid_Users.RealName;
                dic.Remove("TopUserId");
                //支付状态
                int PayStatus = int.Parse(dic["PayStatus"].ToString());
                if (PayStatus == 0) dic["PayStatus"] = "未支付";
                if (PayStatus == 1) dic["PayStatus"] = "支付成功";
                if (PayStatus == 2) dic["PayStatus"] = "支付失败";
                if (PayStatus == 3) dic["PayStatus"] = "支付锁定中";
                if (PayStatus == 4) dic["PayStatus"] = "支付处理中";

                int OrderId = int.Parse(dic["Id"].ToString());
                List<OrderProduct> products = db.OrderProduct.Where(m => m.OrderId == OrderId).ToList();
                foreach (OrderProduct product in products)
                {
                    dic["ProductCode"] = product.ProductCode;  //商品编号
                    dic["ProductName"] = product.ProductName;  //商品名称
                    dic["ProductCount"] = product.ProductCount;  //商品数量
                    dic["ProductPrice"] = product.ProductPrice;  //商品单价
                    dic["NormDetail"] = product.NormDetail;  //商品规格
                    if (i == 1)
                    {
                        ReturnFields.Add("ProductCode", "商品编号");
                        ReturnFields.Add("ProductName", "商品名称");
                        ReturnFields.Add("ProductCount", "商品数量");
                        ReturnFields.Add("ProductPrice", "商品单价");
                        ReturnFields.Add("NormDetail", "商品规格");
                    }
                }
                dic.Remove("Id");
                var row = table.CreateRow(i);
                int index = 0;
                foreach (string key in ReturnFields.Keys)
                {
                    var cell = row.CreateCell(index);
                    string val = dic[key] == null ? "" : dic[key].ToString();
                    ICellStyle style = workbook.CreateCellStyle();
                    style.BorderBottom = BorderStyle.Thin;
                    style.BorderTop = BorderStyle.Thin;
                    style.BorderLeft = BorderStyle.Thin;
                    style.BorderRight = BorderStyle.Thin;
                    style.BottomBorderColor = HSSFColor.Black.Index;
                    style.TopBorderColor = HSSFColor.Black.Index;
                    style.LeftBorderColor = HSSFColor.Black.Index;
                    style.RightBorderColor = HSSFColor.Black.Index;
                    cell.CellStyle = style;
                    cell.SetCellValue(val);
                    index += 1;
                }
                RedisDbconn.Instance.Set("CheckExport:" + RedisKey, i.ToString() + " / " + diclist.Count);
            }

            var title = table.CreateRow(0);
            int j = 0;
            foreach (string key in ReturnFields.Keys)
            {
                var cell = title.CreateCell(j);
                ICellStyle style = workbook.CreateCellStyle();
                style.BorderBottom = BorderStyle.Thin;
                style.BorderTop = BorderStyle.Thin;
                style.BorderLeft = BorderStyle.Thin;
                style.BorderRight = BorderStyle.Thin;
                style.BottomBorderColor = HSSFColor.Black.Index;
                style.TopBorderColor = HSSFColor.Black.Index;
                style.LeftBorderColor = HSSFColor.Black.Index;
                style.RightBorderColor = HSSFColor.Black.Index;
                cell.CellStyle = style;
                cell.SetCellValue(ReturnFields[key].ToString());
                j += 1;
            }
            //打开xls文件，如没有则创建，如存在则在创建是不要打开该文件
            string FilePath = function.getPath("/static/export/");
            if (!System.IO.Directory.Exists(FilePath))
            {
                System.IO.Directory.CreateDirectory(FilePath);
            }
            string FileName = "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx";
            using (var fs = System.IO.File.OpenWrite(FilePath + FileName))
            {
                workbook.Write(fs);   //向打开的这个xls文件中写入mySheet表并保存。
            }

            AddSysLog("0", "Orders", "ExportExcel");
            RedisDbconn.Instance.Set("CheckExport:" + RedisKey, "finish");
            return "success|/static/export/" + FileName;
        }

        public string CheckExport(string RedisKey = "ExportKey")
        {
            string result = RedisDbconn.Instance.Get<string>("CheckExport:" + RedisKey);
            return result;
        }

        #endregion


        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportsExcel(Orders data, string UserIdMakerCode, string UserIdRealName, string PayModeSelect, string StoreIdStoreNo, string StoreIdStoreName, string StatusSelect, string RefundStatusSelect, string DeliveryTypeSelect, string SendStatusSelect, string ProductIdSelect, string StoreTypeSelect, string StoreUserIdMakerCode, string StoreUserIdRealName, string PayStatusSelect, string CreateDateData, string SendDateData, string PayDateData, string RedisKey = "ExportKey")
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            // Fields.Add("CreateDate", "3"); //时间
            Fields.Add("OrderNo", "1"); //订单号
            Fields.Add("RealName", "1"); //姓名
            Fields.Add("Mobile", "1"); //手机号
            Fields.Add("ErpCode", "1"); //运单号
            Fields.Add("TradeNo", "1"); //支付交易号
            Fields.Add("StoreContact", "1"); //仓库联系人
            Fields.Add("SnNos", "2"); //SN编号
            Fields.Add("TopUserId", "0");

            string condition = " and Status>=-1 and Sort=0";
            //创客编号
            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(PayModeSelect))
            {
                condition += " and PayMode=" + PayModeSelect;
            }
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                condition += " and StoreId in (select StoreId from StoreHouseForStoreNo where StoreNo='" + StoreIdStoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                condition += " and StoreId in (select StoreId from StoreHouseForStoreName where StoreName='" + StoreIdStoreName + "')";
            }
            //订单状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //退款状态
            if (!string.IsNullOrEmpty(RefundStatusSelect))
            {
                condition += " and RefundStatus=" + RefundStatusSelect;
            }
            //提货类型
            if (!string.IsNullOrEmpty(DeliveryTypeSelect))
            {
                condition += " and DeliveryType=" + DeliveryTypeSelect;
            }
            //发货状态
            if (!string.IsNullOrEmpty(SendStatusSelect))
            {
                condition += " and SendStatus=" + SendStatusSelect;
            }
            //商品名称
            if (!string.IsNullOrEmpty(ProductIdSelect))
            {
                condition += " and ProductId=" + ProductIdSelect;
            }
            //仓库类型
            if (!string.IsNullOrEmpty(StoreTypeSelect))
            {
                condition += " and StoreType=" + StoreTypeSelect;
            }
            //仓库归属创客编号
            if (!string.IsNullOrEmpty(StoreUserIdMakerCode))
            {
                condition += " and StoreUserId in (select StoreUserId from UserForMakerCode where MakerCode='" + StoreUserIdMakerCode + "')";
            }
            //仓库归属创客真实姓名
            if (!string.IsNullOrEmpty(StoreUserIdRealName))
            {
                condition += " and StoreUserId in (select StoreUserId from UserForRealName where RealName='" + StoreUserIdRealName + "')";
            }
            //支付状态
            if (!string.IsNullOrEmpty(PayStatusSelect))
            {
                condition += " and PayStatus=" + PayStatusSelect;
            }
            //支付时间
            if (!string.IsNullOrEmpty(PayDateData))
            {
                string[] datelist = PayDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and PayDate>='" + start + " 00:00:00' and PayDate<='" + end + " 23:59:59'";
            }
            //下单时间
            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(SendDateData))
            {
                string[] datelist = SendDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and SendDate>='" + start + " 00:00:00' and SendDate<='" + end + " 23:59:59'";
            }
            // Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Orders", Fields, "Id desc", "0", 1, 20000, condition, "UserId,OrderNo,RealName,Mobile,TotalPrice,Areas,Address,ErpName,ErpCode,SendDate,PayMode,PayDate,TradeNo,StoreId,RefundStatus,DeliveryType,SendStatus,ProductId,StoreContact,StoreType,StoreUserId,TopUserId,PayStatus,BuyCount,Remark,Id", false);
            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("Orders", Fields, "Id desc", "0", 1, 20000, condition, "UserId,OrderNo,RealName,Mobile,TotalPrice,Areas,Address,ErpName,ErpCode,SendDate,PayMode,PayDate,TradeNo,StoreId,DeliveryType,ProductId,StoreContact,StoreType,StoreUserId,TopUserId,Status,BuyCount,Remark,Id", 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["ErpName"] = RelationClass.GetErpCompanysInfo(dic["ErpName"].ToString());

                //支付方式
                int PayMode = int.Parse(dic["PayMode"].ToString());
                if (PayMode == 1) dic["PayMode"] = "支付宝";
                if (PayMode == 2) dic["PayMode"] = "微信";
                if (PayMode == 3) dic["PayMode"] = "账户余额";
                if (PayMode == 0) dic["PayMode"] = "";

                //仓库
                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 RefundStatus = int.Parse(dic["RefundStatus"].ToString());
                // if (RefundStatus == 0) dic["RefundStatus"] = "未退款";
                // if (RefundStatus == 1) dic["RefundStatus"] = "已退款";

                //提货类型
                int DeliveryType = int.Parse(dic["DeliveryType"].ToString());
                if (DeliveryType == 1) dic["DeliveryType"] = "邮寄到付";
                if (DeliveryType == 2) dic["DeliveryType"] = "上门自提";
                if (DeliveryType == 0) dic["DeliveryType"] = "";

                // //发货状态
                // int SendStatus = int.Parse(dic["SendStatus"].ToString());
                // if (SendStatus == 0) dic["SendStatus"] = "未发货";
                // if (SendStatus == 1) dic["SendStatus"] = "已发货";
                // if (SendStatus == 2) dic["SendStatus"] = "已退货";

                //商品名称
                dic["ProductId"] = RelationClass.GetProductsInfo(int.Parse(dic["ProductId"].ToString()));

                //仓库类型
                int StoreType = int.Parse(dic["StoreType"].ToString());
                if (StoreType == 0) dic["StoreType"] = "总仓";
                if (StoreType == 1) dic["StoreType"] = "分仓";

                //仓库归属创客
                int StoreUserId = int.Parse(function.CheckInt(dic["StoreUserId"].ToString()));
                Users storeuserid_Users = db.Users.FirstOrDefault(m => m.Id == StoreUserId) ?? new Users();
                dic["StoreUserIdMakerCode"] = storeuserid_Users.MakerCode;
                dic["StoreUserIdRealName"] = storeuserid_Users.RealName;
                dic.Remove("StoreUserId");

                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserIdMakerCode"] = topuserid_Users.MakerCode;
                dic["TopUserIdRealName"] = topuserid_Users.RealName;
                dic.Remove("TopUserId");

                // //支付状态
                // int PayStatus = int.Parse(dic["PayStatus"].ToString());
                // if (PayStatus == 0) dic["PayStatus"] = "未支付";
                // if (PayStatus == 1) dic["PayStatus"] = "支付成功";
                // if (PayStatus == 2) dic["PayStatus"] = "支付失败";
                // if (PayStatus == 3) dic["PayStatus"] = "支付锁定中";
                // if (PayStatus == 4) dic["PayStatus"] = "支付处理中";

                int OrderId = int.Parse(dic["Id"].ToString());
                List<OrderProduct> products = db.OrderProduct.Where(m => m.OrderId == OrderId).ToList();
                foreach (OrderProduct product in products)
                {
                    dic["ProductCode"] = product.ProductCode;  //商品编号
                    dic["ProductName"] = product.ProductName;  //商品名称
                    dic["ProductCount"] = product.ProductCount;  //商品数量
                    dic["ProductPrice"] = product.ProductPrice;  //商品单价
                    dic["NormDetail"] = product.NormDetail;  //商品规格
                }
                dic.Remove("Id");
            }

            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("UserIdMakerCode", "创客编号");
            ReturnFields.Add("UserIdRealName", "创客真实姓名");
            ReturnFields.Add("OrderNo", "订单号");
            ReturnFields.Add("RealName", "姓名");
            ReturnFields.Add("Mobile", "手机号");
            ReturnFields.Add("TotalPrice", "总价");
            ReturnFields.Add("Areas", "所在地区");
            ReturnFields.Add("Address", "详细地址");
            ReturnFields.Add("ErpName", "物流名称");
            ReturnFields.Add("ErpCode", "运单号");
            ReturnFields.Add("SendDate", "发货时间");
            ReturnFields.Add("PayMode", "支付方式");
            ReturnFields.Add("PayDate", "支付时间");
            ReturnFields.Add("TradeNo", "支付交易号");
            ReturnFields.Add("StoreIdStoreNo", "仓库编号");
            ReturnFields.Add("StoreIdStoreName", "仓库名称");
            // ReturnFields.Add("RefundStatus", "退款状态");
            ReturnFields.Add("DeliveryType", "提货类型");
            // ReturnFields.Add("SendStatus", "发货状态");
            ReturnFields.Add("ProductId", "商品名称");
            ReturnFields.Add("StoreContact", "仓库联系人");
            ReturnFields.Add("StoreType", "仓库类型");
            ReturnFields.Add("StoreUserIdMakerCode", "仓库归属创客编号");
            ReturnFields.Add("StoreUserIdRealName", "仓库归属创客姓名");
            ReturnFields.Add("TopUserIdMakerCode", "顶级创客编号");
            ReturnFields.Add("TopUserIdRealName", "顶级创客姓名");
            // ReturnFields.Add("PayStatus", "支付状态");
            ReturnFields.Add("BuyCount", "下单数量");
            ReturnFields.Add("Remark", "订单备注");
            ReturnFields.Add("ProductCode", "商品编号");
            ReturnFields.Add("ProductName", "商品名称");
            ReturnFields.Add("ProductCount", "商品数量");
            ReturnFields.Add("ProductPrice", "商品单价");
            ReturnFields.Add("NormDetail", "商品规格");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "Orders", "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 OrderNo, string UserIdMakerCode, string UserIdRealName, string PayModeSelect, string StoreIdStoreNo, string StoreIdStoreName, string RefundStatusSelect, string DeliveryTypeSelect, string SendStatusSelect, string ProductIdSelect, string StoreTypeSelect, string StoreUserIdMakerCode, string StoreUserIdRealName, string PayStatusSelect, string CreateDateData, string SendDateData, string PayDateData)
        {

            string SqlString = " where 1=1 and a.Status>=-1 and a.Sort=0";
            //订单号
            if (!string.IsNullOrEmpty(OrderNo))
            {
                SqlString += " and a.OrderNo='" + OrderNo + "'";
            }
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                SqlString += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //创客真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                SqlString += " and a.UserId in (select UserId from UserForRealName where RealName='" + UserIdRealName + "')";
            }
            //支付方式
            if (!string.IsNullOrEmpty(PayModeSelect))
            {
                SqlString += " and a.PayMode=" + PayModeSelect;
            }
            //仓库编号
            if (!string.IsNullOrEmpty(StoreIdStoreNo))
            {
                SqlString += " and a.StoreId in (select StoreId from StoreForCode where StoreNo='" + StoreIdStoreNo + "')";
            }
            //仓库名称
            if (!string.IsNullOrEmpty(StoreIdStoreName))
            {
                SqlString += " and a.StoreId in (select Id from StoreHouse where StoreName='" + StoreIdStoreName + "')";
            }
            //退款状态
            if (!string.IsNullOrEmpty(RefundStatusSelect))
            {
                SqlString += " and a.RefundStatus=" + RefundStatusSelect;
            }
            //提货类型
            if (!string.IsNullOrEmpty(DeliveryTypeSelect))
            {
                SqlString += " and a.DeliveryType=" + DeliveryTypeSelect;
            }
            //发货状态
            if (!string.IsNullOrEmpty(SendStatusSelect))
            {
                SqlString += " and a.SendStatus=" + SendStatusSelect;
            }
            //商品名称
            if (!string.IsNullOrEmpty(ProductIdSelect))
            {
                // SqlString += " and a.ProductId=" + ProductIdSelect;
                SqlString += " and a.Id in (select OrderId from OrderProduct where ProductId=" + ProductIdSelect + ")";
            }
            //仓库类型
            if (!string.IsNullOrEmpty(StoreTypeSelect))
            {
                SqlString += " and a.StoreType=" + StoreTypeSelect;
            }
            //仓库归属创客编号
            if (!string.IsNullOrEmpty(StoreUserIdMakerCode))
            {
                SqlString += " and a.StoreUserId in (select StoreUserId from UserForMakerCode where MakerCode='" + StoreUserIdMakerCode + "')";
            }
            //仓库归属创客真实姓名
            if (!string.IsNullOrEmpty(StoreUserIdRealName))
            {
                SqlString += " and a.StoreUserId in (select StoreUserId from UserForRealName where RealName='" + StoreUserIdRealName + "')";
            }
            //支付状态
            if (!string.IsNullOrEmpty(PayStatusSelect))
            {
                SqlString += " and a.PayStatus=" + PayStatusSelect;
            }
            //支付时间
            if (!string.IsNullOrEmpty(PayDateData))
            {
                string[] datelist = PayDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                SqlString += " and a.PayDate>='" + start + " 00:00:00' and a.PayDate<='" + end + " 23:59:59'";
            }
            //下单时间
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                SqlString += " and a.CreateDate>='" + start + " 00:00:00' and a.CreateDate<='" + end + " 23:59:59'";
            }
            //发货时间
            if (!string.IsNullOrEmpty(SendDateData))
            {
                string[] datelist = SendDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                SqlString += " and a.SendDate>='" + start + " 00:00:00' and a.SendDate<='" + end + " 23:59:59'";
            }
            var Sql = "SELECT b.MakerCode '创客编号',b.RealName '创客真实姓名',a.OrderNo '订单号',a.Mobile '手机号',a.RealName '姓名',a.TotalPrice '总价',a.Areas '所在地区',a.Address '详细地址',a.ErpName '物流名称',a.ErpCode '运单号',DATE_FORMAT(a.SendDate,'%Y-%m-%d %H:%i:%s') '发货时间',(CASE WHEN a.PayMode=1 THEN '支付宝' WHEN a.PayMode=2 THEN '微信' WHEN a.PayMode=3 THEN '账户余额' ELSE '' end) '支付方式',DATE_FORMAT(a.PayDate,'%Y-%m-%d %H:%i:%s') '支付时间',a.TradeNo '支付交易号',c.StoreNo '仓库编号',c.StoreName '仓库名称',(CASE WHEN a.RefundStatus=0 THEN '未退款' WHEN a.RefundStatus=1 THEN '已退款' end) '退款状态',(CASE WHEN a.DeliveryType=1 THEN '邮寄到付' WHEN a.DeliveryType=2 THEN '上门自提' ELSE '' end) '提货类型',(CASE WHEN a.SendStatus=0 THEN '未发货' WHEN a.SendStatus=1 THEN '已发货' WHEN a.SendStatus=2 THEN '已退货' ELSE '' end) '发货状态',d.ProductName '商品名称',a.BuyCount '下单数量',d.TotalPrice '商品单价',d.NormDetail '商品规格',a.StoreContact '仓库联系人',(CASE WHEN a.StoreType=0 THEN '总仓' WHEN a.StoreType=1 THEN '分仓' ELSE '' end) '仓库类型',e.MakerCode '仓库归属创客编号',e.RealName '仓库归属创客姓名',(CASE WHEN a.PayStatus=0 THEN '未支付' WHEN a.PayStatus=1 THEN '支付成功' WHEN a.PayStatus=2 THEN '支付失败' WHEN a.PayStatus=3 THEN '支付锁定中' WHEN a.PayStatus=4 THEN '支付处理中' ELSE '' end) '支付状态',a.Remark '订单备注' FROM Orders a LEFT JOIN Users b ON a.UserId=b.Id LEFT JOIN StoreHouse c ON a.StoreId=c.Id LEFT JOIN OrderProduct d ON a.Id=d.OrderId LEFT JOIN Users e ON a.StoreUserId=e.Id" + SqlString + "";
            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


        #region 查询直推奖励100

        public Dictionary<string, string> Prize100(int Id)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            string result = "";
            Orders order = db.Orders.FirstOrDefault(m => m.Id == Id) ?? new Orders();
            if (order.PayStatus < 1)
            {
                result += "未付款\n";
                dic.Add("code", "1");
                dic.Add("result", result);
                return dic;
            }
            Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId) ?? new Users();
            Users puser = db.Users.FirstOrDefault(m => m.Id == user.ParentUserId) ?? new Users();
            result += "订单号：" + order.OrderNo + "\n";
            result += "下单创客\n创客编号：" + user.MakerCode + "，姓名：" + user.RealName + "，手机号：" + user.Mobile + "\n";
            result += "上级创客\n创客编号：" + puser.MakerCode + "，姓名：" + puser.RealName + "，手机号：" + puser.Mobile + "\n";
            int machineCount = db.PosMachinesTwo.Count(m => m.UserId == puser.Id && m.PosSnType == 0); //判断是否拥有3台兑换机
            int ActiveCount = db.PosMachinesTwo.Count(m => m.UserId == puser.Id && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
            if (machineCount + ActiveCount >= 3)
            {
                string IsGet = "未发放";
                int ToUserId = 0;
                UserAccountRecord item = db.UserAccountRecord.FirstOrDefault(m => m.QueryCount == Id);
                if (item == null)
                {
                    DateTime start = order.PayDate.Value.AddMinutes(-2);
                    DateTime end = order.PayDate.Value.AddMinutes(2);
                    item = db.UserAccountRecord.FirstOrDefault(m => m.UserId == puser.Id && m.ChangeType == 112 && m.ChangeAmount == 100 && m.CreateDate >= start && m.CreateDate <= end);
                }
                if (item != null)
                {
                    IsGet = "已发放(发放时间:" + item.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") + ")";
                    ToUserId = item.UserId;
                    dic.Add("code", "1");
                }
                else
                {
                    dic.Add("code", "0");
                }
                Users touser = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                result += "是否发放：" + IsGet + "\n";
                result += "应该发放对象\n创客编号：" + puser.MakerCode + "，姓名：" + puser.RealName + "，手机号：" + puser.Mobile + "\n";
                result += "实际发放对象\n创客编号：" + touser.MakerCode + "，姓名：" + touser.RealName + "，手机号：" + touser.Mobile + "\n";
            }
            else
            {
                result += "上级创客未满足条件\n兑换机：" + machineCount + "台，激活机：" + ActiveCount + "台\n";
                dic.Add("code", "1");
            }
            dic.Add("result", result);
            return dic;
        }
        public string AddPrize100(int Id)
        {
            Orders order = db.Orders.FirstOrDefault(m => m.Id == Id);
            if (order != null)
            {
                //机具券逻辑
                OrderProduct pro = db.OrderProduct.FirstOrDefault(m => m.OrderId == Id);
                if (pro != null)
                {
                    //推荐下单奖励
                    if (pro.ProductId == 10 || pro.ProductId == 11)
                    {
                        Users user = db.Users.FirstOrDefault(m => m.Id == order.UserId);
                        if (user != null)
                        {
                            int ParentUserId = user.ParentUserId;
                            int machineCount = db.PosMachinesTwo.Count(m => m.UserId == ParentUserId && m.PosSnType == 0); //判断是否拥有3台兑换机
                            int ActiveCount = db.PosMachinesTwo.Count(m => m.UserId == ParentUserId && m.ActivationState == 1); //判断是否拥有3台激活机（不限购买或赠送）
                            if (machineCount + ActiveCount >= 3)
                            {
                                UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == ParentUserId);
                                if (account == null)
                                {
                                    account = db.UserAccount.Add(new UserAccount()
                                    {
                                        Id = ParentUserId,
                                        UserId = ParentUserId,
                                    }).Entity;
                                    db.SaveChanges();
                                }
                                decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                                decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                                decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                                account.BalanceAmount += 100;
                                account.TotalAmount += 100;
                                decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                                decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                                decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                                UserAccountRecord add = db.UserAccountRecord.Add(new UserAccountRecord()
                                {
                                    CreateDate = DateTime.Now,
                                    UpdateDate = DateTime.Now,
                                    UserId = ParentUserId, //创客
                                    ChangeType = 112, //变动类型
                                    ChangeAmount = 100, //变更金额
                                    BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                                    AfterTotalAmount = AfterTotalAmount, //变更后总金额
                                    BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                                    AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                                    BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                                    AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                                    QueryCount = order.Id,
                                }).Entity;
                                db.SaveChanges();
                                PublicFunction.SplitUserAccountRecord(add);

                                //推荐下单上级获得30天的机具循环天数
                                var posList = db.PosMachinesTwo.Select(m => new { m.Id, m.UserId, m.BindingState, m.RecycEndDate }).Where(m => m.UserId == ParentUserId && m.BindingState == 0 && m.RecycEndDate != null).ToList();
                                foreach (var subPos in posList)
                                {
                                    PosMachinesTwo pos = db.PosMachinesTwo.FirstOrDefault(m => m.Id == subPos.Id);
                                    if (pos != null)
                                    {
                                        pos.RecycEndDate = pos.RecycEndDate.Value.AddDays(30);
                                    }
                                }
                                db.SaveChanges();
                                return "success";
                            }
                            else
                            {
                                return "上级创客未满足条件：兑换机：" + machineCount + "台，激活机：" + ActiveCount + "台";
                            }
                        }
                    }
                }
            }
            return "操作失败";
        }

        #endregion
    }
}
