/*
 * 待扣款明细
 */

using System;
using System.Web;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Data;
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 ToChargeBackRecordController : BaseController
    {
        public ToChargeBackRecordController(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(ToChargeBackRecord data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

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

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

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



            string condition = " and Status>-1";
            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(PosSn))
            {
                condition += " and Remark=" + PosSn;
            }
            //待扣类型
            if (!string.IsNullOrEmpty(ChargeTypeSelect))
            {
                condition += " and ChargeType=" + ChargeTypeSelect;
            }
            //待扣类别
            if (!string.IsNullOrEmpty(KindSelect))
            {
                condition += " and Kind=" + KindSelect;
            }
            //扣款状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ToChargeBackRecord", 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["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                dic["UserIdMobile"] = userid_Users.Mobile;
                dic.Remove("UserId");

                //待扣类型
                int ChargeType = int.Parse(dic["ChargeType"].ToString());
                if (ChargeType == 124) dic["ChargeTypeName"] = "过期机具扣款";
                if (ChargeType == 1) dic["ChargeTypeName"] = "普通预扣款";
                if (ChargeType == 2) dic["ChargeTypeName"] = "分期预扣款";
                if (ChargeType == 0) dic["ChargeTypeName"] = "";

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

                //扣款状态
                int Status = int.Parse(dic["Status"].ToString());
                if (!string.IsNullOrEmpty(dic["UpdateDate"].ToString()))
                {
                    var updateDate = DateTime.Parse(dic["UpdateDate"].ToString());
                    if (updateDate >= DateTime.Parse("2023-12-26 00:48:00") && updateDate <= DateTime.Parse("2023-12-26 00:48:59"))
                    {
                        Status = 4;
                        if (Status == 4) dic["StatusName"] = "未实扣";
                    }
                }
                if (Status == 0) dic["StatusName"] = "待扣款";
                if (Status == 1) dic["StatusName"] = "已扣款";
                if (Status == 2) dic["StatusName"] = "已退还";
                if (Status == 3) dic["StatusName"] = "暂停扣款";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string SuccessAmount = "0.00";//已扣款总金额
            string WaitAmount = "0.00";//待扣款总金额
            string StopAmount = "0.00";//暂停扣款总金额
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(if(Status=1,ChargeAmount,0)),SUM(if(Status=0,ChargeAmount,0)),SUM(if(Status=3,ChargeAmount,0)) FROM ToChargeBackRecord WHERE 1=1 " + condition);
            if (dt.Rows.Count > 0)
            {
                SuccessAmount = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
                WaitAmount = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString())).ToString("f2");
                StopAmount = decimal.Parse(function.CheckNum(dt.Rows[0][2].ToString())).ToString("f2");
            }
            other.Add("SuccessAmount", SuccessAmount);
            other.Add("WaitAmount", WaitAmount);
            other.Add("StopAmount", StopAmount);
            obj.Add("other", other);
            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(ToChargeBackRecord data, string MakerCode)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            var user = db.Users.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new Users();
            if (user.Id == 0)
            {
                return "创客" + MakerCode + "不存在或编号错误";
            }
            Fields.Add("UserId", user.Id); //创客Id
            Fields.Add("ChargeAmount", data.ChargeAmount); //待扣金额
            Fields.Add("ChargeType", 1); //待扣类型
            Fields.Add("Kind", data.Kind); //待扣别
            Fields.Add("Remark", data.Remark); //备注
            Fields.Add("Field1", data.Field1); //备用字段

            Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
            Fields.Add("SeoKeyword", data.SeoKeyword);
            Fields.Add("SeoDescription", data.Remark);
            int Id = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Add("ToChargeBackRecord", Fields, 0);
            var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == user.Id);
            if (user.Id == 0)
            {
                return "失败：" + MakerCode + "创客不存在" + '\n';
            }
            else
            {
                if (userAccount == null)
                {
                    userAccount = db.UserAccount.Add(new UserAccount()
                    {
                        Id = user.Id,
                        UserId = user.Id,
                    }).Entity;
                    db.SaveChanges();
                }
                if (data.Kind == 0) userAccount.ToChargeAmount += decimal.Parse(data.ChargeAmount.ToString());
                if (data.Kind == 1) userAccount.LeaderToChargeAmount += decimal.Parse(data.ChargeAmount.ToString());
                if (data.Kind == 2) userAccount.OperateToChargeAmount += decimal.Parse(data.ChargeAmount.ToString());
            }
            AddSysLog(data.Id.ToString(), "ToChargeBackRecord", "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;


            ToChargeBackRecord editData = db.ToChargeBackRecord.FirstOrDefault(m => m.Id == Id) ?? new ToChargeBackRecord();
            var user = db.Users.FirstOrDefault(m => m.Id == editData.UserId) ?? new Users();
            ViewBag.data = editData;
            ViewBag.MakerCode = user.MakerCode;
            return View();
        }

        #endregion

        #region 修改待扣款明细

        /// <summary>
        /// 增加或修改待扣款明细信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(ToChargeBackRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();
            var editInfo = "";
            var info = db.ToChargeBackRecord.FirstOrDefault(m => m.Id == data.Id) ?? new ToChargeBackRecord();
            if (info.ChargeAmount != data.ChargeAmount)
            {
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == info.UserId) ?? new UserAccount();
                editInfo = "变更前：" + "\n" + "创客预扣款：" + userAccount.ToChargeAmount + " " + "盟主预扣款：" + userAccount.LeaderToChargeAmount + " " + "合伙人预扣款：" + userAccount.OperateToChargeAmount + "\n";
                if (info.ChargeAmount > data.ChargeAmount)
                {
                    if (info.Kind == 0) userAccount.ToChargeAmount -= info.ChargeAmount - data.ChargeAmount;
                    if (info.Kind == 1) userAccount.LeaderToChargeAmount -= info.ChargeAmount - data.ChargeAmount;
                    if (info.Kind == 2) userAccount.OperateToChargeAmount -= info.ChargeAmount - data.ChargeAmount;
                }
                if (info.ChargeAmount < data.ChargeAmount)
                {
                    if (info.Kind == 0) userAccount.ToChargeAmount += data.ChargeAmount - info.ChargeAmount;
                    if (info.Kind == 1) userAccount.LeaderToChargeAmount += data.ChargeAmount - info.ChargeAmount;
                    if (info.Kind == 2) userAccount.OperateToChargeAmount += data.ChargeAmount - info.ChargeAmount;
                }
                editInfo = "变更后：" + "\n" + "创客预扣款：" + userAccount.ToChargeAmount + " " + "盟主预扣款：" + userAccount.LeaderToChargeAmount + " " + "合伙人预扣款：" + userAccount.OperateToChargeAmount + "\n";
            }
            Fields.Add("ChargeAmount", data.ChargeAmount); //待扣金额
            // Fields.Add("Kind", data.Kind); //待扣金额
            Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
            Fields.Add("SeoDescription", data.SeoDescription);
            if (info.ChargeType != 124)
            {
                Fields.Add("Remark", data.SeoDescription);
            }
            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeBackRecord", Fields, data.Id);
            AddSysLog(data.Id.ToString() + "\n" + editInfo, "ToChargeBackRecord", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除待扣款明细信息

        /// <summary>
        /// 删除待扣款明细信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ToChargeBackRecord", "del");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                var toChargeBackRecord = db.ToChargeBackRecord.FirstOrDefault(m => m.Id == id) ?? new ToChargeBackRecord();
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == toChargeBackRecord.UserId) ?? new UserAccount();
                if (toChargeBackRecord.Kind == 0) userAccount.ToChargeAmount -= toChargeBackRecord.ChargeAmount;//删除预扣款记录时扣减相应预扣额度
                if (toChargeBackRecord.Kind == 1) userAccount.LeaderToChargeAmount -= toChargeBackRecord.ChargeAmount;//删除预扣款记录时扣减相应预扣额度
                if (toChargeBackRecord.Kind == 2) userAccount.OperateToChargeAmount -= toChargeBackRecord.ChargeAmount;//删除预扣款记录时扣减相应预扣额度
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", -1);
                Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeBackRecord", 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, "ToChargeBackRecord", "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("ToChargeBackRecord", 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, "ToChargeBackRecord", "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("ToChargeBackRecord", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion


        #region 暂停扣款

        /// <summary>
        /// 暂停扣款
        /// </summary>
        /// <returns></returns>
        public string Break(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "ToChargeBackRecord", "Break");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("Status", 3);
                Fields.Add("SeoTitle", SysUserName + "_" + SysRealName);
                new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("ToChargeBackRecord", Fields, id);
            }
            db.SaveChanges();
            return "success";
        }

        #endregion

        #region 开启扣款

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

            AddSysLog(Id.ToString(), "ToChargeBackRecord", "sort");
            return "success";
        }
        #endregion


        #region 导入预扣信息
        /// <summary>
        /// 导入预扣信息
        /// </summary>
        /// <param name="ExcelData"></param>
        public string ChargeImport(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            var info = "";
            var error = "";
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string itemJson = dr.ToJson();
                string MakerCode = itemJson.Contains("\"A\"") ? dr["A"].ToString() : "";
                string Name = itemJson.Contains("\"B\"") ? dr["B"].ToString() : "";
                string Amount = itemJson.Contains("\"C\"") ? dr["C"].ToString() : "";
                string Remark = itemJson.Contains("\"D\"") ? dr["D"].ToString() : "";
                string KindName = itemJson.Contains("\"E\"") ? dr["E"].ToString() : "";
                int Kind = 0;
                var userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
                var users = db.Users.FirstOrDefault(m => m.Id == userForMakerCode.UserId && m.RealName == Name) ?? new Users();
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == users.Id);
                if (users.Id == 0)
                {
                    error += "失败：" + MakerCode + "_" + Name + "创客不存在或创客编号和姓名不匹配" + '\n';
                }
                else
                {
                    if (userAccount == null)
                    {
                        userAccount = db.UserAccount.Add(new UserAccount()
                        {
                            Id = users.Id,
                            UserId = users.Id,
                        }).Entity;
                        db.SaveChanges();
                    }
                    if (KindName == "创客预扣款")
                    {
                        Kind = 0;
                        userAccount.ToChargeAmount += decimal.Parse(Amount);
                    }
                    if (KindName == "盟主预扣款")
                    {
                        Kind = 1;
                        userAccount.LeaderToChargeAmount += decimal.Parse(Amount);
                    }
                    if (KindName == "运营中心预扣款")
                    {
                        Kind = 2;
                        userAccount.OperateToChargeAmount += decimal.Parse(Amount);
                    }
                    var ToChargeBackRecord = db.ToChargeBackRecord.Add(new ToChargeBackRecord
                    {
                        CreateDate = DateTime.Now,
                        SeoTitle = SysUserName + "_" + SysRealName,
                        SeoDescription = Remark,
                        Remark = Remark,
                        ChargeType = 1,
                        Kind = Kind,
                        ChargeAmount = decimal.Parse(Amount),
                        UserId = users.Id,
                    }).Entity;
                    info += "创客编号：" + MakerCode + "；创客姓名：" + Name + "；金额：" + Amount + "；备注：" + Remark + "<br/>";
                }
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            string text = string.Format("预扣信息: '" + info + "'，Time'" + DateTime.Now + "'");
            function.WriteLog(text, "导入预扣信息");//机具扣款退还
            db.SaveChanges();
            AddSysLog("0", "ToChargeBackRecord", "ChargeImport");
            return "success";
        }
        #endregion


        #region 机具扣款退还
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Import(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            var info = "";
            var error = "";
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string PosSn = dr[0].ToString(); // 机具Sn
                var toChargeBackRecord = db.ToChargeBackRecord.FirstOrDefault(m => m.Status < 2 && m.Remark == PosSn) ?? new ToChargeBackRecord();
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == toChargeBackRecord.UserId) ?? new UserAccount();
                if (toChargeBackRecord.Id == 0)
                {
                    error += "失败" + PosSn + ',' + "不符合退还条件" + '\n';
                }
                if (toChargeBackRecord.Id > 0 && toChargeBackRecord.Status == 0)//待扣款
                {
                    userAccount.ToChargeAmount -= toChargeBackRecord.ChargeAmount;
                    toChargeBackRecord.Status = 2;
                }
                if (toChargeBackRecord.Id > 0 && toChargeBackRecord.Status == 1)//已扣款
                {
                    var userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord
                    {
                        CreateDate = DateTime.Now,
                        UserId = toChargeBackRecord.UserId,
                        BeforeBalanceAmount = userAccount.BalanceAmount,
                        AfterBalanceAmount = userAccount.BalanceAmount + toChargeBackRecord.ChargeAmount,
                        ChangeAmount = toChargeBackRecord.ChargeAmount,
                        ChangeType = 126,
                        Remark = "机具货款退还",

                    }).Entity;
                    userAccount.BalanceAmount += toChargeBackRecord.ChargeAmount;
                    toChargeBackRecord.Status = 2;
                    toChargeBackRecord.SeoTitle = SysUserName + "_" + SysRealName;
                    info += toChargeBackRecord.Remark + "," + toChargeBackRecord.ChargeAmount + "<br/>";
                }
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            string text = string.Format("退款信息: '" + info + "'，Time'" + DateTime.Now + "'");
            function.WriteLog(text, "机具扣款退还");//机具扣款退还
            db.SaveChanges();
            AddSysLog("0", "ToChargeBackRecord", "Import");
            return "success";
        }
        #endregion


        #region 机具回收确认退还
        /// <summary>
        /// 导入数据
        /// </summary>
        /// <param name="ExcelData"></param>
        public string Imports(string ExcelData)
        {
            ExcelData = HttpUtility.UrlDecode(ExcelData);
            JsonData list = JsonMapper.ToObject(ExcelData);
            var info = "";
            var error = "";
            for (int i = 1; i < list.Count; i++)
            {
                JsonData dr = list[i];
                string PosSn = dr[0].ToString(); // 机具Sn
                var toChargeBackRecord = db.ToChargeBackRecord.FirstOrDefault(m => m.Remark == PosSn) ?? new ToChargeBackRecord();
                var recycMachineOrderPos = db.RecycMachineOrderPos.FirstOrDefault(m => m.Status == 1 && m.SnNo == PosSn) ?? new RecycMachineOrderPos();
                if (recycMachineOrderPos.Id == 0)
                {
                    error += "以下操作失败" + PosSn + ',' + "不符合退还条件" + '\n';
                }
                else
                {
                    var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == toChargeBackRecord.UserId) ?? new UserAccount();
                    //已扣款
                    if (toChargeBackRecord.Status == 1)
                    {
                        var userAccountRecord = db.UserAccountRecord.Add(new UserAccountRecord
                        {
                            CreateDate = DateTime.Now,
                            UserId = toChargeBackRecord.UserId,
                            BeforeBalanceAmount = userAccount.BalanceAmount,
                            AfterBalanceAmount = userAccount.BalanceAmount + toChargeBackRecord.ChargeAmount,
                            ChangeAmount = toChargeBackRecord.ChargeAmount,
                            ChangeType = 126,
                            Remark = "机具货款退还",

                        }).Entity;
                        userAccount.BalanceAmount += toChargeBackRecord.ChargeAmount;
                        toChargeBackRecord.Status = 2;
                        toChargeBackRecord.SeoTitle = SysUserName + "_" + SysRealName;
                        info += toChargeBackRecord.Remark + "," + toChargeBackRecord.ChargeAmount + "<br/>";
                    }
                    //未扣款
                    if (toChargeBackRecord.Status == 0)
                    {
                        toChargeBackRecord.Status = 2;
                    }
                }
            }
            if (!string.IsNullOrEmpty(error))
            {
                return "Warning|" + error;
            }
            if (!string.IsNullOrEmpty(info))
            {
                string text = string.Format("退款信息: '" + info + "'，Time'" + DateTime.Now + "'");
                function.WriteLog(text, "机具回收确认退还");//机具回收确认退还
            }
            db.SaveChanges();
            AddSysLog("0", "ToChargeBackRecord", "Import");
            return "success";
        }
        #endregion


        #region 导出Excel

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

            string condition = " and Status>-1";
            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(ChargeTypeSelect))
            {
                condition += " and ChargeType=" + ChargeTypeSelect;
            }
            //待扣类别
            if (!string.IsNullOrEmpty(KindSelect))
            {
                condition += " and Kind=" + KindSelect;
            }
            //扣款状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("ToChargeBackRecord", Fields, "Id desc", "0", 1, 20000, condition, "Id,UserId,ChargeAmount,ChargeType,Kind,Remark", false);
            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["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                dic["UserIdMobile"] = userid_Users.Mobile;
                dic.Remove("UserId");
                //待扣类型
                int ChargeType = int.Parse(dic["ChargeType"].ToString());
                if (ChargeType == 124) dic["ChargeType"] = "过期机具扣款";
                if (ChargeType == 1) dic["ChargeType"] = "普通预扣款";
                if (ChargeType == 2) dic["ChargeType"] = "分期预扣款";
                if (ChargeType == 0) dic["ChargeType"] = "";

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

                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                var toChargeBackRecord = db.ToChargeBackRecord.FirstOrDefault(m => m.Id == Id) ?? new ToChargeBackRecord();
                //扣款状态
                if (toChargeBackRecord.Status == 0) dic["Status"] = "待扣款未返还";
                if (toChargeBackRecord.Status == 1) dic["Status"] = "已扣款未返还";
                if (toChargeBackRecord.Status == 2) dic["Status"] = "已返还";
                decimal ChargeAmount = decimal.Parse(dic["ChargeAmount"].ToString());//应扣金额
                decimal ChargeAmountf = 0;//实扣金额
                dic["ChargeAmountf"] = "";
                if (toChargeBackRecord.Status == 1)//已扣款
                {
                    ChargeAmountf = ChargeAmount;
                    dic["ChargeAmountf"] = ChargeAmountf;
                }
                var pos = db.PosMachinesTwo.FirstOrDefault(m => m.PosSn == toChargeBackRecord.Remark) ?? new PosMachinesTwo();
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(pos.BrandId);
                if (pos.PosSnType == 0) dic["PosSnType"] = "兑换机";
                if (pos.PosSnType == 1) dic["PosSnType"] = "循环机";
                dic["RecycEndDate"] = pos.RecycEndDate;

            }

            Dictionary<string, object> result = new Dictionary<string, object>();
            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("Id", "Id");
            ReturnFields.Add("ChargeType", "待扣类型");
            ReturnFields.Add("Kind", "待扣类别");
            ReturnFields.Add("Remark", "机具sn");
            ReturnFields.Add("BrandId", "品牌");
            ReturnFields.Add("PosSnType", "机具类型");
            ReturnFields.Add("RecycEndDate", "循环过期时间");
            ReturnFields.Add("UserIdMakerCode", "创客编号");
            ReturnFields.Add("UserIdRealName", "创客姓名");
            ReturnFields.Add("UserIdMobile", "创客手机号");
            ReturnFields.Add("ChargeAmount", "应扣金额");
            ReturnFields.Add("ChargeAmountf", "实扣金额");
            ReturnFields.Add("Status", "扣款状态");

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

        #endregion



        #region 快捷导出Excel
        public IActionResult QuickExportExcel(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(string UserIdMakerCode, string PosSn, string CreateDateData, string ChargeTypeSelect, string KindSelect, string StatusSelect)
        {

            string SqlString = " where 1=1 and a.Status>-1";
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                SqlString += " and a.CreateDate>='" + start + " 00:00:00' and a.CreateDate<='" + end + " 23:59:59'";
            }
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                SqlString += " and a.UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            if (!string.IsNullOrEmpty(PosSn))
            {
                SqlString += " and a.Remark=" + PosSn;
            }
            //待扣类别
            if (!string.IsNullOrEmpty(KindSelect))
            {
                SqlString += " and a.Kind=" + KindSelect;
            }
            //待扣类型
            if (!string.IsNullOrEmpty(ChargeTypeSelect))
            {
                SqlString += " and a.ChargeType=" + ChargeTypeSelect;
            }
            //扣款状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                SqlString += " and a.Status=" + StatusSelect;
            }
            var Sql = "SELECT b.MakerCode '创客编号',b.RealName '创客真实姓名',b.Mobile '手机号',DATE_FORMAT(a.CreateDate,'%Y-%m-%d %H:%i:%s') '创建时间',a.ChargeAmount '扣款金额',(CASE WHEN a.ChargeType=124 THEN '过期机具扣款' WHEN a.ChargeType=1 THEN '普通预扣款' WHEN a.ChargeType=2 THEN '分期预扣款' ELSE '' end) '扣款类型',(CASE WHEN a.Kind=0 THEN '创客预扣款' WHEN a.Kind=1 THEN '盟主预扣款' WHEN a.Kind=2 THEN '运营中心预扣款' ELSE '' end) '扣款类别',DATE_FORMAT(a.UpdateDate,'%Y-%m-%d %H:%i:%s') '扣款/更新时间',(CASE WHEN a.`Status`=0 THEN '待扣款' WHEN a.`Status`=1 THEN '已扣款' WHEN a.`Status`=2 THEN '已退还' WHEN a.`Status`=3 THEN '暂停扣款'  ELSE '' end) '扣款状态',a.Remark '机具Sn',a.SeoDescription '备注',a.SeoTitle '操作人' FROM ToChargeBackRecord a LEFT JOIN Users b ON a.UserId=b.Id " + SqlString + "";
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.AdminName == SysUserName && m.Status > -1);
            var FileName = "创客预扣款记录" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string SendData = "{\"Operater\":\"" + sysAdmin.Id + "\",\"SqlString\":\"" + Sql + "\",\"FileName\":\"" + FileName + "\",\"MaxCount\":\"0\"}";
            RedisDbconn.Instance.AddList("ExportQueue", SendData);
            return "success";
        }
        #endregion


        #region 分期扣款

        public IActionResult ChangeInfoDo(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        public string ChangeInfoDo(string PosCouponCodes, string FromMakerCode)
        {
            var result = "";
            return result;
        }
        #endregion

    }
}
