using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.tel
{
    public class WorkcalendarController : BaseController
    {

        private BLL.T_Sys_WorkTimes workTimesBLL = new BLL.T_Sys_WorkTimes();
        private readonly BLL.T_Sys_Department deptBLL = new BLL.T_Sys_Department();
        // 获取工作日历
        public ActionResult GetCalendarList(string strdate)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = "";
                try
                {
                    if (strdate != null && strdate.Trim() != "")
                    {
                        BLL.T_Sys_WorkCalendar WorkCalendar = new BLL.T_Sys_WorkCalendar();
                        sql = "  DATEDIFF (m,'" + strdate + "',F_DateId )=0 ";
                        List<Model.T_Sys_WorkCalendar> modelList = WorkCalendar.GetModelList(sql);
                        if (modelList.Count > 0)
                        {
                            res = Success("日历加载成功", modelList);
                        }
                        else
                        {
                            res = Error("日历加载失败");
                        }
                    }
                    else
                    {
                        res = Error("获取参数失败");
                    }
                }
                catch (Exception ex)
                {
                    res = Error("获取日历失败,错误：" + ex.Message);
                }
            }
            return res;
        }

        //设置(非)工作日
        public ActionResult Setworkingday(string date)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                if (date != null && date != "")
                {
                    DateTime dt = new DateTime();
                    if (DateTime.TryParse(date, out dt))
                    {
                        Model.T_Sys_WorkCalendar wc = new BLL.T_Sys_WorkCalendar().GetModel(dt);
                        if (wc != null)
                        {
                            if (wc.F_EditFlag == false) //没有修改过
                            {
                                if (wc.F_WorkingFlag)
                                {
                                    wc.F_WorkingFlag = false;
                                }
                                else
                                {
                                    wc.F_WorkingFlag = true;
                                }
                                wc.F_EditFlag = true;
                            }
                            else//修改过 
                            {
                                if (wc.F_WorkingFlag)
                                {
                                    wc.F_WorkingFlag = false;
                                }
                                else
                                {
                                    wc.F_WorkingFlag = true;
                                }
                                wc.F_EditFlag = false;
                            }
                            bool rvalue = new BLL.T_Sys_WorkCalendar().Update(wc);
                            if (rvalue)
                            {
                                res = Success("设置成功！");
                            }
                            else
                            {
                                res = Error("设置失败！");
                            }
                        }
                        else
                        {
                            res = Error("获取对象失败");
                        }
                    }
                    else
                    {
                        res = Error("日期格式不正确");
                    }
                }
                else
                {
                    res = Error("获取参数失败");
                }

            }
            return res;
        }

        //获取上班时间段
        public ActionResult GetTimesList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = "";
                DataTable dt = new DataTable();


                string keyword = HttpUtility.UrlDecode(RequestString.GetQueryString("keyword"));
                if (keyword.Trim() != "" && keyword != "undefined")
                {
                    sql += " and (convert(varchar,F_WorkEndTimes,120) like '%" + keyword.Trim() + "%' or convert(varchar,F_WorkEndTimes,120) like '%" + keyword.Trim()
                        + "%' or F_TimeName like '%" + keyword.Trim() + "%'or F_Remark like '%" + keyword.Trim() + "%')";
                }

                var depts = deptBLL.DataTableToListForLevel(DbHelperSQL.Query($"with cte(F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,lvl) as( select F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,0 lvl from T_Sys_Department where F_DeptId={CurrentUser.UserData.F_DeptId} union all select dept.F_DeptId,dept.F_DeptName,dept.F_ParentId,dept.F_DeptCode,dept.F_Layer,lvl+1 from T_Sys_Department dept inner join cte on dept.F_DeptId = cte.F_ParentId) select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,lvl from  cte ").Tables[0]);
                var deptCompany = depts.Where(x => x.Layer == 1).OrderBy(x => x.Level).FirstOrDefault();
                sql += $"  and   F_DeptId={deptCompany?.DeptId ?? CurrentUser.UserData.F_DeptId}   ";


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

                if (strpageindex.Trim() != "")
                {
                    pageindex = Convert.ToInt32(strpageindex);
                }

                if (strpagesize.Trim() != "")
                {
                    pagesize = Convert.ToInt32(strpagesize);
                }
                int recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                    "T_Sys_WorkTimes",
                    "F_Id",
                    "*",
                    sql,
                    "ORDER BY F_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

                var obj = new
                {
                    state = "success",
                    message = "成功",
                    rows = dt,
                    total = recordCount
                };

                res = Content(obj.ToJson());

            }
            return res;
        }

        //获取某一条时间段信息
        public ActionResult GetTimes(string id)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                if (id != null && id.Trim() != "")
                {
                    BLL.T_Sys_WorkTimes dBLL = new BLL.T_Sys_WorkTimes();
                    Model.T_Sys_WorkTimes dModel = dBLL.GetModel(int.Parse(id.Trim()));
                    if (dModel != null)
                    {
                        res = Success("获取成功", dModel);
                    }
                    else
                    {
                        res = Error("获取失败");
                    }
                }
                else
                {
                    res = Error("获取参数失败");
                }


            }
            return res;
        }

        //添加/修改上班时间段
        public ActionResult AddTimes(string workid, string workstart, string workend, string timename, string remark)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        res = Error("操作失败");
                        if (workid != null && workid != "")
                        {
                            int id = 0;
                            if (int.TryParse(workid, out id))
                            {
                                BLL.T_Sys_WorkTimes dBLL = new BLL.T_Sys_WorkTimes();
                                Model.T_Sys_WorkTimes dModel = dBLL.GetModel(id);
                                if (dModel != null)
                                {
                                    if (!string.IsNullOrWhiteSpace(workstart.Trim()))
                                    {
                                        DateTime dt1 = new DateTime();
                                        if (DateTime.TryParse(workstart.Trim(), out dt1))
                                            dModel.F_WorkStartTimes = Convert.ToDateTime(dt1.ToString("1900-01-01 HH:mm:ss"));
                                    }
                                    if (!string.IsNullOrWhiteSpace(workend.Trim()))
                                    {
                                        DateTime dt1 = new DateTime();
                                        if (DateTime.TryParse(workend.Trim(), out dt1))
                                            dModel.F_WorkEndTimes = Convert.ToDateTime(dt1.ToString("1900-01-01 HH:mm:ss"));
                                    }
                                    if (!string.IsNullOrWhiteSpace(timename.Trim()))
                                    {
                                        dModel.F_TimeName = timename.Trim();
                                    }
                                    if (!string.IsNullOrWhiteSpace(remark.Trim()))
                                    {
                                        dModel.F_Remark = remark.Trim();
                                    }

                                    bool b = dBLL.Update(dModel);
                                    if (b)
                                    {
                                        res = Success("编辑成功");
                                    }
                                    else
                                    {
                                        res = Error("编辑失败");
                                    }
                                }
                            }
                        }
                        else
                        {
                            Model.T_Sys_WorkTimes _model = new Model.T_Sys_WorkTimes();
                            if (!string.IsNullOrWhiteSpace(workstart.Trim()))
                            {
                                DateTime dt2 = new DateTime();
                                if (DateTime.TryParse("1900-01-01 " + workstart.Trim(), out dt2))
                                    _model.F_WorkStartTimes = Convert.ToDateTime(dt2.ToString("1900-01-01 HH:mm:ss"));
                            }
                            if (!string.IsNullOrWhiteSpace(workend.Trim()))
                            {
                                DateTime dt2 = new DateTime();
                                if (DateTime.TryParse("1900-01-01 " + workend.Trim(), out dt2))
                                    _model.F_WorkEndTimes = Convert.ToDateTime(dt2.ToString("1900-01-01 HH:mm:ss"));
                            }
                            if (!string.IsNullOrWhiteSpace(timename.Trim()))
                            {
                                _model.F_TimeName = timename.Trim();
                            }
                            if (!string.IsNullOrWhiteSpace(remark.Trim()))
                            {
                                _model.F_Remark = remark.Trim();
                            }
                            var depts = deptBLL.DataTableToListForLevel(DbHelperSQL.Query($"with cte(F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,lvl) as( select F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,0 lvl from T_Sys_Department where F_DeptId={CurrentUser.UserData.F_DeptId} union all select dept.F_DeptId,dept.F_DeptName,dept.F_ParentId,dept.F_DeptCode,dept.F_Layer,lvl+1 from T_Sys_Department dept inner join cte on dept.F_DeptId = cte.F_ParentId) select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,lvl from  cte ").Tables[0]);
                            var deptCompany = depts.Where(x => x.Layer == 1).OrderBy(x => x.Level).FirstOrDefault();
                            _model.F_DeptId = deptCompany?.DeptId ?? CurrentUser.UserData.F_DeptId;

                            int b = new BLL.T_Sys_WorkTimes().Add(_model);
                            if (b > 0)
                            {
                                res = Success("添加成功");
                            }
                            else
                            {
                                res = Error("添加失败");
                            }
                        }
                    }
                }

            }
            return res;
        }

        //删除上班时间段
        public ActionResult DelTimes(string[] ids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                if (ids != null && ids.Length > 0)
                {
                    string idd = " ";
                    foreach (string str in ids)
                    {
                        idd += "'" + str + "',";
                    }
                    if (new BLL.T_Sys_WorkTimes().DeleteList(idd.TrimEnd(',')))
                    {
                        res = Success("删除成功");
                    }
                    else
                        res = Error("删除失败");
                }
                else
                {
                    res = Error("请选择要删除的记录");
                }

            }
            return res;
        }

        [Authority]
        public ActionResult GetIsOnDutyTime()
        {
            var deptId = CurrentUser.UserData.F_DeptId;
            var list = workTimesBLL.DataTableToList(workTimesBLL.GetList($" F_DeptId={deptId} ").Tables[0]);
            var isOnDutyTime = true;
            var now = DateTime.Now.TimeOfDay;
            foreach (var item in list)
            {
                var start = item.F_WorkStartTimes == null ? DateTime.MinValue : Convert.ToDateTime(item.F_WorkStartTimes);
                var end = item.F_WorkEndTimes == null ? DateTime.MinValue : Convert.ToDateTime(item.F_WorkEndTimes);

                var startTime = start.TimeOfDay;
                var endTime = end.TimeOfDay;
                if (now > startTime && now < endTime)
                {
                    isOnDutyTime = true;
                    break;
                }
                continue;
            }
            if (isOnDutyTime)
                return Success("");
            return Error("未在正常上班时间，无法拨出电话");
        }
    }
}