/*
 * 机具券变更记录
 */

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


            return View();
        }

        #endregion

        #region 根据条件查询机具券列表

        /// <summary>
        /// 机具券列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(PosCoupons data, string UseDateData, string UserIdMakerCode, string LeaderIdMakerCode, string ExchangeCode, string IsUseSelect, string IsLockSelect, string TypeSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("OrderNo", "1"); //单号


            string condition = " and Status>-1";
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //盟主创客编号
            if (!string.IsNullOrEmpty(LeaderIdMakerCode))
            {
                condition += " and LeaderUserId in (select UserId from UserForMakerCode where MakerCode='" + LeaderIdMakerCode + "')";
            }
            //兑换码
            if (!string.IsNullOrEmpty(ExchangeCode))
            {
                condition += " and ExchangeCode =" + ExchangeCode;
            }
            //机具券类型
            if (!string.IsNullOrEmpty(TypeSelect))
            {
                if (int.Parse(TypeSelect) == 1)
                {
                    condition += " and QueryCount =1";
                }
                else
                {
                    condition += " and QueryCount =2";
                }
            }
            //是否使用
            if (!string.IsNullOrEmpty(IsUseSelect))
            {
                condition += " and IsUse =" + IsUseSelect;
            }
            //是否锁定
            if (!string.IsNullOrEmpty(IsLockSelect))
            {
                condition += " and IsLock=" + IsLockSelect;
            }

            if (!string.IsNullOrEmpty(UseDateData))
            {
                string[] datelist = UseDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UseDate >='" + start + " 00:00:00' and UseDate <='" + end + " 23:59:59'";
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PosCoupons", 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 fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["UserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("UserId");

                //盟主创客信息
                int LeaderUserId = int.Parse(function.CheckInt(dic["LeaderUserId"].ToString()));
                Users leaderuserid_Users = db.Users.FirstOrDefault(m => m.Id == LeaderUserId) ?? new Users();
                dic["LeaderUserIdMakerCode"] = leaderuserid_Users.MakerCode;
                dic["LeaderUserIdRealName"] = leaderuserid_Users.RealName;
                dic.Remove("LeaderUserId");

                //是否使用
                int IsUse = int.Parse(dic["IsUse"].ToString());
                if (IsUse == 0) dic["IsUseName"] = "否";
                if (IsUse == 1) dic["IsUseName"] = "是";

                //是否锁定
                int IsLock = int.Parse(dic["IsLock"].ToString());
                if (IsLock == 0) dic["IsLockName"] = "否";
                if (IsLock == 1) dic["IsLockName"] = "是";

                //机具券类型
                int QueryCount = int.Parse(dic["QueryCount"].ToString());
                if (QueryCount == 1) dic["QueryCount"] = "电签券";
                if (QueryCount == 2) dic["QueryCount"] = "大POS";

            }
            return Json(obj);
        }

        #endregion


        #region 商机券列表

        /// <summary>
        /// 根据条件查询商机券列表
        /// </summary>
        /// <returns></returns>
        public IActionResult SJQ(PosCoupons data, string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;


            return View();
        }

        #endregion

        #region 根据条件查询商机券列表

        /// <summary>
        /// 商机券列表
        /// </summary>
        /// <returns></returns>
        public JsonResult SJQData(PosCoupons data, string UseDateData, string UserIdMakerCode, string ExchangeCode, string IsUseSelect, string IsLockSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("OrderNo", "1"); //单号


            string condition = " and Status>-1 and HelpProfitFlag=1";
            //创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //兑换码
            if (!string.IsNullOrEmpty(ExchangeCode))
            {
                condition += " and ExchangeCode =" + ExchangeCode;
            }
            //是否使用
            if (!string.IsNullOrEmpty(IsUseSelect))
            {
                condition += " and IsUse =" + IsUseSelect;
            }
            //是否锁定
            if (!string.IsNullOrEmpty(IsLockSelect))
            {
                condition += " and IsLock=" + IsLockSelect;
            }

            if (!string.IsNullOrEmpty(UseDateData))
            {
                string[] datelist = UseDateData.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and UseDate >='" + start + "' and UseDate <='" + end + " 23:59:59'";

            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PosCoupons", 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 fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == UserId) ?? new Users();
                dic["UserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["UserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("UserId");

                //盟主创客信息
                int LeaderUserId = int.Parse(function.CheckInt(dic["LeaderUserId"].ToString()));
                Users leaderuserid_Users = db.Users.FirstOrDefault(m => m.Id == LeaderUserId) ?? new Users();
                dic["LeaderUserIdMakerCode"] = leaderuserid_Users.MakerCode;
                dic["LeaderUserIdRealName"] = leaderuserid_Users.RealName;
                dic.Remove("LeaderUserId");

                //是否使用
                int IsUse = int.Parse(dic["IsUse"].ToString());
                if (IsUse == 0) dic["IsUseName"] = "否";
                if (IsUse == 1) dic["IsUseName"] = "是";

                //是否锁定
                int IsLock = int.Parse(dic["IsLock"].ToString());
                if (IsLock == 0) dic["IsLockName"] = "否";
                if (IsLock == 1) dic["IsLockName"] = "是";

                //是否是商机券
                int HelpProfitFlag = int.Parse(dic["HelpProfitFlag"].ToString());
                if (HelpProfitFlag == 0) dic["IsSJName"] = "否";
                if (HelpProfitFlag == 1) dic["IsSJName"] = "是";

                //是否使用商机券
                int HelpProfitStatus = int.Parse(dic["HelpProfitStatus"].ToString());
                if (HelpProfitStatus == 0) dic["SJUseName"] = "否";
                if (HelpProfitStatus == 1) dic["SJUseName"] = "是";

                //助利宝商户信息
                int HelpProfitMerchantId = int.Parse(function.CheckInt(dic["HelpProfitMerchantId"].ToString()));
                PosMerchantInfo posMerchantInfo = db.PosMerchantInfo.FirstOrDefault(m => m.Id == HelpProfitMerchantId) ?? new PosMerchantInfo();
                dic["posMerchantInfo"] = posMerchantInfo.MerchantNo + "<br />" + posMerchantInfo.MerchantName;

            }
            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(PosCoupons 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("PosCoupons", Fields, 0);
            AddSysLog(data.Id.ToString(), "PosCoupons", "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;


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

        #endregion

        #region 修改机具券变更记录

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

            return "success";
        }

        #endregion

        #region 删除机具券变更记录信息

        /// <summary>
        /// 删除机具券变更记录信息
        /// </summary>
        /// <returns></returns>
        public string Delete(string Id)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PosCoupons", "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("PosCoupons", 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, "PosCoupons", "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("PosCoupons", 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, "PosCoupons", "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("PosCoupons", 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("PosCoupons", Sort, Id);

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(PosCoupons data, string FromUserIdMakerCode, string FromUserIdRealName, string ToUserIdMakerCode, string ToUserIdRealName, string ChangeKindSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("CreateDate", "3"); //时间
            Fields.Add("OrderNo", "1"); //单号


            string condition = " and Status>-1";
            //来源创客编号
            if (!string.IsNullOrEmpty(FromUserIdMakerCode))
            {
                condition += " and FromUserId in (select FromUserId from UserForMakerCode where MakerCode='" + FromUserIdMakerCode + "')";
            }
            //来源创客真实姓名
            if (!string.IsNullOrEmpty(FromUserIdRealName))
            {
                condition += " and FromUserId in (select FromUserId from UserForRealName where RealName='" + FromUserIdRealName + "')";
            }
            //目标创客编号
            if (!string.IsNullOrEmpty(ToUserIdMakerCode))
            {
                condition += " and ToUserId in (select ToUserId from UserForMakerCode where MakerCode='" + ToUserIdMakerCode + "')";
            }
            //目标创客真实姓名
            if (!string.IsNullOrEmpty(ToUserIdRealName))
            {
                condition += " and ToUserId in (select ToUserId from UserForRealName where RealName='" + ToUserIdRealName + "')";
            }
            //变更类型
            if (!string.IsNullOrEmpty(ChangeKindSelect))
            {
                condition += " and ChangeKind=" + ChangeKindSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("PosCoupons", Fields, "Id desc", "0", 1, 20000, condition, "FromUserId,ToUserId,OrderNo,BeforeStock,BeforeTotal,BeforeOut,AfterStock,AfterTotal,AfterOut,ChangeCount,ChangeKind", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //来源创客
                int FromUserId = int.Parse(function.CheckInt(dic["FromUserId"].ToString()));
                Users fromuserid_Users = db.Users.FirstOrDefault(m => m.Id == FromUserId) ?? new Users();
                dic["FromUserIdMakerCode"] = fromuserid_Users.MakerCode;
                dic["FromUserIdRealName"] = fromuserid_Users.RealName;
                dic.Remove("FromUserId");
                //目标创客
                int ToUserId = int.Parse(function.CheckInt(dic["ToUserId"].ToString()));
                Users touserid_Users = db.Users.FirstOrDefault(m => m.Id == ToUserId) ?? new Users();
                dic["ToUserIdMakerCode"] = touserid_Users.MakerCode;
                dic["ToUserIdRealName"] = touserid_Users.RealName;
                dic.Remove("ToUserId");

            }

            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("FromUserIdMakerCode", "来源创客编号");
            ReturnFields.Add("FromUserIdRealName", "来源创客真实姓名");
            ReturnFields.Add("ToUserIdMakerCode", "目标创客编号");
            ReturnFields.Add("ToUserIdRealName", "目标创客真实姓名");
            ReturnFields.Add("OrderNo", "单号");
            ReturnFields.Add("BeforeStock", "变更前机具券库存");
            ReturnFields.Add("BeforeTotal", "变更前机具券总数");
            ReturnFields.Add("BeforeOut", "变更前机具券使用数");
            ReturnFields.Add("AfterStock", "变更后机具券库存");
            ReturnFields.Add("AfterTotal", "变更后机具券总数");
            ReturnFields.Add("AfterOut", "变更后机具券使用数");
            ReturnFields.Add("ChangeCount", "变更数量");
            ReturnFields.Add("ChangeKind", "变更类型");

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

        #endregion


        #region 设置盟主券

        /// <summary>
        /// 设置盟主券
        /// </summary>
        /// <returns></returns>
        public IActionResult BatchSetting(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion


        #region 设置盟主券

        /// <summary>
        /// 设置盟主券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string BatchSetting(string Id, string MakerCode)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PosCoupons", "PosCouponsBatchSetting");
            var userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
            if (userForMakerCode.UserId > 0)
            {
                var user = db.Users.FirstOrDefault(m => m.Id == userForMakerCode.UserId) ?? new Users();
                if (user.Id > 0 && user.LeaderLevel > 0)
                {
                    DataTable dt = OtherMySqlConn.dtable("UPDATE PosCoupons SET LeaderUserId=" + user.Id + ",SeoTitle=" + SysUserName + "_" + SysRealName + " WHERE Id IN (" + Id + ")");
                    db.SaveChanges();
                }
                else
                {
                    return "该创客不是盟主或者账号不存在";
                }
            }
            return "success";
        }

        #endregion


        #region 取消盟主券

        /// <summary>
        /// 取消盟主券
        /// </summary>
        /// <returns></returns>
        public IActionResult BatchCancle(string right)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

            return View();
        }

        #endregion


        #region 取消盟主券

        /// <summary>
        /// 取消盟主券
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string BatchCancle(string Id, string MakerCode)
        {
            string[] idlist = Id.Split(new char[] { ',' });
            AddSysLog(Id, "PosCoupons", "PosCouponsBatchCancle");
            var userForMakerCode = db.UserForMakerCode.FirstOrDefault(m => m.MakerCode == MakerCode) ?? new UserForMakerCode();
            if (userForMakerCode.UserId > 0)
            {
                var user = db.Users.FirstOrDefault(m => m.Id == userForMakerCode.UserId) ?? new Users();
                if (user.Id > 0)
                {
                    var posCoupons = db.PosCoupons.Where(m => m.LeaderUserId == user.Id).ToList();
                    var error = "";
                    foreach (var item in idlist)
                    {
                        var check = posCoupons.Any(m => m.Id == int.Parse(item) && m.LeaderUserId == user.Id);
                        if (!check)
                        {
                            error += "ID为" + item + "的机具券不是盟主" + MakerCode + "的机具券";
                        }
                    }

                    if (!string.IsNullOrEmpty(error))
                    {
                        return "Warning|" + error;
                    }
                    DataTable dt = OtherMySqlConn.dtable("UPDATE PosCoupons SET LeaderUserId=0,SeoTitle=" + SysUserName + "_" + SysRealName + " WHERE Id IN (" + Id + ") AND LeaderUserId=" + user.Id + "");
                    db.SaveChanges();
                }
            }
            return "success";
        }

        #endregion

    }
}
