using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
//using System.ServiceModel;
//using System.ServiceModel.Web;
using System.Runtime.Serialization;
using System.Web.Mvc;
using System.Web.Script.Serialization;
using CallCenter.Utility;

namespace CallCenterApi.Interface.Controllers.workorder
{
    public class WorkTypeController : BaseController
    {
        /// <summary>
        /// 加载工单类型
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTreeList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                DataTable dt = new DataTable();

                try
                {
                    //F_CategoryType=1为工单类型
                    dt = new BLL.T_RepositoryCategory().GetList("F_ParentId=0 and F_DeleteFlag=0 and F_CategoryType=1").Tables[0];
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        System.Collections.Generic.List<Model.TreeModel > modelList = BindTree(dt, "0");
                        //将对象转为json字符串
                        //resstr = new JavaScriptSerializer().Serialize(modelList);
                        res = Success("获取成功", modelList);
                    }
                    else
                    {
                        //res = Success("获取成功", modelList);
                        res = Error("没有对应数据");
                    }
                }
                catch (Exception e)
                {
                    res = Error("获取失败" + e.Message);
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            return res;
        }
        /// <summary>
        /// 删除工单类型
        /// </summary>
        /// <returns></returns>
        public ActionResult DeleteById()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            string resstr = "";
            //获取选中的类别id
            string id = RequestString.GetQueryString("id");
            if (id != null && id.Length > 0)
            {
                //获取它下面的子类别
                //DataTable dt = new BLL.T_RepositoryCategory().GetList("F_DeleteFlag=0 and F_ParentId=" + Convert.ToInt32(id) + " and F_CategoryType=1").Tables[0];
                string rid = string.Empty;
                resstr = DeleteWoType(id);

                if (resstr == "")
                    res = Success("删除成功");
                else
                {
                    res = Error("删除失败");
                }
            }
            else
            {
                res = Error("获取参数失败");
            }

            return res;
        }
        /// <summary>
        /// 添加/修改工单类别
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            string id = RequestString.GetQueryString("id");
            try
            {//set
                T_RepositoryCategory = new BLL.T_RepositoryCategory().GetModel(Convert.ToInt32(id));
                string pname = "";
                if (!string.IsNullOrEmpty(pid) && pid != "0")
                {
                    var pmodel = new BLL.T_RepositoryCategory().GetModel(Convert.ToInt32(pid));
                    if (pmodel != null)
                    {
                        pname = pmodel.F_CategoryName;
                    }
                }
                var obj = new
                {
                    catagoryname = name,
                    parentid = pid,
                    sort = sort,
                    pname = pname
                };
                res = Success("获取成功", obj);
            }
            catch (Exception e)
            {
                res = Error("获取失败" + e.Message);
            }
            return res;
        }
        /// <summary>
        /// 类别保存
        /// </summary>
        /// <returns></returns>
        public ActionResult Save()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            id = RequestString.GetFormString("id");
            if (!string.IsNullOrEmpty(id))
            {
                bool b = new BLL.T_RepositoryCategory().Update(T_RepositoryCategory);
                if (b)
                    res = Success("修改成功", T_RepositoryCategory);
                else
                    res = Success("修改失败");
            }
            else
            {
                int bl = new BLL.T_RepositoryCategory().Add(T_RepositoryCategory);
                if (bl > 0)
                {
                    res = Success("新增成功", T_RepositoryCategory);
                }
                else
                {
                    res = Error("新增失败");
                }
            }
            return res;
        }

        /// <summary>
        /// 递归获取树形结构
        /// </summary>
        /// <param name="tab">数据源</param>
        /// <param name="parentid">父节点ID</param>
        /// <returns></returns>
        public List<Model.TreeModel> BindTree(DataTable tab, string parentid)
        {
            DataTable tab2 = new DataTable();

            if (tab != null && tab.Rows.Count > 0)
            {
                System.Collections.Generic.List<Model.T_RepositoryCategory> categorylist = new BLL.T_RepositoryCategory().DataTableToList(tab);
                System.Collections.Generic.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_CategoryId.ToString();//当前功能ID
                    model.id = currentID;
                    model.IconCls = "";//图标
                    model.text = categorylist[i].F_CategoryName;
                    tab2 = new BLL.T_RepositoryCategory().GetList("F_ParentId=" + currentID + " and F_DeleteFlag=0 and F_CategoryType=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="f_catagoryid">要删除的工单类别的类别id</param>
        /// <returns></returns>
        public string DeleteWoType(string f_catagoryid)
        {
            //获取它下面的子类别
            string res = string.Empty;
            DataTable dt = new BLL.T_RepositoryCategory().GetList("F_DeleteFlag=0 and F_ParentId=" + Convert.ToInt32(f_catagoryid) + " and F_CategoryType=1").Tables[0];
            string rid = string.Empty;
            if (dt.Rows.Count > 0)
            {
                //先删除子类类别，再删除父类
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    rid = dt.Rows[i]["F_CategoryId"].ToString();
                    if (!string.IsNullOrEmpty(rid))
                    {
                        DataTable dtsub = new BLL.T_RepositoryCategory().GetList("F_DeleteFlag=0 and F_ParentId=" + Convert.ToInt32(rid) + " and F_CategoryType=1").Tables[0];
                        if (dtsub.Rows.Count > 0)
                        {
                            DeleteWoType(dtsub.Rows[i]["F_CategoryId"].ToString());
                        }
                        else
                        {
                            new BLL.T_RepositoryCategory().Delete(Convert.ToInt32(rid));
                        }
                    }
                }
            }
            else
            {
                rid = f_catagoryid;
                new BLL.T_RepositoryCategory().Delete(Convert.ToInt32(rid));
            }
            return res;
        }

        #region 公共属性
        string id = "";
        string name = "";
        string pid = "";
        string sort = "";

        private Model.T_RepositoryCategory T_RepositoryCategory
        {
            get
            {
                Model.T_RepositoryCategory _model = new Model.T_RepositoryCategory();
                id = RequestString.GetFormString("id");
                if (id.Trim() != "")
                {
                    _model.F_CategoryId = Convert.ToInt32(id.Trim());
                }
                else
                {
                    _model.F_CategoryId = 0;
                }
                name = RequestString.GetFormString("name");
                _model.F_CategoryName = name.Trim();

                pid = RequestString.GetFormString("pid");
                try
                {
                    _model.F_ParentId = Convert.ToInt32(pid.Trim());
                }
                catch
                {
                    _model.F_ParentId = 0;
                }

                sort = RequestString.GetFormString("sort");
                try
                {
                    _model.F_Sort = Convert.ToInt32(sort.Trim());
                }
                catch
                {
                    _model.F_Sort = 0;
                }
                if (_model.F_CreateOn == null)
                    _model.F_CreateOn = DateTime.Now;
                //_model.F_DeleteFlag = 0;
                //F_CategoryType = 1为工单类别
                _model.F_CategoryType = 1;
                return _model;
            }
            set
            {
                if (value != null)
                {
                    id = value.F_CategoryId.ToString();
                    pid = value.F_ParentId.ToString();
                    name = value.F_CategoryName;
                    sort = value.F_Sort.ToString();
                }
            }
        }
        #endregion
    }
}