/*
 * 待扣款明细
 */

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


            return View();
        }

        #endregion

        #region 根据条件查询待扣款明细列表

        /// <summary>
        /// 待扣款明细列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(ToChargeBackRecordSub data, string OrderNo, string StatusSelect, string KindSelect, string CreateDateData, int page = 1, int limit = 30)
        {

            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("ParentId", "1");

            string condition = " and Status>-1";

            //分期单号
            if (!string.IsNullOrEmpty(OrderNo))
            {
                var toChargeByStage = db.ToChargeByStage.FirstOrDefault(m => m.SeoKeyword == OrderNo) ?? new ToChargeByStage();
                var toChargeBackRecordSub = db.ToChargeBackRecordSub.FirstOrDefault(m => m.ParentId == toChargeByStage.Id) ?? new ToChargeBackRecordSub();
                condition += " and ParentId=" + toChargeByStage.Id;
            }

            //待扣类别
            if (!string.IsNullOrEmpty(KindSelect))
            {
                condition += " and Kind=" + KindSelect;
            }

            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }

            //创建时间
            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'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ToChargeBackRecordSub", 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)
            {
                //状态
                int Status = int.Parse(function.CheckInt(dic["Status"].ToString()));
                dic["StatusName"] = "";
                if (Status == 0)
                {
                    dic["StatusName"] = "待扣款";
                }
                if (Status == 1)
                {
                    dic["StatusName"] = "已扣款";
                }
                if (Status == 2)
                {
                    dic["StatusName"] = "扣款中";
                }

                //待扣类别
                int Kind = int.Parse(dic["Kind"].ToString());
                if (Kind == 0) dic["KindName"] = "创客预扣款";
                if (Kind == 1) dic["KindName"] = "盟主预扣款";
                if (Kind == 2) dic["KindName"] = "运营中心预扣款";

                //分期单号
                int ParentId = int.Parse(function.CheckInt(dic["ParentId"].ToString()));
                var toChargeByStage = db.ToChargeByStage.FirstOrDefault(m => m.Id == ParentId) ?? new ToChargeByStage();
                dic["OrderNo"] = toChargeByStage.SeoKeyword;
            }
            return Json(obj);
        }

        #endregion

        #region 增加待扣款明细

        /// <summary>
        /// 增加或修改待扣款明细信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Add(string right, string ParentId)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.ParentId = ParentId;


            return View();
        }

        #endregion

        #region 增加待扣款明细

        /// <summary>
        /// 增加或修改待扣款明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Add(ToChargeBackRecordSub data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            Fields.Add("ParentId", data.ParentId);

            Fields.Add("ChargeAmount", data.ChargeAmount); //待扣金额
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("StartDate", data.StartDate); //扣款开始时间
            Fields.Add("TimeNumber", data.TimeNumber); //期数

            Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.SeoDescription);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("ToChargeBackRecordSub", Fields, 0);
            AddSysLog(data.Id.ToString(), "ToChargeBackRecordSub", "add");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 修改待扣款明细

        /// <summary>
        /// 增加或修改待扣款明细信息
        /// </summary>
        /// <returns></returns>
        public IActionResult Edit(string right, string ParentId, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.ParentId = ParentId;


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

        #endregion

        #region 修改待扣款明细

        /// <summary>
        /// 增加或修改待扣款明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(ToChargeBackRecordSub data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            var toChargeBackRecordSub = db.ToChargeBackRecordSub.FirstOrDefault(m => m.Id == data.Id) ?? new ToChargeBackRecordSub();
            var toChargeByStage = db.ToChargeByStage.FirstOrDefault(m => m.Id == toChargeBackRecordSub.ParentId) ?? new ToChargeByStage();
            if (toChargeByStage.QueryCount > 0)
            {
                return "该扣款记录正处于扣款中或已经结束，不能修改！";
            }
            if (toChargeBackRecordSub.ChargeAmount != data.ChargeAmount)
            {

                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == toChargeByStage.UserId) ?? new UserAccount();
                if (toChargeBackRecordSub.ChargeAmount > data.ChargeAmount)
                {
                    toChargeByStage.TotalAmount -= toChargeBackRecordSub.ChargeAmount - data.ChargeAmount;
                    if (toChargeBackRecordSub.Kind == 0) userAccount.ToChargeAmount -= toChargeBackRecordSub.ChargeAmount - data.ChargeAmount;
                    if (toChargeBackRecordSub.Kind == 1) userAccount.LeaderToChargeAmount -= toChargeBackRecordSub.ChargeAmount - data.ChargeAmount;
                    if (toChargeBackRecordSub.Kind == 2) userAccount.OperateToChargeAmount -= toChargeBackRecordSub.ChargeAmount - data.ChargeAmount;
                }
                if (toChargeBackRecordSub.ChargeAmount < data.ChargeAmount)
                {
                    toChargeByStage.TotalAmount += data.ChargeAmount - toChargeBackRecordSub.ChargeAmount;

                    if (toChargeBackRecordSub.Kind == 0) userAccount.ToChargeAmount += data.ChargeAmount - toChargeBackRecordSub.ChargeAmount;
                    if (toChargeBackRecordSub.Kind == 1) userAccount.LeaderToChargeAmount += data.ChargeAmount - toChargeBackRecordSub.ChargeAmount;
                    if (toChargeBackRecordSub.Kind == 2) userAccount.OperateToChargeAmount += data.ChargeAmount - toChargeBackRecordSub.ChargeAmount;
                }
            }
            Fields.Add("ChargeAmount", data.ChargeAmount); //待扣金额
            Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("StartDate", data.StartDate); //扣款开始时间
            Fields.Add("TimeNumber", data.TimeNumber); //期数

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

            return "success";
        }

        #endregion

        #region 删除待扣款明细信息

        /// <summary>
        /// 删除待扣款明细信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ToChargeBackRecordSub", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeBackRecordSub", 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, "ToChargeBackRecordSub", "open");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 1);
                Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeBackRecordSub", 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, "ToChargeBackRecordSub", "close");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 0);
                Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeBackRecordSub", 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("ToChargeBackRecordSub", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(ToChargeBackRecordSub data)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间


            string condition = " and Status>-1";


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ToChargeBackRecordSub", Fields, "Id desc", "0", 1, 20000, condition, "ChargeAmount,Remark", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {

            }

            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("ChargeAmount", "待扣金额");
            ReturnFields.Add("Remark", "备注");

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

        #endregion

    }
}
