/*
 * 盟主兑换机具券
 */

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


            return View();
        }

        #endregion

        #region 根据条件查询盟主兑换机具券列表

        /// <summary>
        /// 根据条件查询盟主兑换机具券列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(LeaderReserveRecord data, string UserIdMakerCode, string SourceMakerCode, string RemarkSelect, string CreateDateData, int page = 1, int limit = 30)
        {

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

            Fields.Add("SeoKeyword", "1"); //订单编号


            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //购券创客
            if (!string.IsNullOrEmpty(SourceMakerCode))
            {
                condition += " and SourceUserId in (select UserId from UserForMakerCode where MakerCode='" + SourceMakerCode + "')";
            }
            //变动类型
            if (!string.IsNullOrEmpty(RemarkSelect))
            {
                condition += " and Remark='" + RemarkSelect + "'";
            }
            //创建时间
            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("LeaderReserveRecord", 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();
                UserAccount userAccount = db.UserAccount.FirstOrDefault(m => m.Id == UserId) ?? new UserAccount();
                dic["LeaderBalanceAmount"] = userAccount.LeaderBalanceAmount;
                dic["UserIdMakerCode"] = userid_Users.MakerCode;
                dic["UserIdRealName"] = userid_Users.RealName;
                dic.Remove("UserId");

                //购券创客
                int SourceUserId = int.Parse(function.CheckInt(dic["SourceUserId"].ToString()));
                if (SourceUserId > 0)
                {
                    Users sourceUser = db.Users.FirstOrDefault(m => m.Id == SourceUserId) ?? new Users();
                    dic["SourceMakerCode"] = sourceUser.MakerCode;
                    dic.Remove("SourceUserId");
                }

                //变动类型
                int ChangeType = int.Parse(function.CheckInt(dic["ChangeType"].ToString()));
                if (ChangeType == 1) dic["ChangeTypeName"] = "增加";
                if (ChangeType == 2) dic["ChangeTypeName"] = "减少";

                // else
                // {
                //     int OrderId = int.Parse(function.CheckInt(dic["OrderId"].ToString()));
                //     var order = db.Orders.FirstOrDefault(m => m.Id == OrderId) ?? new Orders();
                //     Users sourceUser = db.Users.FirstOrDefault(m => m.Id == order.UserId) ?? new Users();
                //     dic["SourceMakerCode"] = sourceUser.MakerCode;
                //     dic.Remove("OrderId");
                // }

                // //购券创客
                // int SourceUserId = int.Parse(function.CheckInt(dic["SourceUserId"].ToString()));
                // Users sourceUser = db.Users.FirstOrDefault(m => m.Id == SourceUserId) ?? new Users();
                // dic["SourceMakerCode"] = sourceUser.MakerCode;
                // dic.Remove("SourceUserId");

                // //订单来源创客
                // int OrderId = int.Parse(function.CheckInt(dic["OrderId"].ToString()));
                // var order = db.Orders.FirstOrDefault(m => m.Id == OrderId) ?? new Orders();
                // Users sourceOrderUser = db.Users.FirstOrDefault(m => m.Id == order.UserId) ?? new Users();
                // dic["SourceOrderMakerCode"] = sourceOrderUser.MakerCode;
                // dic.Remove("OrderId");

                //订单信息
                JsonData ApplyList = JsonMapper.ToObject(dic["SeoTitle"].ToString());//申请数据
                dic["dPosCoupons"] = "";
                dic["bPosCoupons"] = "";
                if (!string.IsNullOrEmpty(dic["SeoTitle"].ToString()))
                {
                    for (int i = 0; i < ApplyList.Count; i++)
                    {
                        int num = Convert.ToInt32(ApplyList[i]["Num"].ToString());
                        int type = Convert.ToInt32(ApplyList[i]["Type"].ToString());
                        if (type == 1)
                        {
                            dic["dPosCoupons"] = num + "张";
                        }
                        else
                        {
                            dic["bPosCoupons"] = num + "张";
                        }
                    }
                }

                //券码
                int OrderId = int.Parse(function.CheckInt(dic["Id"].ToString()));
                if (OrderId >= 2300)
                {

                    var info = db.UserSnDelayChange.Where(m => m.QueryCount == OrderId).ToList();
                    var PosCoupons = "";
                    foreach (var item in info)
                    {
                        PosCoupons += item.SnNo + ",";
                    }
                    dic["PosCoupons"] = PosCoupons;
                }
                else
                {
                    dic["PosCoupons"] = dic["SeoDescription"].ToString();
                }
            }
            return Json(obj);
        }

        #endregion

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

            return View();
        }

        [HttpPost]
        public string QuickExportExcelDo(string UserIdMakerCode, string SourceMakerCode, string RemarkSelect, string CreateDateData, string SeoKeyword)
        {

            string SqlString = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                SqlString += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //购券创客
            if (!string.IsNullOrEmpty(SourceMakerCode))
            {
                SqlString += " and SourceUserId in (select UserId from UserForMakerCode where MakerCode='" + SourceMakerCode + "')";
            }
            //变动类型
            if (!string.IsNullOrEmpty(RemarkSelect))
            {
                SqlString += " and Remark='" + RemarkSelect + "'";
            }
            //创建时间
            if (!string.IsNullOrEmpty(CreateDateData))
            {
                string[] datelist = CreateDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                SqlString += " and CreateDate>='" + start + " 00:00:00' and CreateDate<='" + end + " 23:59:59'";
            }
            //订单编号
            if (!string.IsNullOrEmpty(SeoKeyword))
            {
                SqlString += " and SeoKeyword=" + SeoKeyword;
            }
            var Sql = "SELECT c.MakerCode '创客编号',c.RealName '创客姓名',DATE_FORMAT(c.CreateDate,'%Y-%m-%d %H:%i:%s') '创建时间',c.Remark '变动类型',c.SeoDescription '备注',(CASE WHEN c.ChangeType=1 THEN '增加' WHEN c.ChangeType=2 THEN '减少' ELSE '' end) '操作类型',c.Type1Num '电签兑换券张数',c.Type2Num '大POS兑换券张数',d.LeaderBalanceAmount '可提现余额',c.ChangeAmt '使用额度',c.BeforeAmt '使用前剩余额度',c.AfterAmt '使用后剩余额度' FROM(SELECT a.*,b.MakerCode,b.RealName FROM(SELECT Id,UserId,CreateDate,ChangeAmt,BeforeAmt,AfterAmt,Remark,SeoDescription,ChangeType,REPLACE (JSON_EXTRACT (SeoTitle, '$[0].Num'),'\\\"','') AS 'Type1Num', REPLACE (JSON_EXTRACT (SeoTitle, '$[1].Num'),'\\\"','') AS 'Type2Num' FROM LeaderReserveRecord WHERE 1=1 " + SqlString + ") a LEFT JOIN Users b ON a.UserId=b.Id) c LEFT JOIN UserAccount d ON c.UserId=d.Id";
            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 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(LeaderReserveRecord data, string UserIdMakerCode, string SourceMakerCode, string RemarkSelect, string CreateDateData, string SeoKeyword)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //购券创客
            if (!string.IsNullOrEmpty(SourceMakerCode))
            {
                condition += " and SourceUserId in (select UserId from UserForMakerCode where MakerCode='" + SourceMakerCode + "')";
            }
            //变动类型
            if (!string.IsNullOrEmpty(RemarkSelect))
            {
                condition += " and Remark='" + RemarkSelect + "'";
            }
            //创建时间
            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(SeoKeyword))
            {
                condition += " and SeoKeyword='" + SeoKeyword + "'";
            }

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

                int Id = int.Parse(function.CheckInt(dic["Id"].ToString()));
                var leaderReserveRecord = db.LeaderReserveRecord.FirstOrDefault(m => m.Id == Id) ?? new LeaderReserveRecord();
                dic["BeforeAmount"] = leaderReserveRecord.BeforeAmt;
                dic["AfterAmount"] = leaderReserveRecord.AfterAmt;

                Users userid_Users = db.Users.FirstOrDefault(m => m.Id == leaderReserveRecord.UserId) ?? new Users();
                var userAccount = db.UserAccount.FirstOrDefault(m => m.Id == leaderReserveRecord.UserId) ?? new UserAccount();
                dic["MakerCode"] = userid_Users.MakerCode;
                dic["RealName"] = userid_Users.RealName;
                dic["LeaderBalanceAmount"] = userAccount.LeaderBalanceAmount;

                dic["Remark"] = leaderReserveRecord.Remark;
                dic["SeoDescription"] = leaderReserveRecord.SeoDescription;
                dic["CreateDate"] = leaderReserveRecord.CreateDate;

                //变动类型
                int ChangeType = leaderReserveRecord.ChangeType;
                if (ChangeType == 1) dic["ChangeTypeName"] = "增加";
                if (ChangeType == 2) dic["ChangeTypeName"] = "减少";

                // //盟主等级
                // int LeaderLevel = userid_Users.LeaderLevel;
                // if (LeaderLevel == 1) dic["LeaderLevel"] = "小盟主";
                // if (LeaderLevel == 2) dic["LeaderLevel"] = "大盟主";
                // if (LeaderLevel == 0) dic["LeaderLevel"] = "";

                //订单信息
                dic["dPosCoupons"] = "";
                dic["bPosCoupons"] = "";
                if (!string.IsNullOrEmpty(leaderReserveRecord.SeoTitle))
                {
                    JsonData ApplyList = JsonMapper.ToObject(leaderReserveRecord.SeoTitle);//申请数据
                    for (int i = 0; i < ApplyList.Count; i++)
                    {
                        int num = Convert.ToInt32(ApplyList[i]["Num"].ToString());
                        int type = Convert.ToInt32(ApplyList[i]["Type"].ToString());
                        if (type == 1)
                        {
                            dic["dPosCoupons"] = num + "张";
                        }
                        else
                        {
                            dic["bPosCoupons"] = num + "张";
                        }
                    }
                }
                dic.Remove("Id");
            }
            // 导出表格包含创客姓名、创客编号、创建时间、变动类型、电签兑换券张数、大POS兑换券张数、可提现余额、使用前剩余额度、使用后剩余额度
            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("MakerCode", "创客编号");
            ReturnFields.Add("RealName", "创客姓名");
            ReturnFields.Add("CreateDate", "创建时间");
            ReturnFields.Add("Remark", "变动类型");
            ReturnFields.Add("SeoDescription", "备注");
            ReturnFields.Add("ChangeTypeName", "操作类型");
            ReturnFields.Add("dPosCoupons", "电签兑换券张数");
            ReturnFields.Add("bPosCoupons", "大POS兑换券张数");
            ReturnFields.Add("LeaderBalanceAmount", "可提现余额");
            ReturnFields.Add("BeforeAmount", "使用前剩余额度");
            ReturnFields.Add("AfterAmount", "使用后剩余额度");

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

        #endregion

    }
}
