using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.EnterpriseServices.Internal;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Http;
using Dapper;
using DigitalSchoolApi.Models;
using DigitalSchoolApi.SynServiceReference;
using DigitalSchoolApi.WebReference;
using Learun.Application.Organization;
using Learun.Application.TwoDevelopment.EducationalAdministration;
using Learun.Application.TwoDevelopment.ReceiveSendFeeManagement;
using Learun.Util;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace DigitalSchoolApi.Controllers
{
    public static class YKTTrabs
    {
        private static string _coresqlConnection =
            ConfigurationManager.ConnectionStrings["CoreDBString"].ConnectionString;

        private static string _coresqlConnection2 =
            ConfigurationManager.ConnectionStrings["CoreDBString2"].ConnectionString;

        private static string _sqlConnection =
            ConfigurationManager.ConnectionStrings["ConnectionPfcMisDBString"].ConnectionString;

        private static string _sqlConnection2 =
            ConfigurationManager.ConnectionStrings["ConnectionPfcMisDBString2"].ConnectionString;

        private static string _yktConnection = ConfigurationManager.ConnectionStrings["YKTDBString"].ConnectionString;
        private static string _mjConnection = ConfigurationManager.ConnectionStrings["mjDBString"].ConnectionString;
        private static string _tsConnection = ConfigurationManager.ConnectionStrings["tsDBString"].ConnectionString;
        private static string _bachujavaConnection = ConfigurationManager.ConnectionStrings["bachuJavaDBString"].ConnectionString;
        //西昌中间库
        private static string _xzMiddleConnection = ConfigurationManager.ConnectionStrings["XCMiddleDBString"].ConnectionString;

        public static IEnumerable<TSource> DistinctBy<TSource, TKey>
            (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
        {
            HashSet<TKey> seenKeys = new HashSet<TKey>();
            foreach (TSource element in source)
            {
                if (seenKeys.Add(keySelector(element)))
                {
                    yield return element;
                }
            }
        }
        private static readonly HttpClient Client;
        static YKTTrabs()
        {
            Client = new HttpClient();
        }
        public class dept
        {
            public string deptName { get; set; }
            public string deptType { get; set; }
            public string deptCode { get; set; }
            public string upCode { get; set; }
            public int delState { get; set; }
        }

        public class user
        {
            public int sex { get; set; }
            public string phone { get; set; }
            public string name { get; set; }
            public string account { get; set; }
            public string deptCode { get; set; }
            public int delState { get; set; }
        }

        public class lesson
        {
            public string courseNature { get; set; }
            public int? credits { get; set; }
            public string deptCode { get; set; }
            public string courseCode { get; set; }
            public int? delState { get; set; }
            public string courseName { get; set; }
        }

        public class major
        {
            public decimal eduTypeCode { get; set; }
            public string deptCode { get; set; }
            public string majorCode { get; set; }
            public string majorName { get; set; }
            public string majorTeacherAmount { get; set; }
            public int? delState { get; set; }
        }

        public class classInfo

        {
            public int? graduateState { get; set; }
            public string headTeacherNum { get; set; }
            public string classCode { get; set; }
            public string className { get; set; }
            public string majorCode { get; set; }
            public int? delState { get; set; }
            public string springAutumn { get; set; }
            public string headCount { get; set; }
            public string gradeCode { get; set; }
        }

        public class studentInfo
        {
            /// <summary>
            /// 部门 经管部
            /// </summary>
            public string facultyName { get; set; }
            /// <summary>
            /// 2017级
            /// </summary>
            public string gradeName { get; set; }
            public string idCard { get; set; }
            /// <summary>
            /// 在校
            /// </summary>
            public string status { get; set; }
            /// <summary>
            /// 汉族
            /// </summary>
            public string nationName { get; set; }
            /// <summary>
            /// 家庭住址
            /// </summary>
            public string nativeplace { get; set; }
            /// <summary>
            /// 年龄16 17
            /// </summary>
            public string age { get; set; }
            /// <summary>
            /// 学号 178020242
            /// </summary>
            public string studentNumber { get; set; }
            /// <summary>
            /// 姓名
            /// </summary>
            public string name { get; set; }
            /// <summary>
            /// 班级名称 17财税02
            /// </summary>
            public string className { get; set; }
            /// <summary>
            /// 专业 金融财税
            /// </summary>
            public string majorName { get; set; }
        }

        ///// <summary>
        /////  处理结果类
        /////  </summary>
        ///// <typeparam name="T"></typeparam>
        //public class ResultDTO<T>
        //{
        //    /// <summary>
        //    ///  返回代码，100 处理成功，其它失败
        //    ///  </summary>
        //    public int code;
        //    /// <summary>
        //    ///  返 回消息
        //    ///  </summary>
        //    public string msg;
        //    /// <summary>
        //    ///  返回的结果集
        //    ///  </summary>
        //    List<T> record;

        //}
        public class PayResult
        {
            public List<PayStudent> result { get; set; }
        }

        public class PayStudent
        {
            public string xjdm { get; set; }
            public string xsxm { get; set; }
            public string createTime { get; set; }
        }


        public static void BgeinHeNanXinAn()
        {
            try
            {
                string depturl = ConfigurationManager.AppSettings["depturl"];
                string userurl = ConfigurationManager.AppSettings["userurl"];
                string lessonurl = ConfigurationManager.AppSettings["lessonurl"];
                string classurl = ConfigurationManager.AppSettings["classurl"];
                string majorurl = ConfigurationManager.AppSettings["majorurl"];
                string studenturl = ConfigurationManager.AppSettings["studenturl"];
                string GenerateTeachersRoleId = ConfigurationManager.AppSettings["GenerateTeachersRoleId"];
                string secretcode = ConfigurationManager.AppSettings["secretcode"];
                string pwdcode = ConfigurationManager.AppSettings["pwdcode"];
                IEnumerable<UserEntity> baseuserlist = null;
                HttpClient httpClient = new HttpClient();
                string deptjsonstring = httpClient.GetStringAsync(depturl).Result;
                if (!string.IsNullOrEmpty(deptjsonstring))
                {
                    var deptobj = JsonConvert.DeserializeObject<List<dept>>(deptjsonstring);
                    if (deptobj != null && deptobj.Count > 0)
                    {
                        foreach (var dep in deptobj)
                        {
                            using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                            {
                                if (conn.Query<dynamic>(
                                            "select * from LR_Base_Department where F_EnCode='" + dep.deptCode + "'")
                                        .Count() == 0)
                                {
                                    conn.Execute(
                                        "insert into LR_Base_Department(F_DepartmentId,F_ParentId,F_EnCode,F_FullName,F_DeleteMark,F_EnabledMark) " +
                                        " values(newid(),'0','" + dep.deptCode + "','" + dep.deptName + "',0,1)");
                                    conn.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条部门数据',getdate())");
                                }
                            }

                            using (IDbConnection conn = new SqlConnection(_coresqlConnection2))
                            {
                                if (conn.Query<dynamic>(
                                            "select * from LR_Base_Department where F_EnCode='" + dep.deptCode + "'")
                                        .Count() == 0)
                                {
                                    conn.Execute(
                                        "insert into LR_Base_Department(F_DepartmentId,F_ParentId,F_EnCode,F_FullName,F_DeleteMark,F_EnabledMark) " +
                                        " values(newid(),'0','" + dep.deptCode + "','" + dep.deptName + "',0,1)");
                                    conn.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条部门数据',getdate())");
                                }
                            }


                            //系
                            using (IDbConnection conn = new SqlConnection(_sqlConnection))
                            {
                                if (conn.Query<dynamic>("SELECT * FROM dbo.CdDept WHERE DeptNo ='" + dep.deptCode + "'")
                                        .Count() == 0)
                                {
                                    conn.Execute(
                                        $"INSERT dbo.CdDept ( DeptId, DeptNo, DeptName) VALUES (   NEWID(), '{dep.deptCode}', '{dep.deptName}')");
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条系部数据',getdate())");
                                    }

                                }
                            }

                            using (IDbConnection conn = new SqlConnection(_sqlConnection2))
                            {
                                if (conn.Query<dynamic>("SELECT * FROM dbo.CdDept WHERE DeptNo ='" + dep.deptCode + "'")
                                        .Count() == 0)
                                {
                                    conn.Execute(
                                        $"INSERT dbo.CdDept ( DeptId, DeptNo, DeptName) VALUES (   NEWID(), '{dep.deptCode}', '{dep.deptName}')");
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection2))
                                    {
                                        conncore.Execute(
                                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条系部数据',getdate())");
                                    }

                                }
                            }
                        }
                    }
                }

                string userjsonstring = httpClient.GetStringAsync(userurl).Result;
                //人员
                if (!string.IsNullOrEmpty(userjsonstring))
                {
                    var userobj = JsonConvert.DeserializeObject<List<user>>(userjsonstring);
                    if (userobj != null && userobj.Count > 0)
                    {
                        foreach (var use in userobj)
                        {
                            using (IDbConnection conn = new SqlConnection(_sqlConnection))
                            {
                                if (conn.Query<dynamic>("select * from EmpInfo where EmpNo='" + use.account + "'")
                                        .Count() == 0)
                                {
                                    conn.Execute("insert into EmpInfo(EmpId,EmpNo,EmpName,GenderNo) " +
                                                 "values(newid(),'" + use.account + "','" + use.name + "'," + (use.sex == 1 ? 1 : 0) + ")");
                                }
                            }

                            using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                            {
                                string userid = Guid.NewGuid().ToString();
                                if (conn.Query<dynamic>("select * from LR_Base_User where F_Account='" + use.account +
                                                        "'")
                                        .Count() == 0)
                                {
                                    conn.Execute(
                                        "insert into LR_Base_User(F_UserId,F_EnCode,F_Account,F_RealName,F_Password,F_Secretkey,F_Gender,F_DeleteMark,F_EnabledMark,F_Description) " +
                                        " values('" + userid + "','" + use.account + "','" + use.account + "','" +
                                        use.name +
                                        "','" + pwdcode + "','" + secretcode + "','" + (use.sex == 1 ? 1 : 0) +
                                        "',0,1,'教师')");
                                    conn.Execute(
                                        "insert into LR_Base_UserRelation(F_UserRelationId,F_UserId,F_Category,F_ObjectId) values(newid(),'" +
                                        userid + "',1,'" + GenerateTeachersRoleId + "')");
                                    conn.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条用户数据',getdate())");
                                }
                            }

                            using (IDbConnection conn = new SqlConnection(_sqlConnection2))
                            {
                                if (conn.Query<dynamic>("select * from EmpInfo where EmpNo='" + use.account + "'")
                                        .Count() == 0)
                                {
                                    conn.Execute("insert into EmpInfo(EmpId,EmpNo,EmpName,GenderNo) " +
                                                 "values(newid(),'" + use.account + "','" + use.name + "'," + (use.sex == 1 ? 1 : 0) + ")");
                                }
                            }

                            using (IDbConnection conn = new SqlConnection(_coresqlConnection2))
                            {
                                string userid = Guid.NewGuid().ToString();
                                if (conn.Query<dynamic>("select * from LR_Base_User where F_Account='" + use.account +
                                                        "'")
                                        .Count() == 0)
                                {
                                    conn.Execute(
                                        "insert into LR_Base_User(F_UserId,F_EnCode,F_Account,F_RealName,F_Password,F_Secretkey,F_Gender,F_DeleteMark,F_EnabledMark,F_Description) " +
                                        " values('" + userid + "','" + use.account + "','" + use.account + "','" +
                                        use.name +
                                        "','" + pwdcode + "','" + secretcode + "','" + (use.sex == 1 ? 1 : 0) +
                                        "',0,1,'教师')");
                                    conn.Execute(
                                        "insert into LR_Base_UserRelation(F_UserRelationId,F_UserId,F_Category,F_ObjectId) values(newid(),'" +
                                        userid + "',1,'" + GenerateTeachersRoleId + "')");
                                    conn.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条用户数据',getdate())");
                                }
                            }
                        }
                    }
                }

                //课程
                string lessonJsonString = httpClient.GetStringAsync(lessonurl).Result;
                var lessonJsonObj = JsonConvert.DeserializeObject<List<lesson>>(lessonJsonString);
                if (lessonJsonObj != null && lessonJsonObj.Count > 0)
                {
                    foreach (var item in lessonJsonObj)
                    {
                        using (IDbConnection conn = new SqlConnection(_sqlConnection))
                        {
                            if (conn.Query<dynamic>(
                                        $"SELECT * FROM dbo.LessonInfo WHERE LessonNo='{item.courseCode}'")
                                    .Count() == 0)
                            {
                                conn.Execute(
                                    $"INSERT dbo.LessonInfo ( LessonId, LessonNo, LessonName, TeachDeptNo,LessonSortNo ) VALUES ( NEWID(),'{item.courseCode}','{item.courseName}','{item.deptCode}','1')"
                                );
                            }
                        }

                        using (IDbConnection conn = new SqlConnection(_sqlConnection2))
                        {
                            if (conn.Query<dynamic>(
                                        $"SELECT * FROM dbo.LessonInfo WHERE LessonNo='{item.courseCode}'")
                                    .Count() == 0)
                            {
                                conn.Execute(
                                    $"INSERT dbo.LessonInfo ( LessonId, LessonNo, LessonName, TeachDeptNo,LessonSortNo ) VALUES ( NEWID(),'{item.courseCode}','{item.courseName}','{item.deptCode}','1')"
                                );
                            }
                        }

                    }

                }



                //专业
                string majorJsonString = httpClient.GetStringAsync(majorurl).Result;
                var majorJsonObj = JsonConvert.DeserializeObject<List<major>>(majorJsonString);
                if (majorJsonObj != null && majorJsonObj.Count > 0)
                {
                    foreach (var item in majorJsonObj)
                    {
                        using (IDbConnection conn = new SqlConnection(_sqlConnection))
                        {
                            if (conn.Query<dynamic>(
                                        $"SELECT * FROM dbo.CdMajor WHERE MajorNo='{item.majorCode}'")
                                    .Count() == 0)
                            {
                                conn.Execute(
                                    $"INSERT dbo.CdMajor ( ID, MajorNo, MajorName, LengthOfSchooling, DeptNo,CheckMark ) VALUES (NEWID(), '{item.majorCode}', '{item.majorName}', {item.eduTypeCode}, '{item.deptCode}',1 )"
                                );
                            }
                        }

                        using (IDbConnection conn = new SqlConnection(_sqlConnection2))
                        {
                            if (conn.Query<dynamic>(
                                        $"SELECT * FROM dbo.CdMajor WHERE MajorNo='{item.majorCode}'")
                                    .Count() == 0)
                            {
                                conn.Execute(
                                    $"INSERT dbo.CdMajor ( ID, MajorNo, MajorName, LengthOfSchooling, DeptNo,CheckMark ) VALUES (NEWID(), '{item.majorCode}', '{item.majorName}', {item.eduTypeCode}, '{item.deptCode}',1 )"
                                );
                            }
                        }

                    }

                }




                //班级
                string classJsonString = httpClient.GetStringAsync(classurl).Result;
                var classJsonObj = JsonConvert.DeserializeObject<List<classInfo>>(classJsonString);
                if (classJsonObj != null && classJsonObj.Count > 0)
                {
                    foreach (var item in classJsonObj)
                    {
                        using (IDbConnection conn = new SqlConnection(_sqlConnection))
                        {
                            if (conn.Query<dynamic>(
                                        $"SELECT * FROM dbo.ClassInfo WHERE ClassNo='{item.classCode}'")
                                    .Count() == 0)
                            {
                                conn.Execute(
                                    $"INSERT dbo.ClassInfo ( ClassId, ClassNo, ClassName, MajorNo, Grade, ClassDiredctorNo,CheckMark) VALUES (NEWID(), '{item.classCode}', '{item.className}', '{item.majorCode}', '{item.gradeCode}', '{item.headTeacherNum}',1 )"
                                );

                            }
                        }

                        using (IDbConnection conn = new SqlConnection(_sqlConnection2))
                        {
                            if (conn.Query<dynamic>(
                                        $"SELECT * FROM dbo.ClassInfo WHERE ClassNo='{item.classCode}'")
                                    .Count() == 0)
                            {
                                conn.Execute(
                                    $"INSERT dbo.ClassInfo ( ClassId, ClassNo, ClassName, MajorNo, Grade, ClassDiredctorNo,CheckMark) VALUES (NEWID(), '{item.classCode}', '{item.className}', '{item.majorCode}', '{item.gradeCode}', '{item.headTeacherNum}',1 )"
                                );

                            }
                        }

                    }

                }

                bool hasdata = true;
                int pagenum = 1;
                while (hasdata)
                {
                    //学生数据
                    string studentJsonString = httpClient.GetStringAsync(studenturl + "&currentPage=" + pagenum.ToString()).Result;
                    var studentJsonObj = JsonConvert.DeserializeObject<List<studentInfo>>(studentJsonString);
                    if (studentJsonObj != null && studentJsonObj.Count > 0)
                    {
                        pagenum++;
                        foreach (var item in studentJsonObj)
                        {
                            using (IDbConnection conn = new SqlConnection(_sqlConnection))
                            {
                                if (conn.Query<dynamic>(
                                            $"SELECT * FROM dbo.StuInfoBasic WHERE StuNo='{item.studentNumber}'")
                                        .Count() == 0)
                                {
                                    try
                                    {
                                        conn.Execute(
                                            $"INSERT dbo.StuInfoBasic ( StuId, StuNo, StuName,DeptNo, MajorNo, ClassNo,Grade, IdentityCardNo,NationalityNo,MailAddress,CheckMark) " +
                                            $"VALUES (NEWID(), '{item.studentNumber}', '{item.name}', (select top 1 DeptNo from CdDept where DeptName='{item.facultyName}'), " +
                                            $"(select top 1 MajorNo from CdMajor where MajorName='{item.majorName}'), (select top 1 ClassNo from ClassInfo where ClassName='{item.className}')," +
                                            $"'{item.gradeName?.Replace("级", "")?.Substring(2)}','{item.idCard}',(select top 1 NationalityNo from BCdNationality where Nationality='{item.nationName}'),'{item.nativeplace}','1')"
                                        );
                                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                        {
                                            conncore.Execute(
                                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条学生学籍数据，总计：" + studentJsonObj.Count + "',getdate())");
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                        {
                                            conncore.Execute(
                                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'河南新安获取数据报错','" +
                                                e.Message + "',getdate())");
                                        }
                                    }

                                }
                            }

                            using (IDbConnection conn = new SqlConnection(_sqlConnection2))
                            {
                                if (conn.Query<dynamic>(
                                            $"SELECT * FROM dbo.StuInfoBasic WHERE StuNo='{item.studentNumber}'")
                                        .Count() == 0)
                                {
                                    try
                                    {
                                        conn.Execute(
                                            $"INSERT dbo.StuInfoBasic ( StuId, StuNo, StuName,DeptNo, MajorNo, ClassNo,Grade, IdentityCardNo,NationalityNo,MailAddress,CheckMark) " +
                                            $"VALUES (NEWID(), '{item.studentNumber}', '{item.name}', (select top 1 DeptNo from CdDept where DeptName='{item.facultyName}'), " +
                                            $"(select top 1 MajorNo from CdMajor where MajorName='{item.majorName}'), (select top 1 ClassNo from ClassInfo where ClassName='{item.className}')," +
                                            $"'{item.gradeName?.Replace("级", "")?.Substring(2)}','{item.idCard}',(select top 1 NationalityNo from BCdNationality where Nationality='{item.nationName}'),'{item.nativeplace}','1')"
                                        );
                                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection2))
                                        {
                                            conncore.Execute(
                                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'定时同步操作','插入了一条学生学籍数据，总计：" + studentJsonObj.Count + "',getdate())");
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection2))
                                        {
                                            conncore.Execute(
                                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'河南新安获取学生数据报错','" +
                                                e.Message + "',getdate())");
                                        }
                                    }

                                }
                            }

                        }
                    }
                    else
                    {
                        hasdata = false;
                        pagenum = 1;
                    }
                }
            }
            catch (Exception e)
            {
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),888,'河南新安获取数据报错','" +
                        e.Message + "',getdate())");
                }
            }
        }

        /// <summary>
        /// 西昌新生缴费状态查询
        /// </summary>
        public static void QueryPayData()
        {
            string param = "beginDate=" + DateTime.Now.ToString("yyyy-MM-dd") + "&endDate=" + DateTime.Now.ToString("yyyy-MM-dd");
            byte[] byteData = Encoding.ASCII.GetBytes(param);
            string strURL = "http://onlinepay.xcmzyz.com:58081/xcm/already";
            HttpWebRequest request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            request.ContentType = "application/x-www-form-urlencoded";

            Stream stream = null;
            try
            {
                stream = request.GetRequestStream();
                stream.Flush();
                stream.Write(byteData, 0, byteData.Length);
                stream.Close();
            }
            catch (Exception)
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'缴费状态更新','连接服务器失败',getdate())");
                }
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                    stream.Dispose();
                }
            }

            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
                StreamReader streamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                string responseText = streamReader.ReadToEnd();
                streamReader.Close();
                PayResult paystudentsList = JsonConvert.DeserializeObject<PayResult>(responseText);
                if (paystudentsList != null && paystudentsList.result.Count > 0)
                {
                    foreach (var studentitem in paystudentsList.result.DistinctBy(m => m.xjdm))
                    {
                        using (IDbConnection connmis = new SqlConnection(_sqlConnection))
                        {
                            DateTime dtout = new DateTime();
                            connmis.Execute("update StuInfoFresh set PayFeeStatus=1,PayFeeDate='" + (DateTime.TryParse(studentitem.createTime, out dtout) ? studentitem.createTime : DateTime.Now.ToString()) + "' where StuNo='" + studentitem.xjdm + "' and (PayFeeStatus=0 or PayFeeStatus is null)");
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'缴费状态更新','返回数据错误" +
                        ex.Message + "',getdate())");
                }
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                    response.Dispose();
                }
            }
        }
        /// <summary>
        /// 批量开具发票
        /// </summary>
        public static void BatchInvoiceMethod()
        {
            try
            {

                Encoding encoding = Encoding.UTF8;
                string batchInvoiceUrl = "http://192.168.53.135:5000/colleges-proxy/api/college/batchInvoiceEBill";
                HttpWebRequest biRequest = (System.Net.HttpWebRequest)WebRequest.Create(batchInvoiceUrl);
                biRequest.Method = "POST";
                biRequest.ContentType = "application/json";

                Random ran = new Random();
                BatchInvoiceParam biParam = new BatchInvoiceParam();
                var key = "05a754b0b1897aa8ac07c3d951";
                var appid = "XCMZYESFGDZKXX0071670";
                biParam.busType = appid;
                biParam.batchNo = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
                biParam.date = DateTime.Now.ToString("yyyy-MM-dd");

                List<eBillListClass> eBillList = new List<eBillListClass>();
                eBillListClass eBillListitem = new eBillListClass();
                eBillListitem.busNo = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
                eBillListitem.ivcDate = DateTime.Now.ToString("yyyy-MM-dd");
                eBillListitem.placeCode = "004";
                eBillListitem.billCode = "4004";
                eBillListitem.channel = "23";
                eBillListitem.payerType = "1";
                eBillListitem.recer = "财务部刘亦菲";
                eBillListitem.stuName = "曾巧玲";
                eBillListitem.@operator = "曾巧玲";
                eBillListitem.totalAmt = 688.00;

                List<itemDetailClass> itemdetailList = new List<itemDetailClass>();
                itemDetailClass itemdetail = new itemDetailClass();
                itemdetail.itemCode = "0301002";
                itemdetail.itemName = "代收伙食费";
                itemdetail.count = 1;
                itemdetail.standard = 600;
                itemdetail.amt = 600.00;
                itemdetailList.Add(itemdetail);
                itemDetailClass itemdetail1 = new itemDetailClass();
                itemdetail1.itemCode = "0301003";
                itemdetail1.itemName = "代收水电气费";
                itemdetail1.count = 1;
                itemdetail1.standard = 88;
                itemdetail1.amt = 88.00;
                itemdetailList.Add(itemdetail1);

                eBillListitem.itemDetail = itemdetailList;
                eBillList.Add(eBillListitem);
                biParam.eBillList = eBillList;

                biParam.totalCount = eBillList.Count();

                var data = Convert.ToBase64String(encoding.GetBytes(JsonConvert.SerializeObject(biParam)));
                var noise = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
                var biparams = "{\"appid\":" + appid + ",\"data\":" + data + ",\"noise\":" + noise + "}";
                string A = "appid=" + appid + "&data=" + data + "&noise=" + noise;
                string SignTemp = A + "&key=" + key + "&version=1.0";
                var sign = Md5Helper.Hash(SignTemp).ToUpper();
                biparams = "{\"appid\":\"" + appid + "\",\"data\":\"" + data + "\",\"noise\":\"" + noise + "\",\"version\":\"1.0\",\"sign\":\"" + sign + "\"}";

                //var aa = "{\"busType\":\"XCMZYESFGDZKXX0071670\"}";
                //var bb = Convert.ToBase64String(encoding.GetBytes(aa));
                //string A1 = "appid=" + appid + "&data=" + bb + "&noise=" + noise;
                //string SignTemp1 = A1 + "&key=" + key + "&version=1.0";
                //var sign1 = Md5Helper.Hash(SignTemp1.ToUpper());
                //var str = "{\"appid\":\"" + appid + "\",\"data\":" + aa + ",\"noise\":\"" + noise + "\",\"version\":\"1.0\"" +
                //           ",\"sign\":\"" + sign1 + "\"}";

                byte[] buffer = encoding.GetBytes(biparams);
                biRequest.ContentLength = buffer.Length;
                biRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse biresponse = (HttpWebResponse)biRequest.GetResponse();
                using (StreamReader reader = new StreamReader(biresponse.GetResponseStream(), Encoding.UTF8))
                {
                    dynamic res = JsonConvert.DeserializeObject(reader.ReadToEnd());
                    File.AppendAllText("d:\\test.txt", "返回结果：" + res);
                    File.AppendAllText("d:\\test.txt", "返回result：" + res.result);
                    File.AppendAllText("d:\\test.txt", "返回message：" + res.message);
                }
            }
            catch (Exception ex)
            {
                File.AppendAllText("d:\\test.txt", "出现异常：" + ex.Message);
            }
        }

        /// <summary>
        /// 单张票据开具接口
        /// </summary>
        public static void InvoiceEBillMethod(string OrderId, bool IsNewOrOld)
        {
            try
            {
                using (IDbConnection conn = new SqlConnection(_sqlConnection))
                {
                    StuEnrollFeeOrderEntity orderEntity = conn.QuerySingle<StuEnrollFeeOrderEntity>("select * from StuEnrollFeeOrder where orderid='" + OrderId + "'");

                    if (orderEntity.Status == 1 || orderEntity.Status == 999)
                    {
                        List<StuEnrollFeeOrderDetailEntity> stuEnrollFeeOrderDetailList =
                            conn.Query<StuEnrollFeeOrderDetailEntity>(@"select a.*, b.InvoiceTypeCode from StuEnrollFeeOrderDetail a
                         join StuEnrollInvoiceTypeCode b on a.chargeItemId = b.ProjectCode
                         where a.OrderId = '" + orderEntity.Id + "'").ToList();

                        var groupDetail = stuEnrollFeeOrderDetailList.GroupBy(x => x.InvoiceTypeCode);
                        foreach (IGrouping<string, StuEnrollFeeOrderDetailEntity> item in groupDetail)
                        {
                            try
                            {
                                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                {
                                    conncore.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'typecode','开票typecode:" + item.Key + "',getdate())");
                                }
                                InvoiceEBillByType(conn, OrderId, IsNewOrOld, orderEntity, item.Key, item);
                            }
                            catch (Exception ex)
                            {
                                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                {
                                    conncore.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','开票异常:" + ex.Message + "',getdate())");
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','开票异常:" + ex.Message + "',getdate())");
                }
            }
        }

        /// <summary>
        /// 单张票据开具接口
        /// </summary>
        public static void InvoiceEBillMethodTwo(FinaChargeStuOrderEntity orderEntity)
        {
            try
            {
                using (IDbConnection conn = new SqlConnection(_sqlConnection))
                {
                    List<FinaChargeStuYearItemEntity> stuEnrollFeeOrderDetailList =
                        conn.Query<FinaChargeStuYearItemEntity>(@"select a.*, b.InvoiceTypeCode from FinaChargeStuYearItem a
                         join StuEnrollInvoiceTypeCode b on a.chargeItemcode = b.ProjectCode
                         where a.FSYId = '" + orderEntity.FSYId + "'").ToList();

                    var groupDetail = stuEnrollFeeOrderDetailList.GroupBy(x => x.InvoiceTypeCode);
                    foreach (IGrouping<string, FinaChargeStuYearItemEntity> item in groupDetail)
                    {
                        try
                        {
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'typecode','FCSOId:" + orderEntity.Id + " 开票typecode:" + item.Key + "',getdate())");
                            }
                            InvoiceEBillByTypeTwo(conn, orderEntity, item.Key, item);
                        }
                        catch (Exception ex)
                        {
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 开票异常:" + ex.Message + "',getdate())");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 开票准备报错:" + ex.Message + "',getdate())");
                }
            }
        }

        private static void InvoiceEBillByType(IDbConnection conn, string OrderId, bool IsNewOrOld, StuEnrollFeeOrderEntity orderEntity, string billCode, IGrouping<string, StuEnrollFeeOrderDetailEntity> stuEnrollFeeOrderDetailList)
        {
            Encoding encoding = Encoding.UTF8;
            string StuName = conn.QuerySingle("select StuName from Stuinfobasic where stuno='" + orderEntity.StuNo + "'").StuName;

            Random ran = new Random();
            InvoiceEBillParam biParam = new InvoiceEBillParam();
            var key = "6b50096e01a3af32b62c1d3ab0";
            var appid = "XCMZYESFGDZKXX8371735";
            biParam.busType = appid;
            biParam.busNo = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
            biParam.ivcDate = DateTime.Now.ToString("yyyy-MM-dd");
            biParam.placeCode = "004";
            biParam.billCode = billCode;//"4004";
            biParam.channel = "28";
            if (orderEntity.PayMode == "BHK" || orderEntity.PayMode == "THK")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "28";
            }
            if (orderEntity.PayMode == "CFT")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "23";
            }
            if (orderEntity.PayMode == "ZFB")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "24";
            }
            if (orderEntity.PayMode == "ExcelOffLine")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "26";
            }
            biParam.payerType = "1";
            biParam.recer = "林智慧";
            biParam.stuName = StuName;
            //biParam.stuNo = orderEntity.StuNo;
            biParam.memo = "缴费年度:" + orderEntity.YearNo + ",学号:" + orderEntity.StuNo;
            biParam.@operator = "林智慧";
            biParam.reViewer = "陈劲华";
            biParam.totalAmt = Convert.ToDouble(stuEnrollFeeOrderDetailList.Sum(x => x.YJAmount));// Convert.ToDouble(orderEntity.YJAmount);
            biParam.noticeMode = "0";
            List<InvoiceEBillItem> itemdetailList = new List<InvoiceEBillItem>();
            foreach (var itemEntity in stuEnrollFeeOrderDetailList)
            {
                InvoiceEBillItem itemdetail = new InvoiceEBillItem();
                itemdetail.itemCode = itemEntity.ChargeItemID;
                itemdetail.itemName = itemEntity.ChargeItemName;
                itemdetail.count = 1;
                itemdetail.standard = Convert.ToDouble(itemEntity.YJAmount);
                itemdetail.amt = Convert.ToDouble(itemEntity.YJAmount);
                itemdetailList.Add(itemdetail);
            }
            biParam.itemDetail = itemdetailList;
            //JsonConvert.SerializeObject(biParam)
            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
            {
                conncore.Execute(
                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','发送给开票系统原始数据:" + JsonConvert.SerializeObject(biParam) + "',getdate())");
            }
            var data = Convert.ToBase64String(encoding.GetBytes(JsonConvert.SerializeObject(biParam)));
            var noise = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
            var biparams = "{\"appid\":" + appid + ",\"data\":" + data + ",\"noise\":" + noise + "}";
            string A = "appid=" + appid + "&data=" + data + "&noise=" + noise;
            string SignTemp = A + "&key=" + key + "&version=1.0";
            var sign = Md5Helper.Hash(SignTemp).ToUpper();
            biparams = "{\"appid\":\"" + appid + "\",\"data\":\"" + data + "\",\"noise\":\"" + noise + "\",\"version\":\"1.0\",\"sign\":\"" + sign + "\"}";

            byte[] buffer = encoding.GetBytes(biparams);
            string batchInvoiceUrl = ConfigurationManager.AppSettings["Invoiceurl"];
            try
            {
                HttpWebRequest biRequest = (HttpWebRequest)WebRequest.Create(batchInvoiceUrl);
                biRequest.Method = "POST";
                biRequest.ContentType = "application/json";
                biRequest.ContentLength = buffer.Length;
                biRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse biresponse = (HttpWebResponse)biRequest.GetResponse();
                using (StreamReader reader = new StreamReader(biresponse.GetResponseStream(), Encoding.UTF8))
                {
                    dynamic res = JsonConvert.DeserializeObject(reader.ReadToEnd());
                    string datain = res.data.ToString();
                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                    {
                        conncore.Execute(
                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','开票系统返回:" + datain + "',getdate())");
                    }
                    string returnresult = encoding.GetString(Convert.FromBase64String(datain));
                    if (returnresult != "")
                    {
                        dynamic resultobj = JsonConvert.DeserializeObject(returnresult);
                        string message = resultobj.message;
                        string messagedecode = encoding.GetString(Convert.FromBase64String(message));

                        if (resultobj.result == "S0000")
                        {
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','开票系统成功返回:" + messagedecode + "',getdate())");
                            }
                            dynamic billInfo = JsonConvert.DeserializeObject(messagedecode);
                            string eBillCode = billInfo.eBillCode;
                            string eBillNo = billInfo.eBillNo;
                            string checkCode = billInfo.checkCode;
                            //记录票号
                            var recordId = Guid.NewGuid();
                            conn.Execute($"insert into StuEnrollInvoiceRecord(Id,YearNo,StuNo,billNo,random,billStatus) values('{recordId}','{orderEntity.YearNo}','{orderEntity.StuNo}','{eBillNo}','{checkCode}','1')");
                            //conn.Execute("update StuEnrollFeeOrder set billBatchCode='" + eBillCode + "',billNo='" + eBillNo + "',random='" + checkCode + "',billStatus=1 where orderid='" + OrderId + "'");
                            if (IsNewOrOld)
                            {
                                //记录开票状态
                                conn.Execute("update StuInfoFresh set IsInvoice=1 where stuno='" + orderEntity.StuNo + "'");
                            }
                            else
                            {
                                conn.Execute("update StuInfoBasic_PayFee set InvoiceStatus=1 where stuno='" + orderEntity.StuNo + "' and payyear='" + orderEntity.YearNo + "'");
                            }
                            //查询票据url
                            var invoiceobj = new { billBatchCode = eBillCode, billNo = eBillNo, random = checkCode, channelMode = "1" };
                            var datainvoice = Convert.ToBase64String(encoding.GetBytes(JsonConvert.SerializeObject(invoiceobj)));
                            var noiseinvoice = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
                            var paramsinvoice = "{\"appid\":" + appid + ",\"data\":" + datainvoice + ",\"noise\":" + noiseinvoice + "}";
                            string Ainvoice = "appid=" + appid + "&data=" + datainvoice + "&noise=" + noiseinvoice;
                            string SignTempinvoice = Ainvoice + "&key=" + key + "&version=1.0";
                            var signinvoice = Md5Helper.Hash(SignTempinvoice).ToUpper();
                            paramsinvoice = "{\"appid\":\"" + appid + "\",\"data\":\"" + datainvoice + "\",\"noise\":\"" + noiseinvoice + "\",\"version\":\"1.0\",\"sign\":\"" + signinvoice + "\"}";

                            byte[] bufferinvoice = encoding.GetBytes(paramsinvoice);
                            string getEBillPicUrl = ConfigurationManager.AppSettings["EBillPicUrl"];
                            HttpWebRequest invoiceRequest = (HttpWebRequest)WebRequest.Create(getEBillPicUrl);
                            invoiceRequest.Method = "POST";
                            invoiceRequest.ContentType = "application/json";
                            invoiceRequest.ContentLength = bufferinvoice.Length;
                            invoiceRequest.GetRequestStream().Write(bufferinvoice, 0, bufferinvoice.Length);
                            HttpWebResponse invoiceresponse = (HttpWebResponse)invoiceRequest.GetResponse();
                            using (StreamReader readerinvoice = new StreamReader(invoiceresponse.GetResponseStream(), Encoding.UTF8))
                            {
                                dynamic resinvoice = JsonConvert.DeserializeObject(readerinvoice.ReadToEnd());
                                datainvoice = resinvoice.data.ToString();
                                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                {
                                    conncore.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','查询开票url返回:" + datainvoice + "',getdate())");
                                }
                                string returnresultinvoice = encoding.GetString(Convert.FromBase64String(datainvoice));
                                resultobj = JsonConvert.DeserializeObject(returnresultinvoice);
                                message = resultobj.message;
                                messagedecode = encoding.GetString(Convert.FromBase64String(message));
                                if (resultobj.result == "S0000")
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','查询开票url成功返回:" + messagedecode + "',getdate())");
                                    }
                                    dynamic InvoiceUrlInfo = JsonConvert.DeserializeObject(messagedecode);
                                    string pictureUrl = InvoiceUrlInfo.pictureUrl;
                                    //pictureUrl = pictureUrl.Replace("[ip]:[port]", ConfigurationManager.AppSettings["InvoiceWebUrl"]);
                                    //记录发票url
                                    //conn.Execute("update StuEnrollFeeOrder set billUrl='" + pictureUrl + "' where orderid='" + OrderId + "'");
                                    conn.Execute("update StuEnrollInvoiceRecord set billUrl='" + pictureUrl + "' where Id='" + recordId + "'");
                                }
                                else
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','查询开票url错误:" + messagedecode + "',getdate())");
                                    }
                                }
                            }
                        }
                        else
                        {

                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','开票系统错误:" + messagedecode + "',getdate())");
                            }
                        }
                    }

                }
            }
            catch (Exception e)
            {
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','开票系统报错:" + e.Message + "',getdate())");
                }
            }
        }

        private static void InvoiceEBillByTypeTwo(IDbConnection conn, FinaChargeStuOrderEntity orderEntity, string billCode, IGrouping<string, FinaChargeStuYearItemEntity> stuEnrollFeeOrderDetailList)
        {
            Encoding encoding = Encoding.UTF8;
            string StuName = conn.QuerySingle("select StuName from FinaChargeStudent where stuno='" + orderEntity.StuNo + "'").StuName;

            Random ran = new Random();
            InvoiceEBillParam biParam = new InvoiceEBillParam();
            var key = "6b50096e01a3af32b62c1d3ab0";
            var appid = "XCMZYESFGDZKXX8371735";
            biParam.busType = appid;
            biParam.busNo = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
            biParam.ivcDate = DateTime.Now.ToString("yyyy-MM-dd");
            biParam.placeCode = "004";
            biParam.billCode = billCode;//"4004";
            biParam.channel = "28";
            if (orderEntity.PayMode == "BHK" || orderEntity.PayMode == "THK")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "28";
            }
            if (orderEntity.PayMode == "CFT")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "23";
            }
            if (orderEntity.PayMode == "ZFB")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "24";
            }
            if (orderEntity.PayMode == "ExcelOffLine")//BHK:建行;THK:他行;ZFB:支付宝;CFT:微信 
            {
                biParam.channel = "11";
            }
            biParam.payerType = "1";
            biParam.recer = "林智慧";
            biParam.stuName = StuName;
            //biParam.stuNo = orderEntity.StuNo;
            biParam.memo = "缴费年度:" + orderEntity.YearNo + ",学号:" + orderEntity.StuNo;
            biParam.@operator = "林智慧";
            biParam.reViewer = "陈劲华";
            biParam.noticeMode = "0";
            List<InvoiceEBillItem> itemdetailList = new List<InvoiceEBillItem>();
            foreach (var itemEntity in stuEnrollFeeOrderDetailList)
            {
                InvoiceEBillItem itemdetail = new InvoiceEBillItem();
                itemdetail.itemCode = itemEntity.ChargeItemCode;
                itemdetail.itemName = itemEntity.ChargeItemName;
                itemdetail.count = 1;
                itemdetail.standard = Convert.ToDouble(itemEntity.Standard);
                itemdetail.amt = Convert.ToDouble((itemEntity.SJAmount > itemEntity.Standard ? itemEntity.Standard : itemEntity.SJAmount));
                itemdetailList.Add(itemdetail);
            }
            biParam.totalAmt = Convert.ToDouble(itemdetailList.Sum(m => m.amt));
            biParam.itemDetail = itemdetailList;
            //JsonConvert.SerializeObject(biParam)
            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
            {
                conncore.Execute(
                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 发送给开票系统原始数据:" + JsonConvert.SerializeObject(biParam) + "',getdate())");
            }
            var data = Convert.ToBase64String(encoding.GetBytes(JsonConvert.SerializeObject(biParam)));
            var noise = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
            var biparams = "{\"appid\":" + appid + ",\"data\":" + data + ",\"noise\":" + noise + "}";
            string A = "appid=" + appid + "&data=" + data + "&noise=" + noise;
            string SignTemp = A + "&key=" + key + "&version=1.0";
            var sign = Md5Helper.Hash(SignTemp).ToUpper();
            biparams = "{\"appid\":\"" + appid + "\",\"data\":\"" + data + "\",\"noise\":\"" + noise + "\",\"version\":\"1.0\",\"sign\":\"" + sign + "\"}";

            byte[] buffer = encoding.GetBytes(biparams);
            string batchInvoiceUrl = ConfigurationManager.AppSettings["Invoiceurl"];
            try
            {
                HttpWebRequest biRequest = (HttpWebRequest)WebRequest.Create(batchInvoiceUrl);
                biRequest.Method = "POST";
                biRequest.ContentType = "application/json";
                biRequest.ContentLength = buffer.Length;
                biRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse biresponse = (HttpWebResponse)biRequest.GetResponse();
                using (StreamReader reader = new StreamReader(biresponse.GetResponseStream(), Encoding.UTF8))
                {
                    dynamic res = JsonConvert.DeserializeObject(reader.ReadToEnd());
                    string datain = res.data.ToString();
                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                    {
                        conncore.Execute(
                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 开票系统返回:" + datain + "',getdate())");
                    }
                    string returnresult = encoding.GetString(Convert.FromBase64String(datain));
                    if (returnresult != "")
                    {
                        dynamic resultobj = JsonConvert.DeserializeObject(returnresult);
                        string message = resultobj.message;
                        string messagedecode = encoding.GetString(Convert.FromBase64String(message));

                        if (resultobj.result == "S0000")
                        {
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 开票系统成功返回:" + messagedecode + "',getdate())");
                            }
                            dynamic billInfo = JsonConvert.DeserializeObject(messagedecode);
                            string eBillCode = billInfo.eBillCode;
                            string eBillNo = billInfo.eBillNo;
                            string checkCode = billInfo.checkCode;
                            //记录票号
                            var recordId = Guid.NewGuid();
                            conn.Execute($"insert into StuEnrollInvoiceRecord(Id,YearNo,StuNo,billNo,random,billStatus) values('{recordId}','{orderEntity.YearNo}','{orderEntity.StuNo}','{eBillNo}','{checkCode}','1')");

                            //查询票据url
                            var invoiceobj = new { billBatchCode = eBillCode, billNo = eBillNo, random = checkCode, channelMode = "1" };
                            var datainvoice = Convert.ToBase64String(encoding.GetBytes(JsonConvert.SerializeObject(invoiceobj)));
                            var noiseinvoice = DateTime.Now.ToString("yyyyMMddhhmmss") + ran.Next(0, 100000);
                            var paramsinvoice = "{\"appid\":" + appid + ",\"data\":" + datainvoice + ",\"noise\":" + noiseinvoice + "}";
                            string Ainvoice = "appid=" + appid + "&data=" + datainvoice + "&noise=" + noiseinvoice;
                            string SignTempinvoice = Ainvoice + "&key=" + key + "&version=1.0";
                            var signinvoice = Md5Helper.Hash(SignTempinvoice).ToUpper();
                            paramsinvoice = "{\"appid\":\"" + appid + "\",\"data\":\"" + datainvoice + "\",\"noise\":\"" + noiseinvoice + "\",\"version\":\"1.0\",\"sign\":\"" + signinvoice + "\"}";

                            byte[] bufferinvoice = encoding.GetBytes(paramsinvoice);
                            string getEBillPicUrl = ConfigurationManager.AppSettings["EBillPicUrl"];
                            HttpWebRequest invoiceRequest = (HttpWebRequest)WebRequest.Create(getEBillPicUrl);
                            invoiceRequest.Method = "POST";
                            invoiceRequest.ContentType = "application/json";
                            invoiceRequest.ContentLength = bufferinvoice.Length;
                            invoiceRequest.GetRequestStream().Write(bufferinvoice, 0, bufferinvoice.Length);
                            HttpWebResponse invoiceresponse = (HttpWebResponse)invoiceRequest.GetResponse();
                            using (StreamReader readerinvoice = new StreamReader(invoiceresponse.GetResponseStream(), Encoding.UTF8))
                            {
                                dynamic resinvoice = JsonConvert.DeserializeObject(readerinvoice.ReadToEnd());
                                datainvoice = resinvoice.data.ToString();
                                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                {
                                    conncore.Execute(
                                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 查询开票url返回:" + datainvoice + "',getdate())");
                                }
                                string returnresultinvoice = encoding.GetString(Convert.FromBase64String(datainvoice));
                                resultobj = JsonConvert.DeserializeObject(returnresultinvoice);
                                message = resultobj.message;
                                messagedecode = encoding.GetString(Convert.FromBase64String(message));
                                if (resultobj.result == "S0000")
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 查询开票url成功返回:" + messagedecode + "',getdate())");
                                    }
                                    dynamic InvoiceUrlInfo = JsonConvert.DeserializeObject(messagedecode);
                                    string pictureUrl = InvoiceUrlInfo.pictureUrl;
                                    //pictureUrl = pictureUrl.Replace("[ip]:[port]", ConfigurationManager.AppSettings["InvoiceWebUrl"]);
                                    //记录发票url
                                    //conn.Execute("update StuEnrollFeeOrder set billUrl='" + pictureUrl + "' where orderid='" + OrderId + "'");
                                    conn.Execute("update StuEnrollInvoiceRecord set billUrl='" + pictureUrl + "' where Id='" + recordId + "'");
                                }
                                else
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 查询开票url错误:" + messagedecode + "',getdate())");
                                    }
                                }
                            }
                        }
                        else
                        {

                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 开票系统错误:" + messagedecode + "',getdate())");
                            }
                        }
                    }

                }
            }
            catch (Exception e)
            {
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),121,'piaoju','FCSOId:" + orderEntity.Id + " 开票系统报错:" + e.Message + "',getdate())");
                }
            }
        }

        /// <summary>
        /// 新疆巴楚教育局与java项目帐号同步
        /// </summary>
        public static void BeginBachuAccount()
        {
            try
            {
                IEnumerable<BachuJavaUserEntity> javalist = null;
                IEnumerable<UserEntity> baseuserlist = null;

                using (IDbConnection conn = new MySqlConnection(_bachujavaConnection))
                {
                    javalist = conn.Query<BachuJavaUserEntity>(
                        "select login_name,name,mobile from sys_user where del_flag=0 and login_name<>'system' and login_name<>'admin'");
                }

                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    baseuserlist =
                        conn.Query<UserEntity>(
                            "select F_Account from LR_Base_User where F_DeleteMark = 0");
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'定时同步操作','java系统获取用户数：" +
                        javalist.Count() + "条',getdate())");
                    foreach (var oauser in javalist)
                    {
                        if (baseuserlist.Where(m => m.F_Account == oauser.login_name).Count() == 0)
                        {
                            string guid = Guid.NewGuid().ToString();
                            string key = Md5Helper.Encrypt(Common.CreateNo(), 16).ToLower();
                            string pwd = Md5Helper.Encrypt(DESEncrypt.Encrypt(Md5Helper.Encrypt("123456", 32).ToLower(), key).ToLower(), 32).ToLower();
                            conn.Execute("insert into LR_Base_User(F_UserId,F_Account,F_RealName,F_EnCode,F_Password,F_Secretkey,F_HeadIcon,F_Gender,F_DeleteMark,F_EnabledMark,F_Mobile,F_Description) " +
                                         "values('" + guid + "','" + oauser.login_name + "','" + oauser.name + "','" + oauser.login_name + "','" + pwd + "','" + key + "','/Content/images/head/on-boy.jpg',1,0,1,'" + oauser.mobile + "','教师')");
                            conn.Execute("insert into LR_Base_UserRelation(F_UserRelationId,F_UserId,F_Category,F_ObjectId) values(newid(),'" + guid + "',1,'bc624869-b258-4f8b-af34-5c59c7ee69cb')");
                            conn.Execute("insert into LR_Base_UserRelation(F_UserRelationId,F_UserId,F_Category,F_ObjectId) values(newid(),'" + guid + "',1,'d61e1853-cdee-4d49-a5e1-e230f1098e52')");
                        }
                    }
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'定时同步操作','从java系统获取新增用户插入完毕',getdate())");
                }

            }
            catch (Exception e)
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'定时同步操作','错误信息：" +
                        e.Message + "',getdate())");
                }
            }
        }

        /// <summary>
        /// 西昌一卡通
        /// </summary>
        public static void BeginTrans()
        {
            try
            {
                IEnumerable<YKTEntity> yktlist = null;
                IEnumerable<UserEntity> baseuserlist = null;

                using (IDbConnection conn = new OracleConnection(_yktConnection))
                {
                    yktlist = conn.Query<YKTEntity>(
                        "select * from YKTV_ACCOUNT where zjh is not null and kh is not null and zhyxrq is not null");
                }

                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    baseuserlist =
                        conn.Query<UserEntity>(
                            "select a.*,b.F_FullName as DeptName from LR_Base_User a left join LR_Base_Department b on a.F_DepartmentId=b.F_DepartmentId where a.F_DeleteMark = 0");
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'定时同步操作','一卡通获取记录数：" +
                        yktlist.Count() + "条',getdate())");
                }

                var fulllist = (
                        from a in yktlist
                        join b in baseuserlist on a.zjh.TrimEnd() equals b.F_IdentityCardNo into b_join
                        from x in b_join.DefaultIfEmpty()
                        select new
                        {
                            zjh = a?.zjh,
                            Mobile = x?.F_Mobile,
                            zhyxrq = a?.zhyxrq,
                            Period = x?.F_Account,
                            UserType = x?.F_Description,
                            PerName = x?.F_RealName,
                            PerSex = x?.F_Gender == 1 ? "男" : "女",
                            Sex = x?.F_Gender,
                            PerType = 1,
                            Positions = "",
                            State = a?.zhzt[1] == '0' ? 0 : 1,
                            CardID2 = a?.zhzt[1] == '0' ? a?.kh.PadLeft(10, '0') : "",
                            UserDept = x?.DeptName,
                            UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                        }
                    ).ToList().Where(a => !string.IsNullOrEmpty(a.PerName) && !string.IsNullOrEmpty(a.zjh))
                    .DistinctBy(a => a.CardID2);
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'定时同步操作','一卡通和系统关联数量：" +
                        fulllist.Count() + "条',getdate())");
                }

                using (IDbConnection conn = new SqlConnection(_mjConnection))
                {
                    try
                    {
                        conn.Execute("truncate table doormiddle");
                        foreach (var userdata in fulllist)
                        {
                            string sql = @"insert into doormiddle  ([Perid]
                                ,[PerName]
                            ,[PerSex]
                            ,[PerType]
                            ,[Positions]
                            ,[CardID2]
                            ,[State]
                            ,[UpdateTime])
                        VALUES  ('" + userdata.Period + "','" + userdata.PerName + "','" + userdata.PerSex + "'," +
                                         userdata.PerType + ",'" + userdata.Positions + "','" + userdata.CardID2 +
                                         "'," +
                                         userdata.State + ",'" + userdata.UpdateTime + "')";
                            conn.Execute(sql);
                        }
                    }
                    catch (Exception e)
                    {
                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                        {
                            conncore.Execute(
                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'门禁系统同步报错','" +
                                e.Message + "',getdate())");
                        }
                    }

                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                    {
                        conncore.Execute(
                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'门禁系统同步完成','门禁系统同步数量：" +
                            fulllist.Count() + "条',getdate())");
                    }
                }

                using (IDbConnection conn = new SqlConnection(_tsConnection))
                {
                    try
                    {
                        conn.Execute("truncate table bookmiddle");
                        foreach (var userdata in fulllist)
                        {
                            string sql = @"insert into bookmiddle  ([Action]
                           ,[Userno]
                           ,[User_name]
                           ,[Sex]
                           ,[Usertype]
                           ,[Member_id]
                           ,[dep]
                           ,[Idcard]
                           ,[Tel]
                           ,[State]
                           ,[Duetime]
                           ,[updatetime]) 
                        VALUES  (1,'" + userdata.Period + "','" + userdata.PerName + "'," + userdata.Sex + ",'" +
                                         userdata.UserType + "','" + userdata.CardID2.PadLeft(10, '0') + "','" +
                                         userdata.UserDept + "','" + userdata.zjh + "','" + userdata.Mobile + "'," +
                                         userdata.State + ",'" + userdata.zhyxrq + "','" + userdata.UpdateTime + "')";
                            conn.Execute(sql);
                        }
                    }
                    catch (Exception e)
                    {
                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                        {
                            conncore.Execute(
                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'图书系统同步报错','" +
                                e.Message + "',getdate())");
                        }
                    }

                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                    {
                        conncore.Execute(
                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'图书系统同步完成','图书系统同步数量：" +
                            fulllist.Count() + "条',getdate())");
                    }
                }
            }
            catch (Exception e)
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'定时同步操作','错误信息：" +
                        e.Message + "',getdate())");
                }
            }
        }
        /// <summary>
        /// 西昌中间库更新学生数据
        /// </summary>
        public static void MiddleDBUpdStuData()
        {
            try
            {
                using (IDbConnection conn_oracle = new OracleConnection(_xzMiddleConnection))
                {
                    try
                    {
                        #region 记录获取数据条数
                        //专业
                        List<V_ZYXX> zyxx = conn_oracle.Query<V_ZYXX>("select * from V_ZYXX").ToList();
                        //课程信息
                        List<V_KCXX> kcxx = conn_oracle.Query<V_KCXX>("select * from V_KCXX").ToList();
                        //部门
                        List<V_Dept> depts = conn_oracle.Query<V_Dept>("select * from V_DEPT").ToList();
                        //教师
                        List<V_JSXX> jsxx = conn_oracle.Query<V_JSXX>("select * from V_JSXX").ToList();
                        //行政班级表
                        List<V_BJXX> bjxx = conn_oracle.Query<V_BJXX>("select * from V_BJXX").ToList();
                        //教室组织机构
                        List<V_JS_ZZJG> zzjg = conn_oracle.Query<V_JS_ZZJG>("select * from V_JS_ZZJG where ID!='0'").ToList();
                        //学生信息
                        List<V_XSXX> xsxx = conn_oracle.Query<V_XSXX>("select * from V_XSXX ").ToList();
                        //记录获取数据条数
                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                        {
                            conncore.Execute(
                              $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库专业数据','获取oracle专业数据共{zyxx.Count()}条',getdate())");
                            conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库课程数据','获取oracle课程数据共{kcxx.Count()}条',getdate())");
                            conncore.Execute(
                                     $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库部门数据','获取oracle部门数据共{depts.Count()}条',getdate())");
                            conncore.Execute(
                                     $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库教师数据','获取oracle教师数据共{jsxx.Count()}条',getdate())");
                            conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库班级数据','获取oracle班级数据共{bjxx.Count()}条',getdate())");
                            conncore.Execute(
                                    $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库教室数据','获取oracle教室数据共{jsxx.Count()}条',getdate())");
                            conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'中间库学生数据','获取oracle学生数据共{xsxx.Count()}条',getdate())");
                        }

                        #endregion

                        var teachinfo = new List<TeachModel>();

                        using (IDbConnection conncores = new SqlConnection(_sqlConnection))
                        {
                            #region 专业
                            //获取中间库数据
                            List<CdMajorModel> cdMajors = conncores.Query<CdMajorModel>("select * from CdMajor").ToList();
                            int anumMajor = 0;
                            int unumMajor = 0;
                            if (zyxx.Count() > 0)
                            {
                                foreach (var item in zyxx)
                                {
                                    try
                                    {
                                        if (cdMajors.Exists(x => x.MajorNo == item.CODE_ && x.MajorName == item.NAME_ && x.DeptNo == item.PID))
                                        {
                                            StringBuilder sb = new StringBuilder("update CdMajor set ");
                                            if (!string.IsNullOrEmpty(item.PID))
                                            {
                                                sb.Append($" DeptNo='{item.PID}',");
                                            }
                                            if (!string.IsNullOrEmpty(item.ORDER_))
                                            {
                                                sb.Append($" F_ORDER='{item.ORDER_}',");
                                            }
                                            if (!string.IsNullOrEmpty(item.ZYFL_CODE))
                                            {
                                                sb.Append($" ZYFL_CODE='{item.ZYFL_CODE}',");
                                            }
                                            sb.Append(@" CheckMark='" + (item.ISTRUE == true ? 1 : 0) + "',");
                                            //去掉最后一个逗号
                                            if (sb.ToString().Contains(","))
                                            {
                                                sb.Remove(sb.ToString().LastIndexOf(","), 1);
                                            }
                                            //修改条件
                                            sb.Append($" where MajorNo='{item.CODE_}' and MajorName='{item.NAME_}'");
                                            unumMajor += conncores.Execute(sb.ToString());
                                        }
                                        else
                                        {
                                            int mysql = conncores.Execute($"insert into CdMajor(ID,MajorNo,MajorName,DeptNo,CheckMark,F_SchoolId,ZYFL_CODE,F_ORDER) values(newid(),'{item.CODE_}','{item.NAME_}','{item.PID}','{item.ISTRUE}','207fa1a9-160c-4943-a89b-8fa4db0547ce','{item.ZYFL_CODE}','{item.ORDER_}')");
                                            anumMajor += mysql;
                                        }
                                    }
                                    catch (Exception e)
                                    {
                                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                        {
                                            conncore.Execute(
                                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新专业数据','编号（{item.CODE_}），姓名（{item.NAME_}）更新时出现异常：{e.Message}',getdate())");
                                        }
                                    }
                                }
                            }

                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                //记录修改数据总数
                                conncore.Execute(
                                    $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新专业数据','新增数据{anumMajor}条，修改数据{unumMajor}条,共计{anumMajor + unumMajor}条,获取数据{zyxx.Count()}',getdate())");
                            }

                            #endregion

                            #region 课程

                            List<LessonInfoModel> LessonInfos = conncores.Query<LessonInfoModel>("select * from lessoninfo").ToList();
                            int anumLesson = 0;
                            int unumlesson = 0;
                            foreach (var item in kcxx)
                            {
                                try
                                {
                                    if (LessonInfos.Exists(x => x.LessonNo == item.CODE_ && x.LessonName == item.NAME_))
                                    {
                                        StringBuilder sb = new StringBuilder("update lessoninfo set ");
                                        if (!string.IsNullOrEmpty(item.COURSE_TYPE_CODE))
                                        {
                                            sb.Append($" LessonTypeId='{item.COURSE_TYPE_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.COURSE_ATTR_CODE))
                                        {
                                            sb.Append($" LessonSortDetailNo='{item.COURSE_ATTR_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.COURSE_NATURE_CODE))
                                        {
                                            sb.Append($" LessonSortNo='{item.COURSE_NATURE_CODE}',");
                                        }
                                        sb.Append(@" CheckMark='" + (item.ISTRUE == true ? 1 : 0) + "',");
                                        //去掉最后一个逗号
                                        if (sb.ToString().Contains(","))
                                        {
                                            sb.Remove(sb.ToString().LastIndexOf(","), 1);
                                        }
                                        //修改条件
                                        sb.Append($" where lessonno='{item.CODE_}' and lessonName='{item.NAME_}'");
                                        unumlesson += conncores.Execute(sb.ToString());
                                    }
                                    else
                                    {
                                        int mysql = conncores.Execute($"insert into LessonInfo(LessonId,LessonNo,LessonName,CheckMark,F_SchoolId,LessonSortNo,LessonSortDetailNo,LessonTypeId) values(newid(), '{item.CODE_}', '{item.NAME_}', '{item.ISTRUE}', '207fa1a9-160c-4943-a89b-8fa4db0547ce', '{item.COURSE_NATURE_CODE}', '{item.COURSE_ATTR_CODE}', '{item.COURSE_TYPE_CODE}')");
                                        anumLesson += mysql;
                                    }
                                }
                                catch (Exception e)
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新课程数据','编号（{item.CODE_}），姓名（{item.NAME_}）更新时出现异常：{e.Message}',getdate())");
                                    }
                                }
                            }

                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                //记录修改数据总数
                                conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新课程数据','新增数据{anumLesson}条，修改数据{unumlesson}条,共计{unumlesson + anumLesson}条,获取数据{kcxx.Count()}',getdate())");
                            }

                            #endregion

                            #region 教师信息
                            teachinfo = conncores.Query<TeachModel>("select * from empinfo").ToList();
                            int anumTeach = 0;
                            int unumTeach = 0;
                            foreach (var item in jsxx)
                            {
                                try
                                {
                                    if (teachinfo.Exists(x => x.EmpNo == item.TEA_NO))
                                    {
                                        StringBuilder sb = new StringBuilder("update empinfo set ");
                                        sb.Append($" EmpName='{item.NAME_}',");
                                        sb.Append($" UpdateTime='{DateTime.Now}', ");
                                        if (!string.IsNullOrEmpty(item.ZZJG_ID))
                                        {
                                            sb.Append($" ZZJG_ID='{item.ZZJG_ID}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.DEPT_ID))
                                        {
                                            sb.Append($" F_DepartmentId='{item.DEPT_ID}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.BZLX_CODE))
                                        {
                                            sb.Append($" BZLX_CODE='{item.BZLX_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.TEA_STATUS_CODE))
                                        {
                                            sb.Append($" IsInActiveStatus='{item.TEA_STATUS_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.BZLB_CODE))
                                        {
                                            sb.Append($" BZLB_CODE='{item.BZLB_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.IDNO))
                                        {
                                            sb.Append($" IdentityCardNo='{item.IDNO}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.BIRTH_DATE))
                                        {
                                            sb.Append($" Birthday='{item.BIRTH_DATE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PHONE))
                                        {
                                            sb.Append($" mobile='{item.PHONE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.EDU_ID))
                                        {
                                            sb.Append($" HighestRecord='{item.EDU_ID}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.DEGREE_ID))
                                        {
                                            sb.Append($" DegreeNo='{item.DEGREE_ID}',");
                                        }
                                        sb.Append(@" CheckMark='" + (item.IS_NORMAL == true ? 1 : 0) + "',");
                                        //去掉最后一个逗号
                                        if (sb.ToString().Contains(","))
                                        {
                                            sb.Remove(sb.ToString().LastIndexOf(","), 1);
                                        }
                                        //修改条件
                                        sb.Append($" where empno='{item.TEA_NO}'");
                                        unumTeach += conncores.Execute(sb.ToString());
                                    }
                                    else
                                    {
                                        int mysql = conncores.Execute($"insert into empinfo (empid,ZZJG_ID,F_DepartmentId,empNo,empName,Birthday,IdentityCardNo,mobile,DegreeNo,HighestRecord,CheckMark,F_CompanyId,BZLB_CODE,BZLX_CODE,IsInActiveStatus,UpdateTime) values (newid(), '{item.ZZJG_ID}', '{item.DEPT_ID}', '{item.TEA_NO}', '{item.NAME_}', '{item.BIRTH_DATE}', '{item.IDNO}', '{item.PHONE}', '{item.EDU_ID}', '{item.DEGREE_ID}', '{item.IS_NORMAL}', '207fa1a9-160c-4943-a89b-8fa4db0547ce', '{item.BZLB_CODE}', '{item.BZLX_CODE}', '{item.TEA_STATUS_CODE}','{DateTime.Now}')");
                                        anumTeach += mysql;
                                    }
                                }
                                catch (Exception e)
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新教师数据','编号（{item.TEA_NO}），姓名（{item.NAME_}）更新时出现异常：{e.Message}',getdate())");
                                    }
                                }
                            }
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                //记录修改数据总数
                                conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新教师数据','新增数据{anumTeach}条，修改数据{unumTeach}条,共计{unumTeach + anumTeach}条,获取数据{jsxx.Count()}',getdate())");

                            }

                            #endregion

                            #region 班级信息
                            List<ClassModel> classModels = conncores.Query<ClassModel>("select * from classinfo").ToList();
                            int anumClass = 0;
                            int unumClass = 0;
                            foreach (var item in bjxx)
                            {
                                try
                                {
                                    if (classModels.Exists(x => x.ClassName == item.NAME_ && x.ClassNo == item.NO_))
                                    {
                                        StringBuilder sb = new StringBuilder("update classinfo set ");
                                        if (!string.IsNullOrEmpty(item.MAJOR_CODE))
                                        {
                                            sb.Append($" MajorNo='{item.MAJOR_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.LENGTH_SCHOOLING))
                                        {
                                            sb.Append($" Educational='{item.LENGTH_SCHOOLING}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PYCC_CODE))
                                        {
                                            sb.Append($" PYCC_CODE='{item.PYCC_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.GRADE))
                                        {
                                            sb.Append($" Grade='{item.GRADE.Substring(2)}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.GRADUATE_YEAR))
                                        {
                                            sb.Append($" GRADUATE_YEAR='{item.GRADUATE_YEAR}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.GRADUATE_SCHOOLYEAR))
                                        {
                                            sb.Append($" GRADUATE_SCHOOLYEAR='{item.GRADUATE_SCHOOLYEAR}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.GRADUATE_DATE))
                                        {
                                            sb.Append($" GRADUATE_DATE='{item.GRADUATE_DATE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PINYIN))
                                        {
                                            sb.Append($" PINYIN='{item.PINYIN}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.NAME_SHORT))
                                        {
                                            sb.Append($" NAME_SHORT='{item.NAME_SHORT}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PINYIN_SHORT))
                                        {
                                            sb.Append($" PINYIN_SHORT='{item.PINYIN_SHORT}',");
                                        }
                                        sb.Append(@" CheckMark='" + (item.ISTRUE == true ? 1 : 0) + "',");
                                        //去掉最后一个逗号
                                        if (sb.ToString().Contains(","))
                                        {
                                            sb.Remove(sb.ToString().LastIndexOf(","), 1);
                                        }
                                        //修改条件
                                        sb.Append($" where classno='{item.NO_}' and className='{item.NAME_}'");
                                        unumClass += conncores.Execute(sb.ToString());
                                    }
                                    else
                                    {
                                        int mysql = conncores.Execute($"insert into classinfo (ClassId, ClassNo, ClassName, MajorNo, Educational, PYCC_CODE, Grade, GRADUATE_YEAR, GRADUATE_SCHOOLYEAR, GRADUATE_DATE, PINYIN, NAME_SHORT, PINYIN_SHORT, CheckMark) values (newid(), '{item.NO_}', '{item.NAME_}', '{item.MAJOR_CODE}', '{item.LENGTH_SCHOOLING}', '{item.PYCC_CODE}', '{item.GRADE.Substring(2)}', '{item.GRADUATE_YEAR}', '{item.GRADUATE_SCHOOLYEAR}', '{item.GRADUATE_DATE}', '{item.PINYIN}', '{item.NAME_SHORT}', '{item.PINYIN_SHORT}', '{item.ISTRUE}')");
                                        anumClass += mysql;
                                    }
                                }
                                catch (Exception e)
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新班级数据','编号（{item.NO_}），姓名（{item.NAME_}）更新时出现异常：{e.Message}',getdate())");

                                    }

                                }
                            }

                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                //记录修改数据总数
                                conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新班级数据','新增数据{anumClass}条，修改数据{unumClass}条,共计{unumClass + anumClass}条,获取数据{bjxx.Count()}',getdate())");

                            }

                            #endregion

                            #region 教室信息
                            List<ClassRoomModel> classRoomModels = conncores.Query<ClassRoomModel>("select * from classroominfo").ToList();
                            int anumCroom = 0;
                            int unumCroom = 0;
                            foreach (var item in zzjg)
                            {
                                try
                                {
                                    if (classRoomModels.Exists(x => x.ClassroomNo == item.CODE_ && x.ClassroomName == item.NAME_))
                                    {
                                        StringBuilder sb = new StringBuilder("update classroominfo set ");
                                        if (!string.IsNullOrEmpty(item.PID))
                                        {
                                            sb.Append($" PID='{item.PID}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PATH_))
                                        {
                                            sb.Append($" PATH_='{item.PATH_}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.LEVEL_))
                                        {
                                            sb.Append($" ClassroomFloor='{item.LEVEL_}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.LEVEL_TYPE))
                                        {
                                            sb.Append($" LEVEL_TYPE='{item.LEVEL_TYPE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.ORDER_))
                                        {
                                            sb.Append($" ORDER_='{item.ORDER_}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.JSLX_CODE))
                                        {
                                            sb.Append($" ClassroomTypeNo='{item.JSLX_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.ZW_COUNT))
                                        {
                                            sb.Append($" ContainStuNum='{item.ZW_COUNT}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.JXL_ID))
                                        {
                                            sb.Append($" ClassroomBuildingNo='{item.JXL_ID}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.XQ_ID))
                                        {
                                            sb.Append($" F_SchoolId='{item.XQ_ID}',");
                                        }
                                        sb.Append(@" CheckMark='" + (item.ISTRUE == true ? 1 : 0) + "',");
                                        //去掉最后一个逗号
                                        if (sb.ToString().Contains(","))
                                        {
                                            sb.Remove(sb.ToString().LastIndexOf(","), 1);
                                        }
                                        //修改条件
                                        sb.Append($" where classroomno='{item.CODE_}' and classroomName='{item.NAME_}'");
                                        unumCroom += conncores.Execute(sb.ToString());
                                    }
                                    else
                                    {
                                        int mysql = conncores.Execute($"insert into classroominfo (ClassroomId, ClassroomNo, ClassroomName, PID, PATH_, ClassroomFloor, LEVEL_TYPE, ORDER_, ClassroomTypeNo, ContainStuNum, ClassroomBuildingNo, F_SchoolId, CheckMark) values  (newid(), '{item.CODE_}', '{item.NAME_}', '{item.PID}', '{item.PATH_}', '{item.LEVEL_}', '{item.LEVEL_TYPE}', '{item.ORDER_}', '{item.JSLX_CODE}', '{item.ZW_COUNT}', '{item.JXL_ID}', '{item.XQ_ID}', '{item.ISTRUE}')");
                                        anumCroom += mysql;
                                    }
                                }
                                catch (Exception e)
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新教室数据','编号（{item.CODE_}），姓名（{item.NAME_}）更新时出现异常：{e.Message}',getdate())");

                                    }

                                }
                            }

                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                //记录修改数据总数
                                conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新教室数据','新增数据{anumCroom}条，修改数据{unumCroom}条,共计{unumCroom + anumCroom}条,获取数据{zzjg.Count()}',getdate())");

                            }

                            #endregion
                        }

                        using (IDbConnection db = new SqlConnection(_coresqlConnection))
                        {

                            #region 部门
                            List<DepartmentEntity> departments = db.Query<DepartmentEntity>("select * from LR_Base_Department").ToList();
                            int anumDept = 0;
                            int unumDept = 0;

                            foreach (var item in depts)
                            {
                                try
                                {
                                    if (item.LEVEL_TYPE.ToLower() != "xx" && item.LEVEL_TYPE.ToLower() != "zy")
                                    {
                                        var manager = string.Empty;
                                        if (!string.IsNullOrWhiteSpace(item.ADMIN_MANAGE_TEA_NO))
                                        {
                                            manager = teachinfo.FirstOrDefault(x => x.EmpNo == item.ADMIN_MANAGE_TEA_NO)?.EmpId ?? "";
                                        }
                                        if (departments.Any(x => x.F_DepartmentId == item.ID))
                                        {
                                            var sql = $"update LR_Base_Department set F_FullName='{item.NAME_}',F_ParentId='{item.PID}',F_EnCode='{item.CODE_}',F_ShortName='{item.NAME_SHORT}',F_Manager='{manager}',F_Description='{item.LEVEL_TYPE}',F_ModifyDate='{DateTime.Now}' where F_DepartmentId='{item.ID}'";
                                            anumDept += db.Execute(sql);
                                        }
                                        else
                                        {
                                            var sql = $"insert into LR_Base_Department (F_DepartmentId,F_CompanyId,F_ParentId,F_EnCode,F_FullName,F_ShortName,F_Manager,F_Description,F_SortCode,F_DeleteMark,F_EnabledMark,F_CreateDate,F_Order) values ('{item.ID}','207fa1a9-160c-4943-a89b-8fa4db0547ce','{item.PID}','{item.CODE_}','{item.NAME_}','{item.NAME_SHORT}','{manager}','{item.LEVEL_TYPE}',0,0,1,'{DateTime.Now}',0)";
                                            anumDept += db.Execute(sql);
                                        }
                                    }

                                }
                                catch (Exception ex)
                                {
                                    db.Execute(
                                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'更新部门数据','编号（{item.ID}），姓名（{item.NAME_}）更新时出现异常：{ex.Message}',getdate())");
                                }
                            }

                            #endregion
                        }
                        //获取oracle学生数据
                        //List<XCStudentEntity> xcStudentList = conn_oracle.Query<XCStudentEntity>(@"select ID,stu_no,name_,
                        //(case when dept_id in ('01','02','03') then dept_id when dept_id='00' then '06' when dept_id='23' then '04' when dept_id='06' then '07' else ''  end )as  dept_id,
                        //MAJOR_CODE,class_id,birthday,(case sex_code when '2' then '0' else '1' end) as sex_code,NATION_CODE,POLITICS_CODE,LENGTH_SCHOOLING,ENROLL_DATE,substr(ENROLL_GRADE,3,2) as ENROLL_GRADE  from v_lq_xs_stu").ToList();

                        //                        List<XCStudentEntity> xcStudentList = conn_oracle.Query<XCStudentEntity>(@"select ID,stu_no,name_,
                        //(case when dept_id in ('01','02','03') then dept_id when dept_id='00' then '06' when dept_id='23' then '04' when dept_id='06' then '07' else ''  end )as  dept_id,
                        //MAJOR_CODE,class_id,birthday,(case sex_code when '2' then '0' else '1' end) as sex_code,NATION_CODE,POLITICS_CODE,LENGTH_SCHOOLING,ENROLL_DATE,substr(ENROLL_GRADE,3,2) as ENROLL_GRADE  from v_lq_xs_stu 
                        //where class_id like  '21010130%'").ToList();
                        //using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                        //{
                        //    conncore.Execute(
                        //        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),578,'从西昌中间库更新学生数据','获取oracle学生数据{xsxx.Count()}条',getdate())");
                        //}
                        using (IDbConnection conn = new SqlConnection(_sqlConnection))
                        {
                            //西昌学生信息表
                            List<StuInfoBasicModel> stuInfoBasicList = conn.Query<StuInfoBasicModel>(@"select * from StuInfoBasic ").ToList();

                            ////数据字典表
                            List<MiddleDicEntity> dicList = conn.Query<MiddleDicEntity>(@"select * from MiddleDictionary ").ToList();
                            int anum = 0;
                            int unum = 0;
                            foreach (var item in xsxx)
                            {
                                try
                                {
                                    if (stuInfoBasicList.Exists(x => x.StuNo == item.STU_NO))
                                    {
                                        //学生存在，修改
                                        #region 拼接SQL
                                        StringBuilder sb = new StringBuilder("update StuInfoBasic set ");
                                        sb.Append($" StuName='{item.NAME_}',");
                                        sb.Append($" UpdateTime='{DateTime.Now}', ");
                                        if (!string.IsNullOrEmpty(item.DEPT_ID))
                                        {
                                            sb.Append($" DeptNo='{item.DEPT_ID}',");
                                        }
                                        //专业
                                        if (!string.IsNullOrEmpty(item.MAJOR_CODE))
                                        {
                                            sb.Append($" MajorNo='{item.MAJOR_CODE}',");
                                        }
                                        //班级
                                        if (!string.IsNullOrEmpty(item.CLASS_ID))
                                        {
                                            sb.Append($" ClassNo='{item.CLASS_ID}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.FORMER_NAME))
                                        {
                                            sb.Append($" FORMER_NAME='{item.FORMER_NAME}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PINYIN))
                                        {
                                            sb.Append($" SpellFull='{item.PINYIN}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.BIRTHDAY))
                                        {
                                            var date = Convert.ToDateTime(item.BIRTHDAY);
                                            sb.Append($" Birthday='{date}',");
                                        }

                                        if (!string.IsNullOrEmpty(item.IDNO))
                                        {
                                            sb.Append($" IdentityCardNo='{item.IDNO}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.SEX_CODE))
                                        {
                                            sb.Append(" GenderNo='" + (item.SEX_CODE == "1" ? "1" : "0") + "',");
                                        }
                                        //民族
                                        if (!string.IsNullOrEmpty(item.NATION_CODE))
                                        {
                                            var NationalityNo = dicList.Where(x =>
                                                x.TName == "National" && x.Mcode == item.NATION_CODE).Select(x => x.Code).FirstOrDefault();
                                            if (!string.IsNullOrEmpty(NationalityNo))
                                            {
                                                sb.Append($" NationalityNo='{NationalityNo}',");
                                            }
                                        }
                                        //政治面貌
                                        if (!string.IsNullOrEmpty(item.POLITICS_CODE))
                                        {
                                            sb.Append($" PartyFaceNo='{item.POLITICS_CODE}',");
                                        }
                                        //学制
                                        if (!string.IsNullOrEmpty(item.LENGTH_SCHOOLING))
                                        {
                                            sb.Append($" EduSystem='{item.LENGTH_SCHOOLING}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.PYCC_CODE))
                                        {
                                            sb.Append($" PYCC_CODE='{item.PYCC_CODE}',");
                                        }
                                        ////入学日期 oracle中格式有误，先不更新
                                        //if (!string.IsNullOrEmpty(item.ENROLL_DATE))
                                        //{
                                        //    var date = Convert.ToDateTime(item.ENROLL_DATE);
                                        //    sb.Append($" RegisterDate='{date}',");
                                        //}
                                        //入学年级
                                        if (!string.IsNullOrEmpty(item.ENROLL_GRADE))
                                        {
                                            sb.Append($" Grade='{item.ENROLL_GRADE.Substring(2)}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.STU_STATE_CODE))
                                        {
                                            sb.Append($" STU_STATE_CODE='{item.STU_STATE_CODE}',");
                                        }
                                        if (!string.IsNullOrEmpty(item.STU_ROLL_CODE))
                                        {
                                            sb.Append($" STU_ROLL_CODE='{item.STU_ROLL_CODE}',");
                                        }
                                        sb.Append(@" InSchoolStatus='" + (item.IS_NORMAL) + "',");
                                        //去掉最后一个逗号
                                        if (sb.ToString().Contains(","))
                                        {
                                            sb.Remove(sb.ToString().LastIndexOf(","), 1);
                                        }
                                        sb.Append($" where StuNo='{item.STU_NO}'");
                                        //System.IO.File.AppendAllText(@"c:\test.txt", sb.ToString() + "\r\n");
                                        #endregion
                                        unum += conn.Execute(sb.ToString());
                                    }
                                    else
                                    {
                                        //新增学生
                                        //拼接SQL
                                        string mysql = GetAddSql(dicList, item);
                                        anum += conn.Execute(mysql);
                                    }
                                }
                                catch (Exception e)
                                {
                                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                                    {
                                        conncore.Execute(
                                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),578,'从西昌中间库更新学生数据','学生学号（{item.STU_NO}），姓名（{item.NAME_}）更新时出现异常：{e.Message}.',getdate())");
                                    }
                                }
                            }
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),578,'从西昌中间库更新学生数据','新增学生数据{anum}条，修改学生数据{unum}条',getdate())");
                            }
                        }


                    }
                    catch (Exception e)
                    {
                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                        {
                            conncore.Execute(
                                "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),578,'从西昌中间库获取数据','异常信息：" +
                                e.Message + "',getdate())");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),578,'从西昌中间库更新基础数据','错误信息：" +
                        e.Message + "',getdate())");
                }
            }
        }

        private static string GetAddSql(List<MiddleDicEntity> dicList, V_XSXX xsxx)
        {
            string mysql = "insert into StuInfoBasic(";
            StringBuilder fieleSb = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            fieleSb.Append("StuId,stuno,stuname,CheckMark,F_SchoolId,UpdateTime,");
            sb.Append($" NEWID(),'{xsxx.STU_NO}','{xsxx.NAME_}','1','207fa1a9-160c-4943-a89b-8fa4db0547ce','{DateTime.Now}',");
            if (!string.IsNullOrEmpty(xsxx.DEPT_ID))
            {
                fieleSb.Append("DeptNo,");
                sb.Append($" '{xsxx.DEPT_ID}',");
            }
            //专业
            if (!string.IsNullOrEmpty(xsxx.MAJOR_CODE))
            {
                fieleSb.Append("MajorNo,");
                sb.Append($" '{xsxx.MAJOR_CODE}',");
            }
            if (!string.IsNullOrEmpty(xsxx.CLASS_ID))
            {
                fieleSb.Append("ClassNo,");
                sb.Append($" '{xsxx.CLASS_ID}',");
            }
            if (!string.IsNullOrEmpty(xsxx.PINYIN))
            {
                fieleSb.Append("SpellFull,");
                sb.Append($" '{xsxx.PINYIN}',");
            }
            if (!string.IsNullOrEmpty(xsxx.BIRTHDAY))
            {
                var date = Convert.ToDateTime(xsxx.BIRTHDAY);
                fieleSb.Append("Birthday,");
                sb.Append($" '{date}',");
            }
            if (!string.IsNullOrEmpty(xsxx.IDNO))
            {
                fieleSb.Append("IdentityCardNo,");
                sb.Append($" '{xsxx.IDNO}',");
            }
            if (!string.IsNullOrEmpty(xsxx.SEX_CODE))
            {
                fieleSb.Append("GenderNo,");
                sb.Append(" '" + (xsxx.SEX_CODE == "1" ? "1" : "0") + "',");
            }
            //民族
            if (!string.IsNullOrEmpty(xsxx.NATION_CODE))
            {
                var NationalityNo = dicList.Where(x =>
                    x.TName == "National" && x.Mcode == xsxx.NATION_CODE).Select(x => x.Code).FirstOrDefault();
                if (!string.IsNullOrEmpty(NationalityNo))
                {
                    fieleSb.Append("NationalityNo,");
                    sb.Append($" '{NationalityNo}',");
                }
            }
            //政治面貌
            if (!string.IsNullOrEmpty(xsxx.POLITICS_CODE))
            {
                fieleSb.Append("PartyFaceNo,");
                sb.Append($" '{xsxx.POLITICS_CODE}',");
            }
            //学制
            if (!string.IsNullOrEmpty(xsxx.LENGTH_SCHOOLING))
            {
                fieleSb.Append("EduSystem,");
                sb.Append($" '{xsxx.LENGTH_SCHOOLING}',");
            }
            if (!string.IsNullOrEmpty(xsxx.PYCC_CODE))
            {
                fieleSb.Append("PYCC_CODE,");
                sb.Append($" '{xsxx.PYCC_CODE}',");
            }

            //入学日期
            //if (!string.IsNullOrEmpty(xsxx.ENROLL_DATE))
            //{
            //    var date = Convert.ToDateTime(xsxx.ENROLL_DATE);
            //    fieleSb.Append("RegisterDate,");
            //    sb.Append($" '{date}',");
            //}
            //入学年级
            if (xsxx.ENROLL_GRADE != null)
            {
                fieleSb.Append("Grade,");
                sb.Append($" '{xsxx.ENROLL_GRADE.ToString().Substring(2)}',");
            }

            if (xsxx.IS_NORMAL != null)
            {
                fieleSb.Append("InSchoolStatus,");
                sb.Append(" '" + (xsxx.IS_NORMAL) + "',");
            }
            //去掉最后一个逗号
            if (fieleSb.ToString().Contains(",") && sb.ToString().Contains(","))
            {
                fieleSb.Remove(fieleSb.ToString().LastIndexOf(","), 1);
                sb.Remove(sb.ToString().LastIndexOf(","), 1);
            }
            mysql += fieleSb.ToString() + ") values (" + sb.ToString() + ")";
            return mysql;
        }

        public static System.Net.CookieContainer cookieContainer = new System.Net.CookieContainer();
        static WebReference.SynService synService = new SynService() { Timeout = 300000, CookieContainer = cookieContainer };

        static string Loginkey = "123456789";
        static string enCode = "00000000";
        public static void GetConsumeInfo()
        {
            using (IDbConnection conn = new SqlConnection(_coresqlConnection))
            {
                conn.Execute(
                    "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'一卡通同步操作','开始同步消费记录',getdate())");
            }
            var tokenResult = synService.GetToken("1");
            if (tokenResult.code == 100)
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'一卡通同步操作','获取Token成功',getdate())");
                }
                var pwd = Md5Helper.Encrypt(tokenResult.msg + Loginkey, 32).ToUpper();
                var loginInfo = synService.Logon("1", pwd);

                using (IDbConnection conn = new SqlConnection(_sqlConnection))
                {
                    var beginKey = -1;
                    var result1 = conn.Query<string>("SELECT TOP 1 ID FROM dbo.StuConsumption ORDER BY ID DESC");
                    if (result1.Count() > 0)
                    {
                        beginKey = Convert.ToInt32(result1.FirstOrDefault());
                    }
                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                    {
                        conncore.Execute(
                            "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'一卡通同步操作','同步开始：本次从+" + beginKey + "开始同步500条记录',getdate())");
                    }
                    var result = synService.GetEcardConsumeRecord(enCode, 0, beginKey, 500);
                    if (result.Record != null && result.Record.Length > 0)
                    {
                        foreach (var item in result.Record)
                        {
                            var entity = new StuConsumptionEntity();
                            entity.ACCCODE = item.ACCCODE.ToString();
                            entity.ASN = item.ASN.ToString();
                            entity.CARDSN = item.CARDSN.ToString();
                            entity.CUSTOMERID = item.CUSTOMERID.ToString();
                            entity.DSCRP = item.DSCRP.ToString();
                            entity.ECODE = item.ECODE.ToString();
                            entity.ID = item.ID.ToString();
                            entity.MNGFARE = item.MNGFARE.ToString();
                            entity.NOTECASE = item.NOTECASE.ToString();
                            entity.ODDFARE = item.ODDFARE.ToString();
                            entity.OPCOUNT = item.OPCOUNT.ToString();
                            entity.OPDT = item.OPDT;
                            entity.OPFARE = item.OPFARE.ToString();
                            entity.OUTID = item.OUTID.ToString();
                            entity.RECNO = item.RECNO.ToString();
                            entity.SAMCARDNO = item.ACCCODE.ToString();
                            entity.SAMTRADENO = item.SAMTRADENO.ToString();
                            entity.SOURCETABLE = item.SOURCETABLE.ToString();
                            entity.TAC = item.TAC.ToString();
                            entity.TERMID = item.TERMID.ToString();
                            entity.TRADECARDTYPE = item.TRADECARDTYPE.ToString();
                            entity.UPLOADDATE = item.UPLOADDATE;
                            entity.Create();
                            conn.Execute(
                                $"INSERT dbo.StuConsumption ( SID, SOURCETABLE, ID, ECODE, NOTECASE, CUSTOMERID, OUTID, CARDSN, OPCOUNT, OPDT, ODDFARE, OPFARE, MNGFARE, ACCCODE, DSCRP, TERMID, RECNO, UPLOADDATE, SAMCARDNO, SAMTRADENO, TRADECARDTYPE, TAC, ASN) VALUES (NEWID(), N'{entity.SOURCETABLE}',N'{entity.ID}',N'{entity.ECODE}',N'{entity.NOTECASE}',N'{entity.CUSTOMERID}',N'{entity.OUTID}',N'{entity.CARDSN}',N'{entity.OPCOUNT}','{entity.OPDT}', N'{entity.ODDFARE}',N'{entity.OPFARE}',N'{entity.MNGFARE}',N'{entity.ACCCODE}',N'{entity.DSCRP}',N'{entity.TERMID}',N'{entity.RECNO}','{entity.UPLOADDATE}',N'{entity.SAMCARDNO}',N'{entity.SAMTRADENO}',N'{entity.TRADECARDTYPE}',N'{entity.TAC}',N'{entity.ASN}')");
                        }

                        GetConsumeInfo();
                    }
                    else
                    {
                        var stuData = conn.Query("SELECT StuNo FROM dbo.StuInfoBasic");
                        foreach (var stu in stuData)
                        {
                            var StuNo = stu.StuNo.ToString();
                            conn.Execute(
                                $"UPDATE dbo.StuInfoBasic SET Balance=(SELECT TOP 1 ODDFARE FROM dbo.StuConsumption WHERE OUTID='{StuNo}' ORDER BY ID DESC) WHERE StuNo='{StuNo}'");

                        }
                    }
                }
            }
            else
            {
                using (IDbConnection conn = new SqlConnection(_coresqlConnection))
                {
                    conn.Execute(
                        "insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),999,'一卡通同步操作','获取Token失败',getdate())");
                }
            }
        }
        /// <summary>
        /// 获取充值记录
        /// </summary>
        public static void GetSaveRecordInfo()
        {

            var tokenResult = synService.GetToken("1");
            if (tokenResult.code == 100)
            {
                var pwd = Md5Helper.Encrypt(tokenResult.msg + Loginkey, 32).ToUpper();
                var loginInfo = synService.Logon("1", pwd);

                using (IDbConnection conn = new SqlConnection(_sqlConnection))
                {
                    var beginKey = -1;
                    var result1 = conn.Query<string>("SELECT TOP 1 ID FROM dbo.StuSaveRecord ORDER BY ID DESC");
                    if (result1.Count() > 0)
                    {
                        beginKey = Convert.ToInt32(result1.FirstOrDefault());
                    }

                    var result = synService.GetEcardSaveRecord(enCode, 0, beginKey, 500);
                    if (result.Record.Length > 0)
                    {
                        foreach (var item in result.Record)
                        {
                            var entity = new StuSaveRecordEntity();
                            entity.ACCCODE = item.ACCCODE.ToString();
                            entity.ASN = item.ASN.ToString();
                            entity.CARDSN = item.CARDSN.ToString();
                            entity.CUSTOMERID = item.CUSTOMERID.ToString();
                            entity.DSCRP = item.DSCRP.ToString();
                            entity.ECODE = item.ECODE.ToString();
                            entity.ID = item.ID.ToString();
                            entity.MNGFARE = item.MNGFARE.ToString();
                            entity.NOTECASE = item.NOTECASE.ToString();
                            entity.ODDFARE = item.ODDFARE.ToString();
                            entity.SAVEOPCOUNT = item.SAVEOPCOUNT.ToString();
                            entity.OPCOUNT = item.OPCOUNT.ToString();
                            entity.OPDT = item.OPDT;
                            entity.OPFARE = item.OPFARE.ToString();
                            entity.OUTID = item.OUTID.ToString();
                            entity.RECNO = item.RECNO.ToString();
                            entity.SAMCARDNO = item.ACCCODE.ToString();
                            entity.SAMTRADENO = item.SAMTRADENO.ToString();
                            entity.SOURCETABLE = item.SOURCETABLE.ToString();
                            entity.TAC = item.TAC.ToString();
                            entity.TERMID = item.TERMID.ToString();
                            entity.TRADECARDTYPE = item.TRADECARDTYPE.ToString();
                            entity.UPLOADDATE = item.UPLOADDATE;
                            entity.Create();
                            conn.Execute(
                                $"INSERT dbo.StuSaveRecord ( SID, SOURCETABLE, ID, ECODE, NOTECASE, CUSTOMERID, OUTID, CARDSN,SAVEOPCOUNT, OPCOUNT, OPDT, ODDFARE, OPFARE, MNGFARE, ACCCODE, DSCRP, TERMID, RECNO, UPLOADDATE, SAMCARDNO, SAMTRADENO, TRADECARDTYPE, TAC, ASN) VALUES (NEWID(), N'{entity.SOURCETABLE}',N'{entity.ID}',N'{entity.ECODE}',N'{entity.NOTECASE}',N'{entity.CUSTOMERID}',N'{entity.OUTID}',N'{entity.CARDSN}',N'{entity.SAVEOPCOUNT}',N'{entity.OPCOUNT}','{entity.OPDT}', N'{entity.ODDFARE}',N'{entity.OPFARE}',N'{entity.MNGFARE}',N'{entity.ACCCODE}',N'{entity.DSCRP}',N'{entity.TERMID}',N'{entity.RECNO}','{entity.UPLOADDATE}',N'{entity.SAMCARDNO}',N'{entity.SAMTRADENO}',N'{entity.TRADECARDTYPE}',N'{entity.TAC}',N'{entity.ASN}')");
                        }

                        GetSaveRecordInfo();
                    }

                }

            }






        }

        public static void PushWeixin()
        {
            Uri uri = new Uri(ConfigurationManager.AppSettings["apiUrl"] + "/mpManagement/pushWeixin?data=ceshimpid");

            using (WebClient client = new WebClient())
            {
                client.Headers["Type"] = "GET";
                client.Headers["Accept"] = "application/json";
                client.Encoding = Encoding.UTF8;
                client.DownloadStringCompleted += (senderobj, es) =>
                {
                    var obj = es.Result;
                };
                client.DownloadStringAsync(uri);
            }
        }
        /// <summary>
        /// 长阳一卡通交易流水
        /// </summary>
        public static void GetChangeYangYKT()
        {
            try
            {
                string Token = "";
                #region 登陆获取token
                //获取配置文件
                string CYLoginUrl = ConfigurationManager.AppSettings["CYLoginUrl"];
                string UserName = ConfigurationManager.AppSettings["UserName"];
                string PassWord = ConfigurationManager.AppSettings["PassWord"];

                HttpContent httpContent = new StringContent("{\"username\":\"" + UserName + "\",\"password\":\"" + PassWord + "\"}");
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                string Results = Client.PostAsync(CYLoginUrl, httpContent).Result.Content.ReadAsStringAsync().Result;
                var Result = JsonConvert.DeserializeObject<LoginResult>(Results);
                if (Results != null && Result.code == 0)
                {
                    Token = Result.token;
                }
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'一卡通交易流水','Token秘钥获取成功',getdate())");
                }
                #endregion

                #region 插入数据
                using (IDbConnection conn = new SqlConnection(_sqlConnection))
                {
                    var tday = DateTime.Now.ToShortDateString();
                    DateTime StartTime = DateTime.Today.AddHours(0);
                    DateTime EndTime = DateTime.Today.AddHours(1);

                    string JylsUrl = ConfigurationManager.AppSettings["JylsUrl"];
                    var Historylist = Convert.ToInt64(conn.ExecuteScalar("select isnull(Max(centralNo),0) from MealCardRunTab "));
                    string data = "{ \"pageNo\":\"1\",\"PageSize\":\"1000\",\"Date\":\"" + tday + "\",\"StartTime\":\"00:00:00\",\"EndTime\":\"23:59:59\",\"depcode\":\"7D\"}";
                    var responses = HttpMethods.sendHttpPost(JylsUrl, Token, data);
                    var RequsetList = JsonConvert.DeserializeObject<JSONList>(responses);


                    using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                    {
                        conncore.Execute(
                            $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'一卡通数据()','本次一共" + RequsetList.total + "条数据',getdate())");
                    }


                    for (int k = 0; k <= 23; k++)
                    {
                        using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                        {
                            conncore.Execute(
                                $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'一卡通数据','第" + k + "次循环',getdate())");
                        }
                        if (k != 0)
                        {
                            StartTime = StartTime.AddHours(1);
                            EndTime = EndTime.AddHours(1);
                        }
                        data = "{ \"pageNo\":\"1\",\"PageSize\":\"1000\",\"Date\":\"" + tday + "\",\"StartTime\":\"" + StartTime + "\",\"EndTime\":\"" + EndTime + "\",\"depcode\":\"7D\"}";
                        responses = HttpMethods.sendHttpPost(JylsUrl, Token, data);
                        RequsetList = JsonConvert.DeserializeObject<JSONList>(responses);

                        if (RequsetList.pageTotal > 0)
                        {
                            int total = (int)Math.Ceiling((decimal)RequsetList.total / 1000);
                            using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                            {
                                conncore.Execute(
                                    $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'一卡通交易流水1','一共" + RequsetList.total + "条数据',getdate())");
                            }

                            for (int i = 1; i <= total; i++)
                            {
                                data = "{ \"pageNo\":\"" + i + " \",\"PageSize\":\"1000\",\"Date\":\"" + tday + "\",\"StartTime\":\"" + StartTime + "\",\"EndTime\":\"" + EndTime + "\",\"depcode\":\"7D\"}";
                                responses = HttpMethods.sendHttpPost(JylsUrl, Token, data);
                                RequsetList = JsonConvert.DeserializeObject<JSONList>(responses);
                                if (RequsetList.data.flowlist.Count > 0)
                                {
                                    var NowCen = RequsetList.data.flowlist.Max(x => x.centralNo);
                                    if (NowCen > Historylist)
                                    {
                                        for (int j = 0; j < RequsetList.data.flowlist.Count; j++)
                                        {
                                            var nowCen = Convert.ToInt32(conn.ExecuteScalar("select Count(*) from MealCardRunTab where centralNo='" + RequsetList.data.flowlist[j].centralNo + "' "));
                                            if (nowCen <= 0)
                                            {
                                                conn.Execute(
                                                    "insert into MealCardRunTab(Id,accountNo,accountName,depName,personId,identiName,flowtype,flowamount,balance,cardNo,centralTm,centralNo,occurTime,node,bigGroup,smallGroup,seg,pos) " +
                                                    "values(newid(), '" + RequsetList.data.flowlist[j].accountNo + "', '" + RequsetList.data.flowlist[j].accountName + "', '" + RequsetList.data.flowlist[j].depName + "','" + RequsetList.data.flowlist[j].personId + "','" + RequsetList.data.flowlist[j].identiName + "','" + RequsetList.data.flowlist[j].flowType + "','" + RequsetList.data.flowlist[j].flowAmount +
                                                    "','" + RequsetList.data.flowlist[j].balance + "','" + RequsetList.data.flowlist[j].cardNo + "','" + RequsetList.data.flowlist[j].centralTm + "','" + RequsetList.data.flowlist[j].centralNo + "','" + RequsetList.data.flowlist[j].occurTime + "','" + RequsetList.data.flowlist[j].node + "','" + RequsetList.data.flowlist[j].bigGroup + "','" + RequsetList.data.flowlist[j].group + "','" + RequsetList.data.flowlist[j].seg + "','" + RequsetList.data.flowlist[j].pos + "')");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                }
                #endregion
            }
            catch (Exception e)
            {
                using (IDbConnection conncore = new SqlConnection(_coresqlConnection))
                {
                    conncore.Execute(
                        $"insert into LR_Base_Log(F_LogId,F_CategoryId,F_SourceObjectId,F_SourceContentJson,F_OperateTime) values(newid(),55555,'交易流水插入数据失败','" + e + "',getdate())");
                }
                Console.WriteLine(e);
                throw;
            }
        }
        /// <summary>
        /// 长阳登录返回
        /// </summary>
        public class LoginResult
        {
            public int code { get; set; }
            public string token { get; set; }
        }

        public class JSONList
        {
            public int code { get; set; }
            public string msg { get; set; }
            public int total { get; set; }
            public int pageTotal { get; set; }
            public int pageNo { get; set; }
            public int pageSize { get; set; }
            public dataobj data { get; set; }
        }

        public class dataobj
        {
            public List<flowlistobj> flowlist { get; set; }
        }

        public class flowlistobj
        {
            /// <summary>
            /// 中心序号
            /// </summary>
            public int centralNo { get; set; }
            /// <summary>
            /// 中心时间
            /// </summary>
            public DateTime centralTm { get; set; }
            /// <summary>
            /// 发生时间
            /// </summary>
            public DateTime occurTime { get; set; }
            /// <summary>
            /// 节点名称
            /// </summary>
            public string node { get; set; }
            /// <summary>
            /// 学生卡账号
            /// </summary>
            public int accountNo { get; set; }
            /// <summary>
            /// 学生卡名称
            /// </summary>
            public string accountName { get; set; }
            /// <summary>
            /// 身份证号
            /// </summary>
            public string personId { get; set; }
            /// <summary>
            /// 部门名称
            /// </summary>
            public string depName { get; set; }
            /// <summary>
            /// 部门编码
            /// </summary>
            public string deptCode { get; set; }
            /// <summary>
            /// 身份名称
            /// </summary>
            public string identiName { get; set; }
            /// <summary>
            /// 流水类型
            /// </summary>
            public string flowType { get; set; }
            /// <summary>
            /// 余额变化
            /// </summary>
            public string flowAmount { get; set; }
            /// <summary>
            /// 余额
            /// </summary>
            public string balance { get; set; }
            /// <summary>
            /// 卡号
            /// </summary>
            public string cardNo { get; set; }
            /// <summary>
            /// 营业大组名称
            /// </summary>
            public string bigGroup { get; set; }
            /// <summary>
            /// 营业小组名称
            /// </summary>
            public string group { get; set; }
            /// <summary>
            /// 营业餐次
            /// </summary>
            public string seg { get; set; }
            /// <summary>
            /// pos机序号
            /// </summary>
            public string pos { get; set; }
        }




    }
}
