/*
 * 开机机具快照
 */

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

            return View();
        }

        #endregion

        #region 根据条件查询开机机具快照列表

        /// <summary>
        /// 开机机具快照列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(OpenSnSnapshot data, string MakerCode, string RealName, string MerchantNo, string MerchantName, int page = 1, int limit = 30)
        {

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

            Fields.Add("TradeDate", "3"); //达标日期
            Fields.Add("BrandId", "0"); //品牌
            Fields.Add("SnNo", "1"); //SN号
            Fields.Add("MerNo", "1"); //渠道商户号
            Fields.Add("TopUserId", "0"); //顶级创客
            Fields.Add("OpenDetailRec", "2"); //明细单号

            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(MerchantNo))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForCode where Code='" + MerchantNo + "')";
            }
            //商户名称
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForName where Name='" + MerchantName + "')";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("OpenSnSnapshot", 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)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));

                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;

                int TopUserId = int.Parse(dic["TopUserId"].ToString());
                Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopMakerCode"] = tuser.MakerCode;
                dic["TopRealName"] = tuser.RealName;
                
                int DirectUserId = int.Parse(dic["DirectUserId"].ToString());
                Users duser = db.Users.FirstOrDefault(m => m.Id == DirectUserId) ?? new Users();
                dic["DirectMakerCode"] = duser.MakerCode;
                dic["DirectRealName"] = duser.RealName;

                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = merchant.Name;

                int RewardType = int.Parse(dic["RewardType"].ToString());
                if (RewardType == 0) dic["RewardType"] = "无开机奖励";
                if (RewardType == 1) dic["RewardType"] = "开机直接奖励";
                if (RewardType == 2) dic["RewardType"] = "开机间接奖励";

                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["Status"] = "失败";
                if (Status == 1) dic["Status"] = "成功";
            }
            Dictionary<string, object> other = new Dictionary<string, object>();
            string PrizeAmt = "0.00", BuyPosCount = "0.00", StadardBuyPosCount = "0.00";//奖励金额 兑换机数量 标准兑换机数量
            DataTable dt = OtherMySqlConn.dtable("select sum(PrizeAmt),sum(BuyPosCount),sum(StadardBuyPosCount) from OpenSnSnapshot where 1=1" + condition);
            if(dt.Rows.Count > 0)
            {
                PrizeAmt = dt.Rows[0][0].ToString();
                BuyPosCount = dt.Rows[0][1].ToString();
                StadardBuyPosCount = dt.Rows[0][2].ToString();
            }
            other.Add("PrizeAmt", 0);
            other.Add("BuyPosCount", 0);
            other.Add("StadardBuyPosCount", 0);
            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(OpenSnSnapshot 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("OpenSnSnapshot", Fields, 0);
            AddSysLog(data.Id.ToString(), "OpenSnSnapshot", "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;


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

        #endregion

        #region 修改开机机具快照

        /// <summary>
        /// 增加或修改开机机具快照信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(OpenSnSnapshot 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("OpenSnSnapshot", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "OpenSnSnapshot", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 删除开机机具快照信息

        /// <summary>
        /// 删除开机机具快照信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "OpenSnSnapshot", "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("OpenSnSnapshot", 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, "OpenSnSnapshot", "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("OpenSnSnapshot", 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, "OpenSnSnapshot", "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("OpenSnSnapshot", 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("OpenSnSnapshot", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(OpenSnSnapshot data, string MakerCode, string RealName, string MerchantNo, string MerchantName)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();

            Fields.Add("TradeDate", "3"); //达标日期
            Fields.Add("BrandId", "0"); //品牌
            Fields.Add("SnNo", "1"); //SN号
            Fields.Add("MerNo", "1"); //渠道商户号
            Fields.Add("TopUserId", "0"); //顶级创客
            Fields.Add("OpenDetailRec", "2"); //明细单号

            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(MerchantNo))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForCode where Code='" + MerchantNo + "')";
            }
            //商户名称
            if (!string.IsNullOrEmpty(MerchantName))
            {
                condition += " and MerchantId in (select MerchantId from MerchantForName where Name='" + MerchantName + "')";
            }

            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("OpenSnSnapshot", Fields, "Id desc", "0", 1, 20000, condition, "TradeDate,UserId,TopUserId,BrandId,MerchantId,DirectUserId,SnNo,MerNo,StandardDate,RewardType,RewardTips,OpenRewardNo,BuySnNum,StdBuySnNum,RewardAmount,FailReason,Status", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                dic["BrandId"] = RelationClass.GetKqProductBrandInfo(int.Parse(dic["BrandId"].ToString()));

                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;

                int TopUserId = int.Parse(dic["TopUserId"].ToString());
                Users tuser = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopMakerCode"] = tuser.MakerCode;
                dic["TopRealName"] = tuser.RealName;
                
                int DirectUserId = int.Parse(dic["DirectUserId"].ToString());
                Users duser = db.Users.FirstOrDefault(m => m.Id == DirectUserId) ?? new Users();
                dic["DirectMakerCode"] = duser.MakerCode;
                dic["DirectRealName"] = duser.RealName;

                int MerchantId = int.Parse(dic["MerchantId"].ToString());
                MerchantInfo merchant = db.MerchantInfo.FirstOrDefault(m => m.Id == MerchantId) ?? new MerchantInfo();
                dic["MerchantNo"] = "";
                dic["MerchantName"] = merchant.Name;

                int RewardType = int.Parse(dic["RewardType"].ToString());
                if (RewardType == 0) dic["RewardType"] = "无开机奖励";
                if (RewardType == 1) dic["RewardType"] = "开机直接奖励";
                if (RewardType == 2) dic["RewardType"] = "开机间接奖励";

                int Status = int.Parse(dic["Status"].ToString());
                if (Status == 0) dic["Status"] = "失败";
                if (Status == 1) dic["Status"] = "成功";

                dic.Remove("UserId");
                dic.Remove("TopUserId");
                dic.Remove("DirectUserId");
                dic.Remove("MerchantId");
            }

            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("OpenRewardNo", "开机奖励明细单号");
            ReturnFields.Add("MakerCode", "奖励创客编号");
            ReturnFields.Add("RealName", "奖励创客名称");
            ReturnFields.Add("TradeDate", "达标日期");
            ReturnFields.Add("TopMakerCode", "顶级创客编号");
            ReturnFields.Add("TopRealName", "顶级创客名称");
            ReturnFields.Add("BrandId", "产品名称");
            ReturnFields.Add("BuySnNum", "兑换机数量");
            ReturnFields.Add("StdBuySnNum", "标准兑换机数量");
            ReturnFields.Add("RewardAmount", "奖励金额");
            ReturnFields.Add("MerchantNo", "商户编号");
            ReturnFields.Add("MerchantName", "商户名称");
            ReturnFields.Add("DirectMakerCode", "商户直属创客编号");
            ReturnFields.Add("DirectRealName", "商户直属创客名称");
            ReturnFields.Add("MerNo", "快钱商户编号");
            ReturnFields.Add("SnNo", "快钱SN号");
            ReturnFields.Add("StandardDate", "商户的激活日期");
            ReturnFields.Add("RewardType", "奖励类型");
            ReturnFields.Add("RewardTips", "奖励描述");
            ReturnFields.Add("Status", "状态");
            ReturnFields.Add("FailReason", "失败原因");
            ReturnFields.Add("CreateDate", "创建时间");
            result.Add("Fields", ReturnFields);
            AddSysLog("0", "OpenSnSnapshot", "ExportExcel");
            return Json(result);
        }

        #endregion

    }
}
