using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System.Data;
using System.Net.Http;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using System.IO;


namespace YDSP.Core.Controllers
{
    [Produces("application/json")]
    [Route("api/[controller]/[action]")]
    [EnableCors("ydsp")]
    public class ValuesController : Controller
    {
        public static HttpClient httpClient = new HttpClient();

        //以下是跟钉钉对接有关方法,

        #region 钉钉appId及appSecret
        /// <summary>
        /// 钉钉appId及appSecret
        /// </summary>
        /// <returns></returns>
        private app GetApp()
        {
            app a = new app();
            string sql = "select * from ZSystemURL where ZSText = 'appkey'   select * from ZSystemURL where ZSText = 'appsecret'";
            DataSet set = YDSPHepler.GetSet(sql);
            foreach (DataRow i in set.Tables[0].Rows)
            {
                a.appid = Convert.ToString(i["ZSURL"]).Trim();
            }
            foreach (DataRow i in set.Tables[1].Rows)
            {
                a.appsecret = Convert.ToString(i["ZSURL"]).Trim();
            }
            return a;
        }
        #endregion

        #region 获取钉钉接口最终返回userid
        [HttpPost]
        public SystemUser GetSystem([FromBody]SystemUser s)
        {
            SystemUser system = new SystemUser();
            app a = GetApp();
            string access_token = "";
            string uid = "";
            string name = "";
            //获取钉钉access_token
            string URL = "https://oapi.dingtalk.com/gettoken?appkey=" + a.appid + "&appsecret=" + a.appsecret;
            var responseStr = httpClient.GetAsync(URL).Result.Content.ReadAsStringAsync().Result;
            var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
            foreach (var i in obj)
            {
                if (i.Key == "access_token")
                {
                    access_token = i.Value;
                    continue;
                }
            }
            //获取用户钉钉id
            URL = "https://oapi.dingtalk.com/user/getuserinfo?access_token=" + access_token + "&code=" + s.UserCode;
            responseStr = httpClient.GetAsync(URL).Result.Content.ReadAsStringAsync().Result;
            obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
            foreach (var i in obj)
            {
                if (i.Key == "userid")
                {
                    uid = i.Value;
                    continue;
                }
                if (i.Key == "name")
                {
                    name = i.Value;
                    continue;
                }
            }
            List<SystemUser> systemUsers = new List<SystemUser>();
            try
            {
                string sql = "select  *from ZSystemUser";
                DataSet set = YDSPHepler.GetSet(sql);
                foreach (DataRow i in set.Tables[0].Rows)
                {
                    SystemUser user = new SystemUser();
                    user.UserCode = Convert.ToString(i["ZSUserCode"]);
                    user.UserID = Convert.ToString(i["ZSUserId"]);
                    user.UserName = Convert.ToString(i["ZSText"]);
                    user.PWD = Convert.ToString(i["ZSPassword"]);
                    user.URL = "";
                    systemUsers.Add(user);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            if (systemUsers.FirstOrDefault(f => f.UserID == uid) == null)
            {
                if (uid != "")
                {
                    string sql = "insert into ZSystemUser values('', '" + uid + "', '', '')";
                    YDSPHepler.ExecuteNonQuery(sql);
                    sql = "select * from ZSystemUser where ZSUserId = '" + uid + "'";
                    DataSet set = YDSPHepler.GetSet(sql);
                    foreach (DataRow i in set.Tables[0].Rows)
                    {
                        system.UserID = Convert.ToString(i["ZSUserId"]).Trim();
                        system.UserCode = Convert.ToString(i["ZSUserCode"]).Trim();
                        system.UserName = Convert.ToString(i["ZSText"]).Trim();
                        system.PWD = Convert.ToString(i["ZSPassword"]).Trim();
                    }
                }
            }
            else
            {
                system = systemUsers.FirstOrDefault(f => f.UserID == uid);
            }
            return system;
        }
        #endregion

        #region 钉钉修改用户表（根据钉钉id修改usercode）
        /// <summary>
        /// 钉钉修改用户表（根据钉钉id修改usercode）
        /// </summary>
        /// <param name="system"></param>
        /// <returns></returns>
        [HttpPost]
        public string UpdateZSystemUser([FromBody]SystemUser system)
        {
            string sql = "update ZSystemUser set ZSUserCode = '" + system.UserCode + "', ZSText = '" + system.UserName + "' where ZSUserId = '" + system.UserID + "'";
            try
            {
                YDSPHepler.ExecuteNonQuery(sql);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return sql;
        }

        #endregion

        #region 钉钉获取钉钉消息接口
        /// <summary>
        /// 钉钉获取钉钉消息接口
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        [HttpPost]
        public string GetInformation([FromBody]SystemUser s)
        {
            app a = GetApp();
            string URL = "";
            string access_token = "";
            //获取钉钉access_token
            try
            {
                URL = "https://oapi.dingtalk.com/gettoken?appkey=" + a.appid + "&appsecret=" + a.appsecret;
                var responseStr = httpClient.GetAsync(URL).Result.Content.ReadAsStringAsync().Result;
                var obj = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
                foreach (var i in obj)
                {
                    if (i.Key == "access_token")
                    {
                        access_token = i.Value;
                        continue;
                    }
                }
                URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + access_token;
                OapiMessageSendToConversationRequest oa = new OapiMessageSendToConversationRequest();
                oa.userid_list = s.UserID;
                string sql = "select * from zsystemurl where ZSText = 'AgentId'     select * from zsystemurl where ZSText = '图片地址'";
                DataSet set = YDSPHepler.GetSet(sql);
                foreach (DataRow i in set.Tables[0].Rows)
                {
                    oa.agent_id = Convert.ToString(i["ZSURL"]);//获取AgentId
                }
                oa.to_all_user = false;
                msgtypeURL msgtypeURL = new msgtypeURL();
                msgtypeURL.msgtype = "link";
                msgtypeURL.link.messageUrl = s.URL;
                foreach (DataRow i in set.Tables[1].Rows)
                {
                    msgtypeURL.link.picUrl = Convert.ToString(i["ZSURL"]);//获取钉钉接口(链接消息的图片参数)
                }
                msgtypeURL.link.title = s.UserCode;
                msgtypeURL.link.text = s.UserName;
                string j = Newtonsoft.Json.JsonConvert.SerializeObject(msgtypeURL);//序列化
                oa.msg = (JObject)JsonConvert.DeserializeObject(j);
                //Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json);
                string data = Newtonsoft.Json.JsonConvert.SerializeObject(oa);//序列化
                HttpContent httpContent = new StringContent(data);
                httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                var responseStrs = httpClient.PostAsync(URL, httpContent).Result.Content.ReadAsStringAsync().Result;
                var objs = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStrs);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            URL = "";

            return URL;
        }
        #endregion

        #region 钉钉获取SystemUser主要数据
        /// <summary>
        /// 钉钉获取SystemUser主要数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("{name}")]
        public string GetUser(string name)
        {
            string sql = "select ZSUserId from zsystemuser where ZSUserCode =  '" + name + "'";
            DataSet set = YDSPHepler.GetSet(sql);
            foreach (DataRow i in set.Tables[0].Rows)
            {
                sql = Convert.ToString(i["ZSUserId"]);
            }
            return sql;
        }
        #endregion

        #region 钉钉根据名称绑定单个地址
        /// <summary>
        /// 钉钉根据名称绑定单个地址
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet("{name}")]
        public string GetDDSystemURL(string name)
        {
            string url = "";
            try
            {
                string sql = "select ZSURL from ZSystemURL where ZSText = '" + name + "'";
                DataTable table = YDSPHepler.GetData(sql);
                foreach (DataRow i in table.Rows)
                {
                    url = Convert.ToString(i["ZSURL"]);
                }
            }
            catch (Exception ex)
            {
                url = ex.Message;
            }
            return url;
        }
        #endregion

        #region 钉钉绑定多个地址
        /// <summary>
        /// 钉钉绑定多个地址
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpPost]
        public WorkFlowCaseVM PostSystemURL([FromBody] WorkFlowCaseVM work)
        {
            WorkFlowCaseVM w = new WorkFlowCaseVM();
            string sql = "select ZSURL from ZSystemURL where ZSText = '" + work.ApplicationCode + "'    select ZSURL from ZSystemURL where ZSText = '" + work.url + "'";
            DataSet set = YDSPHepler.GetSet(sql);
            foreach (DataRow i in set.Tables[0].Rows)
            {
                w.ApplicationCode = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[1].Rows)
            {
                w.url = Convert.ToString(i["ZSURL"]);
            }
            return w;
        }
        #endregion

        #region 钉钉绑定配置地址
        /// <summary>
        /// 钉钉绑定配置地址
        /// </summary>
        /// <returns></returns>
        public List<SystemUser> GetDDSystemURLList()
        {
            List<SystemUser> items = new List<SystemUser>();
            string sql = "select * from ZSystemURL";
            DataTable table = YDSPHepler.GetData(sql);
            foreach (DataRow i in table.Rows)
            {
                items.Add(new SystemUser()
                {

                    UserID = Convert.ToString(i["ZSID"]),
                    UserCode = Convert.ToString(i["ZSURL"]),
                    UserName = Convert.ToString(i["ZSText"]),
                    URL = null,
                    PWD = null,
                });
            }
            return items;
        }
        #endregion

        #region 钉钉修改配置地址
        /// <summary>
        /// 钉钉修改配置地址
        /// </summary>
        /// <param name="id"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        [HttpPost]
        public List<SystemUser> UpdateDDSystemURL([FromBody]List<SystemUser> s)
        {
            try
            {
                foreach (SystemUser item in s)
                {
                    string updateSQL = @"update ZSystemURL set ZSURL = '" + item.UserCode + "',ZSText = '" + item.UserName + "' " +
                        " where ZSID =" + item.UserID;
                    YDSPHepler.ExecuteNonQuery(updateSQL);
                }
                List<SystemUser> items = new List<SystemUser>();
                string sql = "select * from ZSystemURL";
                DataTable table = YDSPHepler.GetData(sql);
                foreach (DataRow i in table.Rows)
                {
                    items.Add(new SystemUser()
                    {

                        UserID = Convert.ToString(i["ZSID"]),
                        UserCode = Convert.ToString(i["ZSURL"]),
                        UserName = Convert.ToString(i["ZSText"]),
                        URL = null,
                        PWD = null,
                    });
                }
                return items;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        //以上是跟钉钉对接有关方法,以下是跟OA对接有关方法

        #region OA获取WorkFlowCase主要数据
        /// <summary>
        /// OA获取WorkFlowCase主要数据
        /// </summary>
        /// <returns></returns>
        [HttpGet("{caseCode}")]
        public WorkFlowCaseVM GetWorkFlowCaseVM(string caseCode)
        {
            string sql = "select ApplicationCode from WorkFlowCase where CaseCode =" + caseCode;
            DataTable table = YDSPHepler.GetData(sql);
            WorkFlowCaseVM workFlow = new WorkFlowCaseVM();
            foreach (DataRow i in table.Rows)
            {
                workFlow.ApplicationCode = Convert.ToString(i["ApplicationCode"]);
            }
            return workFlow;
        }

        #endregion

        #region OA获取附件信息
        /// <summary>
        /// OA获取附件信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("{actcode}")]
        public ActionResult GetWorkFlowFile(string actcode)
        {
            var list = new List<WorkFlowFiles>();

            //获取附件集合
            string filesql = "select AttachMentCode,FileName,Content_Type,am.CreateDate,GuidName from AttachMent am inner join WorkFlowAttachmentType wam on am.AttachMentType = wam.AttachmentType inner join WorkFlowCase wc on wam.ApplicationPath = wc.ApplicationPath and am.MasterCode = wc.ApplicationCode inner join WorkFlowAct wa on wa.CaseCode = wc.CaseCode where wa.ActCode = '" + actcode + "'";
            var dt1 = YDSPHepler.GetSet(filesql).Tables[0];
            for (int i = 0; i < dt1.Rows.Count; i++)
            {
                var attchment = new WorkFlowFiles();
                attchment.filename = dt1.Rows[i]["FileName"].ToString();
                attchment.AttachMentCode = dt1.Rows[i]["AttachMentCode"].ToString();
                list.Add(attchment);

            }
            return Json(list);
        }

        [HttpGet("{code}")]
        
        public FileContentResult ShowImg(string code)
        {
            string filepath = "";
            string creatdate = "";
            string savetype = "";
            string filepathtype = "";
            string filename = "";

            string fileconfigsql = "select * from ConfigItemValue where name = '基础模块-附件存储设置-存储模式' select * from ConfigItemValue where name = '基础模块-附件存储设置-文件存储目录' select * from ConfigItemValue where name = '基础模块-附件存储设置-文件目录模式'";
            DataSet fileconfig = YDSPHepler.GetSet(fileconfigsql);//获取附件配置方法 数据库/磁盘目录 目录保存方法 单一目录/年/年月/年月日
            foreach (DataRow i in fileconfig.Tables[0].Rows)
            {
                savetype = Convert.ToString(i["Value"]);
            }
            if (savetype == "file")//附件存储方法
            {
                foreach (DataRow j in fileconfig.Tables[1].Rows)
                {
                    filepath = Convert.ToString(j["Value"]);//附件目录
                }
                foreach (DataRow l in fileconfig.Tables[2].Rows)
                {
                    filepathtype = Convert.ToString(l["Value"]);

                }
            }

            var sql = $"select * from AttachMent where AttachMentCode='{code}'";
            var dt = YDSPHepler.GetSet(sql).Tables[0];
            creatdate = Convert.ToDateTime(dt.Rows[0]["CreateDate"]).ToString("yyyyMMDD");
            var name = dt.Rows[0]["GuidName"].ToString();
            filename = dt.Rows[0]["FileName"].ToString();
            if (filepathtype == "Root")
            {
                filepath += "/" + name;
            }
            if (filepathtype == "YYYY")
            {
                filepath += "/" + creatdate.Substring(0, 4) + "/" + name;
            }
            if (filepathtype == "YYYYMM")
            {
                filepath += "/" + creatdate.Substring(0, 6) + "/" + name;
            }
            if (filepathtype == "YYYYMMDD")
            {
                filepath += "/" + creatdate + "/" + name;
            }
            var contentType = dt.Rows[0]["content_type"].ToString();

            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
            byte[] infbytes = new byte[(int)fs.Length];
            fs.Read(infbytes, 0, infbytes.Length);
            fs.Close();
            return File(infbytes, contentType,filename);

        }
        #endregion

        #region OA获取表单名称对应界面路径
        /// <summary>
        /// OA获取表单名称对应界面路径
        /// </summary>
        /// <param name="ProcedureName"></param>
        /// <returns></returns>
        [HttpPost]
        public WorkFlowCaseVM GetWorkFlowProcedure([FromBody]SystemUser s)
        {
            string ProcedureName = s.UserName;
            WorkFlowCaseVM w = new WorkFlowCaseVM();
            string sql = @"select ProcedureName,ApplicationPath from WorkFlowProcedure
            group by ProcedureName,ApplicationPath
            having ProcedureName = '" + ProcedureName + "'       select ZSURL from ZSystemURL where ZSText = '" + s.UserID + "'";
            DataSet set = YDSPHepler.GetSet(sql);
            foreach (DataRow i in set.Tables[0].Rows)
            {
                w.ApplicationCode = Convert.ToString(i["ApplicationPath"]).Substring(3).Trim();
            }
            foreach (DataRow i in set.Tables[1].Rows)
            {
                w.url = Convert.ToString(i["ZSURL"]);
            }
            return w;
        }
        #endregion

        #region OA获取更新代办信息数据
        /// <summary>
        /// OA获取更新代办信息数据
        /// </summary>
        /// 
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetWorkFlowNew([FromBody] opinions o)
        {
             var list = new List<Link>();
            
            string sql = @"select ActCode,FromDate,cp1.WorkFlowProcedurePropertyValue as Title from V_WorkFlowAct vwa inner join WorkFlowCaseProperty cp on vwa.CaseCode=cp.WorkFlowCaseCode and cp.WorkFlowProcedurePropertyName='流水号' and cp.WorkFlowProcedurePropertyValue='" + o.opinionConfirm + "' inner join WorkFlowCaseProperty cp1 on vwa.CaseCode=cp1.WorkFlowCaseCode and cp1.WorkFlowProcedurePropertyName='主题' where  vwa.Status in ('End','BlankOut') and vwa.ActUserCode='" + o.opinionDate + "'";
            DataTable set = YDSPHepler.GetSet(sql).Tables[0];
            for (int i = 0; i < set.Rows.Count; i++)
            {
                Link l = new Link();
                l.title = set.Rows[i]["Title"].ToString();
                l.messageUrl = set.Rows[i]["ActCode"].ToString();
                l.picUrl = Convert.ToDateTime(set.Rows[i]["FromDate"]).ToString("yyyyMMddHHmm");
                list.Add(l);

            }
            
            return Json(list);
        }
        #endregion


        #region OA获取SystemUser主要数据
        /// <summary>
        /// OA获取SystemUser主要数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public SystemUsers GetUserVM([FromBody]opinions o)
        {
            string sql = "select UserCode,UserID,UserName from SystemUser where UserCode = '" + o.actUserName + "'      select ZSURL from ZSystemURL where ZSText = '" + o.opinionText + "'       select ZSURL from ZSystemURL where ZSText = '" + o.opinionConfirm + "'   select ZSURL from ZSystemURL where ZSText = '" + o.opinionDate + "'   select ZSURL from ZSystemURL where ZSText = '" + o.taskActorName + "'  select UserCode,UserID,UserName from SystemUser where UserID = '" + o.actUserName + "'";
            DataSet set = YDSPHepler.GetSet(sql);
            SystemUsers user = new SystemUsers();
            foreach (DataRow i in set.Tables[0].Rows)
            {
                user.UserCode = Convert.ToString(i["UserCode"]);
                user.UserID = Convert.ToString(i["UserID"]);
                user.UserName = Convert.ToString(i["UserName"]);
            }
            foreach (DataRow i in set.Tables[1].Rows)
            {
                user.URL = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[2].Rows)
            {
                user.PWD = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[3].Rows)
            {
                user.OpinionDate = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[4].Rows)
            {
                user.TaskActorName = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[5].Rows)
                {
                    if (set.Tables[5].Rows.Count > 0)
                    {
                        user.UserCode = Convert.ToString(i["UserCode"]);
                        user.UserID = Convert.ToString(i["UserID"]);
                        user.UserName = Convert.ToString(i["UserName"]);

                    }
                    
                }
            
            
            return user;
        }
        #endregion

        #region OA根据名称绑定单个地址
        /// <summary>
        /// OA根据名称绑定单个地址
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        [HttpPost]
        public opinions GetSystemURL([FromBody]opinions o)
        {
            opinions opinions = new opinions();
            string sql = "select ZSURL from ZSystemURL where ZSText = '" + o.actUserName + "' select ZSURL from ZSystemURL where ZSText = '" + o.taskActorName + "'  select ZSURL from ZSystemURL where ZSText = '" + o.opinionText + "'   select ZSURL from ZSystemURL where ZSText = '" + o.opinionDate + "'";
            DataSet set = YDSPHepler.GetSet(sql);
            foreach (DataRow i in set.Tables[0].Rows)
            {
                opinions.actUserName = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[1].Rows)
            {
                opinions.taskActorName = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[2].Rows)
            {
                opinions.opinionText = Convert.ToString(i["ZSURL"]);
            }
            foreach (DataRow i in set.Tables[3].Rows)
            {
                opinions.opinionDate = Convert.ToString(i["ZSURL"]);
            }
            
            return opinions;
        }
        #endregion

        #region OA获取单个参数配置
        /// <summary>
        /// OA获取单个参数配置
        /// </summary>
        /// <param name="donglong"></param>
        /// <returns></returns>
        [HttpGet("{donglong}")]
        public string GetDongLong(string donglong)
        {
            string sql = "select * from ZSystemURL where ZSText = '" + donglong + "'";
            DataTable table = YDSPHepler.GetData(sql);
            foreach (DataRow i in table.Rows)
            {
                sql = Convert.ToString(i["ZSURL"]);
            }
            return sql;
        }
        #endregion

        #region OA绑定配置地址
        /// <summary>
        /// OA绑定配置地址
        /// </summary>
        /// <returns></returns>
        public List<SystemUser> GetSystemURLList()
        {
            List<SystemUser> items = new List<SystemUser>();
            string sql = "select * from ZSystemURL";
            DataTable table = YDSPHepler.GetData(sql);
            foreach (DataRow i in table.Rows)
            {
                items.Add(new SystemUser()
                {

                    UserID = Convert.ToString(i["ZSID"]),
                    UserCode = Convert.ToString(i["ZSURL"]),
                    UserName = Convert.ToString(i["ZSText"]),
                    URL = null,
                    PWD = null,
                });
            }
            return items;
        }
        #endregion

        #region OA修改配置地址
        /// <summary>
        /// OA修改配置地址
        /// </summary>
        /// <param name="id"></param>
        /// <param name="s"></param>
        /// <returns></returns>
        [HttpPost]
        public List<SystemUser> UpdateSystemURL([FromBody]List<SystemUser> s)
        {
            try
            {
                foreach (SystemUser item in s)
                {
                    string updateSQL = @"update ZSystemURL set ZSURL = '" + item.UserCode + "',ZSText = '" + item.UserName + "' " +
                        " where ZSID =" + item.UserID;
                    YDSPHepler.ExecuteNonQuery(updateSQL);
                }
                List<SystemUser> items = new List<SystemUser>();
                string sql = "select * from ZSystemURL";
                DataTable table = YDSPHepler.GetData(sql);
                foreach (DataRow i in table.Rows)
                {
                    items.Add(new SystemUser()
                    {

                        UserID = Convert.ToString(i["ZSID"]),
                        UserCode = Convert.ToString(i["ZSURL"]),
                        UserName = Convert.ToString(i["ZSText"]),
                        URL = null,
                        PWD = null,
                    });
                }
                return items;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region OA消息参数
        /// <summary>
        /// OA获取消息参数
        /// </summary>
        /// <returns></returns>
        public List<oamessage> Getoamessagelist()
        {
            List<oamessage> items = new List<oamessage>();
            string sql = "select * from zoamessage where status = '0'";
            DataTable table = YDSPHepler.GetData(sql);
            foreach (DataRow i in table.Rows)
            {
                items.Add(new oamessage()
                {

                    actcode = Convert.ToString(i["actcode"]),
                    usercode = Convert.ToString(i["actusercode"]),
                    userid = Convert.ToString(i["userid"]),
                    fromdate = Convert.ToDateTime(i["fromdate"]).ToString("yyyyMMddHHmm"),
                    type = Convert.ToString(i["type"]),
                    casecode = Convert.ToString(i["casecode"]),
                    omid = Convert.ToString(i["oamessageid"]),
                    flowname = Convert.ToString(i["flowname"]),
                    returndata = null,
                    status = Convert.ToString(i["status"]),



                });
            }
            return items;
        }

        public List<oamessagedb> Getoamessagedblist([FromBody] opinions o)
        {
            List<oamessagedb> items = new List<oamessagedb>();
            string sql = "select au.ActCode,c.CaseCode,c.ApplicationCode,ProcedureName,u.UserName,u.UserCode,a.FromDate,u.UserID as receiver,u1.UserID as creater,cp1.WorkFlowProcedurePropertyValue as title from WorkFlowCaseProperty cp " +
                         " inner join WorkFlowCaseProperty cp1 on cp.WorkFlowCaseCode = cp1.WorkFlowCaseCode and cp1.WorkFlowProcedurePropertyName = '主题'"+
                          " inner join workflowcase c on cp.WorkFlowCaseCode = c.CaseCode" +
                          " inner join WorkFlowAct a on cp.WorkFlowCaseCode = a.CaseCode and a.Status in ('Begin', 'DealWith')" +
                          " inner join WorkFlowActUser au on a.ActCode = au.ActCode" +
                          " inner join SystemUser u on au.UserCode = u.UserCode and u.UserID = '" +o.actUserName+ "'" +
                          " inner join SystemUser u1 on a.FromUserCode = u1.UserCode" +
                          " where cp.WorkFlowProcedurePropertyName = '流水号' and cp.WorkFlowProcedurePropertyValue = '" +o.opinionText +"'";
            DataTable table = YDSPHepler.GetData(sql);
            foreach (DataRow i in table.Rows)
            {
                items.Add(new oamessagedb()
                {

                    CaseCode = Convert.ToString(i["CaseCode"]),
                    ApplicationCode = Convert.ToString(i["ApplicationCode"]),
                    ProcedureName = Convert.ToString(i["ProcedureName"]),
                    FromDate = Convert.ToDateTime(i["fromdate"]).ToString("yyyy-MM-dd HH:mm"),
                    UserName = Convert.ToString(i["UserName"]),
                    UserCode = Convert.ToString(i["UserCode"]),
                    receiver = Convert.ToString(i["receiver"]),
                    creater = Convert.ToString(i["creater"]),
                    title = Convert.ToString(i["title"]),
                    ActCode = Convert.ToString(i["ActCode"]),



                });
            }
            return items;
        }

        #endregion

        #region OA消息更新日志
        /// <summary>
        /// OA消息更新日志
        /// </summary>


        [HttpPost]
        public List<oamessage> Updateoamessage([FromBody]List<oamessage> s)
        {
            try
            {
                foreach (oamessage item in s)
                {
                    string updatesql = @" update zoamessage set status = '1' where oamessageid = '" + item.omid + "'";
                    YDSPHepler.ExecuteNonQuery(updatesql);
                }
                    

                return null;
            }
            catch(Exception)
            {
                return null;
            }
        }
        #endregion

        #region 发送审批流消息体
        
        public List<sendworkflowmessage> Getsendmessagelist()
        {
            List<sendworkflowmessage> items = new List<sendworkflowmessage>();
            string sql = "select * from zzoamessage where status='begin' and issend='0' and isdelete='0' union all select* from zzoamessage where status = 'end' and issend = '1' and isdelete = '0' union all select* from zzoamessage where issend = '1' and isdelete = '1' ";
            DataTable table = YDSPHepler.GetData(sql);
            foreach (DataRow i in table.Rows)
            {
                items.Add(new sendworkflowmessage()
                {

                    flowid = Convert.ToString(i["flowid"]),
                    requestname = Convert.ToString(i["requestname"]),
                    nodename = Convert.ToString(i["nodename"]),
                    pcurl = "",
                    appurl = "",
                    creator = Convert.ToString(i["creator"]),
                    createdatetime = Convert.ToDateTime(i["createdatetime"]).ToString("yyyy-MM-dd HH:mm:ss"),
                    receiver = Convert.ToString(i["receiver"]),
                    receivedatetime = "",
                    status = Convert.ToString(i["status"]),
                    issend = Convert.ToString(i["issend"]),
                    isdelete = Convert.ToString(i["isdelete"]),
                    flownumber = Convert.ToString(i["flownumber"]),
                    actcode = Convert.ToString(i["actcode"]),
                    casecode = Convert.ToString(i["casecode"]),
                    applicantion = Convert.ToString(i["applicantion"]),
                    receiveusercode = Convert.ToString(i["receiveusercode"]),
                    workflowname = Convert.ToString(i["workflowname"]),
                    receiveusername = Convert.ToString(i["receiveusername"]),
                });
            }
            return items;
        }

        #endregion

        #region 更新审批流消息
        /// <summary>
        /// 1更新为待办 2 更新为已办 3 更新为删除
        /// </summary>


        [HttpPost]
        public List<sendworkflowmessage> updatesendmessagelist([FromBody] List<sendworkflowmessage> s)
        {
            try
            {
                foreach (sendworkflowmessage item in s)
                {
                    string updatesql = "";
                    if (item.isdelete == "1")
                    {
                        updatesql = @" update zzoamessage set issend = '1' where flowid = '" + item.flowid + "'"
                        + " update zzoamessage set pcurl = '" + item.pcurl + "' where flowid = '" + item.flowid + "'"
                         + " update zzoamessage set appurl = '" + item.appurl + "' where flowid = '" + item.flowid + "'";
                    }
                    if (item.isdelete == "2")
                    {
                        updatesql = @" update zzoamessage set issend = '2' where flowid = '" + item.flowid + "'";
                    }
                    if (item.isdelete == "3")
                    {
                        updatesql = @" update zzoamessage set isdelete = '2' where flowid = '" + item.flowid + "'";
                    }
                    YDSPHepler.ExecuteNonQuery(updatesql);
                }


                return null ;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

    }
    public class opinions
    {
        public string taskActorName { get; set; }
        public string actUserName { get; set; }
        public string opinionDate { get; set; }
        public string opinionConfirm { get; set; }
        public string opinionText { get; set; }
    }
    /// <summary>
    /// SystemUser视图模型
    /// </summary>
    public class SystemUser
    {
        public string UserCode { get; set; }
        public string UserID { get; set; }
        public string UserName { get; set; }
        public string URL { get; set; }
        public string PWD { get; set; }
    }
    /// <summary>
    /// SystemUser视图模型
    /// </summary>
    public class SystemUsers
    {
        public string UserCode { get; set; }
        public string UserID { get; set; }
        public string UserName { get; set; }
        public string URL { get; set; }
        public string PWD { get; set; }
        public string OpinionDate { get; set; }
        public string TaskActorName { get; set; }
    }
    /// <summary>
    /// WorkFlowCaseVM视图模型
    /// </summary>
    public class WorkFlowCaseVM
    {
        public string ApplicationCode { get; set; }
        public string url { get; set; }
    }
    /// <summary>
    /// appId及appSecret
    /// </summary>
    public class app
    {
        public string appid { get; set; }
        public string appsecret { get; set; }
    }
    public class OapiMessageSendToConversationRequest
    {
        public string userid_list { get; set; }
        public string agent_id { get; set; }
        public bool to_all_user { get; set; }
        public JObject msg { get; set; }
    }
    public class msgtypeURL
    {
        public string msgtype { get; set; }
        public Link link { get; set; } = new Link();
    }
    public class Link
    {
        public string messageUrl { get; set; }
        public string picUrl { get; set; }
        public string title { get; set; }
        public string text { get; set; }
    }

    public class WorkFlowFiles
    {
        public string filename { get; set; }
        public string filecontent { get; set; }
        public string filecontenttype { get; set; }
        public string AttachMentCode { get; set; }
        


    }

    public class oamessage
    {
        public string actcode { get; set; }
        public string usercode { get; set; }
        public string userid { get; set; }
        public string fromdate { get; set; }
        public string type { get; set; }
        public string status { get; set; }
        public string casecode { get; set; }
        public string omid { get; set; }
        public string flowname { get; set; }
        public string returndata { get; set; }
        



    }

    public class oamessagedb
    {
        public string CaseCode { get; set; }
        public string ApplicationCode { get; set; }
        public string ProcedureName { get; set; }
        public string UserName { get; set; }
        public string UserCode { get; set; }
        public string FromDate { get; set; }
        public string receiver { get; set; }
        public string creater { get; set; }
        public string title { get; set; }
        public string ActCode { get; set; }

    

    }

    public class sendworkflowmessage
    {
        public string flowid { get; set; }
        public string requestname { get; set; }
        public string nodename { get; set; }
        public string pcurl { get; set; }
        public string appurl { get; set; }
        public string creator { get; set; }
        public string createdatetime { get; set; }
        public string receiver { get; set; }

        public string receivedatetime { get; set; }
        public string status { get; set; }
        public string issend { get; set; }
        public string isdelete { get; set; }
        public string flownumber     { get; set; }
        public string actcode { get; set; }
        public string casecode { get; set; }
        public string applicantion { get; set; }

        public string receiveusercode { get; set; }
        public string workflowname { get; set; }
        public string receiveusername { get; set; }
    }
}
