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
{
    [Authority]
    public class DepartmentController : BaseController
    {
        private BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();

        #region 部门
        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDeptList(string deptname ,int iscbdw=0)
        {
            DataTable dt = new DataTable();
            
            
            string sql = "";
            if (!string .IsNullOrEmpty (deptname))
            {
                sql += " and F_DeptName like '%" + deptname.Trim() + "%'";
            }
            if (User.F_RoleCode == "GLY" || User.F_RoleCode == "ZXLD" || User.F_RoleCode == "YSZY" || User.F_RoleCode == "MTDD" || User.F_RoleCode == "ZXHWY"
                || User.F_RoleCode == "DBZY" || User.F_RoleCode == "DMTSH")
            {
               
                if (iscbdw == 0)
                {
                    dt = departmentBLL.GetList( "F_State=0" + sql, " F_Sort").Tables[0];
                }
                else if (iscbdw == 1)
                {
                    dt = departmentBLL.GetList( "F_State=0 and  ISNULL(F_IsDept, '0') ='1'" + sql, " F_Sort").Tables[0];
                }
                else if (iscbdw == 2)
                {
                    dt = departmentBLL.GetList("F_State=0 and F_IsDept in(1,2)" + sql, " F_Sort").Tables[0];
                }
            }
            else 
            {
                if (iscbdw == 0)
                {
                    dt = departmentBLL.GetList("F_State=0  and (  F_PartentId='" + User.F_DeptId + "')"+ sql, " F_Sort").Tables[0];
                }
                else if (iscbdw == 2)
                {
                    dt = departmentBLL.GetList("F_State=0  and ( F_DeptId='" + User.F_DeptId + "'  or  F_PartentId='" + User.F_DeptId + "')" + sql, " F_Sort").Tables[0];
                }
                else
                {
                    dt = departmentBLL.GetList("F_State=0 and  ISNULL(F_IsDept, '0') ='1' and F_PartentId='" + User.F_DeptId + "'" + sql, " F_Sort").Tables[0];
                }
               
            }
            
            return Success("加载成功", dt);
        }
        public ActionResult GetZTreeNew()
        {
          
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_Department ().GetList(" 1=1 and   F_IsDept = 1 and F_State = 0 and F_layer = 1").Tables[0];
            string sqltest = "      with cte(F_DeptId  ,F_DeptName ,F_PartentId ,F_Layer,F_State,F_IsDept) as (select F_DeptId, F_DeptName, F_PartentId, F_Layer, F_State, F_IsDept from T_Sys_Department where F_IsDept = 1 and F_State = 0 and F_layer = 1 UNION all select t.F_DeptId, t.F_DeptName,t.F_PartentId,t.F_Layer,t.F_State,t.F_IsDept   from T_Sys_Department as t inner join cte as c on c.F_DeptId = t.F_PartentId )select * from cte  ";
            var tab2 = DbHelperSQL.Query(sqltest).Tables[0];
            List<TreeModelNew> modelList = BindTreeNew(dt, "0", tab2);
          
            if (modelList.Count > 0)
            {
                return Success("加载成功", modelList.ToJson());
            }
            else
                return Error("加载失败");
          

        }
        public class TreeModelNew
        {
            private string _id;
            /// <summary>
            /// Id
            /// </summary>
            public string id
            {
                set { _id = value; }
                get { return _id; }
            }


            private string _title;
            /// <summary>
            /// 树节点显示文本
            /// </summary>
            public string title
            {
                set { _title = value; }
                get { return _title; }
            }
            private List<TreeModelNew> _child;
            public List<TreeModelNew> child
            {
                set { _child = value; }
                get { return _child; }
            }
        }

        ///// <summary>
        ///// 获取部门列表
        ///// </summary>
        ///// <returns></returns>
        //public ActionResult GetDeptList(string deptname, int iscbdw = 0)
        //{
        //    DataTable dt = new DataTable();


        //    string sql = "";
        //    if (!string.IsNullOrEmpty(deptname))
        //    {
        //        sql += " and F_DeptName like '%" + deptname.Trim() + "%'";
        //    }
        //    if (User.F_RoleCode == "GLY" || User.F_RoleCode == "ZXLD" || User.F_RoleCode == "YSZY" || User.F_RoleCode == "MTDD" || User.F_RoleCode == "ZXHWY"
        //        || User.F_RoleCode == "DBZY")
        //    {

        //        if (iscbdw == 0)
        //        {
        //            // dt = departmentBLL.GetList( "F_State=0" + sql, " F_Sort").Tables[0];
        //            string SY = " select(select COUNT(1) from T_Sys_UserAccount b WITH(NOLOCK) where F_DeptId = a.F_DeptId and b.F_CreateOn = b.F_LastActiveTime) as JIHUO  ,* from T_Sys_Department a WITH(NOLOCK)  where F_State = 0 " + sql + "order by F_Sort";
        //            dt = DbHelperSQL.Query(SY).Tables[0];
        //        }
        //        else if (iscbdw == 1)
        //        {
        //            //  dt = departmentBLL.GetList( "F_State=0 and  ISNULL(F_IsDept, '0') ='1'" + sql, " F_Sort").Tables[0];
        //            string SY = " select(select COUNT(1) from T_Sys_UserAccount b WITH(NOLOCK) where F_DeptId = a.F_DeptId and b.F_CreateOn = b.F_LastActiveTime) as JIHUO  ,* from T_Sys_Department a WITH(NOLOCK)  where F_State = 0 and  ISNULL(F_IsDept, '0') ='1'" + sql + "order by F_Sort";
        //            dt = DbHelperSQL.Query(SY).Tables[0];
        //        }
        //        else if (iscbdw == 2)
        //        {
        //            // dt = departmentBLL.GetList("F_State=0 and F_IsDept in(1,2)" + sql, " F_Sort").Tables[0];
        //            string SY = " select(select COUNT(1) from T_Sys_UserAccount b WITH(NOLOCK) where F_DeptId = a.F_DeptId and b.F_CreateOn = b.F_LastActiveTime) as JIHUO  ,* from T_Sys_Department a WITH(NOLOCK)  where F_State = 0 and F_IsDept in(1,2)" + sql + "order by F_Sort";
        //            dt = DbHelperSQL.Query(SY).Tables[0];
        //        }
        //    }
        //    else
        //    {
        //        if (iscbdw == 0)
        //        {
        //            //  dt = departmentBLL.GetList("F_State=0  and (  F_PartentId='" + User.F_DeptId + "')"+ sql, " F_Sort").Tables[0];
        //            string SY = " select(select COUNT(1) from T_Sys_UserAccount b WITH(NOLOCK) where F_DeptId = a.F_DeptId and b.F_CreateOn = b.F_LastActiveTime) as JIHUO  ,* from T_Sys_Department a WITH(NOLOCK)  where F_State = 0   and (  F_PartentId='" + User.F_DeptId + "')" + sql + "order by F_Sort";
        //            dt = DbHelperSQL.Query(SY).Tables[0];
        //        }
        //        else if (iscbdw == 2)
        //        {
        //            //  dt = departmentBLL.GetList("F_State=0  and ( F_DeptId='" + User.F_DeptId + "'  or  F_PartentId='" + User.F_DeptId + "')" + sql, " F_Sort").Tables[0];
        //            string SY = " select(select COUNT(1) from T_Sys_UserAccount b WITH(NOLOCK) where F_DeptId = a.F_DeptId and b.F_CreateOn = b.F_LastActiveTime) as JIHUO  ,* from T_Sys_Department a WITH(NOLOCK)  where F_State = 0   and ( F_DeptId='" + User.F_DeptId + "'  or  F_PartentId='" + User.F_DeptId + "')" + sql + "order by F_Sort";
        //            dt = DbHelperSQL.Query(SY).Tables[0];
        //        }
        //        else
        //        {
        //            // dt = departmentBLL.GetList("F_State=0 and  ISNULL(F_IsDept, '0') ='1' and F_PartentId='" + User.F_DeptId + "'" + sql, " F_Sort").Tables[0];
        //            string SY = " select(select COUNT(1) from T_Sys_UserAccount b WITH(NOLOCK) where F_DeptId = a.F_DeptId and b.F_CreateOn = b.F_LastActiveTime) as JIHUO  ,* from T_Sys_Department a WITH(NOLOCK)  where F_State = 0 and  ISNULL(F_IsDept, '0') ='1' and F_PartentId='" + User.F_DeptId + "'" + sql + "order by F_Sort";
        //            dt = DbHelperSQL.Query(SY).Tables[0];
        //        }

        //    }

        //    return Success("加载成功", dt);
        //}

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public CallCenterApi.Model.T_Sys_Department DataRowToModel1(DataRow row)
        {
            CallCenterApi.Model.T_Sys_Department model = new CallCenterApi.Model.T_Sys_Department();
            if (row != null)
            {
                if (row["F_DeptId"] != null && row["F_DeptId"].ToString() != "")
                {
                    model.F_DeptId = int.Parse(row["F_DeptId"].ToString());
                }
                if (row["F_DeptName"] != null)
                {
                    model.F_DeptName = row["F_DeptName"].ToString();
                }
                if (row["F_PartentId"] != null && row["F_PartentId"].ToString() != "")
                {
                    model.F_PartentId = int.Parse(row["F_PartentId"].ToString());
                }
                if (row["F_layer"] != null && row["F_layer"].ToString() != "")
                {
                    model.F_layer = int.Parse(row["F_layer"].ToString());
                }
                if (row["F_State"] != null && row["F_State"].ToString() != "")
                {
                    model.F_State = int.Parse(row["F_State"].ToString());
                }
                if (row["F_IsDept"] != null && row["F_IsDept"].ToString() != "")
                {
                    model.F_IsDept  = int.Parse(row["F_IsDept"].ToString());
                }
            }
            return model;
        }
        public List<CallCenterApi.Model.T_Sys_Department> DataTableToList1(DataTable dt)
        {
            List<CallCenterApi.Model.T_Sys_Department> modelList = new List<CallCenterApi.Model.T_Sys_Department>();
            int rowsCount = dt.Rows.Count;
            if (rowsCount > 0)
            {
                CallCenterApi.Model.T_Sys_Department model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = DataRowToModel1(dt.Rows[n]);
                    if (model != null)
                    {
                        modelList.Add(model);
                    }
                }
            }
            return modelList;
        }
        private List<TreeModelNew> BindTreeNew(DataTable tab, string parentid, DataTable tabtwo)
        {
            // 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<TreeModelNew> modelList = new List<TreeModelNew>(categorylist.Count);
                for (int i = 0; i < categorylist.Count; i++)
                {
                    TreeModelNew model = new TreeModelNew();
                    string currentID = categorylist[i].F_DeptId .ToString();//当前功能ID
                    model.id = currentID;
                    model.title = categorylist[i].F_DeptName ;
                    DataTable newdt = new DataTable();
                    newdt = tabtwo.Clone();
                    DataRow[] dr = tabtwo.Select(" F_PartentId=" + currentID + " and F_State=0 ");
                    for (int j = 0; j < dr.Length; j++)
                    {
                        newdt.ImportRow((DataRow)dr[j]);
                    }
                    if (newdt != null && newdt.Rows.Count > 0)
                    {
                        model.child = BindTreeNew(newdt, currentID, tabtwo);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        }
        public ActionResult GetDeptListByDept(string dept,int iscbdw = 0)
        {
            string depts = RequestString.FilterSql(dept, 1);
            DataTable dt = new DataTable();
            var sql = " F_State=0   and F_PartentId>0 "
                    + "and F_PartentId not in (select F_DeptId from T_Sys_Department where F_PartentId = 0)";
            if (iscbdw == 0)
                sql += " and  ISNULL(F_IsDealDept, '0') ='1' ";
            if (!string.IsNullOrEmpty(depts))
            {
                sql += " and F_DeptName like '%" + depts.Trim() + "%'";

                dt = departmentBLL.GetList(0, sql, "F_Sort").Tables[0];
            }
            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取二级部门列表
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetSecondDeptList()
        {
            
            

            DataTable dt = new DataTable();
            if (User.F_RoleCode == "GLY")
            {
                dt = departmentBLL.GetList("F_State=0 and  ISNULL(F_IsDept, '0') ='2' " , " F_Sort").Tables[0];
            }
            if (User.F_RoleCode == "WLDW")
            {
                dt = departmentBLL.GetList("F_State=0 and  ISNULL(F_IsDept, '0') ='2'  and F_PartentId='" + User.F_DeptId + "'", " F_Sort").Tables[0];
            }

            return Success("加载成功", dt);
        }

        /// <summary>
        /// 获取部门列表
        /// </summary>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetDeptListtree(int pId = 0)
        {
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_Department().GetList(" F_State=0 and ISNULL(F_IsDealDept, '0') ='1' and F_PartentId=" + pId).Tables[0];
            List<Model.TreeModel> modelList = BindTree(dt, "0");

            if (modelList != null)
            {
                if (modelList.Count > 0)
                    return Success("加载成功", modelList);
            }
            return Error("加载失败");

        }

        /// <summary>
        /// tree  树形部门
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        //[Authority]
        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.IconCls = "";//图标
                    model.text = categorylist[i].F_DeptName;
                    tab2 = new BLL.T_Sys_Department().GetList("F_PartentId=" + currentID + " and F_State=0 and ISNULL(F_IsDealDept, '0') ='1' order by f_sort").Tables[0];
                    if (tab2 != null && tab2.Rows.Count > 0)
                    {
                        model.children = BindTree(tab2, currentID);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult GetDept()
        {
            int id = RequestString.GetInt("id", 0);
            Model.T_Sys_Department dModel = departmentBLL.GetModel(id);
            if (dModel != null)
            {

                string value = "";
                if (dModel.F_Valueid  != null)
                {
                    var dicvalue = new BLL.T_Sys_DictionaryValue ().GetModel((int)dModel.F_Valueid);
                    if (dicvalue != null)
                        value = dicvalue.F_Value ;
                }
                var obj = new
                {
                    F_Address = dModel.F_Address,
                    F_CreateDate = dModel.F_CreateDate,
                    F_CreateUser = dModel.F_CreateUser,
                    F_DeptId = dModel.F_DeptId,
                    F_DeptName = dModel.F_DeptName,
                    F_DeptNameSpell = dModel.F_DeptNameSpell,
                    F_DeptNameSpells = dModel.F_DeptNameSpells,
                    F_DeptPhone = dModel.F_DeptPhone,
                    F_DeptPhone2 = dModel.F_DeptPhone2,
                    F_DeptTelphone = dModel.F_DeptTelphone,
                    F_IsDealDept = dModel.F_IsDealDept,
                    F_IsDept = dModel.F_IsDept,
                    F_LeaderUser = dModel.F_LeaderUser,
                    F_LeaderUserName = dModel.F_LeaderUserName,
                    F_PartentId = dModel.F_PartentId,
                    F_Remark = dModel.F_Remark,
                    F_Sort = dModel.F_Sort,
                    F_State = dModel.F_State,
                    F_TopLeaderUser = dModel.F_TopLeaderUser,
                    F_TopLeaderUserName = dModel.F_TopLeaderUserName,
                    F_TopSplitUser = dModel.F_TopSplitUser,
                    F_TopSplitUserName = dModel.F_TopSplitUserName,
                    F_Type = dModel.F_Type,
                    F_layer = dModel.F_layer,
                    F_Valueid = dModel.F_Valueid,
                    F_Value = value,
                };
                return Success("获取信息成功", dModel);
            }
                
            return Error("获取信息失败");

        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        //[Authority]
        [HttpPost]
        public ActionResult AddDept()
        {
            
            
            int id = RequestString.GetInt("id", 0);
            int did = RequestString.GetInt("did", 0);
            int sort = RequestString.GetInt("sort", 0);
            int isdept = RequestString.GetInt("isdept", 0);
            int isdealdept = RequestString.GetInt("isdealdept", 0);
            int valueid = RequestString.GetInt("valueid", 0);
            string name = RequestString.GetFormString("name");
            string phone = RequestString.GetFormString("phone");
            string leader = RequestString.GetFormString("leader");
            string split = RequestString.GetFormString("split");
            string topleader = RequestString.GetFormString("topleader");
            string remark = RequestString.GetFormString("remark");

            Model.T_Sys_Department dModel = new Model.T_Sys_Department();
            if (id == 0)
            {
                var list = departmentBLL.GetModelList(" F_State=0 and F_PartentId='" + did + "' and F_DeptName='" + name + "' ");
                if (list.Count > 0)
                {
                    return Error("已经存在此部门");
                }
                else
                {
                    dModel.F_PartentId = did;
                    dModel.F_Sort = sort;
                    dModel.F_DeptName = name;
                    dModel.F_DeptPhone = phone;
                    dModel.F_layer = did > 0 ? 1 : 0;
                    dModel.F_Type = 0;
                    dModel.F_LeaderUser = leader;
                    dModel.F_TopSplitUser = split;
                    dModel.F_TopLeaderUser = topleader;
                    dModel.F_State = 0;
                    dModel.F_IsDept = isdept;
                    dModel.F_IsDealDept = isdealdept;
                    dModel.F_CreateDate = DateTime.Now;
                    dModel.F_CreateUser = User.F_UserCode;
                    dModel.F_Valueid  = valueid;
                    
                    int n = departmentBLL.Add(dModel);
                    if (n > 0)
                    {
                        if (valueid > 0)
                        {
                            var value = new BLL.T_Sys_DictionaryValue ().GetModel(valueid);
                            if (value != null)
                            {
                                value.F_Deptid  = n;
                            }
                            var b = new BLL.T_Sys_DictionaryValue().Update(value);
                        }
                        return Success("添加成功", n);
                    }
                       
                    else
                        return Error("添加失败");
                }
            }
            else
            {
                dModel = departmentBLL.GetModel(id);
                if (dModel != null)
                {
                    var list = departmentBLL.GetModelListNoCache(" F_State=0 and F_PartentId='" + did + "' and F_DeptName='" + name + "' and F_DeptId!='" + id + "' ","");
                    if (list.Count > 0)
                    {
                        return Error("已经存在此部门");
                    }
                    else
                    {
                        dModel.F_PartentId = did;
                        dModel.F_Sort = sort;
                        dModel.F_DeptName = name;
                        dModel.F_DeptPhone = phone;
                        dModel.F_LeaderUser = leader;
                        dModel.F_TopSplitUser = split;
                        dModel.F_TopLeaderUser = topleader;
                        dModel.F_IsDept = isdept;
                        dModel.F_IsDealDept = isdealdept;
                        dModel.F_Valueid = valueid;
                        if (departmentBLL.Update(dModel))
                        {
                            if (valueid > 0)
                            {
                                var value = new BLL.T_Sys_DictionaryValue().GetModel(valueid);
                                if (value != null)
                                {
                                    value.F_Deptid = dModel.F_DeptId ;
                                }
                                var b = new BLL.T_Sys_DictionaryValue().Update(value);
                            }
                            return Success("修改成功");
                        }
                        else
                            return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
        }
        //[Authority]
        [HttpPost]
        public ActionResult UpdateDeptRemark()
        {
            if(User==null)
                return Error("权限不足!");
            int id = RequestString.GetInt("id", 0);
            string remark = RequestString.GetFormString("remark");
            if (id <= 0)
                return Error("参数错误");
            Model.T_Sys_Department dModel = departmentBLL.GetModel(id);
            if(dModel==null)
                return Error("参数错误!");
            dModel.F_Remark = remark;
            if (departmentBLL.Update(dModel))
                return Success("修改成功");
            else
                return Error("修改失败");

        }
        public ActionResult UpdateSMSList(string ids,int state)
        {
            if (User == null)
                return Error("权限不足!");
            if (string .IsNullOrEmpty (ids) )
                return Error("请选择部门");
            if (departmentBLL.UpdateSMS(0))
            {
                if (departmentBLL.UpdateSMSList(ids, state))
                    return Success("修改成功");
            }
            return Error("修改失败");
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult DelDept(string[] ids)
        {
            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("删除失败");

        }

        /// <summary>
        /// 删除部门和其下级部门
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        //[Authority]
        public ActionResult DelDepts(int id)
        {
            if (id > 0)
            {
                var model = new BLL.T_Sys_Department().GetModel(id);
                if (DelDeptsByPId(id))
                {
                    new BLL.T_Sys_Department().Delete(id);
                }
                return Success("删除成功");
            }
            else
            {
                return Error("删除失败");
            }

        }
        //[Authority]
        public bool DelDeptsByPId(int id)
        {
            bool bl = true;

            var list = new BLL.T_Sys_Department().GetModelList(" F_PartentId ='" + id + "'");
            foreach (var l in list)
            {
                if (DelDeptsByPId(l.F_DeptId))
                {
                    new BLL.T_Sys_Department().Delete(l.F_DeptId);
                }
            }

            return bl;
        }

        #endregion

    }
}