using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Dapper;
using DigitalSchoolApi.Models;
using Hangfire;
using Learun.Application.Organization;

namespace DigitalSchoolApi.Controllers
{
    public class YKTController : BaseController
    {
        private readonly static string _admsConnection = ConfigurationManager.ConnectionStrings["CoreDBString"].ConnectionString;
        private readonly static string _misConnection = ConfigurationManager.ConnectionStrings["ConnectionPfcMisDBString"].ConnectionString;


        /// <summary>
        /// 西昌一卡通推送
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Begin()
        {
            //西昌
            //YKTTrabs.BeginTrans();
            RecurringJob.AddOrUpdate("YKT",
                () => YKTTrabs.BeginTrans(),
                Cron.Daily(13), TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate("YKT2",
                () => YKTTrabs.BeginTrans(),
                Cron.Daily(22), TimeZoneInfo.Local);
            //金隅
            //RecurringJob.AddOrUpdate("JINYUYKT",
            //    () => YKTTrabs.GetConsumeInfo(),
            //    Cron.Daily(0), TimeZoneInfo.Local);
            //RecurringJob.AddOrUpdate("JINYUYKT2",
            //    () => YKTTrabs.GetConsumeInfo(),
            //    Cron.Daily(14), TimeZoneInfo.Local);
            //RecurringJob.AddOrUpdate("JINYUYKTSAVER",
            //    () => YKTTrabs.GetSaveRecordInfo(),
            //    Cron.Daily(14), TimeZoneInfo.Local);
            //RecurringJob.AddOrUpdate("PUSHWEIXIN",
            //    () => YKTTrabs.PushWeixin(),
            //    Cron.Daily(0), TimeZoneInfo.Local);
            return Ok();
        }
        /// <summary>
        /// 开启金隅一卡通推送
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult BeginJinyu()
        {
            //金隅
            RecurringJob.AddOrUpdate("JINYUYKT",
                () => YKTTrabs.GetConsumeInfo(),
                Cron.Daily(0), TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate("JINYUYKT2",
                () => YKTTrabs.GetConsumeInfo(),
                Cron.Daily(14), TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate("JINYUYKTSAVER",
                () => YKTTrabs.GetSaveRecordInfo(),
                Cron.Daily(14), TimeZoneInfo.Local);

            //YKTTrabs.GetConsumeInfo();
            //RecurringJob.AddOrUpdate("PUSHWEIXIN",
            //    () => YKTTrabs.PushWeixin(),
            //    Cron.Daily(0), TimeZoneInfo.Local);
            return Ok();
        }

        /// <summary>
        /// 西昌在线缴费状态
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult QueryPayData()
        {
            //YKTTrabs.GetEBillPicUrl();
            //YKTTrabs.InvoiceEBillMethod();
            RecurringJob.AddOrUpdate("QueryPayData",
                () => YKTTrabs.QueryPayData(),
                Cron.MinuteInterval(5), TimeZoneInfo.Local);
            return Ok();
        }

        /// <summary>
        /// 西昌中间库学生表更新
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult MiddleDBUpdStuData()
        {
            //YKTTrabs.MiddleDBUpdStuData();
            RecurringJob.AddOrUpdate("MiddleDBUpdStuData",
                () => YKTTrabs.MiddleDBUpdStuData(),
                Cron.Daily(2), TimeZoneInfo.Local);
            return Ok();
        }
        /// <summary>
        /// 长阳获取饭卡流水
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult BeginChangYang()
        {
            //YKTTrabs.GetChangeYangYKT();
            RecurringJob.AddOrUpdate("CHANGYANGYKT1",
                () => YKTTrabs.GetChangeYangYKT(),
                Cron.Daily(9), TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate("CHANGYANGYKT2",
                () => YKTTrabs.GetChangeYangYKT(),
                Cron.Daily(14), TimeZoneInfo.Local);
            RecurringJob.AddOrUpdate("CHANGYANGYKT3",
                () => YKTTrabs.GetChangeYangYKT(),
                Cron.Daily(21), TimeZoneInfo.Local);
            return Ok();
        }

        /// <summary>
        /// 河南新安定时获取部门用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult HeNanXinAnBegin()
        {
            //YKTTrabs.BgeinHeNanXinAn();
            RecurringJob.AddOrUpdate("HNXA",
            () => YKTTrabs.BgeinHeNanXinAn(),
                Cron.Daily(13), TimeZoneInfo.Local);
            return Ok();
        }

        /// <summary>
        /// 金隅消费信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult Balance()
        {
            RecurringJob.Trigger("JINYUYKT");
            //YKTTrabs.GetConsumeInfo();
            return Ok();
        }

        /// <summary>
        /// 测试PUSHWEIXIN
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult PushWeixinTest()
        {
            RecurringJob.Trigger("PUSHWEIXIN");
            return Ok();
        }
        /// <summary>
        /// 金隅充值记录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IHttpActionResult GetSaveRecord()
        {
            RecurringJob.Trigger("JINYUYKTSAVER");
            //YKTTrabs.GetSaveRecordInfo();
            return Ok();
        }

        /// <summary>
        /// 停止西昌一卡通推送
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult Terminate()
        {
            RecurringJob.RemoveIfExists("YKT");
            RecurringJob.RemoveIfExists("YKT2");
            //RecurringJob.RemoveIfExists("JINYUYKT");
            //RecurringJob.RemoveIfExists("JINYUYKT2");
            return Ok();
        }

        /// <summary>
        /// 新疆巴楚教育局与java项目帐号同步
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult StartBachuAccount()
        {
            RecurringJob.AddOrUpdate("BachuAccount",
                () => YKTTrabs.BeginBachuAccount(),
                Cron.Daily(22), TimeZoneInfo.Local);
            return Ok();
        }


        /// <summary>
        /// 开始连接并监听考勤事件
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult StartConnectHK()
        {
            BackgroundJob.Enqueue(() => HKAttendanceController.StartConnect());
            RecurringJob.AddOrUpdate("HKAttendance",
                () => HKAttendanceController.StartConnect(),
                Cron.Yearly, TimeZoneInfo.Local);
            return Ok();
        }

        /// <summary>
        /// 考勤机撤防
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult EndConnectHK()
        {
            BackgroundJob.Enqueue(() => HKAttendanceController.EndConnect());
            return Ok();
        }

        /// <summary>
        /// 开始领导自动考勤
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult BeginLeaderAttendance()
        {
            RecurringJob.AddOrUpdate("LeaderAttendance",
                () => HKAttendanceController.BeginLeaderAttendance(),
                Cron.Daily(19), TimeZoneInfo.Local);
            return Ok();
        }
        /// <summary>
        /// 结束领导自动考勤
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult EndLeaderAttendance()
        {
            RecurringJob.RemoveIfExists("LeaderAttendance");
            return Ok();
        }

        #region 长阳报名\晚归预警
        /// <summary>
        /// 长阳报名  保存后24小时自动提交
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult CYStuVolunteer()
        {
            RecurringJob.AddOrUpdate("CY",
                () => CYStuVolunteerController.StuVolunteer(),
                Cron.Minutely(), TimeZoneInfo.Local);
            return Ok();
        }

        /// <summary>
        /// 长阳晚归预警
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult CYDormitoryReturn()
        {
            int hour = 99;
            try
            {
                using (IDbConnection conn = new SqlConnection(_misConnection))
                {
                    Acc_DormitoryRuleEntity entity = conn.QueryFirstOrDefault<Acc_DormitoryRuleEntity>("select top 1 PushHour from Acc_DormitoryRule where IsEnable=1");
                    if (entity != null && entity.PushHour >= 0)
                    {
                        hour = Convert.ToInt32(entity.PushHour);
                    }
                }
            }
            catch (Exception ex)
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    conn.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),998,'寝室晚归预警获取推送时间点发生异常','{ex.Message}',getdate())");
                }
            }

            if (hour != 99)
            {
                RecurringJob.AddOrUpdate("CYLRP",
                    () => CYDormitoryReturnController.LateReturnPush(),
                    Cron.Daily(hour), TimeZoneInfo.Local);
            }

            return Ok();
        }

        private class Acc_DormitoryRuleEntity
        {
            public int? PushHour { get; set; }
        }


        #endregion

        #region 长阳中间库

        /// <summary>
        /// 往长阳oracle中间库中同步数校基础信息
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult SyncBasicInfoToCYZJMiddle()
        {
            //部门
            //CYDormitoryReturnController.SyncDepartment();
            RecurringJob.AddOrUpdate("SyncDepartmentToCYZJMiddle",
                () => CYDormitoryReturnController.SyncDepartment(),
                Cron.Daily(1), TimeZoneInfo.Local);
            //系部
            //CYDormitoryReturnController.SyncDept();
            RecurringJob.AddOrUpdate("SyncDeptToCYZJMiddle",
                () => CYDormitoryReturnController.SyncDept(),
                Cron.Daily(1), TimeZoneInfo.Local);
            //专业
            //CYDormitoryReturnController.SyncMajor();
            RecurringJob.AddOrUpdate("SyncMajorToCYZJMiddle",
               () => CYDormitoryReturnController.SyncMajor(),
               Cron.Daily(1), TimeZoneInfo.Local);
            //班级
            //CYDormitoryReturnController.SyncClassInfo();
            RecurringJob.AddOrUpdate("SyncClassInfoToCYZJMiddle",
              () => CYDormitoryReturnController.SyncClassInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //教室
            //CYDormitoryReturnController.SyncClassRoom();
            RecurringJob.AddOrUpdate("SyncClassRoomToCYZJMiddle",
              () => CYDormitoryReturnController.SyncClassRoom(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //学生
            //CYDormitoryReturnController.SyncStuInfo();
            RecurringJob.AddOrUpdate("SyncStuInfoToCYZJMiddle",
              () => CYDormitoryReturnController.SyncStuInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //教师
            //CYDormitoryReturnController.SyncEmpInfo();
            RecurringJob.AddOrUpdate("SyncEmpInfoToCYZJMiddle",
              () => CYDormitoryReturnController.SyncEmpInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //宿舍
            //CYDormitoryReturnController.SyncDormitoryBuild();
            RecurringJob.AddOrUpdate("SyncDormitoryBuildToCYZJMiddle",
              () => CYDormitoryReturnController.SyncDormitoryBuild(),
              Cron.Daily(1), TimeZoneInfo.Local);

            return Ok();
        }

        #endregion

        #region 怀来职教中间库

        /// <summary>
        /// 往怀来职教oracle中间库中同步数校基础信息
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult SyncBasicInfoToHLZJMiddle()
        {
            //部门
            //HLSchoolController.SyncDepartment();
            RecurringJob.AddOrUpdate("SyncDepartmentToHLZJMiddle",
                () => HLSchoolController.SyncDepartment(),
                Cron.Daily(1), TimeZoneInfo.Local);
            //系部
            //HLSchoolController.SyncDept();
            RecurringJob.AddOrUpdate("SyncDeptToHLZJMiddle",
                () => HLSchoolController.SyncDept(),
                Cron.Daily(1), TimeZoneInfo.Local);
            //专业
            //HLSchoolController.SyncMajor();
            RecurringJob.AddOrUpdate("SyncMajorToHLZJMiddle",
               () => HLSchoolController.SyncMajor(),
               Cron.Daily(1), TimeZoneInfo.Local);
            //班级
            //HLSchoolController.SyncClassInfo();
            RecurringJob.AddOrUpdate("SyncClassInfoToHLZJMiddle",
              () => HLSchoolController.SyncClassInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //教室
            //HLSchoolController.SyncClassRoom();
            RecurringJob.AddOrUpdate("SyncClassRoomToHLZJMiddle",
              () => HLSchoolController.SyncClassRoom(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //学生
            //HLSchoolController.SyncStuInfo();
            RecurringJob.AddOrUpdate("SyncStuInfoToHLZJMiddle",
              () => HLSchoolController.SyncStuInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //教师
            //HLSchoolController.SyncEmpInfo();
            RecurringJob.AddOrUpdate("SyncEmpInfoToHLZJMiddle",
              () => HLSchoolController.SyncEmpInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //宿舍
            //HLSchoolController.SyncDormitoryBuild();
            RecurringJob.AddOrUpdate("SyncDormitoryBuildToHLZJMiddle",
              () => HLSchoolController.SyncDormitoryBuild(),
              Cron.Daily(1), TimeZoneInfo.Local);

            return Ok();
        }

        #endregion

        #region 塔里木
        /// <summary>
        /// 晚归预警
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult DormitoryIn()
        {
            int hour = 99;
            try
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    Acc_DormitoryRuleEntity entity = conn.QueryFirstOrDefault<Acc_DormitoryRuleEntity>("select top 1 PushHour from Acc_DormitoryRule where IsEnable=1");
                    if (entity != null && entity.PushHour >= 0)
                    {
                        hour = Convert.ToInt32(entity.PushHour);
                    }
                }
            }
            catch (Exception ex)
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    conn.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),998,'寝室晚归预警获取推送时间点发生异常','{ex.Message}',getdate())");
                }
            }

            if (hour != 99)
            {
                RecurringJob.AddOrUpdate("TLMpush",
                    () => TLMSchoolController.LateReturnPush(),
                    Cron.Daily(hour), TimeZoneInfo.Local);
            }
            //TLMSchoolController.LateReturnPush();
            return Ok();
        }
        /// <summary>
        /// 锁定超过60天未登录的教师用户
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult CloseUser()
        {
            RecurringJob.AddOrUpdate("TLMClose",
                () => TLMSchoolController.CloseAccount(),
                Cron.Daily(0), TimeZoneInfo.Local);
            //TLMSchoolController.CloseAccount();
            return Ok();
        }

        /// <summary>
        /// 往塔里木oracle中间库中同步数校基础信息
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult SyncBasicInfoToTLMZYMiddle()
        {
            //部门
            //TLMSchoolController.SyncDepartment();
            RecurringJob.AddOrUpdate("SyncDepartmentToTLMZYMiddle",
                () => TLMSchoolController.SyncDepartment(),
                Cron.Daily(1), TimeZoneInfo.Local);
            //系部
            //TLMSchoolController.SyncDept();
            RecurringJob.AddOrUpdate("SyncDeptToTLMZYMiddle",
                () => TLMSchoolController.SyncDept(),
                Cron.Daily(1), TimeZoneInfo.Local);
            //专业
            //TLMSchoolController.SyncMajor();
            RecurringJob.AddOrUpdate("SyncMajorToTLMZYMiddle",
               () => TLMSchoolController.SyncMajor(),
               Cron.Daily(1), TimeZoneInfo.Local);
            //班级
            //TLMSchoolController.SyncClassInfo();
            RecurringJob.AddOrUpdate("SyncClassInfoToTLMZYMiddle",
              () => TLMSchoolController.SyncClassInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //教室
            //TLMSchoolController.SyncClassRoom();
            RecurringJob.AddOrUpdate("SyncClassRoomToTLMZYMiddle",
              () => TLMSchoolController.SyncClassRoom(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //学生
            //TLMSchoolController.SyncStuInfo();
            RecurringJob.AddOrUpdate("SyncStuInfoToTLMZYMiddle",
              () => TLMSchoolController.SyncStuInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //教师
            //TLMSchoolController.SyncEmpInfo();
            RecurringJob.AddOrUpdate("SyncEmpInfoToTLMZYMiddle",
              () => TLMSchoolController.SyncEmpInfo(),
              Cron.Daily(1), TimeZoneInfo.Local);
            //宿舍
            //TLMSchoolController.SyncDorm();
            RecurringJob.AddOrUpdate("SyncDormToTLMZYMiddle",
              () => TLMSchoolController.SyncDorm(),
              Cron.Daily(1), TimeZoneInfo.Local);

            return Ok();
        }

        /// <summary>
        /// 塔里木，给教职工发送邮件提醒
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult SendEmailToTeacher()
        {
            try
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    //获取“学校邮箱管理”已启用的项
                    List<EmailManagementEntity> entityList = conn.Query<EmailManagementEntity>("select * from EmailManagement where F_EnabledMark=1 ").ToList();
                    if (entityList.Any())
                    {
                        if (entityList[0].F_Minute.HasValue)//时、分
                        {
                            //TLMSchoolController.AssignSendEmail(entityList);
                            RecurringJob.AddOrUpdate("SendEmailToTeacher",
                                () => TLMSchoolController.AssignSendEmail(entityList),
                                Cron.Daily(entityList[0].F_Hour.Value, entityList[0].F_Minute.Value), TimeZoneInfo.Local);
                        }
                        else//时
                        {
                            //TLMSchoolController.AssignSendEmail(entityList);
                            RecurringJob.AddOrUpdate("SendEmailToTeacher",
                            () => TLMSchoolController.AssignSendEmail(entityList),
                            Cron.Daily(entityList[0].F_Hour.Value), TimeZoneInfo.Local);
                        }
                        
                    }
                }
            }
            catch (Exception ex)
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    conn.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),997,'发送邮件提醒','异常：{ex.Message}',getdate())");
                }
            }

            return Ok();
        }

        /// <summary>
        /// 塔里木固定资产，自动更新已提折旧月数
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult UpdateMonthsInFixAssets()
        {
            try
            {
                RecurringJob.AddOrUpdate("UpdateMonthsInFixAssets",
                () => TLMSchoolController.UpdateHaveDepreciationMonths(),
                Cron.Daily(0), TimeZoneInfo.Local);
                //TLMSchoolController.UpdateHaveDepreciationMonths();
            }
            catch (Exception ex)
            {
                using (IDbConnection conn = new SqlConnection(_admsConnection))
                {
                    conn.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),996,'固定资产：自动更新已提折旧月数','异常：{ex.Message}',getdate())");
                }
            }

            return Ok();
        }

        #endregion

        #region 系统授权到期提醒（发送邮件）
        /// <summary>
        /// 授权到期提醒 上午九点
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult EmailSendAM()
        {
            RecurringJob.AddOrUpdate("EmailSendAM",
                () => EmailSendController.Send(),
                Cron.Daily(9), TimeZoneInfo.Local);

            return Ok();
        }
        /// <summary>
        /// 授权到期提醒  下午4点
        /// </summary>
        /// <returns></returns>
        public IHttpActionResult EmailSendPM()
        {
            RecurringJob.AddOrUpdate("EmailSendPM",
                () => EmailSendController.Send(),
                Cron.Daily(16), TimeZoneInfo.Local);
            return Ok();
        }

        #endregion
    }
}
