using LitJson;
using RFrameGenerate.BLL;
using RFrameGenerate.Common;
using RFrameGenerate.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace jiouosdp.Controllers.WX
{
    public class OrderController : BaseWeiXinController
    {
        //
        // GET: /Order/

        public ActionResult Index(int? tag = 0)
        {
            ViewBag.tag = tag ?? 0;
            return View();
        }
        public ActionResult Refund()
        {
            return View();
        }
        public ActionResult RefundApplys(Guid orderDetailGuid)
        {
            var model = OrderDetailsManage.GetEntity(orderDetailGuid);
            return View(model);
        }
        //public ActionResult RefundApplysMoney(Guid orderDetailGuid)
        //{
        //    var model = OrderDetailsManage.GetEntity(orderDetailGuid);
        //    return View(model);
        //}

        public ActionResult RefundApplysOrder(Guid orderGuid)
        {
            var model = OrderManage.GetEntity(orderGuid, RFrameGenerate.Common.CurrentManage.MerchantGuid);
            return View(model);
        }


        /// <summary>
        /// 取消退款
        /// </summary>
        /// <param name="orderDetailGuid"></param>
        /// <returns></returns>
        public JsonResult RefundApplysCancel(Guid refundApplyGuid)
        {
            var result = RefundApplysManage.Action_Cancel(refundApplyGuid, CurrentManage.MerchantGuid);
            if (result.State)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 查看退款
        /// </summary>
        /// <param name="data"></param>
        /// <param name="orderDetailGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        /// 
        public ActionResult RefundApplysMoneyView(Guid orderDetailGuid)
        {
            var model = RefundOrderDetailsManage.GetEntity(orderDetailGuid);
            if (model == null || model.RefundApplyGuid == null)
                return View("RefundEmpty");
            var entity = RefundApplysManage.GetEntity(model.RefundApplyGuid);
            if (entity == null)
                return View("RefundEmpty");
            return View(entity);
        }
        /// <summary>
        /// 查看退单
        /// </summary>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public ActionResult RefundApplysOrderView(Guid orderGuid)
        {
            var entity = RefundApplysManage.GetEntityByOrderGuid(orderGuid);
            if (entity == null)
                return View("RefundEmpty");
            return View(entity);
        }
        /// <summary>
        /// 提交退款申请
        /// </summary>
        /// <param name="refundApplyGuid"></param>
        /// <param name="express"></param>
        /// <param name="expressNumber"></param>
        /// <returns></returns>
        public JsonResult Submit(Guid refundApplyGuid, string express, string expressNumber)
        {
            var result = RefundApplysManage.Submit(refundApplyGuid, express, expressNumber, CurrentManage.MerchantGuid);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }
        /// <summary>
        /// 重新提交退款申请
        /// </summary>
        /// <param name="refundApplyGuid"></param>
        /// <returns></returns>
        public JsonResult ReSubmit(Guid refundApplyGuid)
        {
            var result = RefundApplysManage.ReSubmit(refundApplyGuid, CurrentManage.MerchantGuid);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        public JsonResult UpdateOrderState(Guid orderGuid, int state)
        {
            var result = OrderManage.UpdateState(orderGuid, state);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        public ActionResult QueryLogistics(Guid? orderid, Guid? logid)
        {
            if (orderid != null)
            {
                ViewBag.order = OrderManage.GetOrderList(orderid.Value);
                ViewBag.Logist = LogisticManage.GetLogist(logid);
            }
            else
            {
                ViewBag.order = new List<T_BAS_OrderDetails>();
                ViewBag.Logist = new T_BAS_Logistics();
            }
            return View();
        }

        public ActionResult OrderDetail(Guid orderGuid)
        {
            var mentity = DistributionManage.GetStoreInfo();
            ViewBag.StoreTitle = mentity.SotreTitle;
            var model = OrderManage.GetEntity(orderGuid, RFrameGenerate.Common.CurrentManage.MerchantGuid);
            return View(model);
        }

        public ActionResult EvaluateOrder(Guid? orderid)
        {
            if (orderid != null)
            {
                ViewBag.order = OrderManage.GetOrderList(orderid.Value);
            }
            else
            {
                ViewBag.order = new List<T_BAS_OrderDetails>();
            }
            ViewBag.OrderID = orderid;
            return View();
        }
        //public JsonResult SaveEvaluate(string data, Guid orderGuid, bool isAnon)
        //{
        //    JavaScriptSerializer script = new JavaScriptSerializer();
        //    var list= script.Deserialize<List<Evaluates>>(data);
        //    var result = CommentManage.SaveEvaluate(list, orderGuid, isAnon);
        //    if (result.State == true)
        //        return Json(new { Result = "OK" });
        //    else
        //        return Json(new { Result = "NO", Msg = result.Msg });
        //}

        public JsonResult SaveEvaluate(List<T_BAS_Comments> data, List<T_BAS_CommentsImg> dataImg, Guid guid)
        {
            //JavaScriptSerializer script = new JavaScriptSerializer();
            //var list = script.Deserialize<List<Evaluates>>(data);

            var result = CommentManage.SaveEvaluate(data, dataImg, guid);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });

        }

        public ActionResult EvaluateOrders(Guid? orderid)
        {
            if (orderid != null)
            {
                ViewBag.order = OrderManage.GetOrderList(orderid.Value);
            }
            else
            {
                ViewBag.order = new List<T_BAS_OrderDetails>();
            }
            ViewBag.OrderID = orderid;
            return View();
        }
        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="data"></param>
        /// <param name="orderDetailGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public JsonResult RefundApplysMoney(string data)
        {
            JavaScriptSerializer script = new JavaScriptSerializer();
            var list = script.Deserialize<List<RefundApplysInfo>>(data);

            var result = RefundApplysManage.AddRefundApply(list, RFrameGenerate.Common.CurrentManage.MerchantGuid);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        /// <summary>
        /// 退单
        /// </summary>
        /// <param name="data"></param>
        /// <param name="orderDetailGuid"></param>
        /// <param name="orderGuid"></param>
        /// <returns></returns>
        public JsonResult RefundApplys_Order(string data, Guid orderGuid)
        {
            JavaScriptSerializer script = new JavaScriptSerializer();
            var list = script.Deserialize<List<RefundApplysInfo>>(data);

            var result = RefundApplysManage.AddRefundApplyList(list, orderGuid, RFrameGenerate.Common.CurrentManage.MerchantGuid);
            if (result.State == true)
                return Json(new { Result = "OK" });
            else
                return Json(new { Result = "NO", Msg = result.Msg });
        }

        [HttpPost]
        public void Upload()
        {
            string returnstr = string.Empty;
            string relativePath = string.Empty;
            try
            {
                foreach (string upload in Request.Files)
                {
                    var file = Request.Files[upload];
                    string fileNameExt = Path.GetExtension(file.FileName).ToLower();

                    if (fileNameExt != ".jpg" && fileNameExt != ".gif" && fileNameExt != ".png" && fileNameExt != ".jpeg")
                    {
                        throw new Exception("不合适的文件,只能支持jpg|gif|png|jpeg的文件");
                    }

                    if (!UpLoadFileHelp.HasFile(file)) continue;

                    var dateTimeNow = DateTime.Now;
                    var basePath = string.Empty;

                    basePath = DictionaryConst.UpLoadPath.CommentsImg;

                    var fileName = dateTimeNow.ToString("yyyyMMddHHmmssfff")
                        + RadomCode.DigitalCode(3) + "01" + fileNameExt;

                    relativePath = basePath + "/" + fileName;
                    string DirUrl = Server.MapPath("~" + basePath);

                    UpLoadFileHelp.SaveInFileSystem(file, DirUrl, fileName);

                    var newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff")
                         + RadomCode.DigitalCode(3) + "02" + fileNameExt;

                    var newFilePath = basePath + "/" + newFileName;

                    var newFile = Server.MapPath("~" + newFilePath);

                    //RFramework.Log.Write(System.Threading.Thread.CurrentThread.ManagedThreadId + " >>Upload Src " + fileName);
                    //RFramework.Log.Write(System.Threading.Thread.CurrentThread.ManagedThreadId + " >>Upload Tar " + newFileName);

                    if (file.ContentLength > 1048576 && RFrameGenerate.Common.GraphicHelper.GetPicThumbnail(DirUrl + "\\" + fileName, newFile, 30))
                    {
                        //RFramework.Log.Write(System.Threading.Thread.CurrentThread.ManagedThreadId + " >>Upload  GetPicThumbnail True " + newFilePath);

                        System.IO.File.Delete(DirUrl + "\\" + fileName);

                        relativePath = newFilePath;
                    }
                }

                Hashtable successHash = new Hashtable();
                successHash["error"] = 0;
                successHash["url"] = relativePath;
                Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                Response.Write(JsonMapper.ToJson(successHash));
                Response.End();

            }
            catch (Exception e)
            {
                MvcLog.Write("Error:{0},State:{1}", e.Message, e.StackTrace);
                Hashtable failueHash = new Hashtable();
                failueHash["error"] = 1;
                failueHash["message"] = e.Message;
                Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
                Response.Write(JsonMapper.ToJson(failueHash));
                Response.End();
            }
        }

        /// <summary>
        /// 退款
        /// </summary>
        /// <param name="data"></param>
        /// <param name="orderDetailGuid"></param>
        /// <returns></returns>
        //public JsonResult RefundApplys_Money(string data, Guid orderDetailGuid, Guid orderGuid)
        //{
        //    JavaScriptSerializer script = new JavaScriptSerializer();
        //    var list = script.Deserialize<List<RefundApplysInfo>>(data);

        //    var result = RefundApplysManage.AddRefundApply(list, orderDetailGuid, orderGuid, RFrameGenerate.Common.CurrentManage.MerchantGuid);
        //    if (result.State == true)
        //        return Json(new { Result = "OK" });
        //    else
        //        return Json(new { Result = "NO", Msg = result.Msg });
        //}

        /// <summary>
        /// 查看订单列表
        /// </summary>
        /// <param name="expresses"></param>
        /// <returns></returns>
        public ActionResult LogisticsList(string companyName, string expresses, int? tag)
        {
            ViewBag.CompanyName = companyName;
            ViewBag.Expresses = expresses;
            ViewBag.Tag = tag ?? 0;

            return View();
        }



    }
}
