/*
 * 分期扣款信息
 */

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


            return View();
        }

        #endregion

        #region 根据条件查询分期扣款信息列表

        /// <summary>
        /// 分期扣款信息列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(ToChargeByStage data, string MakerCode, string StatusSelect, string KindSelect, string CreateDateData, int page = 1, int limit = 30)
        {

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

            Fields.Add("SeoTitle", "1"); //创客姓名

            string condition = " and Status>-1";

            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                var userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
                condition += " and UserId=" + userForMakerCode.UserId;
            }
            //待扣类别
            if (!string.IsNullOrEmpty(KindSelect))
            {
                condition += " and Kind=" + KindSelect;
            }

            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                if (StatusSelect == "0")//待扣款
                {
                    condition += " and QueryCount<TimeNumber and QueryCount=0 and Status=0";
                }
                if (StatusSelect == "1")//已扣款
                {
                    condition += " and QueryCount=TimeNumber and Status=1";
                }
                if (StatusSelect == "2")//扣款中
                {
                    condition += " and QueryCount<TimeNumber and QueryCount>0 and Status=0";
                }
            }

            //创建时间
            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("ToChargeByStage", 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 UserId = int.Parse(function.CheckInt(dic["UserId"].ToString()));
                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = userid_Users.MakerCode;
                dic["MakerName"] = userid_Users.RealName;
                dic["MakerMobile"] = userid_Users.Mobile;

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

                //扣款状态
                int TimeNumber = int.Parse(function.CheckInt(dic["TimeNumber"].ToString()));
                int QueryCount = int.Parse(function.CheckInt(dic["QueryCount"].ToString()));
                int Status = int.Parse(function.CheckInt(dic["Status"].ToString()));
                if (QueryCount < TimeNumber && QueryCount == 0 && Status == 0)
                {
                    dic["StatusName"] = "待扣款";
                }
                if (QueryCount == TimeNumber && Status == 1)
                {
                    dic["StatusName"] = "已扣款";
                }
                if (QueryCount < TimeNumber && QueryCount > 0 && Status == 0)
                {
                    dic["StatusName"] = "扣款中";
                }

            }
            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(ToChargeByStage data, string MakerCode, string MakerName, string StartDates, string ChargeAmounts)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            string[] StartDatelist = StartDates.TrimEnd(',').Split(',');
            string[] ChargeAmountslist = ChargeAmounts.TrimEnd(',').Split(',');
            UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode);
            if (user == null)
            {
                return "创客编号不存在";
            }
            var userInfo = db.Users.FirstOrDefault(m => m.Id == user.UserId && m.RealName == MakerName) ?? new Users();
            if (userInfo.Id == 0)
            {
                return "创客编号不存在或创客编号和姓名不匹配";
            }
            var StartTime = DateTime.Parse(DateTime.Parse(data.StartDate.ToString()).ToString("yyyy-MM-20 00:00:00"));
            Fields.Add("UserId", user.UserId); //创客Id
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("Kind", data.Kind); //带扣类型(0 创客预扣款 1 盟主预扣款 2 运营宗欣预扣款)
            Fields.Add("StartDate", StartTime); //扣款开始时间
            Fields.Add("TimeNumber", data.TimeNumber); //期数
            Fields.Add("TotalAmount", data.TotalAmount); //扣款总金额
            Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);//操作人
            Fields.Add("SeoKeyword", "FQ" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + function.get_Random(8));//分期单号
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("ToChargeByStage", Fields, 0);
            for (int i = 0; i < StartDatelist.Length; i++)
            {
                var StartDate = StartDatelist[i];
                var ChargeAmount = ChargeAmountslist[i];
                var toChargeBackRecordSub = db.ToChargeBackRecordSub.Add(new ToChargeBackRecordSub()
                {
                    CreateDate = DateTime.Now,
                    SeoTitle = SysUserName + "_" + SysRealName,
                    StartDate = DateTime.Parse(StartDate),
                    TimeNumber = data.TimeNumber,
                    ChargeAmount = decimal.Parse(ChargeAmount),
                    ParentId = Id,
                    Remark = data.Remark,
                    Kind = data.Kind,
                }).Entity;
            }
            AddSysLog(data.Id.ToString(), "ToChargeByStage", "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;


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

        #endregion

        #region 修改分期扣款信息

        /// <summary>
        /// 增加或修改分期扣款信息信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(ToChargeByStage data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("UserId", data.UserId); //创客
            Fields.Add("ChargeAmount", data.ChargeAmount); //待扣金额
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("Kind", data.Kind); //带扣类型(0 创客预扣款 1 盟主预扣款 2 运营宗欣预扣款)
            Fields.Add("StartDate", data.StartDate); //扣款开始时间
            Fields.Add("TimeNumber", data.TimeNumber); //期数
            Fields.Add("TotalAmount", data.TotalAmount); //扣款总金额

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

            return "success";
        }

        #endregion

        #region 删除分期扣款信息信息

        /// <summary>
        /// 删除分期扣款信息信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ToChargeByStage", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                var toChargeBackRecordSub = db.ToChargeBackRecordSub.Where(m => m.ParentId == id).ToList();
                foreach (var item in toChargeBackRecordSub)
                {
                    var info = toChargeBackRecordSub.FirstOrDefault(m => m.Id == item.Id);
                    info.Status = -1;
                    info.UpdateDate = DateTime.Now;
                    info.SeoTitle = SysUserName + "_" + SysRealName;
                }
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeByStage", 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, "ToChargeByStage", "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("ToChargeByStage", 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, "ToChargeByStage", "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("ToChargeByStage", 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("ToChargeByStage", Sort, Id);

            AddSysLog(Id.ToString(), "ToChargeByStage", "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];
                int UserId = int.Parse(dr["创客"].ToString());
                decimal ChargeAmount = decimal.Parse(dr["待扣金额"].ToString());
                string Remark = dr["备注"].ToString();
                DateTime StartDate = DateTime.Parse(dr["扣款开始时间"].ToString());
                int TimeNumber = int.Parse(dr["期数"].ToString());
                decimal TotalAmount = decimal.Parse(dr["扣款总金额"].ToString());

                db.ToChargeByStage.Add(new ToChargeByStage()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    UserId = UserId,   //创客
                    SeoTitle = SysUserName + "_" + SysRealName,
                    ChargeAmount = ChargeAmount,   //待扣金额
                    Remark = Remark,   //备注
                    StartDate = StartDate,   //扣款开始时间
                    TimeNumber = TimeNumber,   //期数
                    TotalAmount = TotalAmount,   //扣款总金额

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(ToChargeByStage data, int? sUserId, int? eUserId)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("sUserId", "31"); //创客上限
            Fields.Add("eUserId", "32"); //创客下限
            Fields.Add("CreateDate", "3"); //时间


            string condition = " and Status>-1";


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ToChargeByStage", Fields, "Id desc", "0", 1, 20000, condition, "", 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>();

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

        #endregion

    }
}
