using jiouosdp.Controllers;
using OfficeOpenXml.Style;
using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using RFramework.Excel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace jiouosdp.Areas.Orders.Controllers
{
    public class MainController : BaseController
    {
        //
        // GET: /Orders/Main/
        OrderManage ordersManage;
        public MainController()
        {
            if (ordersManage == null)
                ordersManage = new OrderManage();
        }

        [PF(PCode.TradeManage.TradeIndex)]
        public ActionResult Index()
        {

            return View();
        }
        public JsonResult GetOrderDetail(GridModel gridModel, Guid? id)
        {
            if (id != null)
            {
                var list = OrderManage.GetDetailList(id.Value);
                gridModel.datarows = (from s in list
                                      select new
                                      {
                                          id = s.OrderDetailGuid,
                                          cell = new object[]
                                            {
                                                s.ProductName,
                                                s.Price,
                                                s.DiscountPrice == null ||s.DiscountPrice == 0.0m?100:(int)(s.DiscountPrice*100),
                                                s.Quantity,
                                                s.Discount, 
                                                s.IntegralMoney??0,
                                            }
                                      }).ToArray();
            }
            return Json(gridModel.PackagePageModel());
        }

        public JsonResult ChangePrice(Guid id, decimal price,Guid? merchantGuid=null)
        {
            var guid =   merchantGuid.Value;
            var result = OrderManage.ChangePrice(id, price, guid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public ActionResult OrderDetails(Guid guid,Guid merchantGuid)
        {
            ViewBag.CurrentMerchantGuid = merchantGuid;
            var model = ordersManage.GetEntity(guid);
            return View(model);
        }


        #region   订单列表
        /// <summary>
        /// 获取订单列表（分页）
        /// </summary>
        /// <param name="gridModel"></param>
        /// <returns></returns>
        public JsonResult GetPageList(GridModel gridModel, Guid? merchantguid, string orderState, string memberName, string orderNo, string payNo, string reciever)
        {

            var list = ordersManage.GetPageList(gridModel,merchantguid, orderState, memberName, orderNo, payNo, reciever);
            gridModel.datarows = (from s in list
                                  select new
                                  {
                                      id = s.OrderGuid,
                                      cell = new object[]
                                            {
                                                s.OrderGuid,
                                                s.LogisticrGuid,
                                                s.MemberGuid,
                                                s.MerchantGuid,
                                                s.MemberName,
                                                s.OrderNo,
                                                s.TransactionID,
                                                s.OrderTime,
                                                s.PayWay,
                                                s.DeliveryMethod,
                                                s.Reciever,
                                                s.TotalMoney,
                                                s.ExpressCompany,
                                                s.OrderState,
                                                s.GoodsDeliveryType,
                                                s.CommodityRefundAudit,
                                                s.UserID,
                                                s.StoreTitle
                                            }
                                  }).ToArray();
            return Json(gridModel.PackagePageModel());
        }
        /// <summary>
        /// 保存物流信息
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <param name="logisticsGuid"></param>
        /// <returns></returns>

        public JsonResult SaveLogistics(Guid? entityGuid, string expressNumber, Guid expressCompany, Guid recieverAddress, Guid orderGuid,Guid MerchantGuid)
        {
            var result = LogisticManage.SaveLogistics(entityGuid, expressNumber, expressCompany, recieverAddress, orderGuid);

            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 保存备注
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <param name="remark"></param>
        /// <returns></returns>
        public JsonResult SaveRemark(Guid? entityGuid, string remark,Guid merchantGuid)
        {
            var result = OrderManage.SaveRemark(entityGuid, remark,merchantGuid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 付款
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public JsonResult Action_Paid(Guid entityGuid,Guid merchantGuid)
        {
            var result = OrderManage.Action_Paid(entityGuid,merchantGuid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        /// <summary>
        /// 付款-取消订单
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public JsonResult Action_OrderCancel(Guid? entityGuid,Guid merchantGuid)
        {
            var result = OrderManage.Action_OrderCancel(entityGuid,merchantGuid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 发货
        /// </summary>
        /// <param name="entityGuid"></param>
        /// <returns></returns>
        public JsonResult Action_Delivery(Guid entityGuid, Guid logisticsCompanyGuid, string logisticsExpressNumber, Guid recieverAddressGuid,Guid merchantGuid)
        {
            var result = OrderManage.Action_Delivery(entityGuid, logisticsCompanyGuid, logisticsExpressNumber, recieverAddressGuid,merchantGuid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 确认收货
        /// </summary>
        /// <param name="parameterList"></param>
        /// <returns></returns>
        public JsonResult Action_Receipt(Guid? entityGuid,Guid merchantGuid)
        {
            var result = OrderManage.Action_Receipt(entityGuid,merchantGuid);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 保存订单设置
        /// </summary>
        /// <param name="parameterList"></param>
        /// <returns></returns>
        public JsonResult Save_Parameters(List<T_SYS_Parameter> parameterList)
        {
            var result = ParameterManage.Save_Parameters(parameterList);
            if (result.State)
            {
                return Json(new { Result = "OK" });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        /// <summary>
        /// 获取订单设置
        /// </summary>
        /// <param name="parameterList"></param>
        /// <returns></returns>
        public JsonResult GetParameters(Guid merchantGuid)
        {
            List<T_SYS_Parameter> relList = new List<T_SYS_Parameter>();
            var result = ParameterManage.GetParameters_Order(merchantGuid, ref  relList);
            if (result.State)
            {
                return Json(new { Result = "OK", ParametersList = relList });
            }
            return Json(new { Result = "NO", Msg = result.Msg });
        }

        public ContentResult BulkDelivery()
        {
            string fullName = string.Empty;
            string fileName = string.Empty;
            long ticks = DateTime.Now.Ticks;
            string path = string.Empty;
            foreach (string upload in Request.Files)
            {
                var file = Request.Files[upload];
                string fileNameExt = Path.GetExtension(file.FileName).ToLower();
                fullName = file.FileName.Substring(0, file.FileName.LastIndexOf('.')).Trim();

                var basePath = DictionaryConst.UpLoadPath.DeliveryPath;

                fileName = fullName + ticks + fileNameExt;
                string DirUrl = Server.MapPath("~" + basePath);

                path = DirUrl + "\\" + fileName;
                string relativePath = basePath + "/" + fileName;
                //如果不存在就创建文件夹
                if (Directory.Exists(DirUrl) == false)
                {
                    Directory.CreateDirectory(DirUrl);
                }
                UpLoadFileHelp.SaveInFileSystem(file, DirUrl, fileName);
            }
            DataTable dt = ExcelManage.ExcelImportFromFile(path, "sheet1");
            StringBuilder sb = new StringBuilder();
            var result = OrderManage.Delivery(dt, ref sb);
            if (result.State)
                return Content(sb.ToString());
            else
                return Content(sb.ToString());
        }

        public void ExportOrdersByPrm(Guid merchantguid, string orderState, string memberName, string orderNo, string payNo, string reciever)
        {
            DataTable dt = ordersManage.ExportOrdersByPrm(merchantguid, orderState, memberName, orderNo, payNo, reciever);
            if (dt != null && dt.Rows.Count > 0)
            {
                byte[] buffer = RFramework.Excel.ExcelManage.ExportExcelToByte<ExcelWork, OfficeOpenXml.ExcelRange>("订单明细", dt, null, (ExcelWork, ExcelRange) =>
                {
                    var sheet = ExcelWork.Sheet;
                    if (ExcelWork.Style == ExcelWrokStyles.Title)
                    {
                        var title = ExcelRange;
                        #region 样式设置
                        //标题
                        title.Style.Fill.PatternType = ExcelFillStyle.Solid;
                        title.Style.Font.Bold = true;
                        title.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                        title.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                        title.Style.Fill.BackgroundColor.SetColor(Color.Blue);
                        //奇偶行设置颜色
                        //for (int r = 1; r <= sheet.Cells.End.Row; r++)
                        //{
                        //    if (r % 2 == 0)
                        //        sheet.Cells[r, 1, r, sheet.Cells[0].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(252, 228, 214));
                        //    else
                        //        sheet.Cells[r, 1, r, sheet.Cells.End.Column].Style.Fill.BackgroundColor.SetColor(Color.FromArgb(237, 237, 237));
                        //}
                        #endregion
                    }
                    else
                    {
                        var work = ExcelRange;
                        //正文
                        work.Style.Fill.PatternType = ExcelFillStyle.Solid;
                        work.Style.Fill.BackgroundColor.SetColor(Color.WhiteSmoke);
                        work.Style.Border.Top.Style = ExcelBorderStyle.Thin;
                        work.Style.Border.Top.Color.SetColor(Color.Black);
                        work.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                        work.Style.Border.Right.Color.SetColor(Color.Black);
                        work.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
                        work.Style.Border.Bottom.Color.SetColor(Color.Black);
                        work.Style.Border.Left.Style = ExcelBorderStyle.Thin;
                        work.Style.Border.Left.Color.SetColor(Color.Black);

                        
                    }
                });
                Response.BinaryWrite(buffer);
                string fileName = string.Format("订单明细" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                if (Request.UserAgent.ToLower().IndexOf("msie") > -1)
                {
                    fileName = HttpUtility.UrlPathEncode(fileName);
                }
                if (Request.UserAgent.ToLower().IndexOf("firefox") > -1)
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
                }
                else
                {
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
                }
            }
        }
        #endregion

        #region 订单详情

        #endregion
    }
}
