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

namespace CallCenterApi.Interface.Controllers
{
    //[Authority]
    public class DepartmentController : BaseController
    {
        private BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();

        /// <summary>
        /// 获取部门列表  - Pc和微信（不用身份验证）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllList()
        {
            //if (Request.IsAuthenticated)
            //{
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_Department().GetList(" F_State=1 ").Tables[0];
            return Success("加载成功", dt);
            //}
            //return NoToken("未知错误，请重新登录");
        }
        /// <summary>
        /// 获取大区分公司
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLinkList(int F_Layer)
        {
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_Department().GetList(" F_State=1 and F_Layer=+" + F_Layer).Tables[0];
            List<Model.TreeModel> modelList = BindTree(dt, "0");

            if (modelList != null)
            {
                if (modelList.Count > 0)
                    return Success("加载成功", modelList);
            }
            return Success(null );
        }
        /// <summary>
        /// 获取大区分公司
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(int F_Layer, string F_DeptName="" )
        {
                DataTable dt = new DataTable();
            if (F_DeptName!="")
            {
                Model.T_Sys_Department dModel = departmentBLL.GetModel(F_DeptName);
                if (dModel!=null )
                {
                    dt = new BLL.T_Sys_Department().GetList(" F_State=1 and F_Layer=" + F_Layer+ " and F_ParentId=" + dModel.F_DeptId ).Tables[0];
                }
                else
                {
                    return Success(null );
                }
               
            }
            else
            {
                dt = new BLL.T_Sys_Department().GetList(" F_State=1 and F_Layer=" + F_Layer  ).Tables[0];
            }
             if (dt != null)
                {
                    if (dt.Rows .Count > 0)
                        return Success("加载成功", dt);
                }
            return Success(null);
        }
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public ActionResult GetDept(int deptId = 0)
        {
            if (Request.IsAuthenticated)
            {
                BLL.T_Sys_Department dBLL = new BLL.T_Sys_Department();
                Model.T_Sys_Department dModel = dBLL.GetModel(deptId);
                if (dModel != null)
                    return Success("获取部门信息成功", new
                    {
                        deptid = dModel.F_DeptId,
                        depname = dModel.F_DeptName,
                        sort = dModel.F_Sort,
                        parentid = dModel.F_ParentId,
                        parentname = dModel.F_ParentName,
                        remark = dModel.F_Remark,
                        layerType=dModel .F_Layer,
                        //部门类型0不区分1大区2分公司
                        //    headerid = dModel.F_Header,    //部门权限范围：9全部，1区域，2项目，3期
                        //   TypeId = dModel.F_Type,    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                    });
                return Error("获取部门信息失败");
            }
            return NoToken("未知错误，请重新登录");
        }
        private readonly BLL.T_Sys_UserAccount userAccountBLL = new BLL.T_Sys_UserAccount();
        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public ActionResult GetWXDept(string name)
        {
         
                BLL.T_Sys_Department dBLL = new BLL.T_Sys_Department();
                int deptId = 0;
            int userid = 0;
                Model.T_Sys_UserAccount user = userAccountBLL.GetworkModel(name);
                if (user != null)
                {
                    deptId = user.F_DeptId;
                userid = user.F_UserId;
                }
                else
                {
                    Model.T_Sys_UserAccount userer = userAccountBLL.GetName(name);
                    if (userer != null)
                    {
                        deptId = userer.F_DeptId;
                    userid = userer.F_UserId;
                }
                }
                if (deptId==0)
                    return Error("请输入正确的姓名或编号");
                Model.T_Sys_Department dModel = dBLL.GetModel(deptId);
                if (dModel != null)
                    return Success("获取部门信息成功", new
                    {
                        deptid = dModel.F_DeptId,
                        depname = dModel.F_DeptName,
                        sort = dModel.F_Sort,
                        parentid = dModel.F_ParentId,
                        parentname = dModel.F_ParentName,
                        remark = dModel.F_Remark,
                        layerType = dModel.F_Layer,
                        userid,
                        //部门类型0不区分1大区2分公司
                        //    headerid = dModel.F_Header,    //部门权限范围：9全部，1区域，2项目，3期
                        //   TypeId = dModel.F_Type,    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                    });
                return Error("获取部门信息失败");
         
        }
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddDept(DepartmentInput input)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string pcode = "";
                Model.T_Sys_Department dModel = new Model.T_Sys_Department();
                dModel.F_ParentId = input.PId;
                if (input.PId != 0)
                {
                    Model.T_Sys_Department pdModel = departmentBLL.GetModel(input.PId);
                    if (pdModel != null)
                    {
                        pcode = dModel.F_ParentCode = pdModel.F_DeptCode;
                    }
                }
                dModel.F_Sort = input.Sort;
                dModel.F_DeptName = input.DeptName;
                if (!string.IsNullOrEmpty(input.Remark))
                    dModel.F_Remark = input.Remark;
                dModel.F_State = 1;
                dModel.F_Layer = input.F_Layer;//部门类型0不区分1大区2分公司
                                               //  dModel.F_Header = input.Headerid;    //部门权限范围：9全部，1区域，2项目，3期
                                               //  dModel.F_Type = input.TypeId;    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                int id = departmentBLL.Add(dModel);
                if (id > 0)
                {
                    departmentBLL.UpdateDeptCode(pcode + id.ToString() + "|", id);
                    res = Success("添加成功");
                }
                else
                    res = Success("添加失败");
            }
            return res;
        }

        /// <summary>
        /// 编辑部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditDept(DepartmentInput input)
        {
            if (Request.IsAuthenticated)
            {
                if (input.DeptId <= 0)
                    return Error("请选择要编辑的部门");
                BLL.T_Sys_Department dBLL = new BLL.T_Sys_Department();
                Model.T_Sys_Department dModel = dBLL.GetModel(input.DeptId);
                if (dModel == null)
                    return Error("获取信息失败");
                dModel.F_ParentId = input.PId;
                if (input.PId != 0)
                {
                    Model.T_Sys_Department pdModel = departmentBLL.GetModel(input.PId);
                    if (pdModel != null)
                    {
                        dModel.F_ParentCode = pdModel.F_DeptCode;
                        dModel.F_DeptCode = pdModel.F_DeptCode + input.DeptId.ToString() + "|";
                    }
                }
                dModel.F_Sort = input.Sort;
                dModel.F_DeptName = input.DeptName;
                if (!string.IsNullOrEmpty(input.Remark))
                    dModel.F_Remark = input.Remark;
                dModel.F_Layer = input.F_Layer;//部门类型0不区分1大区2分公司
                                               // dModel.F_Header = input.Headerid;    //部门权限范围：9全部，1区域，2项目，3期
                                               //  dModel.F_Type = input.TypeId;    //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                if (dBLL.Update(dModel))
                    return Success("编辑成功");
                return Error("编辑失败");
            }
            return NoToken("未知错误，请重新登录");
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelDept(string[] ids)
        {
            if (Request.IsAuthenticated)
            {
                if (ids == null || ids.Length <= 0)
                    return Error("请选择要删除的部门");

                var idStr = string.Join(",", ids);
                if (string.IsNullOrEmpty(idStr.Trim()))
                    return Error("请选择要删除的部门");

                if (departmentBLL.DeleteList(idStr))
                    return Success("删除成功");
                return Error("删除失败");
            }
            return NoToken("未知错误，请重新登录");
        }
        /// <summary>
        /// tree  树形部门
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Model.TreeModel> BindAssignTree(DataTable tab, string parentid,int type,int flag=0)
        {
            DataTable tab2 = new DataTable();

            if (tab != null && tab.Rows.Count > 0)
            {
                List<Model.T_Sys_Department> categorylist = new BLL.T_Sys_Department().DataTableToList(tab);
                List<Model.TreeModel> modelList = new List<Model.TreeModel>(categorylist.Count);
                for (int i = 0; i < categorylist.Count; i++)
                {
                    Model.TreeModel model = new Model.TreeModel();
                    string currentID = categorylist[i].F_DeptId.ToString();//当前功能ID
                    model.id = currentID;
                    model.code = categorylist[i].F_DeptCode;
                    model.IconCls = "";//图标
                    model.text = categorylist[i].F_DeptName;
                    model.headerid = categorylist[i].F_Header ?? 0;    //部门权限范围：9全部，1区域，2项目，3期
                    model.flag = 1;//部门标识
                    model.islast = 0; //默认不是最后一层
                    string msg = "";
                    if (type ==0)
                    {
                        msg = " and F_Layer=0";
                    }
                    tab2 = new BLL.T_Sys_Department().GetList("F_ParentId=" + currentID + " and F_State=1"+ msg).Tables[0];
                    if (flag == 1)
                    {
                        if (tab2 != null && tab2.Rows.Count > 0)
                        {
                            model.children = BindAssignTree(tab2, currentID, type, flag);
                        }
                        else
                        {
                            model.islast = 1; //最后一层部门标识
                            model.children = new BLL.T_Sys_UserAccount().GetModelList($" F_DeptId={currentID}").Select(p =>
                             {
                                 return new Model.TreeModel
                                 {
                                     id = p.F_UserId.ToString(),
                                     code = p.F_UserCode,
                                     text = p.F_UserName + "(" + p.F_UserCode + ")",
                                     flag=2 //人员标识
                                 };                    
                             });
                        }
                    }
                    else
                    {
                        if (tab2 != null && tab2.Rows.Count > 0)
                        {
                            model.children = BindAssignTree(tab2, currentID, type);
                        }
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAssignDeptList(int pId = 0, string keywords = "",int type=0,int flag=0)
        {
            //if (Request.IsAuthenticated)
            //{
            DataTable dt = new DataTable();
            if (keywords != "")
            {
                if (keywords.Contains("'"))
                {
                    keywords = keywords.Replace("'", "");
                }
                dt = new BLL.T_Sys_Department().GetList(" F_State=1" + $" and F_DeptName like '%" + keywords.Trim() + "%' and F_DeptId !=2 ").Tables[0];
            }
            else
            {
                dt = new BLL.T_Sys_Department().GetList(" F_State=1 and F_DeptId !=2  and F_ParentId=" + pId).Tables[0];
            }
            List<Model.TreeModel> modelList = BindAssignTree(dt, "0", type, flag);
            if (modelList != null)
            {
                if (modelList.Count > 0)
                    return Success("加载成功", modelList);
            }

            return Success(null);
            //}
            //return NoToken("未知错误，请重新登录");
        }
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeptList(int pId = 0,string keywords = "")
        {
            //if (Request.IsAuthenticated)
            //{
            DataTable dt = new DataTable();
            if (keywords != "")
            {
                if (keywords.Contains("'"))
                {
                    keywords= keywords.Replace("'", "");
                }
                dt = new BLL.T_Sys_Department().GetList(" F_State=1" + $" and F_DeptName like '%" + keywords.Trim()+"%'").Tables[0];
            }
            else
            {
                dt = new BLL.T_Sys_Department().GetList(" F_State=1 and F_ParentId=" + pId).Tables[0];
            }
            List<Model.TreeModel> modelList = BindTree(dt, "0");
            if (modelList != null)
            {
                if (modelList.Count > 0)
                    return Success("加载成功", modelList);
            }

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

        /// <summary>
        /// 获取部门列表 by 处理人员
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeptListbyReceive(int pId = 0)
        {
            DataTable dt = new DataTable();
            string sqlstr = "SELECT F_ParentId FROM dbo.T_Sys_Department WHERE F_Type = 2"; //一级
            //string sqlstr2 = "SELECT F_DeptId FROM dbo.T_Sys_Department WHERE F_Type = 2";  //二级
            string sqlstr3 = "SELECT F_ParentId FROM dbo.T_Sys_Department WHERE F_Type = 3";  //一级 区域客服（分类显示成其他）
            //string sqlstr4 = "SELECT TOP 1 F_DeptId FROM dbo.T_Sys_Department WHERE F_Type = 3 ORDER BY F_Sort ASC";  //二级 区域客服（分类显示成其他）
            //dt = new BLL.T_Sys_Department().GetList($" F_State=1 and (F_ParentId=0 OR F_DeptId IN({sqlstr}) OR F_DeptId IN({sqlstr2}) OR F_DeptId IN({sqlstr3}) OR F_DeptId IN({sqlstr4}) )").Tables[0];
            dt = new BLL.T_Sys_Department().GetList($" F_State=1 and (F_ParentId=0 OR F_DeptId IN({sqlstr}) OR F_DeptId IN({sqlstr3}) )").Tables[0];
            List<DepartmentTreeList> list = new List<DepartmentTreeList>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var model = new DepartmentTreeList();
                model.id = Convert.ToInt32(dt.Rows[i]["F_DeptId"]);     //当前功能ID
                model.ParentId = Convert.ToInt32(dt.Rows[i]["F_ParentId"]);
                model.text = dt.Rows[i]["F_DeptName"].ToString();
                model.sort = Convert.ToInt32(dt.Rows[i]["F_Sort"].ToString());
                list.Add(model);
            }
            return Success("加载成功", list);
        }

        /// <summary>
        /// tree  树形部门
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        private List<Model.TreeModel> BindTree(DataTable tab, string parentid)
        {
            DataTable tab2 = new DataTable();

            if (tab != null && tab.Rows.Count > 0)
            {
                List<Model.T_Sys_Department> categorylist = new BLL.T_Sys_Department().DataTableToList(tab);
                List<Model.TreeModel> modelList = new List<Model.TreeModel>(categorylist.Count);
                for (int i = 0; i < categorylist.Count; i++)
                {
                    Model.TreeModel model = new Model.TreeModel();
                    string currentID = categorylist[i].F_DeptId.ToString();//当前功能ID
                    model.id = currentID;
                    model.code = categorylist[i].F_DeptCode;
                    model.IconCls = "";//图标
                    model.text = categorylist[i].F_DeptName;
                    model.headerid = categorylist[i].F_Header ?? 0;    //部门权限范围：9全部，1区域，2项目，3期
                    tab2 = new BLL.T_Sys_Department().GetList("F_ParentId=" + currentID + " and F_State=1 ").Tables[0];
                    if (tab2 != null && tab2.Rows.Count > 0)
                    {
                        model.children = BindTree(tab2, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        }

        public class DepartmentTreeList
        {
            /// <summary>
            /// 文章ID
            /// </summary>
            public int id { get; set; }
            /// <summary>
            /// 父ID
            /// </summary>
            public int ParentId { get; set; }
            /// <summary>
            /// 分类名称
            /// </summary>
            public string text { get; set; }
            /// <summary>
            /// 排序
            /// </summary>
            public int sort { get; set; }
        }
    }
}