/*
 * 参团申请
 */

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 TeamOfferApplyController : BaseController
    {
        public TeamOfferApplyController(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(TeamOfferApply 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(TeamOfferApply data, string AuditResultSelect, string NotifyFlagSelect, string UserIdMakerCode, string UserIdRealName, string TeamIdTeamNo, string TeamIdTeamName, string TeamLeaderMakerCode, string TeamLeaderRealName, string TopUserIdMakerCode, string TopUserIdRealName, string TeamApplyStatusSelect, string TeamStatusSelect, int page = 1, int limit = 30)
        {

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

            Fields.Add("EnterDate", "3"); //报名时间


            string condition = "";
            if (data.Status > 0)
            { 
                condition += " and Status=" + data.Status;
            }
            else
            { 
                condition += " and Status>-1";
            }
            //审核结果
            if (!string.IsNullOrEmpty(AuditResultSelect))
            {
                condition += " and AuditResult=" + AuditResultSelect;
            }
            //提醒标识
            if (!string.IsNullOrEmpty(NotifyFlagSelect))
            {
                condition += " and NotifyFlag=" + NotifyFlagSelect;
            }
            //创客编号
            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(TeamIdTeamNo))
            {
                condition += " and TeamId in (select TeamId from TeamApplyForTeamNo where TeamNo='" + TeamIdTeamNo + "')";
            }
            //团队队伍名称
            if (!string.IsNullOrEmpty(TeamIdTeamName))
            {
                condition += " and TeamId in (select TeamId from TeamApplyForTeamName where TeamName='" + TeamIdTeamName + "')";
            }
            //队长创客编号
            if (!string.IsNullOrEmpty(TeamLeaderMakerCode))
            {
                condition += " and TeamLeader in (select TeamLeader from UserForMakerCode where MakerCode='" + TeamLeaderMakerCode + "')";
            }
            //队长真实姓名
            if (!string.IsNullOrEmpty(TeamLeaderRealName))
            {
                condition += " and TeamLeader in (select TeamLeader from UserForRealName where RealName='" + TeamLeaderRealName + "')";
            }
            //顶级创客编号
            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(TeamApplyStatusSelect))
            {
                condition += " and TeamApplyStatus=" + TeamApplyStatusSelect;
            }
            //状态
            if (!string.IsNullOrEmpty(TeamStatusSelect))
            {
                condition += " and TeamStatus=" + TeamStatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("TeamOfferApply", 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 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 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 TeamId = int.Parse(function.CheckInt(dic["TeamId"].ToString()));
                TeamApply teamid_TeamApply = db.TeamApply.FirstOrDefault(m => m.Id == TeamId) ?? new TeamApply();
                dic["TeamIdTeamNo"] = teamid_TeamApply.TeamNo;
                dic["TeamIdTeamName"] = teamid_TeamApply.TeamName;
                dic.Remove("TeamId");
                //队长
                int TeamLeader = int.Parse(function.CheckInt(dic["TeamLeader"].ToString()));
                Users teamleader_Users = db.Users.FirstOrDefault(m => m.Id == TeamLeader) ?? new Users();
                dic["TeamLeaderMakerCode"] = teamleader_Users.MakerCode;
                dic["TeamLeaderRealName"] = teamleader_Users.RealName;
                dic.Remove("TeamLeader");
                //顶级创客
                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 TeamApplyStatus = int.Parse(dic["TeamApplyStatus"].ToString());
                if (TeamApplyStatus == 0) dic["TeamApplyStatusName"] = "待审核";
                if (TeamApplyStatus == 1) dic["TeamApplyStatusName"] = "已审核通过";
                if (TeamApplyStatus == 2) dic["TeamApplyStatusName"] = "已审核失败";
                //状态
                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"] = "报名成功";
                if (TeamStatus == 5) dic["TeamStatus"] = "报名失败";

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


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

        #endregion

        #region 修改参团申请

        /// <summary>
        /// 增加或修改参团申请信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Edit(TeamOfferApply 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("TeamOfferApply", Fields, data.Id);
            AddSysLog(data.Id.ToString(), "TeamOfferApply", "update");
            db.SaveChanges();

            return "success";
        }

        #endregion

        #region 审核

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

            TeamOfferApply editData = db.TeamOfferApply.FirstOrDefault(m => m.Id == Id) ?? new TeamOfferApply();
            ViewBag.data = editData;

            TeamApply team = db.TeamApply.FirstOrDefault(m=>m.Id == editData.TeamId) ?? new TeamApply();
            ViewBag.TeamNo = team.TeamNo;
            ViewBag.TeamName = team.TeamName;
            ViewBag.WatchWord = team.WatchWord;
            Users user = db.Users.FirstOrDefault(m=>m.Id == editData.UserId) ?? new Users();
            ViewBag.MakerCode = user.MakerCode;
            ViewBag.RealName = user.RealName;
            return View();
        }

        #endregion

        #region 审核

        [HttpPost]
        public string Audit(TeamOfferApply 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("TeamApplyStatus", 1);
                Fields.Add("TeamStatus", 1);
            }
            else
            { 
                Fields.Add("TeamApplyStatus", 2);
                Fields.Add("TeamStatus", 2);
            }

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

            return "success";
        }

        #endregion

        #region 删除参团申请信息

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

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

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

        #region 导出Excel

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <returns></returns>
        public JsonResult ExportExcel(TeamOfferApply data, string AuditResultSelect, string NotifyFlagSelect, string UserIdMakerCode, string UserIdRealName, string TeamIdTeamNo, string TeamIdTeamName, string TeamLeaderMakerCode, string TeamLeaderRealName, string TopUserIdMakerCode, string TopUserIdRealName, string TeamApplyStatusSelect, string TeamStatusSelect)
        {
            Dictionary<string, string> Fields = new Dictionary<string, string>();
            Fields.Add("EnterDate", "3"); //报名时间


            string condition = " and Status>-1";
            //审核结果
            if (!string.IsNullOrEmpty(AuditResultSelect))
            {
                condition += " and AuditResult=" + AuditResultSelect;
            }
            //提醒标识
            if (!string.IsNullOrEmpty(NotifyFlagSelect))
            {
                condition += " and NotifyFlag=" + NotifyFlagSelect;
            }
            //创客编号
            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(TeamIdTeamNo))
            {
                condition += " and TeamId in (select TeamId from TeamApplyForTeamNo where TeamNo='" + TeamIdTeamNo + "')";
            }
            //团队队伍名称
            if (!string.IsNullOrEmpty(TeamIdTeamName))
            {
                condition += " and TeamId in (select TeamId from TeamApplyForTeamName where TeamName='" + TeamIdTeamName + "')";
            }
            //队长创客编号
            if (!string.IsNullOrEmpty(TeamLeaderMakerCode))
            {
                condition += " and TeamLeader in (select TeamLeader from UserForMakerCode where MakerCode='" + TeamLeaderMakerCode + "')";
            }
            //队长真实姓名
            if (!string.IsNullOrEmpty(TeamLeaderRealName))
            {
                condition += " and TeamLeader in (select TeamLeader from UserForRealName where RealName='" + TeamLeaderRealName + "')";
            }
            //顶级创客编号
            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(TeamApplyStatusSelect))
            {
                condition += " and TeamApplyStatus=" + TeamApplyStatusSelect;
            }
            //状态
            if (!string.IsNullOrEmpty(TeamStatusSelect))
            {
                condition += " and TeamStatus=" + TeamStatusSelect;
            }


            Dictionary<string, object> obj = new AdminContentOther(_accessor.HttpContext, PublicFunction.MainTables).IndexData("TeamOfferApply", Fields, "Id desc", "0", 1, 20000, condition, "Areas,EffectStartDate,EffectEndDate,EnterDate,AuditTime,AuditResult,AuditRemark,NotifyFlag,UserId,TeamId,TeamLeader,TopUserId,TeamApplyStatus,TeamStatus", false);
            List<Dictionary<string, object>> diclist = obj["data"] as List<Dictionary<string, object>>;
            foreach (Dictionary<string, object> dic in diclist)
            {
                //审核结果
                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 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 TeamId = int.Parse(function.CheckInt(dic["TeamId"].ToString()));
                TeamApply teamid_TeamApply = db.TeamApply.FirstOrDefault(m => m.Id == TeamId) ?? new TeamApply();
                dic["TeamIdTeamNo"] = teamid_TeamApply.TeamNo;
                dic["TeamIdTeamName"] = teamid_TeamApply.TeamName;
                dic.Remove("TeamId");
                //队长
                int TeamLeader = int.Parse(function.CheckInt(dic["TeamLeader"].ToString()));
                Users teamleader_Users = db.Users.FirstOrDefault(m => m.Id == TeamLeader) ?? new Users();
                dic["TeamLeaderMakerCode"] = teamleader_Users.MakerCode;
                dic["TeamLeaderRealName"] = teamleader_Users.RealName;
                dic.Remove("TeamLeader");
                //顶级创客
                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 TeamApplyStatus = int.Parse(dic["TeamApplyStatus"].ToString());
                if (TeamApplyStatus == 0) dic["TeamApplyStatus"] = "待审核";
                if (TeamApplyStatus == 1) dic["TeamApplyStatus"] = "已审核通过";
                if (TeamApplyStatus == 2) dic["TeamApplyStatus"] = "已审核失败";
                //状态
                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"] = "报名成功";
                if (TeamStatus == 5) 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("UserIdMakerCode", "创客编号");
            ReturnFields.Add("UserIdRealName", "创客姓名");
            ReturnFields.Add("TeamIdTeamNo", "团队队伍编码");
            ReturnFields.Add("TeamIdTeamName", "团队队伍名称");
            ReturnFields.Add("TeamLeaderMakerCode", "队长创客编号");
            ReturnFields.Add("TeamLeaderRealName", "队长真实姓名");
            ReturnFields.Add("TopUserIdMakerCode", "顶级创客编号");
            ReturnFields.Add("TopUserIdRealName", "顶级创客真实姓名");
            ReturnFields.Add("Areas", "特训营所在地区");
            ReturnFields.Add("EffectStartDate", "活动开始时间");
            ReturnFields.Add("EffectEndDate	", "活动结束时间");
            ReturnFields.Add("EnterDate", "报名时间");
            ReturnFields.Add("AuditTime", "审核时间");
            ReturnFields.Add("TeamStatus", "状态");
            ReturnFields.Add("TeamApplyStatus", "组队申请状态");
            ReturnFields.Add("AuditResult", "审核结果");
            ReturnFields.Add("AuditRemark", "审核备注");
            ReturnFields.Add("NotifyFlag", "提醒标识");

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

        #endregion

    }
}
