
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using CallCenterApi.Interface.Models;
using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Model;
using RMYY_CallCenter_Api.Models;
using RMYY_CallCenter_Api.Utility;

namespace RMYY_CallCenter_Api.Controllers
{
    public class GongDanTypeController : BaseController
    {
        private Bll.T_Sys_GongDan gongdanBll = new Bll.T_Sys_GongDan();
       private Bll.T_Sys_GongDanType gongdanTypeBll = new Bll.T_Sys_GongDanType();
        #region 工单类型详情
        /// <summary>
        /// 获取列表 flag=0 一级，flag=1 二级三级
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(int pid = 0, int flag = 0)
        {
            string sql = "";
            DataTable gModel = new DataTable();
            if (flag != 0)
            {
                gModel = gongdanBll.GetList(" F_IsDelete=0").Tables[0];
                //if (pid != 0)
                //     gModel = gongdanBll.GetList("").Tables[0];
                //else
                //    return Error("获取信息错误！");
            }
            else
            {
                 sql += $" F_ParentID=0 and F_IsDelete=0";
                 gModel = gongdanBll.GetList(sql).Tables[0];
            }
            List<T_Sys_GongDan> g_list = gongdanBll.DataTableToList(gModel);
            g_list.Sort((x, y) => x.F_Sort - y.F_Sort);
            var treelist = new List<TreeModel>();
            foreach (var item in g_list)
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_GDId.ToString();
                treeModel.identification = item.F_Identification;
                treeModel.IconCls = item.F_ImgUrl;
                treeModel.text = item.F_Name;
                treeModel.parentid = item.F_ParentID.ToString();
                treeModel.TypeId = item.F_TypeId;//工单级别类型
                treeModel.autoDept = item.F_AutoDept;
                treelist.Add(treeModel);
            }
            if (flag != 0)
            {
                foreach (var item in treelist.Where(p=>p.parentid==pid.ToString()))
                {
                    item.children = treelist.TreeRecursion(item.id);
                }
                return Success("获取成功", treelist.Where(p => p.parentid == pid.ToString()));
            }
            else return Success("获取成功！", treelist);
        }
        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult AddGongDan(T_Sys_GongDan input)
        {
            T_Sys_GongDan model = new T_Sys_GongDan();
            model.F_TimeOut = input.F_TimeOut;
          model.F_RepairTimeLimit = input.F_RepairTimeLimit;
            model.F_Name = input.F_Name;
            model.F_Remark = input.F_Remark;
            model.F_Sort = input.F_Sort;
            model.F_ParentID = input.F_ParentID;
            model.F_CreateTime = DateTime.Now;
            model.F_TypeId = input.F_TypeId;
            model.F_AutoDept = input.F_AutoDept;
            model.F_CanReplayCount = input.F_CanReplayCount;
            //if (!string .IsNullOrEmpty (input.F_Identification))
            //{
            //    if (GetIdentification(input.F_Identification) > 0)
            //        return Error("该标识已存在");
            //}
            model.F_Identification = input.F_Identification;
            model.F_CanUrgeCount = input.F_CanUrgeCount;
            if (gongdanBll.Add(model) > 0)
            {
                return Success("类型添加成功！");
            }
            else
            {
                return Error("添加失败，请重试");
            }
        }
        public int GetIdentification(string Identification)
        {
            if (string.IsNullOrEmpty(Identification))
                return 0;
            var sql = "F_Identification='" + Identification + "'  ";
            var count = DbHelperSQL.GetSingle("select count(1)  from T_Sys_GongDan where " + sql).ToString ();
            return int.Parse(count);
        }
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="mId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetModule(int mId = 0)
        {
            var entity_ModuleInfo = gongdanBll.GetModel(mId);
            if (entity_ModuleInfo != null)
            {
                return Success("加载菜单成功", new
                {
                    name = entity_ModuleInfo.F_Name,
                    remark = entity_ModuleInfo.F_Remark,
                    sort = entity_ModuleInfo.F_Sort,
                    fid = entity_ModuleInfo.F_ParentID,
                    identification = entity_ModuleInfo.F_Identification,
                    cstime = entity_ModuleInfo.F_TimeOut,
                    fxtime = entity_ModuleInfo.F_RepairTimeLimit,
                    autodept = entity_ModuleInfo.F_AutoDept,
                    canreplaycount=entity_ModuleInfo.F_CanReplayCount,
                    canurgecount=entity_ModuleInfo.F_CanUrgeCount,
                    tid =entity_ModuleInfo.F_TypeId
                });
            }
            else
            {
                return Error("加载失败");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelModule(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {                    
                    var model = gongdanBll.GetModel(Convert.ToInt32(str));
                    if(model.F_TypeId==1 )
                        return Error("不能删除一级工单类型！");
                    idd += str + ",";
                }
                #region 判断子栏目是否存在
                var sql = "F_IsDelete=0";
                sql += " and F_ParentID in (" + idd.TrimEnd(',') + ") ";
                var list =gongdanBll.GetList(sql).Tables[0];
                if (list.Rows.Count > 0)
                    return Error("操作失败：子栏目存在，不能删除");
                #endregion
                if (gongdanBll.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败,请重试！");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditGongDan(T_Sys_GongDan input)
        {
            var ModuleInfo = gongdanBll.GetModel(input.F_GDId);
            if (ModuleInfo != null)
            {
                ModuleInfo.F_ParentID = input.F_ParentID;
                ModuleInfo.F_Name = input.F_Name;
                ModuleInfo.F_Remark = input.F_Remark;
                ModuleInfo.F_Sort = input.F_Sort;
                ModuleInfo.F_TypeId = input.F_TypeId;
                ModuleInfo.F_TimeOut = input.F_TimeOut;
                ModuleInfo.F_AutoDept = input.F_AutoDept;
                ModuleInfo.F_CanReplayCount = input.F_CanReplayCount;
                ModuleInfo.F_CanUrgeCount = input.F_CanUrgeCount;
                //if (!string.IsNullOrEmpty(input.F_Identification))
                //{
                //    if (GetIdentification(input.F_Identification) > 0&& input.F_Identification!= ModuleInfo.F_Identification)
                //        return Error("该标识已存在");
                //}
                ModuleInfo.F_Identification = input.F_Identification;
                ModuleInfo.F_RepairTimeLimit = input.F_RepairTimeLimit;
                if (gongdanBll.Update(ModuleInfo))
                {
                    return Success("修改成功");
                }
                else
                {
                    return Error("修改失败,请重试！");
                }
            }
            else
            {
                return Error("对象获取失败");
            }
        }

        #endregion

        #region  工单类型
        /// <summary>
        /// 获取类型列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTypeList(FilterDictionary filter)
        {  
                var recordCount = 0;
                var dt = RMYY_CallCenter_Api.Bll.PagerBll.GetListPager(
                  "T_Sys_GongDanType",
                  "F_TypeId",
                  "*",
                  "",
                  "ORDER BY F_TypeId ",
                  filter.PageSize,
                  filter.PageIndex,
                  true,
                  out recordCount);
                List<T_Sys_GongDanType> modelList = gongdanTypeBll.DataTableToList(dt);
                var obj = new
                {
                    rows = modelList.Select(x => new
                    {
                        name = x.F_TypeName,
                        flag = x.F_TypeId
                    }),
                    total = recordCount
                };
              return  Content(obj.ToJson());
        }
        /// <summary>
        /// 添加类型
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult AddType(T_Sys_GongDanType input)
        {
                T_Sys_GongDanType orderModel = new T_Sys_GongDanType();
                orderModel.F_TypeName = input.F_TypeName;
                orderModel.F_Remark = input.F_Remark;
                orderModel.F_CreateTime = DateTime.Now;
                if (gongdanTypeBll.Add(orderModel)>0)
                   return  Success("添加成功");
                else
                   return  Error("添加失败");

        }
        /// <summary>
        /// 编辑类型
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult EditType(T_Sys_GongDanType input)
        {
                T_Sys_GongDanType orderModel = gongdanTypeBll.GetModel(input.F_TypeId);             
                orderModel.F_TypeName = input.F_TypeName;
                orderModel.F_Remark = input.F_Remark;
                //orderModel.F_Sort = input.Sort;
                if (gongdanTypeBll.Update(orderModel))
                    return Success("修改成功");
                else
                    return Error("修改失败");
        }

        //[Authority]
        /// <summary>
        /// 删除类型
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelType(string[] ids)
        {        
                if (ids == null || ids.Length <= 0)
                    return Error("获取参数失败");
                StringBuilder sb = new StringBuilder();
                foreach (var item in ids)
                {
                    sb.Append("'" + item + "',");
                }
                if (gongdanTypeBll.DeleteList(sb.ToString().Trim(',')))
                return Success("删除成功");
                else
                    return Error("删除失败");
        }
        #endregion
    }
}