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
{
    public class UserClassController : BaseController
    {
        // GET: UserClass

        /// <summary>
        /// 获取用户班别列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string classcode = HttpUtility.UrlDecode(RequestString.GetQueryString("classcode"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

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


            if (usercode.Trim() != "" && usercode != "undefined")
            {
                sql += " and F_UserCode = '" + usercode.Trim() + "' ";
            }
            if (classcode.Trim() != "" && classcode != "undefined")
            {
                sql += " and F_ClassCode = '" + classcode.Trim() + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_Date,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_Date,'" + strendtime + "')>=0   ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            string cols = "*,dbo.GetUserName(F_UserCode) as UserName";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Sys_UserClass where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("用户班别列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Sys_UserClass",
                "F_Id",
                cols,
                sql,
                "ORDER BY F_Date DESC",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        /// <summary>
        /// 获取用户班别列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetRLList()
        {
            string sql = " F_IsDelete=0 ";
            string usercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            string classcode = HttpUtility.UrlDecode(RequestString.GetQueryString("classcode"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            if (userModel.F_RoleCode == "ZXHWY"|| userModel.F_RoleCode == "ZXBZ")
            {
                sql += " and F_UserCode = '" + userModel.F_UserCode + "' ";
            }

            if (usercode.Trim() != "" && usercode != "undefined")
            {
                sql += " and F_UserCode = '" + usercode.Trim() + "' ";
            }
            if (classcode.Trim() != "" && classcode != "undefined")
            {
                sql += " and F_ClassCode = '" + classcode.Trim() + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_Date,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_Date,'" + strendtime + "')>=0   ";
            }

            var list = new BLL.T_Sys_UserClass().GetModelList(sql);

            var obj = list.Select(p=>{
                var cls = new BLL.T_Sys_Class().GetModelList(" F_Code='" + p.F_ClassCode + "' ").FirstOrDefault();
                string[] ins = cls.F_InTime.Split(':');
                string[] outs = cls.F_OutTime.Split(':');
                bool bl = Int32.Parse(ins[0]) > Int32.Parse(outs[0]);
                var edate = bl?p.F_Date.Value.AddDays(1): p.F_Date.Value;
                return new {
                    id=p.F_Id,
                    title=cls.F_Name+"["+cls.F_InTime+"-"+cls.F_OutTime+"]",
                    start=p.F_Date.Value.ToString("yyyy-MM-dd")+" "+ cls.F_InTime,
                    end= edate.ToString("yyyy-MM-dd") + " " + cls.F_OutTime,
                    code = p.F_ClassCode
                };
            });
            return Content(obj.ToJson());

        }

        /// <summary>
        /// 添加用户班别
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Authority]
        public ActionResult AddUserClass()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);

            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
            string strid = RequestString.GetFormString("id"); ;
            string date = RequestString.GetFormString("date");
            string usercode = RequestString.GetFormString("usercode");
            string classcode = RequestString.GetFormString("classcode");
            long id = 0;
            if (!string.IsNullOrEmpty(strid))
            {
                id = long.Parse(strid);
            }

            Model.T_Sys_UserClass dModel = new Model.T_Sys_UserClass();
            if (id == 0)
            {
                var list = new BLL.T_Sys_UserClass().GetModelList(" F_ClassCode='" + classcode + "' and F_Date='"+ date + "' and F_UserCode='"+ usercode + "' and F_IsDelete=0 ");
                if (list.Count > 0)
                {
                    return Error("已经存在此班别");
                }
                else
                {
                    dModel.F_ClassCode = classcode;
                    dModel.F_Date = Convert.ToDateTime(date);
                    dModel.F_UserCode = usercode;
                    dModel.F_State = 0;
                    dModel.F_IsDelete = 0;
                    dModel.F_CreateUser = userModel.F_UserCode;
                    dModel.F_CreateTime = DateTime.Now;
                    long n = new BLL.T_Sys_UserClass().Add(dModel);
                    if (n > 0)
                        return Success("添加成功", n);
                    else
                        return Error("添加失败");
                }
            }
            else
            {
                dModel = new BLL.T_Sys_UserClass().GetModel(id);
                if (dModel != null)
                {
                    var list = new BLL.T_Sys_UserClass().GetModelList(" F_ClassCode='" + classcode + "' and F_Date='" + date + "' and F_UserCode='" + usercode + "' and F_IsDelete=0 and F_Id!='" + id + "' ");
                    if (list.Count > 0)
                    {
                        return Error("已经存在此班别");
                    }
                    else
                    {
                        dModel.F_ClassCode = classcode;
                        dModel.F_Date = Convert.ToDateTime(date);
                        dModel.F_UserCode = usercode;
                        if (new BLL.T_Sys_UserClass().Update(dModel))
                            return Success("修改成功");
                        else
                            return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
        }

        /// <summary>
        /// 删除班别
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult DelUserClass(long id)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            var model = new BLL.T_Sys_UserClass().GetModel(id);
            model.F_IsDelete = 1;
            model.F_DeleteUser = userModel.F_UserCode;
            model.F_DeleteTime = DateTime.Now;
            if (new BLL.T_Sys_UserClass().Update(model))
            {
                return Success("删除成功");
            }
            return Error("删除失败");
        }
    }
}