using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.WebApi.Client;
using Kingdee.BOS.WebApi.ServicesStub;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Web;

namespace LQKJ.K3.NDR.WebApiBusinessServicePlugIn
{
    public class WebApi : AbstractWebApiBusinessService
    {
        //public string dbid = "64440bd61a2d1c";
        //public string url = "http://k3.newdegreetech.com:89/k3cloud/";//只需要改这里就好了         
        //public string pwd = "KINGDEE@123";
        public string url = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["Url"].Value;
        public string dbid = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["Dbid"].Value;
        public string pwd = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["passWord"].Value;
        public string login = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["login"].Value;
        public WebApi(KDServiceContext context) : base(context) { }
        ResponseWrapper response1 = new ResponseWrapper
        {
            code = 200,
            success = "成功",
        };
        ResponseWrapper response2 = new ResponseWrapper()
        {
            code = 500,
            success = "失败",
        };
        public ResponseWrapper ExecuteCmdSelect(string FName)//查询项目信息
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            Object dt = DBUtils.ExecuteDynamicObject(ctx, string.Format("select FNUMBER as FNumber,FNAME as FName from T_BAS_PREBDONE a left join T_BAS_PREBDONE_L b on a.FID=b.FID where FDOCUMENTSTATUS='C' and FNUMBER like '%{0}%' group by FNUMBER,FNAME", FName));
            response1.msg = "项目信息";
            response1.data = dt;
            return response1;
        }
        public ResponseWrapper ExecuteCmdAdd(string parmeters)//新增
        {
            Logger.Info("进入接口", "");
            ResponseWrapper response = new ResponseWrapper();
            response.code = 500;
            response.msg = "新增失败";
            response.success = "失败";
            response.data = null;
            try
            {
                Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
                int num = 0;
                JObject key1 = JObject.Parse(parmeters);
                JArray jf = (JArray)JsonConvert.DeserializeObject(key1["Model"].ToString());
                decimal sum = 0;
                DateTime time = Convert.ToDateTime(jf[0]["F_LQKJ_Date2"].ToString());
                string holiday = jf[0]["Holiday"].ToString();//是否节假日
                if (holiday.Contains("节"))
                {
                    string SelHoliday = "select F_LQKJ_TEXT3 from LQKJ_t_KAIZHANGSTATE";
                    DataTable data = DBUtils.ExecuteDataSet(ctx, SelHoliday).Tables[0];
                    if (data.Rows.Count > 0 && data.Rows[0]["F_LQKJ_TEXT3"].ToString() == "False")
                    {
                        response.code = 500;
                        response.msg = "节假日不能录入工时";
                        response.success = "失败";
                        return response;
                    }
                }
                string sql6 = "select F_LQKJ_TEXT2,F_LQKJ_TEXT3 from LQKJ_t_KAIZHANGSTATE";
                if ((time.DayOfWeek == DayOfWeek.Sunday || time.DayOfWeek == DayOfWeek.Saturday) && DBUtils.ExecuteDataSet(ctx, sql6).Tables[0].Rows[0]["F_LQKJ_TEXT3"].ToString() == "False")
                {
                    response.code = 500;
                    response.msg = "周末不能录入工时";
                    response.success = "失败";
                    return response;
                }
                if (time.Month != DateTime.Now.Month)
                {
                    var Date = time.ToString("yyyyMM");
                    string sql = $"select F_LQKJ_TEXT from LQKJ_t_KAIZHANGSTATE where F_LQKJ_TEXT1 = '{Date}'";
                    DataTable dataTable= DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                    if (dataTable.Rows.Count > 0)
                    {
                        if (dataTable.Rows[0][0].ToString() != "打开")
                        {
                            response.code = 500;
                            response.msg = "该月份暂未开账";
                            response.success = "失败";
                            return response;
                        }
                        else
                        {
                            for (int i = 0; i < jf.Count; i++)
                            {
                                sum += Convert.ToDecimal(jf[i]["F_LQKJ_WORKTIME"].ToString());
                                string sql2 = $"select F_LQKJ_FITEM from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' and c.FNUMBER = '{jf[i]["F_LQKJ_FITEM"]["FNumber"].ToString()}'";
                                if (DBUtils.ExecuteDataSet(ctx, sql2).Tables[0].Rows.Count == 0)
                                {
                                    num = num + 1;
                                }
                            }
                            string sql1 = $"select F_LQKJ_FITEM from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' group by F_LQKJ_FITEM";
                            if ((DBUtils.ExecuteDataSet(ctx, sql1).Tables[0].Rows.Count + num) > 3)
                            {
                                response.msg = "一天中项目不能添加超过3个";
                                response.code = 500;
                                return response;
                            }
                            sql = $"select isnull(sum(F_LQKJ_WORKTIME),0) F_LQKJ_WORKTIME from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' ";
                            DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                            if ((sum + (Convert.ToDecimal(dt.Rows[0]["F_LQKJ_WORKTIME"].ToString())) <= 8))//判断工时是否超过
                            {
                                K3CloudApiClient client = new K3CloudApiClient(url);
                                var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
                                //K3CloudApiClient client = new K3CloudApiClient("http://192.168.1.37/k3cloud/");
                                //var loginResult = client.ValidateLogin("646c66d0102ca7", "kingdee", "kingdee@1234", 2052);
                                Logger.Info("2", "验证完成开始登录");
                                var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                                Logger.Info("3", resultType.ToString());
                                if (resultType == 1)
                                {
                                    Logger.Info("4", "登录成功开始新增");
                                    JObject keys = JObject.Parse(client.BatchSave("LQKJ_XMGSDJ", parmeters));
                                    Logger.Info("5", "新增完成");
                                    string result = keys["Result"]["ResponseStatus"]["IsSuccess"].ToString();

                                    Logger.Info("6", result);
                                    if (result == "True")
                                    {
                                        Logger.Info("7", "添加成功修改部门");
                                        string name = jf[0]["F_LQKJ_FNAME"]["FName"].ToString();
                                        Logger.Info("8", name);
                                        Logger.Info("获取员工名字", name);
                                        string sql4 = $"update LQKJ_T_PROJECTHOURS set F_LQKJ_FDEPARTMENT=(select FDEPTID from T_BD_STAFF a left join T_BD_STAFFPOSTINFO b on a.FSTAFFID=b.FSTAFFID left join T_BD_STAFF_L c on a.FSTAFFID=c.FSTAFFID where FISFIRSTPOST=1 and FNAME='{name}')" +
                                                      $" where F_LQKJ_FNAME=(select FID from T_HR_EMPINFO_L where FNAME='{name}') and F_LQKJ_DATE2='{time}'";
                                        Logger.Info("执行更新语句", sql4);
                                        DBUtils.Execute(ctx, sql4);
                                        response.code = 200;
                                        string sql2 = $"select isnull(sum(F_LQKJ_WORKTIME),0) F_LQKJ_WORKTIME from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' ";
                                        DataTable dt2 = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                                        response.msg = dt2.Rows[0]["F_LQKJ_WORKTIME"].ToString();
                                        response.success = "成功";
                                        response.data = dt2;
                                        return response;
                                    }
                                    else
                                    {
                                        string message = keys["Result"]["ResponseStatus"]["Errors"][0]["Message"].ToString();
                                        response.msg = message;
                                        response.code = 500;
                                        response.success = "失败";
                                        return response;
                                    }
                                }
                            }
                            else
                            {
                                response.msg = "一天工时不能超过8小时!";
                                response.data = dt;
                                return response;
                            }
                        }
                    }
                    else
                    {
                        response.code = 500;
                        response.msg = "该月份暂未开账";
                        response.success = "失败";
                        return response;
                    }
                }
                if (time.Month==DateTime.Now.Month)//月份等于当前月份
                {
                    for (int i = 0; i < jf.Count; i++)
                    {
                        sum += Convert.ToDecimal(jf[i]["F_LQKJ_WORKTIME"].ToString());
                        string sql2 = $"select F_LQKJ_FITEM from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' and c.FNUMBER = '{jf[i]["F_LQKJ_FITEM"]["FNumber"].ToString()}'";
                        if (DBUtils.ExecuteDataSet(ctx, sql2).Tables[0].Rows.Count == 0)
                        {
                            num = num + 1;
                        }
                    }
                    string sql1 = $"select F_LQKJ_FITEM from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' group by F_LQKJ_FITEM";
                    if ((DBUtils.ExecuteDataSet(ctx, sql1).Tables[0].Rows.Count + num) > 3)
                    {
                        response.msg = "一天中项目不能添加超过3个";
                        response.code = 500;
                        return response;
                    }
                    string sql = $"select isnull(sum(F_LQKJ_WORKTIME),0) F_LQKJ_WORKTIME from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' ";
                    DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                    if ((sum + (Convert.ToDecimal(dt.Rows[0]["F_LQKJ_WORKTIME"].ToString())) <= 8))//判断工时是否超过
                    {
                        K3CloudApiClient client = new K3CloudApiClient(url);
                        var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
                        //K3CloudApiClient client = new K3CloudApiClient("http://192.168.1.37/k3cloud/");
                        //var loginResult = client.ValidateLogin("646c66d0102ca7", "kingdee", "kingdee@1234", 2052);
                        Logger.Info("2", "验证完成开始登录");
                        var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                        Logger.Info("3", resultType.ToString());
                        if (resultType == 1)
                        {
                            Logger.Info("4", "登录成功开始新增");
                            JObject keys = JObject.Parse(client.BatchSave("LQKJ_XMGSDJ", parmeters));
                            Logger.Info("5", "新增完成");
                            string result = keys["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                            
                            Logger.Info("6", result);
                            if (result == "True")
                            {
                                Logger.Info("7", "添加成功修改部门");
                                string name = jf[0]["F_LQKJ_FNAME"]["FName"].ToString();
                                Logger.Info("8", name);
                                Logger.Info("获取员工名字", name);
                                string sql4 = $"update LQKJ_T_PROJECTHOURS set F_LQKJ_FDEPARTMENT=(select FDEPTID from T_BD_STAFF a left join T_BD_STAFFPOSTINFO b on a.FSTAFFID=b.FSTAFFID left join T_BD_STAFF_L c on a.FSTAFFID=c.FSTAFFID where FISFIRSTPOST=1 and FNAME='{name}')" +
                                              $" where F_LQKJ_FNAME=(select FID from T_HR_EMPINFO_L where FNAME='{name}') and F_LQKJ_DATE2='{time}'";
                                Logger.Info("执行更新语句", sql4);
                                DBUtils.Execute(ctx, sql4);
                                response.code = 200;
                                string sql2 = $"select isnull(sum(F_LQKJ_WORKTIME),0) F_LQKJ_WORKTIME from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO_L b on a.F_LQKJ_FNAME=b.FID where b.FNAME='{jf[0]["F_LQKJ_FNAME"]["FName"].ToString()}' and F_LQKJ_DATE2='{time}' ";
                                DataTable dt2 = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                                response.msg = dt2.Rows[0]["F_LQKJ_WORKTIME"].ToString();
                                response.success = "成功";
                                response.data = dt2;
                            }
                            else
                            {
                                string message = keys["Result"]["ResponseStatus"]["Errors"][0]["Message"].ToString();
                                response.msg = message;
                                response.code = 500;
                                response.success = "失败";
                            }
                        }
                    }
                    else
                    {
                        response.msg = "一天工时不能超过8小时!";
                        response.data = dt;
                    }
                }//判断周末层
                else
                {
                    response.msg = "未开帐!";
                }
            }//try层
            catch (Exception ex)
            {
                throw ex;
            }
            return response;
        }//最外层
        public ResponseWrapper ExecuteCmdSelectName(string Name)//查询某一个用户的所有工时信息
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            string sql = string.Empty;
            sql = "select a.FID, F_LQKJ_FNAME, F_LQKJ_FITEM, F_LQKJ_FDEPARTMENT, F_LQKJ_WORKTIME,F_LQKJ_WORKCONATAINER, F_LQKJ_DATE2,F_LQKJ_BILLSTATUS,F_LQKJ_FNAME,FNUMBER,c.FNAME from LQKJ_T_PROJECTHOURS a left join T_BAS_PREBDONE b on a.F_LQKJ_FITEM=b.FID left join T_BAS_PREBDONE_L c on b.FID = c.FID left join T_HR_EMPINFO_L d on a.F_LQKJ_FNAME = d.FID where d.FNAME = '" + Name + "' order by F_LQKJ_DATE2 desc";
            DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
            response1.msg = "查询用户";
            if (dt.Rows.Count == 0)
            {
                response1.msg += ":该用户暂无工时信息";
                response1.code = 500;
            }
            response1.data = dt;
            return response1;
        }
        public ResponseWrapper ExecuteCmdEdit(string parmeters)//修改,修改之前要判断他的工时加在一起是否大过8小时
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            ResponseWrapper response = new ResponseWrapper();
            response.code = 500;

            response.success = "失败";
            try
            {
                Decimal WorkTime = 0;
                JObject key = JObject.Parse(parmeters);
                string FID = key["Model"]["FID"].ToString();
                string sql = string.Format("select isnull(sum(F_LQKJ_WORKTIME),0) F_LQKJ_WORKTIME from LQKJ_T_PROJECTHOURS where F_LQKJ_FNAME = (select F_LQKJ_FNAME from LQKJ_T_PROJECTHOURS where FID = '{0}')  and F_LQKJ_DATE2 = (select F_LQKJ_DATE2 from LQKJ_T_PROJECTHOURS where FID = '{0}') and FID!='{0}'", FID);
                if (DBUtils.ExecuteDataSet(ctx, sql).Tables[0].Rows.Count > 0)
                {
                    WorkTime = Convert.ToDecimal(DBUtils.ExecuteDataSet(ctx, sql).Tables[0].Rows[0]["F_LQKJ_WORKTIME"].ToString());//数据库中存在的工时
                }
                Decimal WorkTime2 = Convert.ToDecimal(key["Model"]["F_LQKJ_WORKTIME"].ToString());
                if (WorkTime + WorkTime2 <= 8)
                {
                    K3CloudApiClient client = new K3CloudApiClient(url);
                    var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
                    var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                    if (resultType == 1)
                    {
                        JObject keys = JObject.Parse(client.Save("LQKJ_XMGSDJ", parmeters));
                        string result = keys["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                        
                        if (result == "True")
                        {
                            response.msg = "修改成功";
                            response.code = 200;
                            response.success = "成功";
                        }
                        else
                        {
                            string message = keys["Result"]["ResponseStatus"]["Errors"][0]["Message"].ToString();
                            response.msg = message;
                            response.code = 500;
                            response.success = "失败";
                        }
                        Dictionary<int, ResponseWrapper> keyValuePairs = new Dictionary<int, ResponseWrapper>();

                    }
                }
                else
                {
                    response.msg = "修改失败";
                    response.code = 500;
                    response.msg = "当天工时不能超过8个小时！";
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return response;
        }
        public string Request(string token, string id)
        {

            string url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?";
            url += "access_token=" + token;
            url += "&userid =" + id;
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;
        }
        public string RequestToken(string corpid, string corpsecret)
        {
            string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?";
            url += "corpid=" + corpid;
            url += "&corpsecret=" + corpsecret;
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            try
            {
                //获取内容
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            finally
            {
                stream.Close();
            }
            return result;
        }
        public ResponseWrapper addUser(string parmeters)
        {
            ResponseWrapper response = new ResponseWrapper();
            response.msg = "绑定成功";
            try
            {

                Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");

                K3CloudApiClient client = new K3CloudApiClient(url);
                var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
                var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                JObject key = JObject.Parse(parmeters);
                string id = key["Model"]["F_LQKJ_ID"].ToString();
                string sql = string.Format("select * from LQKJ_t_EmployeeID  where F_LQKJ_ID='{0}'", id);
                DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    response.msg = "该账号已绑定！";
                    response.code = 200;
                    response.success = "成功";
                }
                else
                {
                    if (resultType == 1)
                    {
                        JObject keys = JObject.Parse(client.Save("LQKJ_QYWXID", parmeters));
                        string result = keys["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                        
                        if (result == "True")
                        {
                            response.code = 200;
                            response.success = "成功";
                        }
                        else
                        {
                            string message = keys["Result"]["ResponseStatus"]["Errors"][0]["Message"].ToString();
                            response.msg = message;
                            response.code = 500;
                            response.success = "失败";
                        }
                    }

                }

            }
            catch (Exception)
            {

                throw;
            }
            return response;
        }
        public ResponseWrapper selectUser(string ID)//通过ID查询
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            ResponseWrapper response = new ResponseWrapper();
            response.success = "失败";
            if (ID == "")
            {
                response.msg = "ID不能为空";
                response.code = 500;
                return response;
            }
            string sql = string.Format("select FNAME from	LQKJ_t_EmployeeID a left join  T_HR_EMPINFO_L b on a.F_LQKJ_FNANEM=b.FID where F_LQKJ_ID='{0}'", ID);
            DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                response.msg = "已存在该用户";
                response.success = "成功";
                response.data = dt;
                response.code = 200;
            }
            else
            {
                response.msg = "该用户不存在！";
                response.code = 500;
            }
            return response;
        }
        public ResponseWrapper State(string yearMonth)
        {
            ResponseWrapper response = new ResponseWrapper();
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            string sql = $"select case F_LQKJ_TEXT when '关闭' then 0 else 1 end as State,case F_LQKJ_TEXT2 when 'False' then 0 else 1 end as ZhouM from LQKJ_t_KAIZHANGSTATE where F_LQKJ_TEXT1='{yearMonth}'";
            DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                response.msg = "查找成功";
                response.data = dt;
                response.code = 200;
                response.success = "成功";
            }
            else
            {
                response.msg = "该月份暂未开账!";
                response.code = 500;
                response.success = "失败";
            }
            return response;
        }
        public ResponseWrapper Login(string ID)//登录方法,用员工编号查找
        {

            //string dbid = Kingdee.BOS.KDConfiguration.Current.CommonConfiguration.AppSettings.Settings["dbid"].Value;
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            ResponseWrapper response = new ResponseWrapper();
            if (ID == null)
            {
                response.success = "失败";
                response.msg = "账号不能为空!";
                response.code = 500;
            }
            try
            {
                string sql = $"select FNAME from T_HR_EMPINFO a left join  T_HR_EMPINFO_L b on a.FID = b.FID where a.FNUMBER ='{ID}'";
                DataTable dynamic = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                if (dynamic.Rows.Count == 0)
                {
                    response.msg = "不存在该员工,请联系管理员维护！";
                    response.success = "失败";
                    response.code = 500;
                }
                else
                {
                    response.msg = "登录成功";
                    response.success = "成功";
                    response.code = 200;
                    response.data = dynamic;
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
            return response;
        }
        public ResponseWrapper Submit(string parmeters)
        {
            ResponseWrapper response = new ResponseWrapper();
            K3CloudApiClient client = new K3CloudApiClient(url);
            var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            if (resultType == 1)
            {
                JObject result = JObject.Parse(client.Submit("LQKJ_XMGSDJ", parmeters));
                if (result["Result"]["ResponseStatus"]["IsSuccess"].ToString() == "True")
                {
                    response.msg = "提交成功";
                    response.code = 200;
                    response.success = "成功";
                }
                else
                {
                    response.msg = "提交失败";
                    response.code = 500;
                    response.success = "失败";
                }
            }
            return response;
        }
        public ResponseWrapper Revocation(string parmeters)
        {
            ResponseWrapper response = new ResponseWrapper();
            K3CloudApiClient client = new K3CloudApiClient(url);
            var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
            var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
            if (resultType == 1)
            {
                JObject result = JObject.Parse(client.CancelAssign("LQKJ_XMGSDJ", parmeters));
                if (result["Result"]["ResponseStatus"]["IsSuccess"].ToString() == "True")
                {
                    response.msg = "撤销成功";
                    response.code = 200;
                    response.success = "成功";
                }
                else
                {
                    response.msg = "撤销失败";
                    response.code = 500;
                    response.success = "失败";
                }
            }
            return response;
        }
        public ResponseWrapper Delete(string Id)
        {
            ResponseWrapper response = new ResponseWrapper();
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            string delStr = $"delete from LQKJ_T_PROJECTHOURS where FID='{Id}'";
            if (DBUtils.Execute(ctx, delStr) == 1)
            {
                response.code = 200;
                response.msg = "删除成功";
                response.success = "成功";
            }
            else
            {
                response.code = 500;
                response.msg = "数据库中没有该条数据！";
                response.success = "失败";
            }

            return response;
        }
        public ResponseWrapper ImportFile()
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            ResponseWrapper response = new ResponseWrapper();
            DataTable dataTable = new DataTable();
            List<SqlObject> sqlObjects = new List<SqlObject>();
            StringBuilder stringBuilder = new StringBuilder();
            //Holiday();
            try
            {
                HttpRequest request = System.Web.HttpContext.Current.Request;
                var FNumber = request.Form[0].ToString();//员工编号
                HttpPostedFile HttpFile = request.Files["file"];
                IWorkbook workbook = null;
                Guid guid = Guid.NewGuid();
                var fileName = Path.GetFileNameWithoutExtension(HttpFile.FileName);//文件名
                var postFix = Path.GetExtension(HttpFile.FileName);//后缀
                var path = HttpContext.Current.Server.MapPath("") + "\\tempfilePath\\" + fileName + guid.ToString() + postFix;
                HttpFile.SaveAs(path);
                bool isXlsx = path.EndsWith(".xlsx", StringComparison.OrdinalIgnoreCase);
                bool isXls = path.EndsWith(".xls", StringComparison.OrdinalIgnoreCase);
                using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    if (isXlsx)//xlsx
                    {
                        workbook = new XSSFWorkbook(fileStream);
                    }
                    else if (isXls)
                    {
                        workbook = new HSSFWorkbook(fileStream);
                    }
                    else
                    {
                        response.msg = "文件格式不正确!";
                        response.code = 500;
                        response.success = "失败";
                        return response;
                    }
                }//判断文件
                #region 处理文件
                Logger.Info("开始处理文件","");
                ISheet sheet = workbook.GetSheetAt(0);
                Logger.Info("获取页签", sheet.ToString());
                IRow rows = sheet.GetRow(0);
                for (int i = 0; i < rows.LastCellNum; i++)//增加表头
                {
                    Logger.Info("增加表头", i.ToString()+":"+rows.GetCell(i).ToString());

                    var ColumnName = rows.GetCell(i);
                    dataTable.Columns.Add(ColumnName.ToString());
                }
                DataTable ErrorDt = dataTable.Clone();//错误信息表
                ErrorDt.Columns.Add("错误原因");
                Logger.Info("表头添加完毕", rows.LastCellNum.ToString());

                DataTable HolidayDt = DBUtils.ExecuteDataSet(ctx, "select * from Holiday_TEMP").Tables[0];//节假日表
                DataTable StateDt = DBUtils.ExecuteDataSet(ctx, "select F_LQKJ_TEXT3,F_LQKJ_TEXT2 from LQKJ_t_KAIZHANGSTATE").Tables[0];//开账状态
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    Logger.Info("循环添加数据", "");
                    var row = sheet.GetRow(i);
                    if (row == null ||(row.LastCellNum==5&& row.GetCell(4)==null)|| row.LastCellNum<5)//row为空,
                    {
                        continue;
                    }
                    DataRow dataRow = dataTable.NewRow(); DataRow ErrorRow = ErrorDt.NewRow();
                    
                    for (int j = row.FirstCellNum; j < row.LastCellNum; j++)//循环每一列
                    {
                        if (row.GetCell(0)?.ToString() == "")
                            break;
                        if (StateDt.Rows[0][0].ToString() == "False" )//关账
                        {
                            bool containsValue = HolidayDt.AsEnumerable().
                                Any(a => a.Field<string>("datetime") == DateTime.FromOADate(row.GetCell(4).NumericCellValue).ToString("yyyy-MM-dd") &&
                                a.Field<string>("message") != "工作日");//判断当天是否节假日
                            if (containsValue)//如果存在节假日中
                            {
                                var cell2 = row.GetCell(j);
                                if (j == 4)
                                {
                                    var value = cell2.NumericCellValue;
                                    ErrorRow[j] = DateTime.FromOADate(value).ToString("yyyy-MM-dd");//设置日期格式
                                }
                                else
                                    ErrorRow[j] = row.GetCell(j)?.ToString() ?? "";//获取每一行字段的值
                                ErrorRow["错误原因"] = "节假日暂未开账";
                                continue;
                            }
                        }
                        //if (StateDt.Rows[0][0].ToString() == "False" && StateDt.Rows[0][1].ToString() == "True")//关账
                        //{
                        //    bool containsValue = HolidayDt.AsEnumerable().
                        //        Any(a => a.Field<string>("datetime") == DateTime.FromOADate(row.GetCell(4).NumericCellValue).ToString("yyyy-MM-dd")
                        //        && a.Field<string>("message")!="休息日");//判断当天是否节假日
                        //    if (containsValue)//如果存在节假日中
                        //    {
                        //        var cell2 = row.GetCell(j);
                        //        if (j == 4)
                        //        {
                        //            var value = cell2.NumericCellValue;
                        //            ErrorRow[j] = DateTime.FromOADate(value).ToString("yyyy-MM-dd");//设置日期格式
                        //        }
                        //        else
                        //            ErrorRow[j] = row.GetCell(j)?.ToString() ?? "";//获取每一行字段的值
                        //        ErrorRow["错误原因"] = "节假日暂未开账";
                        //        continue;
                        //    }
                        //}
                        var cell = row.GetCell(j);
                        if (j == 4) 
                        {
                            var value = cell.NumericCellValue;
                            dataRow[j] = DateTime.FromOADate(value).ToString("yyyy-MM-dd");//设置日期格式
                        }
                        else
                        dataRow[j] = row.GetCell(j)?.ToString() ?? "";//获取每一行字段的值
                    }
                    if (!String.IsNullOrEmpty(ErrorRow["错误原因"].ToString()))
                    {
                        ErrorDt.Rows.Add(ErrorRow);
                    }
                    else if (!String.IsNullOrEmpty(dataRow[0].ToString())) 
                    {
                        dataTable.Rows.Add(dataRow);
                    }
                }
                #endregion
                var dt3 = dataTable.AsEnumerable().Where(e => Convert.ToDateTime(e.Field<string>("工时发生日期")) > DateTime.Now)
                    .Select(a=>new {Date=a.Field<string>("工时发生日期") }).ToList();
                foreach (var item in dt3)
                {
                    var Rows = dataTable.Select($"工时发生日期='{item.Date}'");
                    foreach (var item2 in Rows)
                    {
                        DataRow dataRow = ErrorDt.NewRow();
                        dataRow[0] = item2[0]?.ToString() ?? "";
                        dataRow[1] = item2[1]?.ToString() ?? "";
                        dataRow[2] = item2[2]?.ToString() ?? "";
                        dataRow[3] = item2[3]?.ToString() ?? "";
                        dataRow[4] = item2[4]?.ToString() ?? "";
                        //dataRow[5] = item2[5]?.ToString() ?? "";
                        dataRow[5] = "工时日期不能大于今日";
                        ErrorDt.Rows.Add(dataRow);//给错误表单添加数据  
                        dataTable.Rows.Remove(item2);
                    }
                }
                var dt = dataTable.AsEnumerable().
                                GroupBy(a => new { date = a.Field<string>("工时发生日期") }).
                                Select(a => new
                                {
                                    Date = a.Key.date,
                                    Price = a.Sum(b => Convert.ToDecimal(b.Field<string>("工时")))
                                }).Where(a => a.Price > 8 && Convert.ToDateTime(a.Date)<=DateTime.Now).ToList();                               
                                ;
                foreach(var item in dt)
                {
                   var Rows= dataTable.Select($"工时发生日期='{item.Date}'");
                    foreach(var item2 in Rows)
                    {
                        DataRow dataRow = ErrorDt.NewRow();
                        dataRow[0] = item2[0]?.ToString() ?? "";
                        dataRow[1] = item2[1]?.ToString() ?? "";
                        dataRow[2] = item2[2]?.ToString() ?? "";
                        dataRow[3] = item2[3]?.ToString() ?? "";
                        dataRow[4] = item2[4]?.ToString() ?? "";
                        dataRow[5] = "同一天工时不能超过8个小时";
                        ErrorDt.Rows.Add(dataRow);//给错误表单添加数据  
                        dataTable.Rows.Remove(item2);
                    }
                }
                string InsertSql = " insert into XMGS_TEMP(Number,F_LQKJ_FITEM,F_LQKJ_WORKTIME,F_LQKJ_WORKCONATAINER,F_LQKJ_Date2,F_LQKJ_FNUMBER)values";
                stringBuilder.Append(InsertSql);
                string Start = "(";
                Logger.Info  ("开始循环拼接Sql", "");
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    string Context = "";
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        Context += $"'{dataTable.Rows[i][j]?.ToString() ?? ""}',";
                    }
                    Context = Context.Substring(0, Context.Length - 1);
                    string Last = $",'{FNumber}'),";
                    stringBuilder.Append(Start + Context + Last);
                }
               
                string EndSql = stringBuilder.ToString().Substring(0, stringBuilder.Length - 1);
                if (EndSql.Length > 114)
                {
                    Logger.Info("插入数据存储过程", $"存储过程: /*dialect*/   exec XMGS \r" + EndSql);
                    DBUtils.Execute(ctx, $"/*dialect*/   exec XMGS \r" + EndSql);//存储过程创建表,并且往临时表中插入数据
                    Logger.Info("插入数据存储过程", "");
                    string ItemStr = @"select F_LQKJ_FITEM from XMGS_TEMP T1 left join T_BAS_PREBDONE T2 on T1.F_LQKJ_FITEM=T2.FNUMBER where T2.FID is  null";
                    DataTable dataTable3= DBUtils.ExecuteDataSet(ctx, ItemStr).Tables[0];
                    if (dataTable3.Rows.Count > 0)
                    {
                        for(int i = 0; i < dataTable3.Rows.Count; i++)
                        {
                            var Rows = dataTable.Select($" 项目编号='{dataTable3.Rows[i]["F_LQKJ_FITEM"]?.ToString() ?? ""}'");
                            DBUtils.Execute(ctx, $"delete from XMGS_TEMP where F_LQKJ_FITEM='{dataTable3.Rows[i]["F_LQKJ_FITEM"]?.ToString() ?? ""}'");
                            foreach (var item in Rows)
                            {
                                DataRow dataRow = ErrorDt.NewRow();
                                dataRow[0] = item[0]?.ToString() ?? "";
                                dataRow[1] = item[1]?.ToString() ?? "";
                                dataRow[2] = item[2]?.ToString() ?? "";
                                dataRow[3] = item[3]?.ToString() ?? "";
                                dataRow[4] = item[4]?.ToString() ?? "";
                                dataRow[5] = "项目编号不正确!";
                                ErrorDt.Rows.Add(dataRow);//给错误表单添加数据       
                                dataTable.Rows.Remove(item);
                            }
                        }
                    }
                    string SelStr = @"/*dialect*/ 	select * from (
									select count(FID)FID,F_LQKJ_Date2  from (
									select DISTINCT  T.FID,convert(varchar(10),T.F_LQKJ_Date2,120)F_LQKJ_Date2 from (
									select  c.FID,b.FID FNAME,a.F_LQKJ_Date2 from  XMGS_TEMP a left join T_HR_EMPINFO b on a.F_LQKJ_FNUMBER=b.FNUMBER
                                    left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FNUMBER
									)T 
									left join (
									select  F_LQKJ_FITEM,F_LQKJ_FNAME,F_LQKJ_DATE2 from  LQKJ_T_PROJECTHOURS
									)T2 on T.FID=T2.F_LQKJ_FITEM and T.FNAME=T2.F_LQKJ_FNAME and T.F_LQKJ_Date2=T2.F_LQKJ_DATE2
									)T3
									group by F_LQKJ_Date2
									)T4 where T4.FID>3";
                    DataTable dataTable1 = DBUtils.ExecuteDataSet(ctx, SelStr).Tables[0];
                    Logger.Info("判断项目大于三条", "");
                    if (dataTable1.Rows.Count > 0)//有项目大于三条的
                    {
                        for(int i = 0; i < dataTable1.Rows.Count; i++)
                        {
                            var Rows = dataTable.Select($" 工时发生日期='{dataTable1.Rows[i]["F_LQKJ_Date2"]?.ToString() ?? ""}'");
                            DBUtils.Execute(ctx, $"delete from XMGS_TEMP where F_LQKJ_Date2='{dataTable1.Rows[i]["F_LQKJ_Date2"]?.ToString() ?? ""}'");
                            foreach(var item in Rows)
                            {
                                DataRow dataRow = ErrorDt.NewRow();
                                dataRow[0] = item[0]?.ToString() ?? "";
                                dataRow[1] = item[1]?.ToString() ?? "";
                                dataRow[2] = item[2]?.ToString() ?? "";
                                dataRow[3] = item[3]?.ToString() ?? "";
                                dataRow[4] = item[4]?.ToString() ?? "";
                                dataRow[5] = "同一天项目不能超过3条";
                                ErrorDt.Rows.Add(dataRow);//给错误表单添加数据       
                                dataTable.Rows.Remove(item);
                            }
                        }
                    }
                    SelStr = @"/*dialect*/ select  * from (
									select convert(varchar(10),a.F_LQKJ_Date2,120)F_LQKJ_Date2,工时1+isnull(工时2,0) 总工时 from (
									select sum(F_LQKJ_WORKTIME) 工时1,b.FID FNAME,a.F_LQKJ_Date2 from  XMGS_TEMP a left join T_HR_EMPINFO b on a.F_LQKJ_FNUMBER=b.FNUMBER
                                    left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FNUMBER
									group by F_LQKJ_Date2,b.FID
									) a
									left join 
									(select sum(F_LQKJ_WORKTIME) 工时2,F_LQKJ_FNAME,F_LQKJ_DATE2 from  LQKJ_T_PROJECTHOURS
									group by F_LQKJ_DATE2,F_LQKJ_FNAME
									)b on a.F_LQKJ_Date2=b.F_LQKJ_DATE2 and a.FNAME=b.F_LQKJ_FNAME
									)T
									where  T.总工时>8";
                    dataTable1 = DBUtils.ExecuteDataSet(ctx, SelStr).Tables[0];
                    Logger.Info("判断工时大于8", "");
                    if (dataTable1.Rows.Count > 0)//有项目工时大于8条的
                    {
                        for (int i = 0; i < dataTable1.Rows.Count; i++)
                        {
                            var Rows = dataTable.Select($" 工时发生日期='{dataTable1.Rows[i]["F_LQKJ_Date2"]?.ToString() ?? ""}'");
                            foreach (var item in Rows)
                            {
                                DataRow dataRow = ErrorDt.NewRow();
                                dataRow[0] = item[0]?.ToString() ?? "";
                                dataRow[1] = item[1]?.ToString() ?? "";
                                dataRow[2] = item[2]?.ToString() ?? "";
                                dataRow[3] = item[3]?.ToString() ?? "";
                                dataRow[4] = item[4]?.ToString() ?? "";
                                //dataRow[5] = item2[5]?.ToString() ?? "";
                                dataRow[5] = "同一天工时不能超过8个小时";
                                ErrorDt.Rows.Add(dataRow);//给错误表单添加数据       
                                dataTable.Rows.Remove(item);
                            }
                        }
                    }
                    SelStr = @"/*dialect*/ select  * from (
									select convert(varchar(10),a.F_LQKJ_Date2,120)F_LQKJ_Date2,工时1+isnull(工时2,0) 总工时 from (
									select sum(F_LQKJ_WORKTIME) 工时1,b.FID FNAME,a.F_LQKJ_Date2 from  XMGS_TEMP a left join T_HR_EMPINFO b on a.F_LQKJ_FNUMBER=b.FNUMBER
                                    left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FNUMBER
									group by F_LQKJ_Date2,b.FID
									) a
									left join 
									(select sum(F_LQKJ_WORKTIME) 工时2,F_LQKJ_FNAME,F_LQKJ_DATE2 from  LQKJ_T_PROJECTHOURS
									group by F_LQKJ_DATE2,F_LQKJ_FNAME
									)b on a.F_LQKJ_Date2=b.F_LQKJ_DATE2 and a.FNAME=b.F_LQKJ_FNAME
									)T
									where  T.总工时<8";
                    DataTable dataTable2 = DBUtils.ExecuteDataSet(ctx, SelStr).Tables[0];
                    Logger.Info("判断工时小于8", "");
                    if (dataTable2.Rows.Count > 0)//有项目工时小于8的
                    {
                        for (int i = 0; i < dataTable2.Rows.Count; i++)
                        {
                            var Rows = dataTable.Select($" 工时发生日期='{dataTable2.Rows[i]["F_LQKJ_Date2"]?.ToString() ?? ""}'");
                            foreach (var item in Rows)
                            {
                                DataRow dataRow = ErrorDt.NewRow();
                                dataRow[0] = item[0]?.ToString() ?? "";
                                dataRow[1] = item[1]?.ToString() ?? "";
                                dataRow[2] = item[2]?.ToString() ?? "";
                                dataRow[3] = item[3]?.ToString() ?? "";
                                dataRow[4] = item[4]?.ToString() ?? "";
                                //dataRow[5] = item2[5]?.ToString() ?? "";
                                dataRow[5] = "同一天工时不满8个小时";
                                ErrorDt.Rows.Add(dataRow);//给错误表单添加数据       
                                dataTable.Rows.Remove(item);
                            }
                        }
                    }
                    StringBuilder stringBuilder1 = new StringBuilder();                   
                    //string FIDSql = @"select FID,F_LQKJ_BILLNO from LQKJ_T_PROJECTHOURS where FID=(select max(FID)F_LQKJ_CREATEDATE from LQKJ_T_PROJECTHOURS)";//查询FID
                    string FnameSql = $"	select c.FNAME from T_BD_STAFF a left join T_BD_STAFFPOSTINFO b on a.FSTAFFID=b.FSTAFFID left join T_BD_DEPARTMENT_L c on a.FDEPTID=c.FDEPTID  where FISFIRSTPOST=1 and a.FNUMBER='{FNumber}'";//查询员工信息,名字和部门
                    string NameSql = $"select FNAME from T_HR_EMPINFO a left join T_HR_EMPINFO_L b on a.FID=b.FID where FNUMBER='{FNumber}'";
                    Logger.Info("查询员工姓名", "Sql:" + NameSql);
                    var Name = DBUtils.ExecuteDataSet(ctx, NameSql).Tables[0].Rows[0][0].ToString();
                    Logger.Info("员工姓名", Name);
                    var DepId= DBUtils.ExecuteDataSet(ctx, FnameSql).Tables[0].Rows[0][0].ToString();//查询员工部门
                    Logger.Info("员工部门", DepId);
                    string Item = "";
                    //var UserId = DBUtils.ExecuteDataSet(ctx,$"select FUSERID from T_SEC_user where FNAME='{login}'").Tables[0].Rows[0][0].ToString();
                    string Model = "{\"Model\":[";
                    stringBuilder1.Append(Model);
                    string EndModel = "]}";
                    for (int i = 0; i < dataTable.Rows.Count; i++)
                    {
                        string Json = "{\"F_LQKJ_FITEM\":{\"FNumber\": \""+ dataTable.Rows[i]["项目编号"]?.ToString() + "\"},\"F_LQKJ_WORKCONATAINER\":\""+ dataTable.Rows[i]["工作内容"]?.ToString()  + "\",\"F_LQKJ_WORKTIME\":\""+ Convert.ToDecimal(dataTable.Rows[i]["工时"]?.ToString() ?? "0") + "\",\"F_LQKJ_Date2\":\""+ dataTable.Rows[i]["工时发生日期"]?.ToString() + "\",\"F_LQKJ_FNAME\":{\"FName\":\""+ Name + "\"},\"F_LQKJ_FDEPARTMENT\":{\"FName\":\"" + DepId + "\"},\"F_LQKJ_CheckBox\":\"false\"},";
                        Logger.Info("循环拼接Json", Json);
                        stringBuilder1.Append(Json);
                    }
                    stringBuilder1.Append(EndModel);
                    //K3CloudApiClient client = new K3CloudApiClient("http://192.168.1.37/k3cloud/");
                    //var loginResult = client.ValidateLogin("646c66d0102ca7", "kingdee", "kingdee@1234", 2052);
                    K3CloudApiClient client = new K3CloudApiClient(url);
                    Logger.Info("连接url", url);
                    var loginResult = client.ValidateLogin(dbid, login, pwd, 2052);
                    var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>();
                    if (stringBuilder1.Length > 12)
                    {
                        if (resultType == 1)//登录成功
                        {
                            JObject keys = JObject.Parse(client.BatchSave("LQKJ_XMGSDJ", stringBuilder1.ToString()));
                            Logger.Info("接口Json参数", stringBuilder1.ToString());
                            string result = keys["Result"]["ResponseStatus"]["IsSuccess"].ToString();
                            
                            if (result == "True")
                            {
                                response.msg = "添加成功";
                                response.code = 200;
                            }
                            else
                            {
                                string message = keys["Result"]["ResponseStatus"]["Errors"][0]["Message"].ToString();
                                Logger.Info("接口错误信息", message);
                                response.msg = message;
                                response.code = 500;
                                return response;
                            }
                        }
                        else
                        {
                            response.msg = "账套配置错误，请联系管理员";
                            response.code = 500;
                            response.success = "登录失败";
                            return response;
                        }
                    }
                    else
                    {
                        response.msg = "全部不满足条件";
                        response.code = 502;
                        response.success = "失败";
                    }
                }
                else
                {
                    response.msg = "您没有填写数据！";
                    response.code = 500;
                    response.success = "失败";
                    return response;
                }
                if (ErrorDt.Rows.Count > 0)
                {
                    ExeclFile(ErrorDt, HttpContext.Current.Server.MapPath("") + "\\tempfilePath\\" + "详细错误" + guid + postFix);
                    response.msg = "部分数据添加成功，请下载错误文件";
                    response.code = 501;
                    response.data =url+"\\tempfilePath\\" + "详细错误" + guid + postFix;
                    response.success = "成功";
                }
                File.Delete(path);//删除文件
            }
            catch (Exception ex)
            {

                response.msg = "输入的数据格式不正确";
                response.code = 500;
                response.success = "失败";
            }
            return response;
        }
        private void ExeclFile(DataTable dataTable,string pathUrl)//导出错误信息的Execl文件
        {
            
            var End = Path.GetExtension(pathUrl);
            IWorkbook workbook = null;
            if (End==".xlsx")//xlsx
            {
                workbook = new XSSFWorkbook();
            }
            else if (End==".xls")
            {
                workbook = new HSSFWorkbook();
            }
           ISheet sheet=  workbook.CreateSheet("错误信息");
            IRow row = sheet.CreateRow(0);
            ICell cell = null;
            for (int b = 0; b < dataTable.Columns.Count; b++)//添加表头
            {
                cell = row.CreateCell(b);
                cell.SetCellValue(dataTable.Columns[b].ColumnName);
            }
            for(int i = 0; i < dataTable.Rows.Count; i++)
            {
                row = sheet.CreateRow(i+1);
                for(int j = 0; j < dataTable.Columns.Count; j++)
                {
                     cell = row.CreateCell(j);
                    cell.SetCellValue(dataTable.Rows[i][j].ToString());
                }
            }
            using(FileStream file=new FileStream(pathUrl, FileMode.Create))
            {
                workbook.Write(file);
            }
        }
        public ResponseWrapper DownLoad()
        {
            ResponseWrapper response = new ResponseWrapper();
            response.msg = "下载成功";
            response.data = url + "\\TemplateFiles\\" + "项目工时导入模板.xlsx";
            response.success = "成功";
            response.code = 200;
            return response;
        }
        private void Holiday()
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            string BeforeSql = $"select * from Holiday_TEMP where datetime like '%{(DateTime.Now.Year-1).ToString()}%'";
            string NowSql= $"select * from Holiday_TEMP where datetime like '%{(DateTime.Now.Year ).ToString()}%'";
            string Url = $"https://www.mxnzp.com/api/holiday/list/year/"+DateTime.Now.Year.ToString()+"?ignoreHoliday=false&app_id=tkpjrhqiwehnvncm&app_secret=OW1ucWtka3hMdXdwUEhBSEQ1ckdBZz09";
            //string Url = "";
            Logger.Info("访问节假日接口", "");
            HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
            Request.Method = "GET";
            WebResponse Response = Request.GetResponse();
            using (Stream stream = Response.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream, Encoding.UTF8))
                {
                    DBUtils.Execute(ctx, "exec Holiday");
                    Logger.Info("执行查询节假日存储过程", "");
                    DataTable dt = DBUtils.ExecuteDataSet(ctx, BeforeSql).Tables[0];
                    DataTable dt2= DBUtils.ExecuteDataSet(ctx, NowSql).Tables[0];
                    if (dt.Rows.Count > 0)//如果有上一年的数据就删除
                    {
                        DBUtils.Execute(ctx, "delete from Holiday_TEMP");
                    }
                    if (dt2.Rows.Count > 0)
                    {
                        return;
                    }
                    string result = streamReader.ReadToEnd();
                    StringBuilder stringBuilder = new StringBuilder();
                    string StartSql = @"/*dialect*/ insert into Holiday_TEMP(datetime,message) values";
                    stringBuilder.Append(StartSql);
                    JObject keyValues = (JObject)JsonConvert.DeserializeObject(result);
                    var Data1 = keyValues["data"];
                    Logger.Info("访问节假日接口", ""+Data1);
                    foreach (var item in Data1)
                    {
                        //循环每年的数据
                        JArray array = (JArray)JsonConvert.DeserializeObject(item["days"].ToString());
                        foreach(var itemArray in array)
                        {
                            //循环每月的数据
                            //if (itemArray["typeDes"].ToString() == "工作日")
                            //{
                            //    continue;//继续循环
                            //}
                            var MidSql = $"('{itemArray["date"].ToString()}','{itemArray["typeDes"].ToString()}'),";
                            stringBuilder.Append(MidSql);
                        }
                    }
                    string EndSql = stringBuilder.ToString().Substring(0, stringBuilder.ToString().Length - 1);
                    DBUtils.Execute(ctx, EndSql);
                    var Data = keyValues["data"].ToString().Substring(1);
                    var Obj = JObject.Parse(Data.Substring(0, Data.Length - 1));
                }
            }
        }
        public ResponseWrapper SelectDateTime(string datetime)
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            ResponseWrapper response = new ResponseWrapper();
            string sqlSelect = $"/*dialect*/ select * from Holiday_TEMP where format(convert(datetime,[datetime],20),'yyyyMM')='{datetime}'";
            DataTable dt = DBUtils.ExecuteDataSet(ctx, sqlSelect).Tables[0];
            if (dt.Rows.Count > 0)
            {
                response.code = 200;
                response.data = dt;
                response.msg = "查询成功";
            }
            else
            {
                response.code = 500;
                response.data = null;
                response.msg = "没有数据，请维护";
            }
            return response;
        }
        public ResponseWrapper FastWrite(string Number)
        {
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            ResponseWrapper response = new ResponseWrapper();
            string SelectSql = $@"select F_LQKJ_WORKCONATAINER,F_LQKJ_WORKTIME,c.FNUMBER from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO b on a.F_LQKJ_FNAME=b.FID left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FID where b.FNUMBER='{Number}' and F_LQKJ_DATE2=
                                (select max(F_LQKJ_DATE2) from LQKJ_T_PROJECTHOURS a left join T_HR_EMPINFO b on a.F_LQKJ_FNAME=b.FID left join T_BAS_PREBDONE c on a.F_LQKJ_FITEM=c.FID where b.FNUMBER='{Number}')";
            DataTable dt = DBUtils.ExecuteDataSet(ctx, SelectSql).Tables[0];
            if (dt.Rows.Count == 0)
            {
                response.code = 200;
                response.data = null;
                response.msg = "该员工没有最近填写数据";
                response.success = "成功";
            }
            else
            {
                response.code = 200;
                response.data = dt;
                response.msg = "请求成功";
                response.success = "成功";
            }
            return response;
        }
        public ResponseWrapper YearMonth(string YearMonth,string FNumber)
        {
            Logger.Info("查询员工历史数据接口", "");
            Context ctx = new Context(DatabaseType.MS_SQL_Server, Context.DataBaseCategory.Normal, dbid, "");
            Logger.Info("查询员工历史数据接口", "1");
            ResponseWrapper response = new ResponseWrapper();
            Logger.Info("查询员工历史数据接口", "2");
            Logger.Info("YearMonth", YearMonth.ToString() + "01") ;
            DateTime dateTime = DateTime.ParseExact(YearMonth + "01", "yyyyMMdd", null);
            Logger.Info("查询员工历史数据接口", "3");
            var Year = dateTime.Year;
            var Month = dateTime.Month;
            string SelectSql = $"/*dialect*/ select convert(varchar(10),F_LQKJ_DATE2,120) F_LQKJ_DATE2 from LQKJ_T_PROJECTHOURS where F_LQKJ_FNAME=(select FID from T_HR_EMPINFO where FNUMBER='{FNumber}') and month(F_LQKJ_DATE2)='{Month}' and year(F_LQKJ_DATE2)='{Year}'";
            Logger.Info("查询员工历史数据", SelectSql);
            DataTable dt = DBUtils.ExecuteDataSet(ctx, SelectSql).Tables[0];
            if (dt.Rows.Count == 0)
            {
                response.code = 200;
                response.data = null;
                response.msg = "该员工无录入数据";
                response.success = "成功";
            }
            else
            {
                response.code = 200;
                response.data = dt;
                response.msg = "成功";
                response.success = "成功";
            }
            return response;
        }
    }
}
