using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.Log;
using LQKJ.WebApi.Stub;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using Kingdee.BOS.DataEntity.Metadata.Service;
//using Microsoft.Extensions.Caching.Memory;
using System.Data;
using Kingdee.BOS.ServiceHelper;
using LQKJ.K3.PeiXunSystem.WebApi.Models;
using Newtonsoft.Json;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Collections;
using Kingdee.BOS.WebApi.ServicesStub;
using Kingdee.BOS;
using System.Drawing;
using System.IO;
using static Kingdee.BOS.App.Core.Validation.EntryEntity.CompositePKValidator.KeyHelper;

namespace LQKJ.K3.PeiXunSystem.WebApi
{
    public class WebApiService : CustomWebApiService
    {
        private readonly KDServiceContext context;
        private readonly CustomWebApiService obj = null;
        
        //private static IMemoryCache _memoryCache = null;

        public WebApiService(KDServiceContext context)
            : base(context)
        {
            this.context = context;
            obj = new CustomWebApiService(context);
            //if (_memoryCache == null)
            //{
            //    _memoryCache= new MemoryCache(new MemoryCacheOptions());
            //}
        }
        /// <summary>
        /// 查询所有培训项目
        /// </summary>
        /// <returns></returns>
        public SQLResult CourseSelect(string Phone, int? pageIndex, int pageSize,string Name)
        {
            SQLResult sqlReselt = new SQLResult();
            try
            {
                string sqlSelect = $@"/*dialect*/  select * from (
									select A.FITEMID fItemId,classId,className,classArea,planCount,
                                    subCount,startDate,endDate,FDEADLINE as overDate,case 
	                                    when FDEADLINE>getdate() and planCount>subCount then 0 --正在报名
										when FDEADLINE>getdate() and planCount=subCount then 1
										else 3
	                                    end as classType,case when fisFillInfo=1 then 'true' else 'false' end fisFillInfo ,case when fsFillRiding=1 then 'true' else 'false' end fsFillRiding
									,case when fisFillArrAngEroom=1 then 'true' else 'false' end fisFillArrAngEroom,case when fisFillCohabItant=1 then 'true' else 'false' end fisFillCohabItant,c.FNUMBER as classNumber,
									A.FNUMBER itemNumber,A.FTRAINING as require  from 
                                    T_PX_TRAININGPROINFO A --培训项目
                                    left join T_PX_TRAININGPROINFOENTRY B on A.FITEMID=B.FITEMID -- 培训项目单据体
                                    left join (select T.FCLASSID as classId,fName as className ,FPLANTY as planCount,FCONFIRMQTY as 
                                    subCount,FLOCATION as classArea,
                                    FSTARTDATE as startDate,FENDDATE  as endDate
                                    ,FNUMBER
                                    from T_PX_CLASS T left join T_PX_CLASS_L T2 on T.FCLASSID=T2.FCLASSID ) C on B.FCLASS=C.CLASSID --班级
                                    where B.FISRELEASE=1 and FDOCUMENTSTATUS='C'
									) T where T.classType!=3 and  classId not in 
                                    (select a.FCLASSID from T_PX_CLASS a left join V_PX_ClassStudents b on a.FCLASSID=b.FCLASSID where FPHONENUMBER='{Phone}') --查该学员是否有已经报名的班级";
                sqlReselt = obj.ExecutDataSet(sqlSelect);
                sqlReselt.total = ((DataSet)sqlReselt.data).Tables[0].Rows.Count;
                var dataTable = (from temp in ((DataSet)sqlReselt.data).Tables[0].AsEnumerable()
                                 select new Models.Item
                                 {
                                     classId = temp.Field<int>("classId"),
                                     fItemId = temp.Field<int>("fItemId"),
                                     endDate = temp.Field<DateTime>("endDate"),
                                     className = temp.Field<string>("className"),
                                     startDate = temp.Field<DateTime>("startDate"),
                                     subCount = temp.Field<int>("subCount"),
                                     classArea = temp.Field<string>("classArea"),
                                     classType = temp.Field<int>("classType"),
                                     planCount = temp.Field<int>("planCount"),
                                     fisFillInfo = temp.Field<string>("fisFillInfo"),
                                     fsFillRiding = temp.Field<string>("fsFillRiding"),
                                     fisFillArrAngEroom = temp.Field<string>("fisFillArrAngEroom"),
                                     fisFillCohabItant = temp.Field<string>("fisFillCohabItant"),
                                     classNumber = temp.Field<string>("classNumber"),
                                     overDate = temp.Field<DateTime>("overDate"),
                                     itemNumber = temp.Field<string>("itemNumber"),
                                     require = temp.Field<string>("require")
                                 }).Where(e=>e.className.Contains(Name)).ToList();
                var result = PaginatedList<Item>.Create(
                dataTable, pageIndex ?? 1, pageSize);//执行分页操作
                sqlReselt.data = result;
                sqlReselt.msg = "查询成功";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:CourseSelect", ex.Message, ex);
                sqlReselt.msg = "查询失败";
            }
            return sqlReselt;
        }
        /// <summary>
        /// 查询所属辅助资料信息
        /// </summary>
        /// <param name="TypeId"></param>
        /// <returns></returns>
        public SQLResult InFormAtion()
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $"/*dialect*/ exec inFormAtion";
                sqlResult = obj.ExecuteDynamicObject(sqlSelect);
                sqlResult.code = "200";
                sqlResult.msg = "查询成功";
            }
            catch (Exception ex)
            {

                Logger.Error("ActionName:InFormAtion", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "查询失败";
            }
            return sqlResult;
        }
        /// <summary>
        /// 查询已报名
        /// </summary>
        /// <param name="FID"></param>
        /// <returns></returns>
        public SQLResult CourseIn(string FSTUDENTID, int? pageIndex, int pageSize,string Name)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $@"/*dialect*/  select T3.FCLASSID as classId,T4.FNAME className,FSTARTDATE startDate,FENDDATE endDate,FLOCATION classArea
                                    ,case when FSTARTDATE>getdate() then 2  when FENDDATE<getdate() then 3
									 when FSTARTDATE<getdate() and FENDDATE>getdate() then 4 end classType
                                    from T_PX_ADDRESSBOOK T1  left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
									left join T_PX_CLASS T3 on T1.FCLASS=T3.FCLASSID left join T_PX_CLASS_L T4 on T4.FCLASSID=T3.FCLASSID
									where FSTUDENTID='{FSTUDENTID}'
                                ";
                sqlResult = obj.ExecutDataSet(sqlSelect);
                var dataTable = (from temp in ((DataSet)sqlResult.data).Tables[0].AsEnumerable()
                                 select new Models.Item
                                 {
                                     classId = temp.Field<int>("classId"),
                                     className = temp.Field<string>("className"),
                                     startDate = temp.Field<DateTime>("startDate"),
                                     endDate = temp.Field<DateTime>("endDate"),
                                     classArea = temp.Field<string>("classArea"),
                                     classType = temp.Field<int>("classType")
                                 }).Where(e=>e.className.Contains(Name)).ToList();
                var result = PaginatedList<Item>.Create(
                dataTable, pageIndex ?? 1, pageSize);
                sqlResult.msg = "查询成功!";
                sqlResult.total = ((DataSet)sqlResult.data).Tables[0].Rows.Count;
                sqlResult.data = result;
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:CourseIn", ex.Message, ex);
                sqlResult.msg = "错误原因:" + ex.Message;
                sqlResult.code = "500";
            }
            return sqlResult;
        }
        private DataTable ConvertToDataTable(DataRow[] rows)
        {
            if (rows == null || rows.Length == 0) return null;
            DataTable dtnew = rows[0].Table.Clone();  // 复制DataRow的表结构
            foreach (DataRow dr in rows)
            {
                DataRow drnew = dtnew.NewRow(); //这行是关键
                drnew.ItemArray = dr.ItemArray;//这是加入的是第一行                

                dtnew.Rows.Add(drnew);
            }
            return dtnew;
        }
        /// <summary>
        /// 查询我的课程
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public SQLResult CourseDetail(string Phone, int pageIndex, int pageSize, int type, string classId,string Name,int KqType)
        {
            SQLResult result = new SQLResult();
            try
            {
                string sqlSelect = $@"/*dialect*/ exec CourseAndTeach @Phone='{Phone}'";
                var data = (DataSet)obj.ExecutDataSet(sqlSelect).data;
                var count = (pageIndex - 1) * pageSize;//跳过
                DataTable dataTable = data.Tables[0];
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    result.code = "200";
                    result.msg = "您没有任何课程";
                    return result;
                }
                Dictionary<int, List<State>> State = new Dictionary<int, List<State>>();
                State.Clear();
                var data2 = data.Tables[3].AsEnumerable().GroupBy(e => e.Field<int>("courseId"));
                foreach (var parent in data2)
                {
                    List<State> States = new List<State>();
                    int key = 0;
                    State state = new State();
                    foreach (var child in parent)
                    {
                        var value = child[0].ToString();
                        switch (value)
                        {
                            case "QD"://签到
                            case "QDBQ"://签到补签
                            case "QDQJ"://签到请假
                                state.SingIn = value;
                                state.SingInText = child[2].ToString();
                                break;
                            case "QT"://签退
                            case "QTBQ"://签退补签
                            case "QTQJ"://签退请假
                                state.SingOut = value;
                                state.SingOutText = child[2].ToString();
                                break;
                        }
                        key = (int)child[1];
                    }//构造一个人一节课的打卡信息
                    if ((state.SingIn == "QD" && state.SingOut == "QT") || (state.SingIn == "QDBQ" && state.SingOut == "QTBQ"))
                        state.Type = "0";//正常
                    else if (state.SingIn == "QDQJ" || state.SingOut == "QTQJ")
                        state.Type = "1";//请假
                    else
                        state.Type = "2";//缺勤
                    States.Add(state);
                    State.Add(key, States);
                }
                var DataList = dataTable.AsEnumerable().Select(e => new
                {
                    classId = e.Field<int>("classId"),
                    classArea = e.Field<string>("classArea"),
                    classNumber = e.Field<string>("classNumber"),
                    courseId = e.Field<int>("courseId"),
                    courseName = e.Field<string>("courseName"),
                    startDate = e.Field<DateTime>("startDate").ToString("yyyy-MM-dd HH:mm"),
                    endDate = e.Field<DateTime>("endDate").ToString("yyyy-MM-dd HH:mm"),
                    courseType = e.Field<int>("courseType"),
                    courseNumber = e.Field<string>("courseNumber"),
                    Longitude = e.Field<string>("F_LQKJ_Longitude"),
                    Scope = e.Field<string>("F_LQKJ_Scope"),
                    className2=e.Field<string>("className2"),
                    ItemNumber=e.Field<string>("ItemNumber"),
                    isSignOut = e.Field<int>("isSignOut"),
                    FileCount = FilePath(e.Field<string>("courseNumber")).Count,
                    Teachs = data.Tables[1].AsEnumerable().Where(m => m.Field<int>("courseId") == e.Field<int>("courseId")).
                    Select(t => new
                    {
                        teachName = t.Field<string>("teachName"),
                        teachMsg = t.Field<string>("teachMsg"),
                        courseId = t.Field<int>("courseId"),
                        courseMsg = t.Field<string>("courseMsg"),
                        teachTle = t.Field<string>("teachTle"),
                        Url = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", t.Field<string>("FPHOTO"), obj.UserToken())
                    }),
                    Management = data.Tables[2].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        mgtName = t.Field<string>("FNAME"),
                        className = t.Field<string>("className"),
                        classNumber = t.Field<string>("classNumber"),
                        teachPhone = t.Field<string>("teachPhone")//新增
                    }),
                    State = State.AsEnumerable().Where(m => m.Key == e.Field<int>("courseId")).ToList(),
                    Kqtype = KqTypeStateList(State.AsEnumerable().Where(m => m.Key == e.Field<int>("courseId")).ToList()),
                    iEevaluate =data.Tables[4].AsEnumerable().Where(m=>m.Field<int>("FCOURSE")==e.Field<int>("courseId")).ToList().Count()==0?false:true
                }).Where(e=>e.courseName.Contains(Name) || e.className2.Contains(Name));
                if (classId != "")
                {
                    DataList = DataList.Where(e => e.classId == int.Parse(classId)).OrderByDescending(m=>m.startDate);
                }
                if (type != 5)
                {
                    if (type == 1)
                    {
                        var data4 = DataList.Where(e => e.courseType == type).OrderBy(m => m.startDate).AsEnumerable();
                        var data3 = data4.Skip(count).Take(pageSize).ToArray();
                        result.data = data3;
                        result.total = data4.Count();
                    }
                    else if(type == 2)
                    {
                        // var data4= DataList.Where(e => e.courseType == type).Where(s=>s.State.SelectMany(group => group.Value).Where(kv => kv.SingIn+kv.SingOut=="")))
                        var data4 = DataList.Where(e => e.courseType == type).OrderByDescending(m => m.startDate).AsEnumerable();
                        if (KqType != 0)
                        {
                            data4=data4.Where(e=>e.Kqtype== KqType).OrderByDescending(m => m.startDate).AsEnumerable();
                        }
                        var data3 = data4.Skip(count).Take(pageSize).ToArray();
                        result.data = data3;
                        result.total = data4.Count();
                    }
                    else
                    {
                        
                        var data4 = DataList.Where(e => e.courseType == type).OrderByDescending(m => m.startDate).AsEnumerable();
                        var data3 = data4.Skip(count).Take(pageSize).ToArray();
                        result.data = data3;
                        result.total = data4.Count();
                    }
                }
                else
                {
                    var data3 = DataList.OrderByDescending(m=>m.startDate).Skip(count).Take(pageSize).ToArray();
                    result.data = data3;
                    result.total = DataList.Count();
                }

                if (result.total != 0)
                {
                    result.msg = "课程信息";
                    result.code = "200";
                }
                else
                {
                    result.msg = "没有课程信息";
                    result.code = "200";
                }
                

            }
            catch (Exception ex)
            {
                result.msg = "服务器错误，请联系管理员！";
                result.code = "500";
                Logger.Error("ActionName:CourseDetail", ex.Message, ex);
            }
            return result;
        }
        /// <summary>
        /// 查询我的班级
        /// </summary>
        /// <returns></returns>
        public SQLResult ClassMessage(string Phone, int pageIndex, int pageSize, int type, string studentId,string Name)
        {
            SQLResult result = new SQLResult();
            try
            {
                string sqlSelect = $"/*dialect*/exec  ClassAndCourese @Phone='{Phone}',@StudentId={studentId}";
                var data = (DataSet)obj.ExecutDataSet(sqlSelect).data;
                var count = (pageIndex - 1) * pageSize;//跳过
                DataTable dataTable = data.Tables[0];//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    result.code = "200";
                    result.msg = "您没有任何班级";
                    return result;
                }
                var DataList = dataTable.AsEnumerable().Select(e => new
                {
                    className = e.Field<string>("className"),
                    classId = e.Field<int>("classId"),
                    classArea = e.Field<string>("classArea"),
                    startDate = e.Field<DateTime>("startDate").ToString("yyyy-MM-dd HH:mm"),
                    endDate = e.Field<DateTime>("endDate").ToString("yyyy-MM-dd HH:mm"),
                    classType = e.Field<int>("classType"),
                    classNumber = e.Field<string>("classNumber"),
                    ItemNumber=e.Field<string>("ItemNumber"),
                    Url = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FQRCODE"), obj.UserToken()),
                    courseSum = data.Tables[1]?.AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        Sum = t.Field<int>("courseSum")
                    }),
                    coursePro = data.Tables[2]?.AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        SumPro = t.Field<int>("courseSum")
                    }),
                    Management = data.Tables[3].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        teachName = t.Field<string>("teachName"),
                        teacPhone= t.Field<string>("teachPhone")
                    }),
                    iEevaluate = data.Tables[4].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).ToList().Count == 0 ? false : true
                }).Where(e=>e.className.Contains(Name)).OrderByDescending(m=>m.startDate);
                var data2 = DataList.Where(m => m.classType == type);
                result.data = data2.Skip(count).Take(pageSize).ToArray();
                result.total = data2.Count();
                result.msg = "班级信息";
                result.code = "200";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:ClassMessage", ex.Message, ex);
            }
            return result;
        }
        /// <summary>
        /// 查询我的考勤
        /// </summary>
        /// <returns></returns>
        public SQLResult ClassMessageCheckIn(string Phone, int pageIndex, int pageSize,string Name)
        {
            SQLResult result = new SQLResult();
            try
            {
                string sqlSelect = $"/*dialect*/exec  ClassAndCourese @Phone='{Phone}',@StudentId=''";
                var data = (DataSet)obj.ExecutDataSet(sqlSelect).data;
                var count = (pageIndex - 1) * pageSize;//跳过
                DataTable dataTable = data.Tables[0];//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    result.code = "200";
                    result.msg = "您没有任何班级";
                    return result;
                }
                string SelectKq = $"/*dialect*/select FCLASSID,FCOCKINTYPE,FCOURSEID from T_PX_CLOCKINRECORDS T1 left join T_PX_StudentsInfo T2 on T1.FSTUDENTID=T2.FSTUDENTID where FCLASSID in (select FCLASSID From V_PX_ClassStudents T1 left join T_PX_StudentsInfo T2 on T1.FStudentId=T2.FSTUDENTID where FMOBILE='{Phone}') and FMOBILE='{Phone}'";
                DataTable data2 = obj.ExecuteDataTable(SelectKq);
                Dictionary<int, PeopleNum> State = new Dictionary<int, PeopleNum>();//班级-课程考勤详情
                State.Clear();
                PeopleNum peopleNum = new PeopleNum();
                foreach (var row in data2.AsEnumerable().Select(e=>e.Field<Int32>("FCLASSID")).Distinct())//遍历班级
                {
                    int key = row;
                    State.TryGetValue(key, out peopleNum);
                    if (peopleNum == null)
                    {
                        peopleNum = new PeopleNum();
                    }
                    State state = new State();//创建课程打卡对象
                    foreach (var item in data2.AsEnumerable().Where(e=>e.Field<Int32>("FCLASSID") ==row).Select(e => e.Field<Int32>("FCOURSEID")).Distinct())//遍历课程
                    {
                        foreach (var item1 in data2.AsEnumerable().Where(e => e.Field<Int32>("FCOURSEID") == item))//遍历打卡信息
                        {
                            var value = item1[1].ToString();//打卡类型
                            switch (value)
                            {
                                case "QD"://签到
                                case "QDBQ"://签到补签
                                case "QDQJ"://签到请假
                                    state.SingIn = value;
                                    break;
                                case "QT"://签退
                                case "QTBQ"://签退补签
                                case "QTQJ"://签退请假
                                    state.SingOut = value;
                                    break;
                            }
                        }
                        //遍历课程结束判断考勤状态
                        if ((state.SingIn == "QD" || state.SingIn == "QDBQ")&& (state.SingOut == "QT" || state.SingOut == "QTBQ"))
                            peopleNum.normal += 1;//正常
                        else if (state.SingIn == "QDQJ" || state.SingOut == "QTQJ")
                            peopleNum.leave += 1;//请假
                        else
                            peopleNum.lack += 1;//缺勤
                        state = new State();
                    }
                    State.Add(key, peopleNum);
                }
                var DataList = dataTable.AsEnumerable().Select(e => new
                {
                    className = e.Field<string>("className"),
                    classId = e.Field<int>("classId"),
                    classArea = e.Field<string>("classArea"),
                    startDate = e.Field<DateTime>("startDate").ToString("yyyy-MM-dd HH:mm"),
                    endDate = e.Field<DateTime>("endDate").ToString("yyyy-MM-dd HH:mm"),
                    classType = e.Field<int>("classType"),
                    classNumber = e.Field<string>("classNumber"),
                    ItemNumber = e.Field<string>("ItemNumber"),
                    Url = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FQRCODE"), obj.UserToken()),
                    courseSum = data.Tables[1]?.AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        Sum = t.Field<int>("courseSum")
                    }),
                    coursePro = data.Tables[2]?.AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        SumPro = t.Field<int>("courseSum")
                    }),
                    Management = data.Tables[3].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        teachName = t.Field<string>("teachName"),
                        teacPhone = t.Field<string>("teachPhone")
                    }),
                    State= State.Where(s=>s.Key== e.Field<int>("classId")).Select(s=>s.Value).FirstOrDefault(),

                }).Where(e => e.className.Contains(Name)).OrderByDescending(m => m.startDate);
                result.data = DataList.Skip(count).Take(pageSize).ToArray();
                result.total = DataList.Count();
                result.msg = "班级信息";
                result.code = "200";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:ClassMessage", ex.Message, ex);
                result.msg = "服务端错误，请联系管理员维护";
                result.code = "500";
            }
            return result;
        }

        /// <summary>
        /// 查询个人所在班级通讯录信息
        /// </summary>
        /// <param name="classId"></param>
        /// <returns></returns>
        public SQLResult ClassBook(string classId, int pageIndex, int pageSize, string Phone,string Name,int type,string courseId)
        {
            SQLResult result = new SQLResult();
            try
            {
                string sqlSelect = "";
                var count = (pageIndex - 1) * pageSize;
                if (courseId == "") { //查看班级评价
                     if (type == 0)//已评价
                     {
                         sqlSelect = $@"/*dialect*/  select T4.FNAME as stuName,T2.FPHONENUMBER as Phone,T3.FWORKUNIT1 as stuUnit,FIMAGEFILESERVER as proPhoto,T1.FCLASS,
                                                 T3.FSTUDENTID as studentId
				        					from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
				        					left join T_PX_StudentsInfo T3 on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_StudentsInfo_L T4
				        					on T4.FSTUDENTID=T3.FSTUDENTID where T1.FCLASS={classId} and T2.FPHONENUMBER is not null and T2.FPHONENUMBER!='{Phone}'
                                         and T3.FSTUDENTID  in (   select FSTUDENTID from T_PX_EVALUATIONRECORDS where FCLASS={classId})
                                         ";//班级内码
                     }
                     else if(type == 1)//未评价
                     {
                         sqlSelect = $@"/*dialect*/  select T4.FNAME as stuName,T2.FPHONENUMBER as Phone,T3.FWORKUNIT1 as stuUnit,FIMAGEFILESERVER as proPhoto,T1.FCLASS,
                                                 T3.FSTUDENTID as studentId
				        					from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
				        					left join T_PX_StudentsInfo T3 on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_StudentsInfo_L T4
				        					on T4.FSTUDENTID=T3.FSTUDENTID where T1.FCLASS={classId} and T2.FPHONENUMBER is not null and T2.FPHONENUMBER!='{Phone}'
                                         and T3.FSTUDENTID not in (   select FSTUDENTID from T_PX_EVALUATIONRECORDS  where FCLASS={classId})
                                         ";//班级内码
                     }
                     else //全部
                     {
                         sqlSelect = $@"/*dialect*/  select T4.FNAME as stuName,T2.FPHONENUMBER as Phone,T3.FWORKUNIT1 as stuUnit,FIMAGEFILESERVER as proPhoto,T1.FCLASS,
                                                 T3.FSTUDENTID as studentId
				        					from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
				        					left join T_PX_StudentsInfo T3 on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_StudentsInfo_L T4
				        					on T4.FSTUDENTID=T3.FSTUDENTID where T1.FCLASS={classId} and T2.FPHONENUMBER is not null and T2.FPHONENUMBER!='{Phone}'";//班级内码
                     }
                }
                else
                {
                    if (type == 0)//已评价
                    {
                        sqlSelect = $@"/*dialect*/  select T4.FNAME as stuName,T2.FPHONENUMBER as Phone,T3.FWORKUNIT1 as stuUnit,FIMAGEFILESERVER as proPhoto,T1.FCLASS,
                                            T3.FSTUDENTID as studentId
									from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
									left join T_PX_StudentsInfo T3 on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_StudentsInfo_L T4
									on T4.FSTUDENTID=T3.FSTUDENTID where T1.FCLASS={classId} and T2.FPHONENUMBER is not null and T2.FPHONENUMBER!='{Phone}'
                                    and T3.FSTUDENTID  in (   select FSTUDENTID from T_PX_EVALUATIONRECORDS where FCOURSE={courseId})
                                    ";//班级内码
                    }
                    else if (type == 1)//未评价
                    {
                        sqlSelect = $@"/*dialect*/  select T4.FNAME as stuName,T2.FPHONENUMBER as Phone,T3.FWORKUNIT1 as stuUnit,FIMAGEFILESERVER as proPhoto,T1.FCLASS,
                                            T3.FSTUDENTID as studentId
									from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
									left join T_PX_StudentsInfo T3 on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_StudentsInfo_L T4
									on T4.FSTUDENTID=T3.FSTUDENTID where T1.FCLASS={classId} and T2.FPHONENUMBER is not null and T2.FPHONENUMBER!='{Phone}'
                                    and T3.FSTUDENTID not in (   select FSTUDENTID from T_PX_EVALUATIONRECORDS  where FCOURSE={courseId})
                                    ";//班级内码
                    }
                    else //全部
                    {
                        sqlSelect = $@"/*dialect*/  select T4.FNAME as stuName,T5.FSHOWHIDE, T2.FPHONENUMBER as Phone,T3.FWORKUNIT1 as stuUnit,FIMAGEFILESERVER as proPhoto,T1.FCLASS,
                                            T3.FSTUDENTID as studentId
									from T_PX_ADDRESSBOOK T1 left join T_PX_ADDRESSBOOKENTRY T2 on T1.FID=T2.FID
									left join T_PX_StudentsInfo T3 on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_StudentsInfo_L T4 
									on T4.FSTUDENTID=T3.FSTUDENTID left join T_PX_CLASS T5 on T1.FCLASS=T5.FCLASSID where T1.FCLASS={classId} and T2.FPHONENUMBER is not null and T2.FPHONENUMBER!='{Phone}'";//班级内码
                    }
                }
                result.total = obj.ExecuteDataTable(sqlSelect).Rows.Count;
                if (type == 2)
                {
                    var DataRows = obj.ExecuteDataTable(sqlSelect).AsEnumerable().
                    Where(e => e.Field<string>("Phone").Contains(Name) || e.Field<string>("stuUnit").Contains(Name) || e.Field<string>("stuName").Contains(Name)).
                    Select(e => new {
                        stuName = e.Field<string>("stuName"),
                        Phone = e.Field<string>("Phone"),
                        stuUnit = e.Field<string>("stuUnit"),
                        proPhoto = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("proPhoto"), obj.UserToken()),
                        FCLASS = e.Field<int>("FCLASS"),
                        studentId = e.Field<int>("studentId"),
                        FSHOWHIDE=e.Field<string>("FSHOWHIDE"),
                        courseId = courseId
                    }).
                    Skip(count).Take(pageSize).ToArray();
                    if (DataRows.Length == 0)//如果分页后课程为空
                    {
                        result.code = "200";
                        result.msg = "无数据";
                        return result;
                    }
                    result.data = DataRows;
                    result.code = "200";
                    result.msg = "查找班级通讯录成功";
                }
                else
                {
                    var DataRows = obj.ExecuteDataTable(sqlSelect).AsEnumerable().
                    Where(e => e.Field<string>("Phone").Contains(Name) || e.Field<string>("stuUnit").Contains(Name) || e.Field<string>("stuName").Contains(Name)).
                    Select(e => new {
                        stuName = e.Field<string>("stuName"),
                        Phone = e.Field<string>("Phone"),
                        stuUnit = e.Field<string>("stuUnit"),
                        proPhoto = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("proPhoto"), obj.UserToken()),
                        FCLASS = e.Field<int>("FCLASS"),
                        studentId = e.Field<int>("studentId"),
                        courseId = courseId
                    }).
                    Skip(count).Take(pageSize).ToArray();
                    if (DataRows.Length == 0)//如果分页后课程为空
                    {
                        result.code = "200";
                        result.msg = "无数据";
                        return result;
                    }
                    result.data = DataRows;
                    result.code = "200";
                    result.msg = "查找班级通讯录成功";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:ClassBook", ex.Message, ex);
                result.code = "500";
                result.msg = "查找班级通讯录失败:" + ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 查询评价
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="studentId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SQLResult RemarkDetail(string classId, string studentId, int pageIndex, int pageSize,string courseId)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = "";
                if (!String.IsNullOrWhiteSpace(classId))
                {
                     sqlSelect = $@"select *
									 from T_PX_EVALUATIONRECORDS where FCLASS={classId} and FSTUDENTID={studentId}";
                }
                else
                {
                    sqlSelect = $@"select *
									 from T_PX_EVALUATIONRECORDS where FCOURSE={courseId} and FSTUDENTID={studentId}";
                }
                var count = (pageIndex - 1) * pageSize;//跳过
                var data = obj.ExecuteDataTable(sqlSelect);
                var DataRows = data.AsEnumerable().Skip(count).Take(pageSize).ToArray();//分页
                DataTable dataTable = ConvertToDataTable(DataRows);//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "没有任何评价";
                    return sqlResult;
                }
                sqlResult.data = dataTable;
                sqlResult.code = "200";
                sqlResult.msg = "查询成功";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:RemarkDetail", ex.Message, ex);
            }
            return sqlResult;
        }
        /// <summary>
        /// 教师端查询我的班级
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SQLResult TeachMgt(string Phone, int pageIndex, int pageSize,string Name,int type)
        {
            SQLResult result = new SQLResult();
            try
            {
                string sqlSelect = $"exec AdminManagement @Phone='{Phone}'";
                var data = (DataSet)obj.ExecutDataSet(sqlSelect).data;
                var count = (pageIndex - 1) * pageSize;
                //result.total = obj.ExecuteDataTable(sqlSelect).Rows.Count;
                //var DataRows = obj.ExecuteDataTable(sqlSelect).AsEnumerable().Skip(count).Take(pageSize).ToArray();
                DataTable dataTable = data.Tables[0];//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    result.code = "200";
                    result.msg = "您没有班级信息";
                    return result;
                }
                var DataList = dataTable.AsEnumerable().Select(e => new
                {
                    classId = e.Field<int>("classId"),
                    startDate = e.Field<DateTime>("startDate").ToString("yyyy-MM-dd HH:mm"),
                    endDate = e.Field<DateTime>("endDate").ToString("yyyy-MM-dd HH:mm"),
                    className = e.Field<string>("className"),
                    classArea = e.Field<string>("classArea"),
                    classType = e.Field<int>("classType"),
                    Url = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FQRCODE"), obj.UserToken()),
                    Management = data.Tables[1].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        teachName = t.Field<string>("teachName"),
                        teachPhone = t.Field<string>("teachPhone")
                    }),
                    courseSum = data.Tables[2].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        Sum = t.Field<int>("courseSum")
                    }),
                    coursePro = data.Tables[3].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).
                    Select(t => new
                    {
                        SumPro = t.Field<int>("courseSum")
                    })
                    
                }).Where(e=>e.classType==type && e.className.Contains(Name)).OrderByDescending(m=>m.startDate);
                result.data = DataList.Skip(count).Take(pageSize).ToArray();
                result.code = "200";
                result.total = DataList.Count();
                result.msg = "查询成功";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:TeachMgt", ex.Message, ex);
                result.code = "500";
                result.msg = "查询成功" + ex.Message;
            }
            return result;
        }
        /// <summary>
        /// 考勤详情
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SQLResult StateList(string schema, int courseId, int pageIndex, int pageSize,int type,int KqType)

        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                //        string sqlSelect = $@"select FREASON,T4.FNUMBER as courseNum,T2.FNUMBER as studentNum,T1.FCourseId1 as courseId,FMOBILE as Phone,T3.FNAME as stuName,FCockinType as StateType,
                //T2.FSTUDENTID as studentId,T5.FNUMBER,T1.FEntryID from V_PX_CLASSCLOCKINRECORDS T1
                //left join T_PX_StudentsInfo T2 on T1.FStudentId1=T2.FSTUDENTID left join T_PX_StudentsInfo_L T3 
                //on T3.FSTUDENTID=T2.FSTUDENTID left join T_PX_COURSE T4 on T4.FCOURSEID=T1.FCourseId1 left join
                //                        T_PX_CLASS T5 on T5.FCLASSID=T1.FCLASSID 
                //where T1.FCourseId1={courseId} and T4.FDOCUMENTSTATUS='C' and T4.FFORBIDSTATUS='A' and T5.FDOCUMENTSTATUS='C' and T5.FFORBIDSTATUS='A'" ;
                string sqlSelect = $@"select FREASON,FCockinType as StateType
                                    ,t4.FSTUDENTID as studentId  from T_PX_CLASS t1
                                    left join T_PX_CLASSENTRY t2 on t1.FCLASSID=t2.FCLASSID
                                    left join T_PX_ADDRESSBOOK t3 on t3.FCLASS=t2.FCLASSID
                                    left join T_PX_ADDRESSBOOKENTRY t4 on t3.FID=t4.FID
                                    left join T_PX_CLOCKINRECORDS t5 on t5.FSTUDENTID=t4.FSTUDENTID and t2.FCOURSEID=t5.FCOURSEID
                                    left join T_PX_COURSE T6 on T2.FCOURSEID=T6.FCOURSEID left join T_PX_StudentsInfo T7 on T7.FSTUDENTID=T4.FSTUDENTID
                                    left join T_PX_StudentsInfo_L T8 on T7.FSTUDENTID=T8.FSTUDENTID
									where t2.FCOURSEID={courseId} and T8.FNAME like '%{schema}%' and t4.FSTUDENTID is not null and T1.FDOCUMENTSTATUS='C' and T1.FFORBIDSTATUS='A' and T6.FDOCUMENTSTATUS='C' and T6.FFORBIDSTATUS='A' and T5.FDOCUMENTSTATUS='C' and T5.FFORBIDSTATUS='A'";
                DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                var Data = dataTable.AsEnumerable().GroupBy(e => e.Field<int>("studentId"));
                Dictionary<int, List<State>> State = new Dictionary<int, List<State>>();
                State.Clear();
                foreach (var parent in Data)
                {
                    List<State> States = new List<State>();
                    int key = 0;
                    State state = new State();
                    foreach (var child in parent)
                    {
                        var value = child[1]?.ToString();
                        switch (value)
                        {
                            case "QD"://签到
                            case "QDBQ"://签到补签
                            case "QDQJ"://签到请假
                                state.SingIn = value;
                                state.SingInText = child[0]?.ToString();
                                break;
                            case "QT"://签退
                            case "QTBQ"://签退补签
                            case "QTQJ"://签退请假
                                state.SingOut = value;
                                state.SingOutText = child[0]?.ToString();
                                break;
                        }
                        key = (int)child[2];
                    }//构造一个人一节课的打卡信息
                    if ((state.SingIn == "QD" && state.SingOut == "QT") || (state.SingIn == "QDBQ" && state.SingOut == "QTBQ"))
                        state.Type = "0";//正常
                    else if (state.SingIn == "QDQJ" || state.SingOut == "QTQJ")
                        state.Type = "1";//请假
                    else
                        state.Type = "2";//缺勤
                    States.Add(state);
                    State.Add(key, States);
                }
                sqlSelect = $@"select T6.FNUMBER as courseNum,T7.FNUMBER as studentNum,t2.FCOURSEID as courseId,FMOBILE as Phone,T8.FNAME as stuName,T7.FIMAGEFILESERVER as ImageName
                                    ,t4.FSTUDENTID as studentId ,T1.FNUMBER from T_PX_CLASS t1
                                    left join T_PX_CLASSENTRY t2 on t1.FCLASSID=t2.FCLASSID
                                    left join T_PX_ADDRESSBOOK t3 on t3.FCLASS=t2.FCLASSID
                                    left join T_PX_ADDRESSBOOKENTRY t4 on t3.FID=t4.FID
                                    left join T_PX_CLOCKINRECORDS t5 on t5.FSTUDENTID=t4.FSTUDENTID and t2.FCOURSEID=t5.FCOURSEID
                                    left join T_PX_COURSE T6 on T2.FCOURSEID=T6.FCOURSEID left join T_PX_StudentsInfo T7 on T7.FSTUDENTID=T4.FSTUDENTID
                                    left join T_PX_StudentsInfo_L T8 on T7.FSTUDENTID=T8.FSTUDENTID
                                    where t2.FCOURSEID={courseId} and T8.FNAME like '%{schema}%' and t4.FSTUDENTID is not null and T1.FDOCUMENTSTATUS='C' and T1.FFORBIDSTATUS='A' and T6.FDOCUMENTSTATUS='C' and T6.FFORBIDSTATUS='A'
									group by T6.FNUMBER,T7.FNUMBER ,t2.FCOURSEID ,FMOBILE,T8.FNAME
                                    ,t4.FSTUDENTID  ,T1.FNUMBER,T7.FIMAGEFILESERVER";
                DataTable dataTable1 = obj.ExecuteDataTable(sqlSelect);
                var DataList = dataTable1.AsEnumerable().Select(e => new
                {
                    classNumber=e.Field<string>("FNUMBER"),
                    courseId = e.Field<int>("courseId"),
                    courseNum = e.Field<string>("courseNum"),
                    studentNum = e.Field<string>("studentNum"),
                    Phone = e.Field<string>("Phone"),
                    stuName = e.Field<string>("stuName"),
                    studentId = e.Field<int>("studentId"),
                    ImagePath = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("ImageName"), obj.UserToken()),
                    State = State.AsEnumerable().Where(m => m.Key == e.Field<int>("studentId")).ToList(),
                    KqType= KqTypeStateList(State.AsEnumerable().Where(m => m.Key == e.Field<int>("studentId")).ToList())
                });
                if (KqType != 0)
                {
                    DataList = DataList.Where(e => e.KqType == KqType);
                }
                if (DataList.Count() != 0)
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "查询成功";
                }
                else
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "没有考勤信息";
                }
                sqlResult.data = DataList;
                sqlResult.total = DataList.Count();
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:StateList", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "查询失败" + ex.Message;
            }
            return sqlResult;
        }
        /// <summary>
        /// 考勤详情考勤状态
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        private int KqTypeStateList(List<KeyValuePair<int, List<State>>> list)
        {
            if (list == null)
            {
                return 2;
            }
            var kqtypes = list.Select(state =>
            {
                string signIn = state.Value[0].SingIn == null ? "" : state.Value[0].SingIn.ToString();
                string signOut = state.Value[0].SingOut == null ? "" : state.Value[0].SingOut.ToString();
                int kqtyp = 0;
                switch (signIn.Trim() + "-" + signOut.Trim())
                {
                    case "QDBQ-QT":
                        kqtyp = 1;
                        break;
                    case "QD-QT":
                        kqtyp = 1;
                        break;
                    case "QD-QTBQ":
                        kqtyp = 1;
                        break;
                    case "QDQJ-":
                        kqtyp = 3;
                        break;
                    case "QD-QTQJ":
                        kqtyp = 3;
                        break;
                    default:
                        kqtyp = 2;
                        break;
                }
                return new
                {
                    kqtyp = kqtyp
                };
            }).ToList();
            var firstElement = kqtypes.FirstOrDefault();
            if (firstElement != null)
            {
                return firstElement.kqtyp;
            }
            else
            {
                return 2; // 或者返回适当的默认值
            }
        }
        /// <summary>
        /// 查询打卡界面
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public SQLResult Location(string Phone, int pageIndex, int pageSize, int type,string Name)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $@"select F_LQKJ_TYPE2,T1.FCLASSID as classId,T5.FNAME as courseName,T4.FCOURSEID as courseId,T1.FLOCATION as classArea,T6.FNAME as className,
								T4.F_LQKJ_Longitude as Longitude,
								F_LQKJ_Scope as Scope,
								case when T4.F_LQKJ_Longitude='' then 0 else 1 end StateType,F_LQKJ_HitArea
								from T_PX_CLASS T1 
								left join T_PX_CLASSENTRY T2 on T1.FCLASSID=T2.FCLASSID
								left join T_PX_TEACHER T3 on T1.FTEACHERID=T3.FTEACHERID left join T_PX_COURSE T4 on T4.FCOURSEID=T2.FCOURSEID
								left join T_PX_COURSE_L T5 on T5.FCOURSEID=T4.FCOURSEID left join T_PX_CLASS_L T6 on T6.FCLASSID=T1.FCLASSID
								where T1.FTEACHERID=(select FUSERID  from T_SEC_user where FPHONE='{Phone}') and T4.FCOURSEID is not null and T4.FDOCUMENTSTATUS='C' and T4.FFORBIDSTATUS='A' and T1.FDOCUMENTSTATUS='C' and T1.FFORBIDSTATUS='A'
								and T4.FENDDATE>getdate()";
                var count = (pageIndex - 1) * pageSize;
                //var DataRows = obj.ExecuteDataTable(sqlSelect).AsEnumerable().Skip(count).Take(pageSize).ToArray();
                DataTable dataTable = obj.ExecuteDataTable(sqlSelect);//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "您没有任何记录";
                    return sqlResult;
                }
                var DataList= dataTable.AsEnumerable().Select(e => new
                {
                    classId=e.Field<int>("classId"),
                    type=e.Field<string>("F_LQKJ_TYPE2"),
                    courseName = e.Field<string>("courseName"),
                    courseId = e.Field<int>("courseId"),
                    classArea = e.Field<string>("classArea"),
                    className = e.Field<string>("className"),
                    Longitude = e.Field<string>("Longitude"),
                    Scope = e.Field<string>("Scope"),
                    hitArea = e.Field<string>("F_LQKJ_HitArea"),
                    StateType = e.Field<int>("StateType")
                }).Where(e => e.StateType == type && (e.className.Contains(Name) || e.courseName.Contains(Name)));
                sqlResult.data=DataList.Skip(count).Take(pageSize).ToArray();
                sqlResult.code = "200";
                sqlResult.msg = "设置打卡";
                sqlResult.total = DataList.Count();
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:Sett", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "错误" + ex.Message;
            }
            return sqlResult;
        }
        /// <summary>
        /// 查询PDF路径
        /// </summary>
        /// <param name="courseNumber"></param>
        /// <returns></returns>
        public SQLResult FilePDF(string courseNumber)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                var fileList = obj.FilePath(courseNumber);
                sqlResult.data = fileList;
                sqlResult.code = "200";
                sqlResult.msg = "查询成功";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:FilePDF", ex.Message, ex);
            }
            return sqlResult;
        }
        /// <summary>
        /// 老师端查询我的课程
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public SQLResult TeachAndCourse(string Phone, int pageIndex, int pageSize,int type,string Name)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $"/*dialect*/exec AdminAndCourse @Phone ='{Phone}' ";
                var data = (DataSet)obj.ExecutDataSet(sqlSelect).data;
                //sqlResult.total = data.Tables[0].Rows.Count;
                var count = (pageIndex - 1) * pageSize;//跳过
                //var DataRows = data.Tables[0].AsEnumerable().Skip(count).Take(pageSize).ToArray();//分页
                //DataTable dataTable = ConvertToDataTable(DataRows);//将DataRow[]转换为DataTable
                DataTable dataTable = data.Tables[0];
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "您没有任何课程";
                    return sqlResult;
                }
                var Data = data.Tables[3].AsEnumerable().GroupBy(e => new { studentId = e.Field<int>("FSTUDENTID"), courseId = e.Field<int>("FCOURSEID") });
                //每个学生的每个课程只会有两次打卡记录
                Dictionary<int, PeopleNum> State = new Dictionary<int, PeopleNum>();
                PeopleNum peopleNum = new PeopleNum();
                State.Clear();
                foreach (var parent in Data)
                {
                    int key = 0;
                    State state = new State();
                    foreach (var child in parent)
                    {
                        var value = child[1].ToString();//打卡类型
                        switch (value)
                        {
                            case "QD"://签到
                            case "QDBQ"://签到补签
                            case "QDQJ"://签到请假
                                state.SingIn = value;
                                break;
                            case "QT"://签退
                            case "QTBQ"://签退补签
                            case "QTQJ"://签退请假
                                state.SingOut = value;
                                break;
                        }
                        key = (int)child[2];//课程Id
                    }
                    State.TryGetValue(key, out peopleNum);
                    if (peopleNum == null)
                    {
                        peopleNum = new PeopleNum();
                    }
                    if (state.SingIn == "QD" && state.SingOut == "QT")
                     peopleNum.normal = peopleNum.normal + 1; 
                    else if (state.SingIn == null )
                        peopleNum.lack = peopleNum.lack + 1;
                    else if (state.SingIn == "QDQJ" || state.SingOut == "QTQJ")
                        peopleNum.leave = peopleNum.leave + 1;
                    else if (state.SingIn == "QDBQ" || state.SingOut == "QTBQ")
                        peopleNum.repair = peopleNum.repair + 1;
                    if (State.ContainsKey(key))//如果存在这个课程Id就
                    {
                        State[key] = peopleNum;
                    }
                    else
                    {
                        State.Add(key, peopleNum);
                    }
                }
                var DataList = dataTable.AsEnumerable().Select(e => new
                {
                    className = e.Field<string>("className"),
                    classId = e.Field<int>("classId"),
                    reallyNum=e.Field<int>("FCONFIRMQTY"),
                    classArea = e.Field<string>("classArea"),
                    courseId = e.Field<int>("courseId"),
                    courseName = e.Field<string>("courseName"),
                    startDate = e.Field<DateTime>("startDate").ToString("yyyy-MM-dd HH:mm"),
                    endDate = e.Field<DateTime>("endDate").ToString("yyyy-MM-dd HH:mm"),
                    courseType = e.Field<int>("courseType"),
                    courseNumber = e.Field<string>("courseNumber"),
                    ItemNumber=e.Field<string>("ItemNumber"),
                    FileCount = FilePath(e.Field<string>("courseNumber")).Count,//新增
                    Management = data.Tables[1].AsEnumerable().Where(m => m.Field<int>("courseId") == e.Field<int>("courseId")).
                    Select(t => new
                    {
                        teachName = t.Field<string>("teachName"),
                        teachMsg = t.Field<string>("teachMsg"),
                        courseMsg = t.Field<string>("courseMsg"),
                        teachTle = t.Field<string>("teachTle"),
                        Url= string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", t.Field<string>("FPHOTO"), obj.UserToken())
                    }),
                    States = State.AsEnumerable().Where(m => m.Key == e.Field<int>("courseId")),
                    iEevaluate=data.Tables[4].AsEnumerable().Where(m=>m.Field<int>("FCOURSE")==e.Field<int>("courseId")).ToList().Count()==0?false:true
                }).Where(e=>e.className.Contains(Name)||e.courseName.Contains(Name));
                if (type == 1)
                {
                    sqlResult.data = DataList.Where(t => t.courseType == type).OrderBy(e => e.startDate).Skip(count).Take(pageSize).ToArray();
                    sqlResult.total = DataList.Where(t => t.courseType == type).Count();
                    sqlResult.code = "200";
                    sqlResult.msg = "查询成功";
                }
                else
                {
                    sqlResult.data = DataList.Where(t => t.courseType == type).OrderByDescending(e => e.startDate).Skip(count).Take(pageSize).ToArray();
                    sqlResult.total = DataList.Where(t => t.courseType == type).Count();
                    sqlResult.code = "200";
                    sqlResult.msg = "查询成功";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:TeachAndCourse", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "查询失败"+ex.Message;
            }
            return sqlResult;
        }
        /// <summary>
        /// 教师端课程安排
        /// </summary>
        /// <param name="classId"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public SQLResult TeachCoursDetail(string classId,int pageSize,int pageIndex,string Name)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $@"/*dialect*/select T1.FCLASSID as classId,FLOCATION as classArea,t6.FNAME teachName,T7.FNAME courseName,T3.FNUMBER as courseNumber,
								T3.FSTARDATE as startDate,T3.FENDDATE as endDate,case when T3.FSTARDATE<getdate() and T3.FENDDATE>getdate() then 1
								when T3.FSTARDATE>getdate() then 0 when T3.FENDDATE<getdate() then 2 end as courseType,T8.FNAME as className
								from T_PX_CLASS T1 left join T_PX_CLASSENTRY T2 on T1.FCLASSID=T2.FCLASSID
								left join T_PX_COURSE T3 on T3.FCOURSEID=T2.FCOURSEID left join T_PX_COURSE_L T7 on T7.FCOURSEID=T3.FCOURSEID
								left join LQKJ_t_Cust_Entry100009 T4 on T3.FCOURSEID=T4.FCOURSEID
								left join T_PX_TEACHER T5 on T5.FTEACHERID=T4.FLECTURERS left join T_PX_TEACHER_L T6 on T6.FTEACHERID=T5.FTEACHERID
                                left join T_PX_CLASS_L T8 on T8.FCLASSID=T1.FCLASSID
								where T1.FCLASSID='{classId}' and 
								T1.FCLASSID is not null and T3.FCOURSEID is not null
                                select T1.FCLASSID as classId,count(T2.FCOURSEID) as courseSum from T_PX_CLASS T1 left join T_PX_CLASSENTRY T2 on T1.FCLASSID=T2.FCLASSID
								group by T1.FCLASSID
								select classId,count(courseType)courseSum from (
																select T1.FCLASSID as classId,case when T3.FENDDATE<getdate() then 0 else 1 end courseType
																from T_PX_CLASS T1 left join T_PX_CLASSENTRY T2 on T1.FCLASSID=T2.FCLASSID
																left join T_PX_COURSE T3 on T3.FCOURSEID=T2.FCOURSEID
																)T where courseType=0 
																group by classId";
                var data = (DataSet)obj.ExecutDataSet(sqlSelect).data;
                var count = (pageIndex - 1) * pageSize;
                DataTable dataTable = data.Tables[0];//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "您没有课程信息";
                    return sqlResult;
                }
                var DataList = dataTable.AsEnumerable().Select(e => new
                {
                    classArea=e.Field<string>("classArea"),
                    className=e.Field<string>("className"),
                    courseName =e.Field<string>("courseName"),
                    teachName = e.Field<string>("teachName"),
                    courseNumber = e.Field<string>("courseNumber"),
                    startDate = e.Field<DateTime>("startDate"),
                    endDate = e.Field < DateTime> ("endDate"),
                    courseType=e.Field<int>("courseType"),
                    FileCount=FilePath(e.Field<string>("courseNumber")).Count,
                    courseSum = data.Tables[1].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).Select(t => new
                    {
                        Sum=t.Field<int>("courseSum")
                    }),
                    coursePro = data.Tables[2].AsEnumerable().Where(m => m.Field<int>("classId") == e.Field<int>("classId")).Select(t => new
                    {
                        SumPro=t.Field<int>("courseSum")
                    })
                }).Where(e=>e.courseName.Contains(Name)||e.className.Contains(Name));
                sqlResult.data = DataList.OrderByDescending(e=>e.startDate).Skip(count).Take(pageSize).ToArray();
                sqlResult.code = "200";
                sqlResult.msg = "查询成功";
                sqlResult.total = DataList.Count();
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:TeachCourseDetail", ex.Message, ex);
            }
            return sqlResult;
        }
        /// <summary>
        /// 查询教学地点
        /// </summary>
        /// <param name="Area"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        public SQLResult StudentArea(string Area,string Sd, int pageSize, int pageIndex)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $@"/*dialect*/select FID,FTERRITORIALITY,FTEACHINGPOINTS,FINTERPRETER,FINTRODUCE,FCONTACTS,
								FPHONE,FAMOUNT,FRESERVATION,FREMARKS,(select top(1)FONSPOT from T_PX_FieldTeachingImage where T_PX_FieldTeachingImage.FID=T1.FID and (FSHOWCHECKBOX='1')) 
								As F_LQKJ_IMAGEFILESERVER
								from T_PX_SCENETEACHING T1
								where FDOCUMENTSTATUS='C' and FFORBIDSTATUS='A'and FTEACHINGPOINTS like '%{Area}%' and FTERRITORIALITY like '%{Sd}%'";
                var count = (pageIndex - 1) * pageSize;
                sqlResult.total = obj.ExecuteDataTable(sqlSelect).Rows.Count;
                var DataRows = obj.ExecuteDataTable(sqlSelect).AsEnumerable().Skip(count).Take(pageSize).ToArray();
                DataTable dataTable = ConvertToDataTable(DataRows);//将DataRow[]转换为DataTable
                if (dataTable == null || dataTable.Rows.Count == 0)//如果分页后课程为空
                {
                    sqlResult.code = "200";
                    sqlResult.msg = "没有教学地点";
                    return sqlResult;
                }
                var datalist=dataTable.AsEnumerable().Select(e => new
                {
                    FID = e.Field<Int64>("FID"),
                    FTEACHINGPOINTS = e.Field<string>("FTEACHINGPOINTS"),
                    FTERRITORIALITY = e.Field<string>("FTERRITORIALITY"),
                    FINTERPRETER = e.Field<string>("FINTERPRETER"),
                    FCONTACTS = e.Field<string>("FCONTACTS"),
                    FAMOUNT = e.Field<Decimal>("FAMOUNT"),
                    FPHONE = e.Field<string>("FPHONE"),
                    FRESERVATION = e.Field<string>("FRESERVATION"),
                    FREMARKS = e.Field<string>("FREMARKS"),
                    FINTRODUCE = e.Field<string>("FINTRODUCE"),
                    ImagePath = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("F_LQKJ_IMAGEFILESERVER"), obj.UserToken())
                });
                sqlResult.data = datalist.ToList();
                sqlResult.code = "200";
                sqlResult.msg = "查询成功";
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:StudentArea", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = "查询失败";
            }
            return sqlResult;
        }
        /// <summary>
        /// 老师登录
        /// </summary>
        /// <param name="Phone"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public SQLResult TeachLogin(string Phone,string Password,string OpenID)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                /*select T3.FNAME,T1.FTEACHERID,FPHOTO,T1.FTYPE,T2.FNAME as username from T_PX_TEACHER T1 left join
		                                T_SEC_user T2 on T1.FKINGDEEUSERID1=T2.FUSERID
                                        left join T_PX_TEACHER_L T3 on T1.FTEACHERID=T3.FTEACHERID
		                                where FPHONENUMBER='15077060245'  and T1.FDOCUMENTSTATUS='C'*/
                string sqlSelect = $@"/*dialect*/select FUSERACCOUNT,FNAME,FPHONE,FHeadShot,FHEADIMG,FOPENID  from T_SEC_user where FPHONE='{Phone}' and FFORBIDSTATUS='A'";
                DataTable dataTable = obj.ExecuteDataTable(sqlSelect);
                if (dataTable.Rows.Count > 0)
                {
                    var context = base.KDContext;
                    var dbid = base.dbid;
                    var name = dataTable.Rows[0]["FUSERACCOUNT"].ToString();
                    AuthService authService = new AuthService(context);
                    var loginResult = authService.ValidateUser(dbid, name, Password);
                    if (loginResult.IsSuccessByAPI)
                    {
                        if (!string.IsNullOrWhiteSpace(OpenID))
                        {
                            string sqlSelect1 = $"select 1  from T_SEC_user where FOPENID='{OpenID}' and FFORBIDSTATUS='A'";
                            DataTable dataTable1 = obj.ExecuteDataTable(sqlSelect1);
                            if (dataTable1.Rows.Count < 1)
                            {
                                if (string.IsNullOrWhiteSpace(dataTable.Rows[0]["FOPENID"]?.ToString()))
                                {
                                    string upSwl = $"update T_SEC_user set FOPENID='{OpenID}' where FUSERACCOUNT='{name}'";
                                    obj.Execute(upSwl);//绑定微信成功
                                }
                            }
                            else
                            {
                                sqlResult.code = "500";
                                sqlResult.msg = "该微信已绑定其他账号！！";
                                sqlResult.data = null;
                                return sqlResult;
                            }
                        }
                        //登录成功
                        sqlResult.code = "200";
                        sqlResult.msg = "登录成功";
                        sqlResult.data = dataTable.AsEnumerable().Select(e => new
                        {                           
                            Name = e.Field<string>("FNAME"),
                            //TeachId = e.Field<int>("FPHONE"),
                            img = e.Field<Byte[]>("FHEADIMG"),
                            Image = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FHeadShot"), obj.UserToken())
                        });
                    }
                    else
                    {
                        sqlResult.msg = "账号密码错误";
                        sqlResult.code = "500";
                    }
                }
                else
                {
                    sqlResult.msg = "请联系管理员注册账号";
                    sqlResult.code = "500";
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:TeachLogin", ex.Message, ex);
                sqlResult.code = "500";
                sqlResult.msg = ex.Message;
            }
            return sqlResult;
        }

        public SQLResult TeachPJ(string courseId)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlSelect = $"select* from T_PX_EVALUATIONRECORDS where FCOURSE ={courseId} ";
                sqlResult.data = obj.ExecuteDataTable(sqlSelect);
                sqlResult.msg = "查询成功";
                sqlResult.code = "200";
            }
            catch (Exception)
            {
                throw;
            }
            return sqlResult;
        }
        /// <summary>
        /// 教师列表
        /// </summary>
        /// <param name="PageIndex">页码</param>
        /// <param name="PageSize">每页数量</param>
        /// <returns></returns>
        public SQLResult TeacList(int PageIndex,int ?PageSize,string KeyWords)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string SqlStr = $"/*dialect*/EXEC GetTeachersPaged @PageIndex = {PageIndex}, @PageSize = {PageSize},@KeyWords='{KeyWords}';";
                DataSet Dataset= (DataSet)obj.ExecutDataSet(SqlStr).data;
                if (Dataset == null || Dataset.Tables == null|| Dataset.Tables[1].Rows.Count==0)
                {
                    sqlResult.msg = "无数据";
                    sqlResult.code = "200";
                    sqlResult.data = null;
                }
                else
                {
                    DataTable Dtkc = Dataset.Tables[2];
                    sqlResult.data = Dataset.Tables[1].AsEnumerable().Select(e => new
                    {
                        FTEACHERID = e.Field<Int32>("FTEACHERID"),//ID
                        FNAME = e.Field<string>("FNAME"),//姓名
                        FTITLE = e.Field<string>("FTITLE"),//讲师职称
                        FTYPE = e.Field<string>("FTYPE"),//教师类型
                        FCANCOURSE = Dtkc.AsEnumerable().Where(s => s.Field<Int32>("FTEACHERID") == e.Field<Int32>("FTEACHERID")).FirstOrDefault()?.Field<string>("FDATAVALUE")??"",//可授课程
                        FPHONENUMBER = e.Field<string>("FPHONENUMBER"),//联系电话
                        FINTRODUCE = e.Field<string>("FINTRODUCE"),//讲师简介
                        FSALARY = e.Field<string>("FSALARY"),//课酬参考
                        FPHOTO = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FPHOTO"), obj.UserToken()),//教师照片
                        FTITLEPROVE = string.Format("FileUpLoadServices/download.aspx?fileId={0}&token={1}", e.Field<string>("FTITLEPROVE"), obj.UserToken()),//职称证明
                        FCANCOURSES= Dtkc.AsEnumerable()?.Where(s=>s.Field<Int32>("FTEACHERID") ==e.Field<Int32>("FTEACHERID")).
                        Select(t => new
                        {
                            FDATAVALUE = t.Field<string>("FDATAVALUE")
                        }),
                    });
                    sqlResult.msg = "查询成功";
                    sqlResult.code = "200";
                    sqlResult.total=int.Parse(Dataset.Tables[0].Rows[0][0].ToString());
                }
               
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:TeacList", ex.Message, ex);
                sqlResult.msg = "查询失败,程序出错";
                sqlResult.code = "500";
                sqlResult.data = null;
            }
            return sqlResult;
        }

        /// <summary>
        /// 开放提前签退
        /// </summary>
        /// <param name="FCOURSEID">课程ID</param>
        /// <returns></returns>
        public SQLResult TeacOpenQT(string FCOURSEID)
        {
            SQLResult sqlResult = new SQLResult();
            try
            {
                string sqlselect = $"/*dialect*/select FOPENUPQT,FSTARDATE,FENDDATE from T_PX_COURSE where FCOURSEID='{FCOURSEID}'";
                DataTable dt01 = obj.ExecuteDataTable(sqlselect);
                if (dt01 == null || dt01.Rows.Count < 1)
                {
                    sqlResult.msg = "开放签退失败，查不到该课程信息";
                    sqlResult.code = "500";
                }else if (dt01.Rows[0]["FOPENUPQT"].ToString()=="1")
                {
                    sqlResult.msg = "已开放签退失败，请勿重复操作";
                    sqlResult.code = "500";
                }
                else
                {
                    DateTime FSTARDATE;
                    DateTime FENDDATE;
                    if (DateTime.TryParse(dt01.Rows[0]["FSTARDATE"].ToString(),out FSTARDATE)&& DateTime.TryParse(dt01.Rows[0]["FENDDATE"].ToString(), out FENDDATE)&& FSTARDATE.AddMinutes(30)<DateTime.Now&& FENDDATE.AddMinutes(-30)>DateTime.Now)
                    {
                        obj.Execute($"/*dialect*/update T_PX_COURSE set FOPENUPQT='1' where FCOURSEID='{FCOURSEID}'");
                        sqlResult.msg = "开放签退成功";
                        sqlResult.code = "200";
                    }
                    else
                    {
                        sqlResult.msg = "开放签退失败，开发签退时间需要在上课后30分钟，下课前30分钟";
                        sqlResult.code = "500";
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error("ActionName:TeacOpenQT", ex.Message, ex);
                sqlResult.msg = "查询失败,程序出错";
                sqlResult.code = "500";
                sqlResult.data = null;
            }
            return sqlResult;
        }
    }
}