using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.System
{
    public class DepartmentController : BaseController
    {
        private Bll.T_Sys_Department departmentBLL = new Bll.T_Sys_Department();
        private Bll.T_Wowo_repairyqbll yqBll = new Bll.T_Wowo_repairyqbll();

        // GET: Department
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(string keyword, int hosid = 0, int pid = 0, int pageindex = 1, int pagesize = 10)
        {
            DataTable date = new DataTable();
            string sql = "";
            string where = " and F_State=1";
            if (!string.IsNullOrEmpty(keyword))
                sql += $" and F_DeptName like '%" + keyword + "%'";
            if (pid != 0)
                sql += $" and F_ParentId= " + pid;
            if (hosid != 0)
                sql += $" and T_Woid=" + hosid;
            int recordCount = 0;
            if (!string.IsNullOrEmpty(sql))
            {
                where += sql;
            }
            date = Bll.PagerBll.GetListPager
                                ("T_Sys_Department ",
                                  "F_DeptId",
                                  "*,dbo.GetDepartmentName(F_ParentId) departname",
                                  where,
                                  "order by F_Sort",
                                  pagesize,
                                  pageindex,
                                  true,
                                  out recordCount

                                );
            //  List<Model.T_Sys_Department> carlist = new Bll.T_Sys_Department().DataTableToList(date);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = date,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 返回树形下拉框 菜单数据
        /// </summary>
        /// <returns></returns>
   
        [HttpGet]
        public ActionResult GetTreeList(int hosid=0,int pid=0)
        {
            var hoslist = yqBll.GetListall();
            var dptmodel = departmentBLL.GetModelList(" F_State=1");
            dptmodel.Sort((x, y) => x.F_Sort ?? 0 - y.F_Sort ?? 0);//排序
            var treeList = new List<TreeModel>();
            if (hoslist.Count > 0)
            {
                foreach (var hositem in hoslist)
                {
                    TreeModel treeModel = new TreeModel();
                    treeModel.id = hositem.T_Woid.ToString();
                    treeModel.IconCls = "";
                    
                    treeModel.text = hositem.T_Woname;
                    treeModel.parentid = "-1";
                    treeModel.TypeId = 1;
                    treeModel.children = TreeRecursion(dptmodel, "0", hositem.T_Woid);
                    treeList.Add(treeModel);
                    //var dptlist = dptmodel.Where(p => p.F_ParentId == 0 && p.T_Woid == hositem.T_Woid).ToList();
                }
            }
            //return Content(treeList.ToJson());
            return Success("获取菜单树成功", treeList);
        }

        private List<TreeModel> TreeRecursion(List<Model.T_Sys_Department> data, string parentId = "0", int hosid = 0)
        {
            List<Model.T_Sys_Department> item = null;
            List<TreeModel> newList = new List<TreeModel>();
            //if (parentId != "0")
            //{
            if (hosid != 0)
            {
                item = data.FindAll(t => t.F_ParentId.ToString() == parentId && t.T_Woid == hosid);//data建议在调用此扩展方法前已经排序过
            }
            else
            {
                item = data.FindAll(t => t.F_ParentId.ToString() == parentId);//data建议在调用此扩展方法前已经排序过
            }

            item =  item.OrderBy(t => t.F_Sort).ToList();
            if (item.Count > 0)
            {
                foreach (Model.T_Sys_Department entity in item)
                {
                    TreeModel treeModel = new TreeModel();
                    treeModel.id = entity.F_DeptId.ToString();
                    treeModel.IconCls = "";
                    treeModel.text = entity.F_DeptName;
                    treeModel.parentid = entity.F_ParentId.ToString();
                    treeModel.identification = entity.F_DeptCode;
                    treeModel.TypeId = 2;
                    var child= TreeRecursion(data, entity.F_DeptId.ToString());
                    if(child.Count>0)
                    {
                        treeModel.children = child;
                    }
                    treeModel.location = entity.F_Location;
                    treeModel.phone = entity.F_OfficeTelephone;
                    newList.Add(treeModel);
                }
            }
            //}
            return newList;
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="deptid"></param>
        /// <param name="deptcode"></param>
        /// <returns></returns>
        public ActionResult GetModel(int deptid = 0, string deptcode = "")
        {
            string sql = " 1=1 ";
            if (deptid > 0)
            {
                sql += " and F_DeptId=" + deptid;
            }
            if (!string.IsNullOrWhiteSpace(deptcode))
            {
                sql += " and F_DeptCode='" + deptcode + "'";
            }
            if (string.IsNullOrWhiteSpace(sql))
                return Error("获取失败");

            var role = departmentBLL.GetModelList(sql).FirstOrDefault();
            role.deptype = departmentBLL.GetDeplayer(role.F_DeptId);

            return Success("获取成功", role);
        }



        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Add(int pid, string code, string name,int hosid, string location, string floorDistribution, string officeTelephone, int sort=0,int transfertype=0)
        {
            if (departmentBLL.Exists(code))
            {
                return Error("已经存在此编码");
            }
            else
            {
                Model.T_Sys_Department dModel = new Model.T_Sys_Department();
                dModel.F_ParentId = pid;
                dModel.F_Sort = sort;
                dModel.F_DeptCode = code;
                dModel.F_DeptName = name;
                dModel.F_State = 1;
                dModel.F_CreateTime = DateTime.Now;
                dModel.F_CreateUser = User.F_UserCode;
                dModel.T_Woid = hosid;

                dModel.F_Location = location;
                dModel.F_FloorDistribution = floorDistribution;
                dModel.F_OfficeTelephone = officeTelephone;
                dModel.F_TransferType = transfertype;
                int n = departmentBLL.Add(dModel);
                if (n > 0)
                {
                    return Success("添加成功", n);
                }

                else
                    return Error("添加失败");
            }

        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(int id, int pid, string code, string name, int sort,int hosid,string location,string floorDistribution,string officeTelephone,int transfertype=0)
        {
            Model.T_Sys_Department dModel = departmentBLL.GetModel(id);
            if (dModel != null)
            {
                var list = departmentBLL.GetModelList(" F_DeptCode='" + code + "' and F_DeptId!='" + id + "' ");
                if (list.Count > 0)
                {
                    return Error("已经存在此编码");
                }
                else
                {
                    dModel.F_ParentId = pid;
                    dModel.F_Sort = sort;
                    dModel.F_DeptCode = code;
                    dModel.F_DeptName = name;
                    dModel.F_State = 1;
                    dModel.T_Woid = hosid;

                   dModel.F_Location= location;
                    dModel.F_FloorDistribution= floorDistribution;
                    dModel.F_OfficeTelephone= officeTelephone;
                    dModel.F_TransferType = transfertype;
                    

                    if (departmentBLL.Update(dModel))
                    {
                        return Success("修改成功");
                    }
                    else
                        return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (id > 0)
            {
                bool bl = true;
                var list = departmentBLL.GetList("F_ParentId='" + id + "'").Tables[0];
                if (list.Rows.Count == 0)
                {
                    var list1 = new Bll.T_Sys_UserAccount().GetList("F_DeptId='" + id + "'").Tables[0];
                    if (list1.Rows.Count == 0)
                    {
                        bl = false;
                    }
                }
                if (bl)
                {
                    return Error("正在被使用，不能删除");
                }

                if (departmentBLL.Delete(id))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("删除失败");
            }

        }


        [HttpGet]
        public ActionResult GetTreeListNew()
        {
            int deptid = User.F_DeptId;
           // var hoslist = yqBll.GetListall();
            var dptmodel = departmentBLL.GetModelList(" F_State=1 and F_DeptId='"+deptid+"'");
            var deptmodellist= departmentBLL.GetModelList(" F_State=1 and F_ParentId='" + deptid + "'");
            dptmodel.Sort((x, y) => x.F_Sort ?? 0 - y.F_Sort ?? 0);//排序
            var treeList = new List<TreeModel>();
           
                
                    TreeModel treeModel = new TreeModel();
            treeModel.id = deptid.ToString();
                    treeModel.IconCls = "";
                    treeModel.text = dptmodel.First().F_DeptName;
                    treeModel.parentid = "-1";
                    treeModel.TypeId = 1;
                    treeModel.children = TreeRecursionnew(deptmodellist, "0");
                    treeList.Add(treeModel);
                    //var dptlist = dptmodel.Where(p => p.F_ParentId == 0 && p.T_Woid == hositem.T_Woid).ToList();
            
            //return Content(treeList.ToJson());
            return Success("获取菜单树成功", treeList);
        }

        private List<TreeModel> TreeRecursionnew(List<Model.T_Sys_Department> data, string parentId = "0", int hosid = 0)
        {
            List<Model.T_Sys_Department> item = null;
            List<TreeModel> newList = new List<TreeModel>();
           
                item = data;//data建议在调用此扩展方法前已经排序过
            

            item = item.OrderBy(t => t.F_Sort).ToList();
            if (item.Count > 0)
            {
                foreach (Model.T_Sys_Department entity in item)
                {
                    TreeModel treeModel = new TreeModel();
                    treeModel.id = entity.F_DeptId.ToString();
                    treeModel.IconCls = "";
                    treeModel.text = entity.F_DeptName;
                    treeModel.parentid = entity.F_ParentId.ToString();
                    treeModel.TypeId = 2;
                    var child = TreeRecursion(data, entity.F_DeptId.ToString());
                    if (child.Count > 0)
                    {
                        treeModel.children = child;
                    }
                    treeModel.location = entity.F_Location;
                    treeModel.phone = entity.F_OfficeTelephone;
                    newList.Add(treeModel);
                }
            }
            //}
            return newList;
        }
    }
}