/*
 * 退款申请
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MySystem.Models;
using Library;
using LitJson;
using MySystemLib;

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

        #endregion

        #region 根据条件查询退款申请列表

        /// <summary>
        /// 退款申请列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(OrderRefund data, string OrderNo, string CreateDateData, string UserIdMakerCode, string ProductIdSelect, string RefundStatusSelect, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            string condition = " and Status>-1";
            //平台订单号
            if (!string.IsNullOrEmpty(OrderNo))
            {
                condition += " and OrderNo like '" + OrderNo + "'";
            }
            //退货时间
            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(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //商品名称
            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("OrderRefund", Fields, "Id desc", "False", page, limit, condition);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //创客
                int UserId = int.Parse(function.CheckInt(dic["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");

                //商品名称
                dic["ProductName"] = RelationClass.GetProductsInfo(int.Parse(dic["ProductId"].ToString()));
                
            }
            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(OrderRefund data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("Reason", data.Reason); //退款原因
            Fields.Add("Amount", data.Amount); //退款金额
            Fields.Add("Contents", data.Contents); //补充说明
            Fields.Add("Mobile", data.Mobile); //申请人手机号
            Fields.Add("GoodStatus", data.GoodStatus); //货物状态
            Fields.Add("Photos", data.Photos); //凭证
            Fields.Add("ErpCompany", data.ErpCompany); //快递公司
            Fields.Add("ErpCode", data.ErpCode); //快递运单号

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

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

            string[] idlist = editData.ProductId.Split(',');
            List<int> ids = new List<int>();
            foreach (string idstring in idlist)
            {
                ids.Add(int.Parse(idstring));
            }
            List<OrderProduct> products = db.OrderProduct.Where(m => ids.Contains(m.Id)).ToList();
            ViewBag.products = products;
            return View();
        }

        #endregion

        #region 修改退款申请

        /// <summary>
        /// 增加或修改退款申请信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(OrderRefund data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            OrderRefund refund = db.OrderRefund.FirstOrDefault(m => m.Id == data.Id);
            if (refund != null)
            {
                if (refund.Status == 1)
                {
                    return "已经处理过了";
                }
                refund.Status = 1;
            }
            Fields.Add("Status", 1);
            Orders order = db.Orders.FirstOrDefault(m => m.Id == data.OrderId);
            if (order != null)
            {
                order.Status = 6;
                string result = "";
                PublicAccountSet set = db.PublicAccountSet.FirstOrDefault() ?? new PublicAccountSet();
                if (order.PayMode == 1)
                {
                    result = new Alipay.AlipayPublicClass(_accessor.HttpContext).Refund(set.AlipayAppId, set.AlipayPrivateKey, set.AlipayPublicKey, order.OrderNo, order.ActualPay);
                }
                else if (order.PayMode == 2)
                {
                    result = new WeChat.WeChatPublicClass(_accessor.HttpContext).Refund(set.WeChatAppId, set.WeChatMchId, order.OrderNo, order.TradeNo, order.ActualPay, set.WeChatPayKey, function.getPath("/Public/Cert/WeChat/apiclient_cert.p12"));
                }
                if (result.StartsWith("success|"))
                {
                    int OrderCount = db.OrderForNo.FirstOrDefault(m => m.OrderNo == order.OrderNo).OrderIds.Split(',').Length;
                    if (order.CouponId > 0 && OrderCount == 1)
                    {
                        Coupons coupon = db.Coupons.FirstOrDefault(m => m.Id == order.CouponId);
                        if (coupon != null)
                        {
                            if (coupon.IsReUse == 0)
                            {
                                CouponsForUser couponForUser = db.CouponsForUser.FirstOrDefault(m => m.UserId == order.UserId && m.CouponId == order.CouponId && m.IsUse == 1);
                                if (couponForUser != null)
                                {
                                    couponForUser.IsLock = 0;
                                    couponForUser.IsUse = 0;
                                }
                            }
                        }
                    }
                }
            }
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("OrderRefund", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "OrderRefund", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除退款申请信息

        /// <summary>
        /// 删除退款申请信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "OrderRefund", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Delete("OrderRefund", id);
            }
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 开启

        /// <summary>
        /// 开启
        /// </summary>
        /// <returns></returns>
        public string Open(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "OrderRefund", "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("OrderRefund", 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, "OrderRefund", "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("OrderRefund", 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("OrderRefund", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(OrderRefund data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("Reason", "1"); //退款原因
            Fields.Add("Mobile", "2"); //申请人手机号
            Fields.Add("GoodStatus", "1"); //货物状态

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("OrderRefund", Fields, "Id desc", "False", 1, 20000, "", "", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;

            Dictionary<string, object> result = new Dictionary<string, object>();
            result.Add("Status", "1");
            result.Add("Info", "Excel报表-" + DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss") + ".xlsx");
            result.Add("Obj", diclist);
            Dictionary<string, object> ReturnFields = new Dictionary<string, object>();

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

        #endregion

    }
}