using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Model;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers
{
    public class InternalMessagesController : BaseController
    {
        BLL.T_SMS_InternalMessages bll = new BLL.T_SMS_InternalMessages();
        /// <summary>
        /// 获取所有列表 分页
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllList()
        {
            DataTable dt = new DataTable();
            string SMS_Title = HttpUtility.UrlDecode(RequestString.GetQueryString("title"));
            string SMS_ReceiveUserCode = HttpUtility.UrlDecode(RequestString.GetQueryString("receiveUserCode"));
            string SMS_SendUserCode = HttpUtility.UrlDecode(RequestString.GetQueryString("sendUserCode"));
            string SMS_Content = HttpUtility.UrlDecode(RequestString.GetQueryString("content"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));


            int SMS_IsRead = RequestString.GetInt("IsRead", -1);


            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = string.Empty;
            if (SMS_Title.Trim() != "")
            {
                sql += " and SMS_Title like '%" + SMS_Title + "%'";
            }
            if (SMS_ReceiveUserCode.Trim() != "")
            {
                sql += " and SMS_ReceiveUserCode = '" + SMS_ReceiveUserCode + "'";
            }
            else if (User .F_RoleCode !="GLY")
            {
                sql += " and SMS_ReceiveUserCode = '" + User .F_UserCode  + "'";
            }

            if (SMS_SendUserCode.Trim() != "")
            {
                sql += " and SMS_SendUserCode = '" + SMS_SendUserCode + "'";
            }
            if (SMS_Content.Trim() != "")
            {
                sql += " and SMS_Content like '%" + SMS_Content + "%'";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,SMS_SendUserCode,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,SMS_SendUserCode,'" + strendtime + "')>=0   ";
            }
            if (SMS_IsRead > -1)
            {
                sql += " and SMS_IsRead = '" + SMS_IsRead + "'";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                    "T_SMS_InternalMessages",
                    "SMS_Id",
                    "*",
                    sql,
                    "ORDER BY SMS_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取前几条列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTopList()
        {
            DataTable dt = new DataTable();
            string strWhere = string.Empty;
            int Top = RequestString.GetInt("top", 5);
            string SMS_ReceiveUserCode = RequestString.GetQueryString("receiveUserCode");
            if (SMS_ReceiveUserCode.Trim() != "")
            {
                strWhere += " and SMS_ReceiveUserCode = '" + SMS_ReceiveUserCode + "'";
            }
            dt = bll.GetList(Top, strWhere, " SMS_Order,SMS_SendTime ").Tables[0];
            var obj = new
            {
                rows = dt,
                total = Top
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取一条详细信息
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        public ActionResult GetInfo(string infoid)
        {
            if (infoid != null && infoid.Trim() != "")
            {
                Model.T_SMS_InternalMessages model = bll.GetModel(int.Parse(infoid.Trim()));

                if (model != null)
                {
                    if (model.SMS_IsRead == 0)
                    {
                        model.SMS_IsRead = 1;
                        model.SMS_ReadTime = DateTime.Now;
                        bool b = bll.Update(model);
                        if (b)
                        {
                            return Success("获取成功", model);
                        }
                        else
                        {
                            return Error("获取失败，无更新权限");
                        }
                    }
                    else
                    {
                        return Success("获取成功", model);
                    }
                }
                else
                {
                    return Error("获取失败");
                };
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 保存信息
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveInfo()
        {
            int id = RequestString.GetInt("id", 0);
            string SMS_Title = RequestString.GetFormString("title");
            string SMS_ReceiveUserCode = RequestString.GetFormString("receiveUserCode");
            string SMS_SendUserCode = RequestString.GetFormString("sendUserCode");
            string SMS_Content = RequestString.GetFormString("content");
            int SMS_IsDelete = RequestString.GetInt("isDelete", 0);
            int SMS_IsRead = RequestString.GetInt("isRead", 0);
            int SMS_Order = RequestString.GetInt("order", 0);
            int SMS_IsTop = RequestString.GetInt("isTop", 0);
            int SMS_Type = RequestString.GetInt("smstype", 0);

            if (!string.IsNullOrWhiteSpace(SMS_Title) || !string.IsNullOrWhiteSpace(SMS_ReceiveUserCode) || !string.IsNullOrWhiteSpace(SMS_ReceiveUserCode))
            {
                Model.T_SMS_InternalMessages model = new Model.T_SMS_InternalMessages();
                if (id == 0)
                {
                    model.SMS_Title = SMS_Title;
                    model.SMS_Content = SMS_Content;
                    model.SMS_ReceiveUserCode = SMS_ReceiveUserCode;
                    model.SMS_SendUserCode = SMS_SendUserCode;
                    model.SMS_IsRead = SMS_IsRead;
                    model.SMS_SendTime = DateTime.Now;
                    model.SMS_IsDelete = 0;
                    model.SMS_Order = SMS_Order;
                    model.SMS_IsTop = SMS_IsTop;
                    model.SMS_Type = SMS_Type;
                    int n = bll.Add(model);
                    if (n > 0)
                    {
                        return Success("添加成功", n);
                    }
                    else
                    {
                        return Error("添加失败");
                    }
                }
                else
                {
                    model = bll.GetModel(id);
                    if (model != null)
                    {
                        model.SMS_Id = id;
                        model.SMS_Title = SMS_Title;
                        model.SMS_Content = SMS_Content;
                        model.SMS_ReceiveUserCode = SMS_ReceiveUserCode;
                        model.SMS_SendUserCode = SMS_SendUserCode;
                        model.SMS_IsRead = SMS_IsRead;
                        model.SMS_SendTime = model.SMS_SendTime;
                        model.SMS_IsDelete = 0;
                        model.SMS_Order = SMS_Order;
                        model.SMS_IsTop = SMS_IsTop;
                        model.SMS_Type = SMS_Type;
                        if (bll.Update(model))
                        {
                            return Success("修改成功");
                        }
                        else
                        {
                            return Error("修改失败");
                        }
                    }
                    return Error("信息不存在");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelInfo(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (bll.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("获取参数失败");
            }
        }
        public ActionResult GetCount()
        {
            var modelliset = new BLL.T_SMS_InternalMessages().GetModelList("SMS_ReceiveUserCode='" + User.F_UserCode + "' and" +
                " SMS_IsDelete=0 and SMS_IsRead=0 ");
            int IsRead = 0;
            if (modelliset.Count() > 0)
                IsRead = 1;
            var obj = new
            {
                state = "success",
                message = "成功",
                IsRead = IsRead
            };
            return Content(obj.ToJson());
        }

        public ActionResult GetButtons(int SMS_Id=0)
        {
            if (SMS_Id <= 0)
                return Error("请选择消息");
            DataTable datatable=new DataTable ();
            var SMS = new BLL.T_SMS_InternalMessages().GetModel(SMS_Id);
            List<Button> Buttons = new List<Button>();
            if (SMS != null)
            {
                if (SMS.SMS_Type != 4 && SMS.SMS_Type != 2)
                {
                    var dt = DbHelperSQL.Query
                        ($"select *from  T_Wo_CommonBase  where F_WoCode='{SMS.F_WorkOrderId }'")
                        .Tables[0];

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        if (dt.Rows[0]["F_CreateUser"].ToString() == User.F_UserCode)
                        {
                            datatable = WorkOrderBase.SetOtherField(dt, MENUENUM.我的提交, User.F_UserCode, User.F_RoleId);
                        }
                        else if (SMS.SMS_Type == 0)
                        {
                            datatable = WorkOrderBase.SetOtherField(dt, MENUENUM.工单列表, User.F_UserCode, User.F_RoleId);
                        }
                        else if (SMS.SMS_Type == 1)
                        {
                            datatable = WorkOrderBase.SetOtherField(dt, MENUENUM.报修列表, User.F_UserCode, User.F_RoleId);
                        }
                        else if (SMS.SMS_Type == 3)
                        {
                            datatable = WorkOrderBase.SetOtherField(dt, MENUENUM.调度工单列表, User.F_UserCode, User.F_RoleId);
                        }
                    }
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = datatable

                    };
                    return Content(obj.ToJson());
                }
                else
                {
                    if (SMS.SMS_Type == 2)
                    {
                        var model = new Bll.T_Car_WorkOrder().GetModelByCode(SMS.F_WorkOrderId);
                        string role="0";
                        if (model .F_CreateUser == User.F_RoleCode)
                        {
                            role = "1";
                        }
                        int identity = 0;
                        if (User.F_UserCode == model .F_ProposerCode)
                        {
                            identity = 1;
                        }
                        var button = GetButton(model.F_State.Value, role, identity);
                        if (model.F_State == 0)
                            button.Add(distribution());
                        if (model != null)
                        {
                            var obj = new
                            {
                                state = "success",
                                message = "成功",
                                allButtons = button,
                                model = model
                            };
                            return Content(obj.ToJson());
                        }
                    }
                    else
                    {
                        var model = new BLL.T_Car_AssignWorkOrder ().GetModel (int .Parse ( SMS.F_WorkOrderId));
                        if (model != null)
                        {
                            var obj = new
                            {
                                state = "success",
                                message = "成功",
                                allButtons = GetButton1(model.F_State.Value, User.F_RoleCode),
                                model = model
                            };
                            return Content(obj.ToJson());
                        }
                    }
                }
            }
            else
            {
                return Error("消息不存在");
            }

            
            return Success("获取成功", Buttons);
              
        }
        /// <summary>
        /// 按钮
        /// </summary>
        public class button
        {
            public int key { get; set; }
            public string value { get; set; }
            public button(int _key, string _value)
            {
                key = _key;
                value = _value;
            }
        }
        public static button distribution()
        {
            return new button(1, "分配");
        }
        public static button withdraw()
        {
            return new button(2, "撤回");
        }
        public static button back()
        {
            return new button(3, "退回");
        }
        public static button receiving()
        {
            return new button(4, "接单");
        }
        public static button start()
        {
            return new button(5, "发车");
        }
        public static button end()
        {
            return new button(6, "抵达");
        }
        public static button evaluate()
        {
            return new button(7, "评价");
        }
        public static button edit()
        {
            return new button(8, "编辑");
        }
        public static button delete()
        {
            return new button(8, "删除");
        }
        public List<button> GetButton(int state, string role,int identity=0)
        {
            List<button> buttons = new List<button>();
                    
            if (role =="1")
            {
                switch (state)
                {
                    case -1:
                        buttons.Add(edit());
                        buttons.Add(delete());

                        break;
                    case 0:
                        buttons.Add(withdraw());

                        break;
                    case 7:
                        if (identity==1)
                        buttons.Add(evaluate());
                        break;

                }
            }
          
            return buttons;
        }


        public List<button> GetButton1(int state, string role)
        {
            List<button> buttons = new List<button>();
            switch (state)
            {
                case 0:
                    if (role == "SJ")
                    {
                        buttons.Add(receiving());
                    }
                    break;
                case 2:
                    if (role == "SJ")
                    {
                        buttons.Add(start());
                    }
                    break;
                case 4:
                    if (role == "SJ")
                    {
                        buttons.Add(end());
                    }
                    break;

            }
            return buttons;
        }
        private string FrontURL = ConfigHelper.GetValue("FrontURL");
      
        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="receiveUserCode"></param>
        /// <param name="sendUserCode"></param>
        /// <returns></returns>
        public   bool AddInternalMessagesInfo(string title, string content, string receiveUserCode, string sendUserCode, EnumSmsType smstype = 0, int smstop = 0
            , string workorderid = "",string workordercode="")
        {
            if (!string.IsNullOrWhiteSpace(title) || !string.IsNullOrWhiteSpace(receiveUserCode) || !string.IsNullOrWhiteSpace(sendUserCode))
            {
                var usermoblie = new Bll.T_Sys_UserAccount().GetModel(receiveUserCode);
                if (usermoblie==null )
                 return false;
                Model.T_SMS_InternalMessages model = new Model.T_SMS_InternalMessages();
                model.SMS_Title = title;//标题
                model.SMS_Content = content;//内容
                model.SMS_ReceiveUserCode = receiveUserCode;//接收人
                model.SMS_SendUserCode = sendUserCode;//发送人
                model.SMS_IsRead = 0;//是否阅读
                model.SMS_SendTime = DateTime.Now;
                model.SMS_IsDelete = 0;
                model.SMS_Order = 0;//排序
                model.SMS_IsTop = smstop;
                model.SMS_Type =(int ) smstype;//状态
                model.F_WorkOrderId = workorderid;
                if (string .IsNullOrEmpty (workordercode))
                    model.F_WorkOrderCode  = workorderid;
                else
                    model.F_WorkOrderCode = workordercode;

                int n = bll.Add(model);
                if (n > 0)
                {
                    WebClient web = new WebClient();
                    web.Encoding = Encoding.UTF8;
                    try
                    {
                        string Dataurl = web.DownloadString(FrontURL + $"PushMessage/Push?Title={title}&content={content}&usercode={receiveUserCode}");
                        // PushMessageController.PushApp(title, content, receiveUserCode);
                    }
                   catch(Exception  e)
                    {
                        LogHelper.Error("Push"+e.Message);
                    }
                    try
                    {
                        if (!string.IsNullOrEmpty(usermoblie.F_Telephone))
                        {
                          //  LogHelper.Error("Ding" + usermoblie.F_Telephone);
                            var userid =HttpMethods .HttpGet (FrontURL + "Home/DingTalkMessagesInfoByMobile?mobile=" + usermoblie.F_Telephone.Trim ()+"&content="+ content);// DingTalkHelper.GetUserIdByMobile(usermoblie.F_Telephone);
                           // JObject jo = (JObject)JsonConvert.DeserializeObject(userid);

                            JObject task_id = (JObject)JsonConvert.DeserializeObject(userid);
                            model.SMS_Id = n;
                            model.F_Task_id = task_id["message"].ToString();
                            bll.Update(model);
                        }
                    }
                    catch(Exception e)
                    {
                        LogHelper.Error("Ding" + e.Message);
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 通过钉钉更新是否阅读
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        [AllowAnonymous]
        public ActionResult DingTalkGetMessage()
        {

            var dicvalue = new Bll.T_Sys_DictionaryValue().
              GetModelList("F_DictionaryFlag='DDRS' and F_State=1");
            if (dicvalue!=null && dicvalue.Count >0)
            {
                if (dicvalue[0].F_Name =="1")
                {
                    var sql = " SMS_IsDelete=0 and SMS_IsRead=0 ";
                    sql += " and F_Task_id is not null and datediff(HH,SMS_SendTime,getdate())<=24";
                    var msglist = bll.GetModelList(sql + " order by SMS_IsTop desc,SMS_SendTime  desc");
                    if (msglist != null && msglist.Count > 0)
                    {
                        foreach (var it in msglist)
                        {
                            var usermoblie = new Bll.T_Sys_UserAccount().GetModel(it.SMS_ReceiveUserCode);
                            if (usermoblie == null)
                                continue;
                            if (!string.IsNullOrEmpty(usermoblie.F_Telephone))
                            {
                                var userid = DingTalkHelper.GetUserIdByMobile(usermoblie.F_Telephone);
                                if (!string.IsNullOrEmpty(it.F_Task_id))
                                {
                                    int task_id = DingTalkHelper.GetMessage(it.F_Task_id);
                                    if (task_id == 1)
                                    {
                                        it.SMS_IsRead = 1;
                                        it.SMS_ReadTime = DateTime.Now;
                                        bll.Update(it);
                                    }
                                    else
                                        continue;
                                }
                            }
                        }
                    }
                }
            }
            return Success("成功");
        }
        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult UpdateState(string[] ids, int state = 0)
        {
            if (User == null)
                return Error("权限不足！");
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                string sj = "null";
                if (state == 1)
                {
                    sj = "getdate()";
                }
                string sql = "update T_SMS_InternalMessages set SMS_IsRead=" + state + ",SMS_ReadTime=" + sj + " where SMS_Id in(" + idd.TrimEnd(',') + ")";
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        return Success("更新成功");
                    }
                    else
                    {
                        return Error("更新失败");
                    }
                }
                else
                {
                    return Error("请选择记录");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 获取消息提醒
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMsg(int smstype = 0)
        {


            if (User != null)
            {
               var sql = " SMS_IsDelete=0 and SMS_IsRead=0 ";
                sql += " and SMS_ReceiveUserCode='" + User.F_UserCode + "'";
               if (smstype > 0)
                   sql += " and SMS_Type="+ smstype;
               var msglist = bll.GetModelList(sql + " order by SMS_IsTop desc,SMS_SendTime  desc");
                return Success("获取消息成功", msglist);
               // return Success("获取成功");
            }
            return Error("权限不足");
        }
    }
}