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.Text;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    [Authority]
    public class DictionaryController : BaseController
    {
        private BLL.T_Sys_DictionaryValue dictionaryValueBLL = new BLL.T_Sys_DictionaryValue();
        private BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        public ActionResult GetZTreeList()
        {
            DataTable dt = new DataTable();
            string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
            string sql = " and F_State=0 ";
            if (pid.Trim() != "")
            {
                sql += " and F_PrentId=" + pid.Trim();
            }
            else
            {
                pid = "0";
                sql += " and F_PrentId=0   ";
            }
            if (pid == "0")
            {
                var strList = RedisHelper1.StringGet("ZTreeList_0");
                if (strList != null)
                {
                    return Success("加载成功", strList.ToString().ToObject<List<Model.TreeModel>>());
                }

            }


            dt = new BLL.T_Sys_DictionaryValue().GetList(" 1=1 " + sql).Tables[0];


            //  string sqltest = "       with cte(F_ValueId ,F_Value,F_PrentId,F_Layer,F_IsLeaf,F_State,F_ItemId) as(select F_ValueId, F_Value,F_PrentId,F_Layer,F_IsLeaf,F_State,F_ItemId  from T_Sys_DictionaryValue where   F_State = 0 and   F_Value like'%出租汽车%'  UNION all select t.F_ValueId, t.F_Value,t .F_PrentId ,t.F_Layer,t.F_IsLeaf,t.F_State,t.F_ItemId from T_Sys_DictionaryValue as t inner join cte as c on  c.F_ValueId = t.F_PrentId )select* from cte   ";
            //  dt = DbHelperSQL.Query(sqltest).Tables[0];


            string sqltest = "     with cte(F_ValueId ,F_Value,F_PrentId,F_Layer,F_IsLeaf,F_State,F_ItemId) as(select F_ValueId ,F_Value,F_PrentId,F_Layer,F_IsLeaf,F_State,F_ItemId from T_Sys_DictionaryValue where F_PrentId = " + pid + " UNION all select t.F_ValueId, t.F_Value,t .F_PrentId,t.F_Layer,t.F_IsLeaf,t.F_State,t.F_ItemId from T_Sys_DictionaryValue as t inner join cte as c on  c.F_ValueId = t.F_PrentId )select * from cte  ";


            var tab2 = DbHelperSQL.Query(sqltest).Tables[0];

            List<Model.TreeModel> modelList = BindTree(dt, "0", tab2);
            if (pid == "0")
            {
                RedisHelper1.StringSet("ZTreeList_0", modelList.ToJson());
            }
            if (modelList.Count > 0)
            {
                return Success("加载成功", modelList);
            }
            else
                return Error("加载失败");

        }
        public ActionResult GetZTreeNew()
        {
            DataTable dt = new DataTable();
            string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
            string sql = " and F_State=0 ";
            if (pid.Trim() != "")
            {
                sql += " and F_PrentId=" + pid.Trim();
            }
            else
            {
                pid = "0";
                sql += " and F_PrentId=0   ";
            }
            if (pid == "38")
            {
                string rjson = RedisHelper.StringGet("ztree_38new")?.ToString() ?? "";
                if (!string.IsNullOrEmpty(rjson))
                {
                    return Success("加载成功", rjson);
                }
            }


            dt = new BLL.T_Sys_DictionaryValue().GetList(" 1=1 " + sql).Tables[0];
            string sqltest = "     with cte(F_ValueId ,F_Value,F_PrentId,F_Layer,F_IsLeaf,F_State,F_ItemId) as(select F_ValueId ,F_Value,F_PrentId,F_Layer,F_IsLeaf,F_State,F_ItemId from T_Sys_DictionaryValue where F_PrentId = " + pid + " UNION all select t.F_ValueId, t.F_Value,t .F_PrentId,t.F_Layer,t.F_IsLeaf,t.F_State,t.F_ItemId from T_Sys_DictionaryValue as t inner join cte as c on  c.F_ValueId = t.F_PrentId )select * from cte  ";


            var tab2 = DbHelperSQL.Query(sqltest).Tables[0];

            List<TreeModelNew> modelList = BindTreeNew(dt, "0", tab2);
            if (pid == "38")
            {
                RedisHelper.StringSet("ztree_38new", modelList.ToJson());
            }
            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; }
            }
        }
        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_DictionaryValue> categorylist = new BLL.T_Sys_DictionaryValue().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_ValueId.ToString();//当前功能ID
                    model.id = currentID;
                    model.title = categorylist[i].F_Value;
                    DataTable newdt = new DataTable();
                    newdt = tabtwo.Clone();
                    DataRow[] dr = tabtwo.Select(" F_PrentId=" + 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;
            }

        }

        //tree  树形知识库分类
        private List<Model.TreeModel> BindTree(DataTable tab, string parentid, DataTable tabtwo)
        {
            // DataTable tab2 = new DataTable();

            if (tab != null && tab.Rows.Count > 0)
            {
                List<Model.T_Sys_DictionaryValue> categorylist = new BLL.T_Sys_DictionaryValue().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_ValueId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = "";//图标
                    model.text = categorylist[i].F_Value;

                    //tab2 = new BLL.T_Sys_DictionaryValue().GetList(" F_PrentId=" + currentID + " and F_State=0  ").Tables[0];




                    DataTable newdt = new DataTable();
                    newdt = tabtwo.Clone();
                    DataRow[] dr = tabtwo.Select(" F_PrentId=" + 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.children = BindTree(newdt, currentID, tabtwo);
                    }
                    modelList.Add(model);
                }
                return modelList;

            }
            else
            {
                return null;
            }

        }


        public ActionResult GetZTreeListNew()
        {
            DataTable dt = new DataTable();
            string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
            if (pid == "38")
            {
                string rjson = RedisHelper1.StringGet("ztree_38")?.ToString() ?? "";
                if (!string.IsNullOrEmpty(rjson))
                {
                    return Success("加载成功", rjson.ToObject<DataTable>());
                }

            }
            string sql = " and F_State=0 ";
            if (pid.Trim() != "")
            {
                sql += " and F_PrentId=" + pid.Trim();
            }
            else
            {
                pid = "0";
                sql += " and F_PrentId=0   ";
            }

            string sqltest = "     with cte(F_ValueId ,F_Value,F_PrentId) as(select F_ValueId ,F_Value,F_PrentId from T_Sys_DictionaryValue where 1 =1  " + sql + " UNION all select t.F_ValueId, t.F_Value,t.F_PrentId from T_Sys_DictionaryValue as t inner join cte as c on  c.F_ValueId = t.F_PrentId )select F_ValueId id,F_Value text,F_PrentId pId from cte  ";


            var tab2 = DbHelperSQL.Query(sqltest).Tables[0];

            if (pid == "38")
            {
                RedisHelper1.StringSet("ztree_38", tab2.ToJson());
            }

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

        public ActionResult GetKeyListNew(string key)
        {
            DataTable dt = new DataTable();

            string rjson = RedisHelper1.StringGet("key_38")?.ToString() ?? "";
            if (!string.IsNullOrEmpty(rjson))
            {
                dt = rjson.ToObject<DataTable>();
                var dtnew = new DataTable();
                if (string.IsNullOrEmpty(key))
                {
                    dtnew = dt;
                }
                else
                {
                    var drs = dt.Select(" name like '%" + key + "%'", "names");
                    if (drs.Length > 0)
                    {
                        dtnew = drs.CopyToDataTable();
                    }
                }
                return Success("加载成功", dtnew);
            }

            var tab2 = DbHelperSQL.Query("select * from View_Keys").Tables[0];
            RedisHelper1.StringSet("key_38", tab2.ToJson());

            string sql = "";
            if (string.IsNullOrEmpty(key))
            {
                sql = " where name like '%" + key + "%'";
            }

            return Success("加载成功", DbHelperSQL.Query("select * from View_Keys " + sql + " order by names").Tables[0]);
        }

        #region 字典值操作

        //[Authority]
        /// <summary>
        /// 获取字典值列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDicValueList()
        {
            string name = RequestString.GetQueryString("name");
            int id = RequestString.GetInt("id", 0);
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = "  and F_State=0 ";
            DataTable dt = new DataTable();

            if (id != 0)
            {
                //sql += " and F_ItemId= '" + id + "' ";
                sql += " and F_PrentId= '" + id + "' ";
            }

            if (!string.IsNullOrWhiteSpace(name))
            {
                sql += " and F_Value like '%" + name + "%' ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

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

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Sys_DictionaryValue",
                "F_ValueId",
                "*",
                sql,
                "ORDER BY F_ValueId ",
                pagesize,
                pageindex,
                true,
                out recordCount);
            List<Model.T_Sys_DictionaryValue> modelList = new BLL.T_Sys_DictionaryValue().DataTableToList(dt);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }
        ////[Authority]
        /// <summary>
        /// 获取字典值列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDicValueListById(int type = 0)
        {

            int id = RequestString.GetInt("id", 0);
            var sql = " F_State=0 ";
            if (id == 1)
                sql += " and  (F_PrentId=36 or F_ItemId='" + id + "')";
            else if (id == 2)
                sql += " and  (F_PrentId=37 or F_ItemId='" + id + "')";
            else if (id == 3)
            {
                sql += " and  (F_PrentId=38 or F_ItemId='" + id + "')";
            }
            else
                sql += " and  (F_PrentId='" + id + "' or F_ItemId='" + id + "')";
            DataTable dt = new DataTable();
            dt = new BLL.T_Sys_DictionaryValue().GetList(sql).Tables[0];
            return Success("列表加载成功", dt);
        }

        /// <summary>
        /// 获取字典值列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDicValueListByParentId()
        {
            int pid = RequestString.GetInt("pid", 0);
            DataTable dt = new DataTable();

            dt = new BLL.T_Sys_DictionaryValue().GetList(" F_PrentId='" + pid + "' and F_State=0  ").Tables[0];

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

        }

        /// <summary>
        /// 加载字典值
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDicValue()
        {
            int id = RequestString.GetInt("id", 0);

            Model.T_Sys_DictionaryValue valueModel = dictionaryValueBLL.GetModel(id);
            if (valueModel != null)
            {
                string deptname = "";
                if (valueModel.F_Deptid != null)
                {
                    var dept = new BLL.T_Sys_Department().GetModel((int)valueModel.F_Deptid);
                    if (dept != null)
                        deptname = dept.F_DeptName;
                }
                var obj = new
                {
                    F_CreateDate = valueModel.F_CreateDate,
                    F_CreateUser = valueModel.F_CreateUser,
                    F_IsLeaf = valueModel.F_IsLeaf,
                    F_ItemId = valueModel.F_ItemId,
                    F_Layer = valueModel.F_Layer,
                    F_PrentId = valueModel.F_PrentId,
                    F_Remark = valueModel.F_Remark,
                    F_State = valueModel.F_State,
                    F_Value = valueModel.F_Value,
                    F_ValueId = valueModel.F_ValueId,
                    F_Deptid = valueModel.F_Deptid,
                    F_DeptName = deptname
                };
                return Success("加载字典值成功", obj);
            }

            else
                return Error("加载字典值失败");

        }

        //[Authority]
        /// <summary>
        /// 添加/编辑字典值
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult AddDicValue()
        {
            int id = RequestString.GetInt("id", 0);
            //int iid = RequestString.GetInt("iid", 0);
            int pid = RequestString.GetInt("pid", 0);
            string name = RequestString.GetFormString("name");
            int deptid = RequestString.GetInt("deptid", 0);
            string remark = RequestString.GetFormString("remark");
            Model.T_Sys_DictionaryValue orderModel = new Model.T_Sys_DictionaryValue();
            BLL.T_Sys_DictionaryValue orderBll = new BLL.T_Sys_DictionaryValue();

            if (id == 0)
            {
                //var list = orderBll.GetModelList(" F_Value='" + name + "' and F_ItemId='"+pid+"' ");
                var list = orderBll.GetModelList(" F_Value='" + name + "' and F_PrentId='" + pid + "' and F_State=0 ");
                if (list.Count > 0)
                {
                    return Error("此类别下已经存在此字典值");
                }
                else
                {
                    orderModel.F_ItemId = pid;
                    orderModel.F_Value = name;
                    orderModel.F_PrentId = pid;
                    orderModel.F_State = 0;
                    orderModel.F_Deptid = deptid;
                    orderModel.F_Remark = remark;
                    int n = orderBll.Add(orderModel);
                    if (n > 0)
                    {
                        if (deptid > 0)
                        {
                            var dept = new BLL.T_Sys_Department().GetModel(deptid);
                            if (dept != null)
                            {
                                dept.F_Valueid = n;
                            }
                            var b = new BLL.T_Sys_Department().Update(dept);
                        }
                        return Success("字典值添加成功", n);
                    }

                    else
                        return Error("字典值添加失败");
                }
            }
            else
            {
                orderModel = orderBll.GetModel(id);
                if (orderModel != null)
                {
                    //var list = orderBll.GetModelList(" F_Value='" + name + "' and F_ItemId='" + pid + "' and  F_ValueId!='" + id + "'");
                    var list = orderBll.GetModelListNoCache(" F_Value='" + name + "' and F_PrentId='" + pid + "' and  F_ValueId!='" + id + "' and F_State=0 ");
                    if (list.Count > 0)
                    {
                        return Error("此类别下已经存在此字典值");
                    }
                    else
                    {
                        orderModel.F_ItemId = pid;
                        orderModel.F_Value = name;
                        orderModel.F_PrentId = pid;
                        orderModel.F_Deptid = deptid;
                        orderModel.F_Remark = remark;
                        if (orderBll.Update(orderModel))
                        {
                            if (deptid > 0)
                            {
                                var dept = new BLL.T_Sys_Department().GetModel(deptid);
                                if (dept != null)
                                {
                                    dept.F_Valueid = orderModel.F_ValueId;
                                }
                                var b = new BLL.T_Sys_Department().Update(dept);
                            }
                            return Success("字典值修改成功");
                        }
                        else
                            return Error("字典值修改失败");
                    }
                }
                else
                {
                    return Error("字典值修改失败");
                }
            }

        }

        //[Authority]
        /// <summary>
        /// 删除字典值
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelDicValue(string[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return Error("获取参数失败");
            var idStr = string.Join(",", ids);
            if (new BLL.T_Sys_DictionaryValue().DeleteList1(idStr))
                return Success("删除成功");
            else
                return Error("删除失败");

        }
        #endregion
    }
}