/*
 * 创客奖励记录
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询创客奖励记录列表

        /// <summary>
        /// 创客奖励记录列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(SysRechargeRecord data, string MakerCode, string RealName, string RechargeRecNo, string BatchCode, string BizTimeData, string BizTypeSelect, string StatusSelect, string SyncStatusSelect, int page = 1, int limit = 30)
        {

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

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //奖励单号
            if (!string.IsNullOrEmpty(RechargeRecNo))
            {
                condition += " and RechargeRecNo=" + RechargeRecNo;
            }
            //批次号
            if (!string.IsNullOrEmpty(BatchCode))
            {
                condition += " and BatchCode=" + BatchCode;
            }
            //业务类型
            if (!string.IsNullOrEmpty(BizTypeSelect))
            {
                condition += " and BizType=" + BizTypeSelect;
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //同步状态
            if (!string.IsNullOrEmpty(SyncStatusSelect))
            {
                condition += " and SyncStatus=" + SyncStatusSelect;
            }
            if (!string.IsNullOrEmpty(BizTimeData))
            {
                string[] datelist = BizTimeData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and BizTime>='" + start + " 00:00:00' and BizTime<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("SysRechargeRecord", 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(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["BizType"] = RelationClassForConst.GetChangeTypeInfo(int.Parse(dic["BizType"].ToString()));
                dic["ProductType"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["ProductType"].ToString()));
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["Status"] = "初始";
                if (Status == 1) dic["Status"] = "成功";
                if (Status == 2) dic["Status"] = "失败";
                int SyncStatus = int.Parse(dic["SyncStatus"].ToString());
                if (SyncStatus == 0) dic["SyncStatus"] = "未同步";
                if (SyncStatus == 1) dic["SyncStatus"] = "已同步";
                if (SyncStatus == 2) dic["SyncStatus"] = "同步中";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string BizAmount30 = "0.00";//红包奖励
            string BizAmount31 = "0.00";//活动奖励
            string BizAmount114 = "0.00";//私董会分红
            string BizAmount115 = "0.00";//分仓奖励
            string BizAmount126 = "0.00";//机具货款退还
            DataTable dt = OtherMySqlConn.dtable("SELECT SUM(if(BizType=30,Amount,0)),SUM(if(BizType=31,Amount,0)),SUM(if(BizType=114,Amount,0)),SUM(if(BizType=115,Amount,0)),SUM(if(BizType=126,Amount,0)) FROM SysRechargeRecord where 1=1 " + condition);
            if (dt.Rows.Count > 0)
            {
                BizAmount30 = decimal.Parse(function.CheckNum(dt.Rows[0][0].ToString())).ToString("f2");
                BizAmount31 = decimal.Parse(function.CheckNum(dt.Rows[0][1].ToString())).ToString("f2");
                BizAmount114 = decimal.Parse(function.CheckNum(dt.Rows[0][2].ToString())).ToString("f2");
                BizAmount115 = decimal.Parse(function.CheckNum(dt.Rows[0][3].ToString())).ToString("f2");
                BizAmount126 = decimal.Parse(function.CheckNum(dt.Rows[0][4].ToString())).ToString("f2");
            }
            other.Add("BizAmount30", BizAmount30);
            other.Add("BizAmount31", BizAmount31);
            other.Add("BizAmount114", BizAmount114);
            other.Add("BizAmount115", BizAmount115);
            other.Add("BizAmount126", BizAmount126);
            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(SysRechargeRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


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


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

        #endregion

        #region 修改创客奖励记录

        /// <summary>
        /// 增加或修改创客奖励记录信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(SysRechargeRecord data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();


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

            return "success";
        }

        #endregion

        #region 删除创客奖励记录信息

        /// <summary>
        /// 删除创客奖励记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "SysRechargeRecord", "del");
            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("SysRechargeRecord", 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, "SysRechargeRecord", "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("SysRechargeRecord", 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, "SysRechargeRecord", "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("SysRechargeRecord", 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("SysRechargeRecord", Sort, Id);

            AddSysLog(Id.ToString(), "SysRechargeRecord", "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];
                string BatchCode = dr[0].ToString(); // 批次号
                string RechargeRecNo = dr[1].ToString(); // 业务单号
                string MakerCode = dr[2].ToString(); // 创客编号
                string RealName = dr[3].ToString(); // 创客名称
                int BizType = int.Parse(dr[4].ToString()); // 业务类型
                int ProductType = int.Parse(dr[5].ToString()); // 产品类型
                decimal Amount = decimal.Parse(dr[6].ToString()); // 金额(元)
                string Remark = dr[7].ToString(); // 备注信息
                string Operator = dr[8].ToString(); // 操作人
                UserForMakerCode user = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
                db.SysRechargeRecord.Add(new SysRechargeRecord()
                {
                    CreateDate = DateTime.Now,
                    UpdateDate = DateTime.Now,
                    RechargeRecNo = RechargeRecNo,   //充值流水号
                    ProductType = ProductType,   //产品类型
                    UserId = user.UserId,   //创客
                    BizType = BizType,   //业务类型
                    BizTime = DateTime.Now,   //奖励时间
                    Amount = Amount,   //奖励金额
                    BatchCode = BatchCode,   //批次号
                    SeoDescription = Remark,
                    CreateMan = Operator,
                });
                db.SaveChanges();
            }
            AddSysLog("0", "SysRechargeRecord", "Import");
            return "success";
        }
        #endregion

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(SysRechargeRecord data, string MakerCode, string RealName, string RechargeRecNo, string BatchCode, string BizTimeData, string BizTypeSelect, string StatusSelect, string SyncStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(MakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + MakerCode + "')";
            }
            //创客名称
            if (!string.IsNullOrEmpty(RealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + RealName + "')";
            }
            //奖励单号
            if (!string.IsNullOrEmpty(RechargeRecNo))
            {
                condition += " and RechargeRecNo=" + RechargeRecNo;
            }
            //批次号
            if (!string.IsNullOrEmpty(BatchCode))
            {
                condition += " and BatchCode=" + BatchCode;
            }
            //业务类型
            if (!string.IsNullOrEmpty(BizTypeSelect))
            {
                condition += " and BizType=" + BizTypeSelect;
            }
            //状态
            if (!string.IsNullOrEmpty(StatusSelect))
            {
                condition += " and Status=" + StatusSelect;
            }
            //同步状态
            if (!string.IsNullOrEmpty(SyncStatusSelect))
            {
                condition += " and SyncStatus=" + SyncStatusSelect;
            }
            if (!string.IsNullOrEmpty(BizTimeData))
            {
                string[] datelist = BizTimeData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and BizTime>='" + start + " 00:00:00' and BizTime<='" + end + " 23:59:59'";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("SysRechargeRecord", Fields, "Id desc", "0", 1, 20000, condition, "RechargeRecNo,ProductType,UserId,BizType,BizTime,Amount,SyncStatus,BatchCode,Status,SeoDescription,CreateMan", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                int UserId = int.Parse(dic["UserId"].ToString());
                Users user = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["MakerCode"] = user.MakerCode;
                dic["RealName"] = user.RealName;
                dic["BizType"] = RelationClassForConst.GetChangeTypeInfo(int.Parse(dic["BizType"].ToString()));
                dic["ProductType"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["ProductType"].ToString()));
                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["Status"] = "初始";
                if (Status == 1) dic["Status"] = "成功";
                if (Status == 2) dic["Status"] = "失败";
                int SyncStatus = int.Parse(dic["SyncStatus"].ToString());
                if (SyncStatus == 0) dic["SyncStatus"] = "未同步";
                if (SyncStatus == 1) dic["SyncStatus"] = "已同步";
                if (SyncStatus == 2) dic["SyncStatus"] = "同步中";
                dic.Remove("UserId");
            }

            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("RechargeRecNo", "奖励单号");
            ReturnFields.Add("BatchCode", "批次号");
            ReturnFields.Add("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("BizType", "业务类型");
            ReturnFields.Add("ProductType", "产品类型");
            ReturnFields.Add("Amount", "奖励金额(元)");
            ReturnFields.Add("Status", "状态");
            ReturnFields.Add("SeoDescription", "备注");
            ReturnFields.Add("BizTime", "奖励时间");
            ReturnFields.Add("SyncStatus", "同步状态");
            ReturnFields.Add("CreateMan", "操作员");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "SysRechargeRecord", "ExportExcel");
            return Json(result);
        }

        #endregion




        #region 同步到账户余额

        /// <summary>
        /// 同步到账户余额
        /// </summary>
        /// <returns></returns>
        public string Sycn(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "SysRechargeRecord", "Sycn");
            foreach (string subid in idlist)
            {
                int id = int.Parse(subid);
                SysRechargeRecord edit = db.SysRechargeRecord.FirstOrDefault(m => m.Id == id && m.SyncStatus == 0);
                if (edit != null)
                {
                    edit.Status = 1;
                    edit.SyncStatus = 1;
                    UserAccount account = db.UserAccount.FirstOrDefault(m => m.Id == edit.UserId);
                    if (account == null)
                    {
                        account = db.UserAccount.Add(new UserAccount()
                        {
                            Id = edit.UserId,
                            UserId = edit.UserId,
                        }).Entity;
                        db.SaveChanges();
                    }
                    decimal BeforeTotalAmount = account.TotalAmount; //变更前总金额
                    decimal BeforeFreezeAmount = account.FreezeAmount; //变更前冻结金额
                    decimal BeforeBalanceAmount = account.BalanceAmount; //变更前余额
                    account.TotalAmount += edit.Amount;
                    account.BalanceAmount += edit.Amount;
                    decimal AfterTotalAmount = account.TotalAmount; //变更后总金额
                    decimal AfterFreezeAmount = account.FreezeAmount; //变更后冻结金额
                    decimal AfterBalanceAmount = account.BalanceAmount; //变更后余额
                    UserAccountRecord add = db.UserAccountRecord.Add(new UserAccountRecord()
                    {
                        CreateDate = DateTime.Now,
                        UpdateDate = DateTime.Now,
                        UserId = edit.UserId, //创客
                        ChangeType = edit.BizType, //变动类型
                        ProductType = edit.ProductType, //产品类型
                        ChangeAmount = edit.Amount, //变更金额
                        BeforeTotalAmount = BeforeTotalAmount, //变更前总金额
                        AfterTotalAmount = AfterTotalAmount, //变更后总金额
                        BeforeFreezeAmount = BeforeFreezeAmount, //变更前冻结金额
                        AfterFreezeAmount = AfterFreezeAmount, //变更后冻结金额
                        BeforeBalanceAmount = BeforeBalanceAmount, //变更前余额
                        AfterBalanceAmount = AfterBalanceAmount, //变更后余额
                        Remark = edit.SeoDescription, //备注
                    }).Entity;
                    db.SaveChanges();
                    PublicFunction.SplitUserAccountRecord(add);
                }
            }
            db.SaveChanges();
            return "success";
        }

        #endregion
    }
}
