using CallCenter.Utility;
using CallCenterApi.Common;
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
    {
        // 获取工作日历
        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"));
            string holidayscode = HttpUtility.UrlDecode(RequestString.GetQueryString("holidayscode"));
            if (keyword.Trim() != "" && keyword != "undefined")
            {
                sql += " and (F_StartDate like '%" + keyword.Trim() + "%' or F_EndDate like '%" + keyword.Trim()
                    + "%' or F_Name like '%" + keyword.Trim() + "%'or F_Remark like '%" + keyword.Trim() + "%')";
            }
            if (!string.IsNullOrEmpty(holidayscode))
                sql += " and F_HolidaysCode = '" + holidayscode.Trim() + "' ";

            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);
            List<Model.T_Sys_WorkTimes> modlelist = new BLL.T_Sys_WorkTimes().DataTableToList(dt);
            List<Model.T_Sys_WorkTimes> Input = modeltooip(modlelist);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = Input,
                total = recordCount
            };

            return Content(obj.ToJson());

            //}
            //return res;
        }
        private List<Model.T_Sys_WorkTimes> modeltooip(List<Model.T_Sys_WorkTimes> model1)
        {
            List<Model.T_Sys_WorkTimes> WorkTimes = new List<Model.T_Sys_WorkTimes>();
            foreach (var it in model1)
            {
                string msg = "";
                if (!string .IsNullOrEmpty (it .F_GroupCode))
                {
                    var GroupIDList = it.F_GroupCode.Split('|');
                    if (GroupIDList.Length > 0)
                    {
                        foreach (var iv in GroupIDList)
                        {
                            Model.T_Sys_SeatGroup sm = new BLL.T_Sys_SeatGroup().GetModel(iv);
                            if (sm != null)
                            {
                                if (msg!="")
                                {
                                    msg += "|" + sm.F_ZXZName;
                                }
                                else
                                {
                                    msg += sm.F_ZXZName;
                                }
                                
                            }
                        }
                    }
                    it.F_GroupCodeName = msg;
                    WorkTimes.Add(it);
                }
               
            }
            return WorkTimes;
        }
            //获取某一条时间段信息
            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()));
                    List<Model.T_Sys_WorkTimes> t_Sys_WorkTimes = new List<Model.T_Sys_WorkTimes>();
                    t_Sys_WorkTimes.Add(dModel);
                    List<Model.T_Sys_WorkTimes> Input = modeltooip(t_Sys_WorkTimes);
                    if (dModel != null)
                    {
                        res = Success("获取成功", Input[0]);
                    }
                    else
                    {
                        res = Error("获取失败");
                    }
                }
                else
                {
                    res = Error("获取参数失败");
                }


            }
            return res;
        }

        //添加/修改上班时间段
        public ActionResult AddTimes(string workid, string workstart, string workend, string timename, string remark, string groupcode,string holidayscode = "")
        {
            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)
                    {
                        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)
                                {
                                    dModel.F_StartDate = workstart;
                                    dModel.F_EndDate = workend;
                                    dModel.F_HolidaysCode = holidayscode;
                                    dModel.F_Name = timename.Trim();
                                    dModel.F_Remark = remark.Trim();
                                    dModel .F_GroupCode = groupcode.Trim();
                                    bool b = dBLL.Update(dModel);
                                    if (b)
                                    {
                                        return Success("编辑成功");
                                    }
                                    else
                                    {
                                        return Error("编辑失败");
                                    }
                                }
                            }
                        }
                        else
                        {
                            Model.T_Sys_WorkTimes _model = new Model.T_Sys_WorkTimes();
                            _model.F_StartDate = workstart;
                            _model.F_EndDate = workend;
                            _model.F_Name = timename.Trim();
                            _model.F_Remark = remark.Trim();
                            _model.F_HolidaysCode = holidayscode.Trim();
                            _model.F_GroupCode = groupcode.Trim();
                            _model.F_CreateUser = ua.F_UserCode;
                            _model.F_CreateTime = DateTime.Now;

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

            }
            return NoToken("未知错误，请重新登录");
        }

        //删除上班时间段
        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;
        }
    }
}