using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class QuestionManageController : BaseController
    {

        /// <summary>
        ///获取列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(int pid = 0, string type = "")
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            string sql = $" and F_IsDelete=0";
            DataTable dt = new DataTable();

            string name = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (name.Trim() != "")
            {
                sql += " and F_QuestionName like '%" + name + "%'";
            }
            if (!string.IsNullOrEmpty(type))
            {
                sql += $" and F_Type='{type}'";
            }
            if (pid > 0)
            {
                string idstr = GetQueson(pid);
                if (!string.IsNullOrEmpty(idstr))
                {
                    sql += $" and F_Id in({idstr})";
                }
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Wo_QuestionManage",
                "F_Id",
                "*",
                sql,
                "ORDER BY F_Id desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            res = Content(obj.ToJson());

            return res;
        }



        /// <summary>
        /// 获取工单类别
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public string GetQueson(int fid)
        {
            string tsql = fid.ToString();
            string tsql1 = "";
            string tsql2 = "";
            var model = new BLL.T_Wo_QuestionManage().GetModel(fid);
            if (model != null)
            {
                if (model.F_Label == "1")
                {
                    var glist = new BLL.T_Wo_QuestionManage().GetModelList($"F_ParentId={fid} and F_IsDelete=0 ").Select(p => p.F_Id).ToArray();
                    if (glist.Count() > 0)
                    {
                        tsql1 = string.Join(",", glist);

                        var glist1 = new BLL.T_Wo_QuestionManage().GetModelList($"F_ParentId in ({tsql1}) and F_IsDelete=0").Select(p => p.F_Id).ToArray();
                        if (glist1.Count() > 0)
                        {
                            tsql2 = string.Join(",", glist1);
                            tsql += "," + tsql1 + "," + tsql2;
                        }
                        else
                        {
                            tsql += "," + tsql1;
                        }
                    }
                }
                else if (model.F_Label == "2")
                {
                    var glist = new BLL.T_Wo_QuestionManage().GetModelList($"F_ParentId={fid} and F_IsDelete=0").Select(p => p.F_Id).ToArray();
                    if (glist.Count() > 0)
                    {
                        tsql1 = string.Join(",", glist);
                        tsql += "," + tsql1;
                    }
                }
                return tsql;
            }
            else return "";
        }
        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="fid"></param>
        /// <returns></returns>

        public ActionResult GetDetail(int fid=0)
        {
            if (fid <= 0)
                return Error("参数错误");
            string F_ParentName="";
            var model = new BLL.T_Wo_QuestionManage().GetModel(fid);
            if (model.F_ParentId > 0)
            {
                F_ParentName = new BLL.T_Wo_QuestionManage().GetModel(Convert.ToInt32(model.F_ParentId)).F_QuestionName;
            }

            var objmodel = new
            {
                model=model,
                F_ParentName= F_ParentName

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

        }
        /// <summary>
        /// 获取问题类别
        /// </summary>
        /// <param name="pid"></param>
        /// <param name="keywords"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult GetQuestionList(int pid = 0,string type="")
        {
            DataTable dt = new DataTable();
            List<TreeModel> modelist = new List<TreeModel>();
            string sql = $"  F_IsDelete=0";
            if (!string.IsNullOrEmpty(type))
            {
                sql += $" and F_Type='{type}'";
            }
            List<Model.T_Wo_QuestionManage> questlist = new BLL.T_Wo_QuestionManage().GetModelList(sql);
            foreach (var item in questlist.Where(p=>p.F_ParentId==0))
            {
                TreeModel model = new TreeModel();
                model.id = item.F_Id.ToString();
                model.parentid = item.F_ParentId.ToString();
                model.IconCls = "";//图标
                model.text = item.F_QuestionName;
                model.children = BindQuestionTree(questlist,item.F_Id);
                modelist.Add(model);
            }
            return Success("加载成功",modelist);
           
        }

        private List<TreeModel> BindQuestionTree(List<Model.T_Wo_QuestionManage> questlist, int parentid=0)
        {
            List<TreeModel> modelist = new List<TreeModel>();
            List<Model.T_Wo_QuestionManage> itemlist = questlist.Where(p => p.F_ParentId == parentid).ToList();
            if (itemlist.Count > 0 && parentid>0 )
            {
                foreach (var item in itemlist)
                {
                    TreeModel model = new TreeModel();
                    model.id = item.F_Id.ToString();
                    model.parentid = item.F_ParentId.ToString();
                    model.IconCls = "";//图标
                    model.text = item.F_QuestionName;
                    model.children = BindQuestionTree(questlist, item.F_Id);
                    modelist.Add(model);
                }
                return modelist;

            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 添加/修改问题
        /// </summary>
        /// <returns></returns>
        public ActionResult AddQuestion()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        int id = RequestString.GetInt("id", 0);
                        string content = RequestString.GetFormString("content");
                        string type = RequestString.GetFormString("type");
                        int pid = RequestString.GetInt("pid", 0);
                        int layer = RequestString.GetInt("layer", 1);
                        string deal = RequestString.GetFormString("deal");
                        string remark = RequestString.GetFormString("remark");
                        string usercode = RequestString.GetFormString("usercode");
                        string cont = RequestString.GetFormString("cont");

                        Model.T_Wo_QuestionManage model = new Model.T_Wo_QuestionManage();

                        if (id == 0)
                        {
                            model.F_QuestionName = cont;
                            model.F_QuestionContent = content;
                            model.F_ParentId = pid;
                            model.F_Label = layer.ToString();
                            model.F_DealMethods = deal;
                            model.F_Type = type;
                            model.F_Remark = remark;
                            model.F_CreateBy = ua.F_UserCode;
                            model.F_CreateOn = DateTime.Now;
                            model.F_IsDelete = 0;

                            if (new BLL.T_Wo_QuestionManage().Add(model) > 0)
                            {
                                res = Success("新增成功！");
                            }
                            else
                            {
                                res = Error("新增失败！");
                            }
                        }
                        else
                        {
                            model = new BLL.T_Wo_QuestionManage().GetModel(id);
                            if (model != null)
                            {
                                model.F_QuestionName = cont;
                                model.F_QuestionContent = content;
                                model.F_ParentId = pid;
                                model.F_Label = layer.ToString();
                                model.F_DealMethods = deal;
                                model.F_Type = type;
                                model.F_Remark = remark;
                                model.F_UpdateBy = ua.F_UserCode;
                                model.F_UpdateOn = DateTime.Now;
                                model.F_UpdateCount = model.F_UpdateCount ?? 0 + 1;
                                if (new BLL.T_Wo_QuestionManage().Update(model))
                                {
                                    res = Success("修改成功！");
                                }
                                else
                                {
                                    res = Error("修改失败！");
                                }
                            }
                            else
                            {
                                res = Error("修改失败！");
                            }
                        }
                    }
                }

            }
            return res;
        }


        /// <summary>
        /// 删除问题
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult Delete(string[] ids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                int userId = CurrentUser.UserData.F_UserId;
                if (userId != 0)
                {
                    Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                    if (ua != null)
                    {
                        if (ids != null && ids.Length > 0)
                        {
                            string idd = " ";
                            foreach (string str in ids)
                            {
                                var model = new BLL.T_Wo_QuestionManage().GetModel(Convert.ToInt32(str));
                                if (model != null)
                                {
                                    string sqlstr = $" F_ParentId={model.F_Id} and F_IsDelete=0 ";
                                    var modelson = new BLL.T_Wo_QuestionManage().GetModelList(sqlstr);
                                    if (modelson.Count > 0)
                                    {
                                       return  Error("删除失败，此问题下存在子类问题，请先删除子类问题！");
                                    }
                                }
                                idd += str + ",";
                            }
                            string sql = "update T_Wo_QuestionManage set F_IsDelete=1,F_DeleteBy='" + ua.F_UserCode + "',F_DeleteOn=getdate() where F_Id in(" + idd.TrimEnd(',') + ")";
                            if (!string.IsNullOrEmpty(idd.Trim()))
                            {
                                if (DbHelperSQL.ExecuteSql(sql) > 0)
                                {
                                    res = Success("删除成功");
                                }
                                else
                                {
                                    res = Error("删除失败");
                                }
                            }
                            else
                            {
                                res = Error("请选择记录");
                            }
                        }
                        else
                        {
                            res = Error("获取参数失败");
                        }
                    }
                }
            }
            return res;
        }


    }

}