/*
 * 开团申请
 */

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 TeamApplyController : BaseController
    {
        public TeamApplyController(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(TeamApply data, string right, int Status = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;
            ViewBag.Status = Status.ToString();

            return View();
        }

        #endregion

        #region 根据条件查询开团申请列表

        /// <summary>
        /// 开团申请列表
        /// </summary>
        /// <returns></returns>
        public JsonResult IndexData(TeamApply data, string UserIdMakerCode, string UserIdRealName, string AuditResultSelect, string NotifyFlagSelect, string TopUserIdMakerCode, string TopUserIdRealName, string TeamStatusSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("TeamNo", "1"); //队伍编码
            Fields.Add("TeamName", "1"); //队伍名称
            Fields.Add("EffectStartDate", "3"); //活动开始时间
            Fields.Add("EnterStartDate", "3"); //报名开始时间


            string condition = "";
            if (data.Status > 0)
            { 
                condition += " and Status=" + data.Status;
            }
            else
            { 
                condition += " and Status>-1";
            }
            //队长创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //队长真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + UserIdRealName + "')";
            }
            //审核结果
            if (!string.IsNullOrEmpty(AuditResultSelect))
            {
                condition += " and AuditResult=" + AuditResultSelect;
            }
            //提醒标识
            if (!string.IsNullOrEmpty(NotifyFlagSelect))
            {
                condition += " and NotifyFlag=" + NotifyFlagSelect;
            }
            //顶级创客编号
            if (!string.IsNullOrEmpty(TopUserIdMakerCode))
            {
                condition += " and TopUserId in (select TopUserId from UserForMakerCode where MakerCode='" + TopUserIdMakerCode + "')";
            }
            //顶级创客真实姓名
            if (!string.IsNullOrEmpty(TopUserIdRealName))
            {
                condition += " and TopUserId in (select TopUserId from UserForRealName where RealName='" + TopUserIdRealName + "')";
            }
            //组队状态
            if (!string.IsNullOrEmpty(TeamStatusSelect))
            {
                condition += " and TeamStatus=" + TeamStatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("TeamApply", 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.Remove("UserId");
                //审核结果
                int AuditResult = int.Parse(dic["AuditResult"].ToString());
                if (AuditResult == 1) dic["AuditResult"] = "通过";
                if (AuditResult == 0) dic["AuditResult"] = "不通过";
                //提醒标识
                int NotifyFlag = int.Parse(dic["NotifyFlag"].ToString());
                if (NotifyFlag == 0) dic["NotifyFlag"] = "未提醒";
                if (NotifyFlag == 1) dic["NotifyFlag"] = "已提醒";
                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserIdMakerCode"] = topuserid_Users.MakerCode;
                dic["TopUserIdRealName"] = topuserid_Users.RealName;
                dic.Remove("TopUserId");
                //组队状态
                int TeamStatus = int.Parse(dic["TeamStatus"].ToString());
                if (TeamStatus == 0) dic["TeamStatusName"] = "待审核";
                if (TeamStatus == 1) dic["TeamStatusName"] = "审核通过";
                if (TeamStatus == 2) dic["TeamStatusName"] = "审核失败";
                if (TeamStatus == 3) dic["TeamStatusName"] = "组队成功";
                if (TeamStatus == 4) dic["TeamStatusName"] = "组队失败";

            }
            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(TeamApply data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("TeamNo", data.TeamNo); //队伍编码
            Fields.Add("TeamName", data.TeamName); //队伍名称
            Fields.Add("ManagerName", data.ManagerName); //渠道经理名称
            Fields.Add("Areas", data.Areas); //特训营所在地区
            Fields.Add("EffectStartDate", data.EffectStartDate); //活动开始时间
            Fields.Add("EffectEndDate", data.EffectEndDate); //活动结束时间
            Fields.Add("EnterStartDate", data.EnterStartDate); //报名开始时间
            Fields.Add("EnterEndDate", data.EnterEndDate); //报名结束时间
            Fields.Add("MinUserNum", data.MinUserNum); //最小队伍人数
            Fields.Add("MaxUserNum", data.MaxUserNum); //最大队伍人数
            Fields.Add("WatchWord", data.WatchWord); //口号
            Fields.Add("AuditTime", data.AuditTime); //审核时间
            Fields.Add("AuditRemark", data.AuditRemark); //审核备注
            Fields.Add("Remark", data.Remark); //备注

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


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

        #endregion

        #region 修改开团申请

        /// <summary>
        /// 增加或修改开团申请信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(TeamApply data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("TeamNo", data.TeamNo); //队伍编码
            Fields.Add("TeamName", data.TeamName); //队伍名称
            Fields.Add("ManagerName", data.ManagerName); //渠道经理名称
            Fields.Add("Areas", data.Areas); //特训营所在地区
            Fields.Add("EffectStartDate", data.EffectStartDate); //活动开始时间
            Fields.Add("EffectEndDate", data.EffectEndDate); //活动结束时间
            Fields.Add("EnterStartDate", data.EnterStartDate); //报名开始时间
            Fields.Add("EnterEndDate", data.EnterEndDate); //报名结束时间
            Fields.Add("MinUserNum", data.MinUserNum); //最小队伍人数
            Fields.Add("MaxUserNum", data.MaxUserNum); //最大队伍人数
            Fields.Add("WatchWord", data.WatchWord); //口号
            Fields.Add("AuditTime", data.AuditTime); //审核时间
            Fields.Add("AuditRemark", data.AuditRemark); //审核备注
            Fields.Add("Remark", data.Remark); //备注

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

            return "success";
        }

        #endregion
        
        #region 审核

        public IActionResult Audit(string right, int Id = 0)
        {
            ViewBag.RightInfo = RightInfo;
            ViewBag.right = right;

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

        #endregion

        #region 审核

        [HttpPost]
        public string Audit(TeamApply data)
        {
            Dictionary<string, object> Fields = new Dictionary<string, object>();

            Fields.Add("AuditResult", data.AuditResult);
            Fields.Add("AuditTime", DateTime.Now); //审核时间
            Fields.Add("AuditRemark", data.AuditRemark); //审核备注
            if (data.AuditResult == 1)
            { 
                Fields.Add("TeamStatus", 1);
            }
            else
            { 
                Fields.Add("TeamStatus", 2);
            }

            new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).Edit("TeamApply", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "TeamApply", "Audit");
            db.SaveChanges();

            if (data.AuditResult == 1)
            { 
                var teams = db.TeamApply.Select(m => new { m.Id, m.TeamStatus, m.Sort }).Where(m => m.TeamStatus == 1).OrderByDescending(m => m.Sort).ThenByDescending(m => m.Id).ToList();
                RedisDbconn.Instance.Clear("TeamApplyList");
                foreach (var team in teams)
                {
                    RedisDbconn.Instance.AddList("TeamApplyList", team.Id);
                }
            }

            return "success";
        }

        #endregion

        #region 删除开团申请信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(TeamApply data, string UserIdMakerCode, string UserIdRealName, string AuditResultSelect, string NotifyFlagSelect, string TopUserIdMakerCode, string TopUserIdRealName, string TeamStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("TeamNo", "1"); //队伍编码
            Fields.Add("TeamName", "1"); //队伍名称
            Fields.Add("EffectStartDate", "3"); //活动开始时间
            Fields.Add("EnterStartDate", "3"); //报名开始时间


            string condition = " and Status>-1";
            //队长创客编号
            if (!string.IsNullOrEmpty(UserIdMakerCode))
            {
                condition += " and UserId in (select UserId from UserForMakerCode where MakerCode='" + UserIdMakerCode + "')";
            }
            //队长真实姓名
            if (!string.IsNullOrEmpty(UserIdRealName))
            {
                condition += " and UserId in (select UserId from UserForRealName where RealName='" + UserIdRealName + "')";
            }
            //审核结果
            if (!string.IsNullOrEmpty(AuditResultSelect))
            {
                condition += " and AuditResult=" + AuditResultSelect;
            }
            //提醒标识
            if (!string.IsNullOrEmpty(NotifyFlagSelect))
            {
                condition += " and NotifyFlag=" + NotifyFlagSelect;
            }
            //顶级创客编号
            if (!string.IsNullOrEmpty(TopUserIdMakerCode))
            {
                condition += " and TopUserId in (select TopUserId from UserForMakerCode where MakerCode='" + TopUserIdMakerCode + "')";
            }
            //顶级创客真实姓名
            if (!string.IsNullOrEmpty(TopUserIdRealName))
            {
                condition += " and TopUserId in (select TopUserId from UserForRealName where RealName='" + TopUserIdRealName + "')";
            }
            //组队状态
            if (!string.IsNullOrEmpty(TeamStatusSelect))
            {
                condition += " and TeamStatus=" + TeamStatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("TeamApply", Fields, "Id desc", "0", 1, 20000, condition, "TeamNo,TeamName,UserId,Areas,EffectStartDate,EffectEndDate,EnterStartDate,EnterEndDate,MinUserNum,MaxUserNum,WatchWord,AuditTime,AuditResult,AuditRemark,NotifyFlag,Remark,TopUserId,TeamStatus", 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.Remove("UserId");
                //审核结果
                int AuditResult = int.Parse(dic["AuditResult"].ToString());
                if (AuditResult == 1) dic["AuditResult"] = "通过";
                if (AuditResult == 0) dic["AuditResult"] = "不通过";
                //提醒标识
                int NotifyFlag = int.Parse(dic["NotifyFlag"].ToString());
                if (NotifyFlag == 0) dic["NotifyFlag"] = "未提醒";
                if (NotifyFlag == 1) dic["NotifyFlag"] = "已提醒";
                //顶级创客
                int TopUserId = int.Parse(function.CheckInt(dic["TopUserId"].ToString()));
                Users topuserid_Users = db.Users.FirstOrDefault(m => m.Id == TopUserId) ?? new Users();
                dic["TopUserIdMakerCode"] = topuserid_Users.MakerCode;
                dic["TopUserIdRealName"] = topuserid_Users.RealName;
                dic.Remove("TopUserId");
                //组队状态
                int TeamStatus = int.Parse(dic["TeamStatus"].ToString());
                if (TeamStatus == 0) dic["TeamStatus"] = "待审核";
                if (TeamStatus == 1) dic["TeamStatus"] = "审核通过";
                if (TeamStatus == 2) dic["TeamStatus"] = "审核失败";
                if (TeamStatus == 3) dic["TeamStatus"] = "组队成功";
                if (TeamStatus == 4) dic["TeamStatus"] = "组队失败";

            }

            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("TeamNo", "队伍编码");
            ReturnFields.Add("TeamName", "队伍名称");
            ReturnFields.Add("UserIdMakerCode", "队长创客编号");
            ReturnFields.Add("UserIdRealName", "队长真实姓名");
            ReturnFields.Add("TopUserIdMakerCode", "顶级创客编号");
            ReturnFields.Add("TopUserIdRealName", "顶级创客真实姓名");
            ReturnFields.Add("Areas", "特训营所在地区");
            ReturnFields.Add("EffectStartDate", "活动开始时间");
            ReturnFields.Add("EffectEndDate", "活动结束时间");
            ReturnFields.Add("EnterStartDate", "报名开始时间");
            ReturnFields.Add("EnterEndDate", "报名结束时间");
            ReturnFields.Add("MinUserNum", "最小队伍人数");
            ReturnFields.Add("MaxUserNum", "最大队伍人数");
            ReturnFields.Add("WatchWord", "口号");
            ReturnFields.Add("TeamStatus", "组队状态");
            ReturnFields.Add("AuditResult", "审核结果");
            ReturnFields.Add("AuditTime", "审核时间");
            ReturnFields.Add("AuditRemark", "审核备注");
            ReturnFields.Add("NotifyFlag", "提醒标识");
            ReturnFields.Add("Remark", "备注");

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

        #endregion

    }
}
