web api+遞歸樹型結構

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SqlSugar;
using Models;
using WebApplication.Dao;
using System.Text;

namespace WebApplication.Controllers
{
    /// <summary>
    /// 分類接口
    /// </summary>
    public class classificationController : ApiController
    {
        /// <summary>
        /// 獲取分類列表(條件查詢,分頁) http://192.168.2.177:1222/api/classification/GetclassificationListPage?pageIndex=1&pageSize=10&status=2&title=
        /// </summary>
        /// <param name="pageIndex">分頁索引</param>
        /// <param name="pageSize">分頁大小</param>
        /// <param name="status">狀態:0:下線 1:上線  -1:失效,默認傳入2獲取全部數據</param>
        /// <param name="title"></param>
        /// <returns></returns>
        [Route("api/classification/GetclassificationListPage")]
        [HttpGet]
        public string GetclassificationListPage(int pageIndex, int pageSize, int status, string title)
        {
            try
            {
                using (var db = SugarDao.GetInstance())
                {

                    var qable = db.Queryable<tb_classification>();
                    var dataCountTable = db.Queryable<tb_classification>();

                    if (status != 2)
                    {
                        qable = qable.Where(i => i.status == status);
                        dataCountTable = dataCountTable.Where(i => i.status == status);
                    }
                    if (status == 2)
                    {
                        dataCountTable = dataCountTable.Where(i => i.status != status);
                    }
                    if (!string.IsNullOrEmpty(title))
                    {
                        qable = qable.Where(i => i.title.Contains(title));
                        dataCountTable = dataCountTable.Where(i => i.title.Contains(title));
                    }


                    var data = qable.OrderBy(it => it.createtime, OrderByType.Asc).ToPageList(pageIndex, pageSize);

                    var dataCount = dataCountTable.ToList().Count;

                    if (data.Count > 0)
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據成功", Data = data, Count = dataCount });
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據失敗", Data = data, Count = dataCount });
                    }

                }
            }
            catch (Exception ex)
            {
                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "獲取數據失敗,緣由爲:" + ex.Message });
            }
        }

        /// <summary>
        /// 獲取分類數據,不分頁 http://192.168.2.177:1222/api/classification/GetclassificationList?status=2&title=
        /// </summary>
        /// <param name="status"></param>
        /// <param name="title"></param>
        /// <returns></returns>
        [Route("api/classification/GetclassificationList")]
        [HttpGet]
        public string GetclassificationList(int status, string title)
        {
            try
            {
                using (var db = SugarDao.GetInstance())
                {
                    var qable = db.Queryable<tb_classification>();
                    if (status != 2)
                    {
                        qable = qable.Where(i => i.status == status);
                    }
                    if (!string.IsNullOrEmpty(title))
                    {
                        qable = qable.Where(i => i.title.Contains(title));
                    }
                    var data = qable.OrderBy(it => it.createtime, OrderByType.Asc).ToList();
                    var dataCount = db.Queryable<tb_classification>().Where(it => it.status != status).ToList().Count;
                    if (data.Count > 0)
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據成功", Data = data, Count = dataCount });
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據失敗", Data = data, Count = dataCount });
                    }

                }
            }
            catch (Exception ex)
            {
                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "獲取數據失敗,緣由爲:" + ex.Message });
            }
        }

        /// <summary>
        /// 根據id獲得對象 http://192.168.2.177:1222/api/classification/GetclassificationModel?id=1
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("api/classification/GetclassificationModel")]
        [HttpGet, HttpPost]
        public string GetclassificationModel(int id)
        {
            try
            {
                using (var db = SugarDao.GetInstance())
                {
                    if (id != 0)
                    {
                        var classification = db.Queryable<tb_classification>().Single(it => it.id == id);
                        if (classification != null)
                        {
                            return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據成功", Data = classification });
                        }
                        else
                        {
                            return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據失敗", Data = classification });
                        }
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據失敗,沒法找到id爲:" + id + "的數據", });
                    }

                }
            }
            catch (Exception ex)
            {
                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "獲取數據失敗,緣由爲:" + ex.Message });
            }
        }
        /// <summary>
        /// 新增分類 http://192.168.2.177:1222/api/classification/Postclassification
        /// </summary>
        /// <param name="classification"></param>
        [Route("api/classification/Postclassification")]
        [HttpPost]
        public string Postclassification(tb_classification classification)
        {
            try
            {
                classification.createtime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                using (var db = SugarDao.GetInstance())
                {
                    object result = db.Insert<tb_classification>(classification);
                    if (Convert.ToInt64(result) > 0)
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "添加成功" });
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "添加失敗" });
                    }
                }
            }
            catch (Exception ex)
            {

                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "添加失敗,緣由爲:" + ex.Message });
            }
        }
        /// <summary>
        /// 修改分類
        /// </summary>
        /// <param name="id"></param>
        /// <param name="value"></param>
        [Route("api/classification/Putclassification")]
        [HttpPost]
        public string Putclassification(tb_classification classification)
        {
            try
            {
                classification.createtime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                using (var db = SugarDao.GetInstance())
                {
                    bool result = db.Update<tb_classification>(classification, it => it.id == classification.id);
                    if (result == true)
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "更新成功" });
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "更新失敗" });
                    }
                }
            }
            catch (Exception ex)
            {
                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "更新失敗,緣由爲:" + ex.Message });
            }
        }
        /// <summary>
        /// 刪除 http://192.168.2.177:1222/api/classification/Deleteclassification?ids=4,5
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("api/classification/Deleteclassification")]
        [HttpGet, HttpPost]
        public string Deleteclassification(string ids)
        {
            try
            {
                string[] input = ids.Split(',');
                int[] output = Array.ConvertAll<string, int>(input, delegate (string s) { return int.Parse(s); });

                using (var db = SugarDao.GetInstance())
                {
                    bool result = db.Delete<tb_classification, int>(output);
                    if (result == true)
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "刪除成功" });
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "刪除失敗" });
                    }
                }
            }
            catch (Exception ex)
            {
                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "刪除失敗,緣由爲:" + ex.Message });
            }
        }

        /// <summary>
        /// 更新狀態 http://192.168.2.177:1222/api/classification/UpdateStatus?status=0&ids=2,7
        /// </summary> 
        /// <param name="status">狀態:0:下線 1:上線  -1:失效 </param>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Route("api/classification/UpdateStatus")]
        [HttpGet]
        public string UpdateStatus(int status, string ids)
        {
            try
            {
                string[] input = ids.Split(',');
                int[] output = Array.ConvertAll<string, int>(input, delegate (string s) { return int.Parse(s); });
                using (var db = SugarDao.GetInstance())
                {
                    bool result = db.Update<tb_classification, int>(new { status = status }, output);
                    if (result == true)
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "狀態更改爲功" });
                    }
                    else
                    {
                        return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "狀態更改失敗" });
                    }
                }
            }
            catch (Exception ex)
            {
                return SqlSugar.JsonConverter.Serialize(new { Result = 0, Msg = "狀態更改失敗,緣由爲:" + ex.Message });
            }
        }

        string result = string.Empty;
        /// <summary>
        /// 分類樹形結構  http://192.168.2.177:1222/api/classification/GetclassificationTree
        /// </summary>
        /// <returns></returns>
        [Route("api/classification/GetclassificationTree")]
        [HttpGet]
        public string GetclassificationTree()
        {
         
            WebApplication.Controllers.TreeMethod tm = new TreeMethod();

            // 找到全部的父節點  
            List<TreeEntity> treeList1 = tm.findAllParents();

            if (treeList1 != null)
            {
                for (int i = 0; i < treeList1.Count; i++)
                {
                    TreeEntity tree = treeList1[i];
                    // 打印父節點  
                    result += "|--" + tree.name;
                    // 綁定孩子  
                    result+=tm.BindChildByParent(tree.id, "");
                }
            }
            else
            {
                result += "沒有數據!";
            }
            return SqlSugar.JsonConverter.Serialize(new { Result = 1, Msg = "獲取數據成功",Data= result });
        }
    }
    public class TreeEntity
    {
        public string id { get; set; }
        public string name { get; set; }
        public string pid { get; set; }
    }
    internal class TreeMethod
    {
        /// <summary>
        /// 找到全部的父節點
        /// </summary>
        /// <returns></returns>
        public List<TreeEntity> findAllParents()
        {
            List<TreeEntity> treeList = new List<TreeEntity>();

            using (var db = SugarDao.GetInstance())
            {
                var list = db.Queryable<tb_classification>().Where(it => it.pid == 0 && it.status==1).ToList();
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        TreeEntity myTree = new TreeEntity();
                        myTree.id = list[i].id.ToString();
                        myTree.name = list[i].title;
                        myTree.pid = list[i].pid.ToString();
                        treeList.Add(myTree);
                    }
                }
            }
            return treeList;
        }

        /// <summary>
        /// 根據父節點找到全部的子節點
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public List<TreeEntity> findChildByPid(string pid)
        {
            int p_id = Convert.ToInt32(pid);
            List<TreeEntity> treeList = new List<TreeEntity>();

            using (var db = SugarDao.GetInstance())
            {
                var list = db.Queryable<tb_classification>().Where(it => it.pid == p_id&&it.status==1).ToList();
                if (list.Count > 0)
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        TreeEntity myTree = new TreeEntity();
                        myTree.id = list[i].id.ToString();
                        myTree.name = list[i].title;
                        myTree.pid = list[i].pid.ToString();
                        treeList.Add(myTree);
                    }
                }
            }
            return treeList;
        }
        /// <summary>
        /// 查看是否存在子節點
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public bool HasChild(string pid)
        {
            int p_id = Convert.ToInt32(pid);
            int count = 0;
            bool flag = false;
            using (var db = SugarDao.GetInstance())
            {
                var list = db.Queryable<tb_classification>().Where(it => it.pid == p_id&it.status==1).ToList();

                for (int i = 0; i < list.Count; i++)
                {
                    count++;
                }
                if (count > 0)
                {
                    flag = true;
                }
            }
            return flag;
        }
        string Tree = string.Empty;
        /// <summary>
        /// 使用遞歸拼接父節點的子節點
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="prefix"></param>
        public string BindChildByParent(string pid, string prefix)
        {
           
            if (this.HasChild(pid))
            {
                // 獲得當前父節點下的全部孩子  
                List<TreeEntity> list = this.findChildByPid(pid);
                // 循環打印當前父節點下的孩子  
                for (int i = 0; i < list.Count; i++)
                {
                    Tree += "|----" + prefix + list[i].name;
                    if (this.HasChild(list[i].id))
                    {
                        this.BindChildByParent(list[i].id, "--");
                    }
                }
            }
            return Tree;
        }
    }
}
View Code
相關文章
相關標籤/搜索