using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Filter;
using CallCenterApi.Interface.Models.Input;
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.Question
{
    public class QuestionnaireController : BaseController
    {
        private readonly BLL.T_Ask_QuestionCategory qCategoryBLL = new BLL.T_Ask_QuestionCategory();
        private readonly BLL.T_Ask_Question questionBLL = new BLL.T_Ask_Question();
        private readonly BLL.T_Ask_QuestionItems questionItemBLL = new BLL.T_Ask_QuestionItems();
        private readonly BLL.T_Ask_PagerInfo pagerInfoBLL = new BLL.T_Ask_PagerInfo();
        private readonly BLL.T_Ask_PagerItems pagerInfoItemsBLL = new BLL.T_Ask_PagerItems();

        #region 问卷设置 - 试题问卷
        /// <summary>
        /// 问卷设置 - 试题问卷
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public ActionResult GetPagerInfoList(FilterPagerInfo filter)
        {
            string sql = "";
            if (!string.IsNullOrWhiteSpace(filter.Key))
            {
                sql += $" and (F_Title like '%{ filter.Key.Trim()}%' or F_Remark like '%{ filter.Key.Trim()}%') ";
            }
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Ask_PagerInfo",
                    "F_PagerId",
                    "*",
                    " and F_DeleteFlag=0 " + sql,
                    "ORDER BY F_PagerId desc",
                    filter.PageSize,
                    filter.PageIndex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        public ActionResult GetPagerInfoModel(int pid)
        {
            var model = pagerInfoBLL.GetModel(pid);
            return Success("获取成功", model);
        }
        public ActionResult CreateOrUpdatePager(Pagerinfo input)
        {
            var model = new Model.T_Ask_PagerInfo();
            if (input.Id <= 0)
            {
                model.F_Title = input.Title;
                model.F_Remark = input.Remark;
                model.F_Times = input.Times;
                model.F_DeleteFlag = 0;
                model.F_CreateOn = DateTime.Now;
                model.F_CreateBy = CurrentUser.UserData.F_UserId;
                if (pagerInfoBLL.Add(model) > 0)
                    return Success("添加成功");
                return Error("添加失败");
            }
            model = pagerInfoBLL.GetModel(input.Id);
            model.F_Title = input.Title;
            model.F_Remark = input.Remark;
            model.F_Times = input.Times;
            model.F_DeleteFlag = 0;
            model.F_ModifyBy = CurrentUser.UserData.F_UserId;
            model.F_ModifyOn = DateTime.Now;
            if (pagerInfoBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        public ActionResult GetAllPagerInfo()
        {
            var pagerInfoList = pagerInfoBLL.DataTableToList(pagerInfoBLL.GetList(" F_DeleteFlag=0 ").Tables[0]);
            return Success("获取成功", pagerInfoList.Select(x => new
            {
                id = x.F_PagerId,
                name = x.F_Title
            }));
        }

        /// <summary>
        /// 选择试题 - 修改 - 选择试题（左侧）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQuestionNotItemsList(FilterQuestion filter)
        {
            StringBuilder sb = new StringBuilder();

            if (filter.CategoryId > 0)
            {
                sb.Append(" and F_CategoryId=" + filter.CategoryId);
            }
            if (filter.SelectType > 0)
            {
                sb.Append(" and F_Type=" + filter.SelectType);
            }
            if (filter.PagerId > 0)
            {
                sb.Append(" and F_QuestionId not in (SELECT [F_QuestionId] FROM [T_Ask_PagerItems] where [F_PagerId]=" + filter.PagerId + ") ");
            }
            if (!string.IsNullOrWhiteSpace(filter.Key))
            {
                sb.Append(" and (F_Title like '%" + filter.Key + "%' or F_Content like '%" + filter.Key + "%') ");
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "vw_Ask_Question",
                    "F_QuestionId",
                    "*",
                    " and F_DeleteFlag=0 " + sb.ToString(),
                    "ORDER BY F_QuestionId desc",
                    filter.PageSize,
                    filter.PageIndex,
                    true,
                    out recordCount);
            var quesitemlist = questionItemBLL.GetModelList("");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var items = "";
                string qid = dt.Rows[i]["F_QuestionId"].ToString();
                var quesitem = quesitemlist.Where(qi => qi.F_QuestionId == int.Parse(qid));
                if (quesitem.Count() > 0)
                {
                    foreach (var item in quesitem)
                    {
                        items += "；" + item.F_ItemName;
                    }
                }

                dt.Rows[i]["F_Content"] = items.Trim('；');
            }
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 选择试题 - 修改 - 选择试题（右侧）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetQuestionPageList(FilterQuestion filter)
        {
            StringBuilder sb = new StringBuilder();

            if (filter.PagerId > 0)
            {
                sb.Append(" and F_PagerId=" + filter.PagerId);
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "vw_Ask_PagerQuestion",
                    "F_ItemId",
                    "*",
                    " and F_DeleteFlag=0 " + sb.ToString(),
                    "ORDER BY F_Sort desc",
                    filter.PageSize,
                    filter.PageIndex,
                    true,
                    out recordCount);

            var quesitemlist = questionItemBLL.GetModelList("");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var items = "";
                string qid = dt.Rows[i]["F_QuestionId"].ToString();
                var quesitem = quesitemlist.Where(qi => qi.F_QuestionId == int.Parse(qid));
                if (quesitem.Count() > 0)
                {
                    foreach (var item in quesitem)
                    {
                        items += "；" + item.F_ItemName;
                    }
                }

                dt.Rows[i]["F_Content"] = items.Trim('；');
            }

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        /// <summary>
        /// 选择试题 - 修改 - 批量选入（左侧 -> 右侧）
        /// </summary>
        /// <returns></returns>
        public ActionResult AddPagerItems(string[] ids, string pid, string sort = "0")
        {
            //string[] arrid = ids.Split(',');
            if (ids.Count() > 0)
            {
                int intsort = 0;
                intsort = Convert.ToInt32(sort) + 1;
                int cc = 0;
                foreach (string squestionid in ids)
                {
                    Model.T_Ask_PagerItems model = new Model.T_Ask_PagerItems();
                    int pagerid = 0;
                    int questionid = 0;
                    pagerid = Convert.ToInt32(pid);
                    questionid = Convert.ToInt32(squestionid);
                    model.F_PagerId = pagerid;
                    model.F_QuestionId = questionid;
                    model.F_Sort = intsort;
                    intsort++;
                    if (pagerInfoItemsBLL.Add(model) > 0)
                    {
                        cc++;
                    }
                }
                if (cc == ids.Length)
                {
                    return Success("选入成功");
                }
            }
            return Error("选入失败");
        }
        /// <summary>
        /// 选择试题 - 修改 - 批量选出（右侧 -> 左侧）
        /// </summary>
        /// <returns></returns>
        public ActionResult DelPagerItems(string[] ids)
        {
            //string[] arrid = ids.Split(',');
            if (ids.Length > 0)
            {
                int cc = 0;
                foreach (string itemid in ids)
                {
                    if (pagerInfoItemsBLL.Delete(Convert.ToInt32(itemid)))
                    {
                        cc++;
                    }
                }
                if (cc == ids.Length)
                {
                    return Success("选出成功");
                }
            }
            return Error("选出失败");
        }

        /// <summary>
        /// 删除试题问卷(删除两表信息)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeletePagerInfo(int id = 0)
        {
            if (pagerInfoBLL.Delete(id))
            {
                pagerInfoItemsBLL.DeleteByPagerId(id);
                return Success("删除成功"); ;
            }
            else
            {
                return Error("删除失败");
            }
        }
        #endregion

        #region 问卷设置 - 问卷信息
        public ActionResult GetPagerInfoQ(int pid)
        {
            var model = pagerInfoBLL.GetModel(pid);
            var qlist = questionBLL.GetModelList(" F_DeleteFlag=0 and F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + pid + ")  order by F_QuestionId ");
            var qilist = questionItemBLL.GetModelList(" F_QuestionId in (select F_QuestionId from T_Ask_PagerItems where F_PagerId=" + pid + ")  order by F_ItemId ");

            var newmodel = new
            {
                F_Title = model.F_Title,
                F_Remark = model.F_Remark,
                F_Questions = qlist.Select(q =>
                {
                    return new
                    {
                        quesid = q.F_QuestionId,
                        questitle = q.F_Title,
                        questype = q.F_Type,
                        quescontent = q.F_Content,
                        quesremark = q.F_Remark,
                        quesitems = qilist.Where(qq => qq.F_QuestionId == q.F_QuestionId).Select(qi =>
                        {
                            return new
                            {
                                itemid = qi.F_ItemId,
                                itemname = qi.F_ItemName,
                                itemremark = qi.F_Remark,
                            };
                        })
                    };
                })
            };

            return Success("获取成功", newmodel);
        }
        #endregion

        #region 试题管理 - 试题分类
        /// <summary>
        /// 试题管理 - 试题分类
        /// </summary>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        public ActionResult GetQCategoryList(int pagesize = 10, int pageindex = 1)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Ask_QuestionCategory",
                    "F_CategoryId",
                    "*",
                    "",
                    "ORDER BY F_CategoryId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        public ActionResult GetQCategoryAlllist()
        {
            var alllist = qCategoryBLL.GetModelList(" 1=1 order by F_CategoryId desc");
            return Success("获取试题分类成功", alllist);
        }
        public ActionResult GetQCategoryModel(int id = 0)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = qCategoryBLL.GetModel(id);
            if (model == null)
                return Error("当前数据不存在");
            return Success("", model);
        }
        public ActionResult CreateOrUpdateQCategory(int id = 0, string name = "")
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var model = new Model.T_Ask_QuestionCategory();
            if (string.IsNullOrWhiteSpace(name))
                return Error("请填写名称");
            if (id <= 0)
            {
                model.F_CategoryName = name;
                model.F_CreateOn = DateTime.Now;
                model.F_CreateBy = CurrentUser.UserData.F_UserId;
                model.F_DeleteFlag = 0;
                if (qCategoryBLL.Add(model) > 0)
                    return Success("添加成功");
                return Error("添加失败");
            }
            model = qCategoryBLL.GetModel(id);
            model.F_CategoryName = name;
            if (qCategoryBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        public ActionResult DeleteQCategory(int id = 0)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            if (qCategoryBLL.Delete(id))
                return Success("删除成功");
            return Error("删除失败");
        }
        #endregion

        #region 试题管理 - 试题列表
        public ActionResult GetQuestionList(FilterQuestion filter)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            StringBuilder sb = new StringBuilder();

            if (filter.CategoryId > 0)
            {
                sb.Append(" and F_CategoryId=" + filter.CategoryId);
            }
            if (filter.SelectType > 0)
            {
                sb.Append(" and F_Type=" + filter.SelectType);
            }

            if (!string.IsNullOrWhiteSpace(filter.Key))
            {
                sb.Append(" and (F_Title like '%" + filter.Key + "%' or F_Content like '%" + filter.Key + "%') ");
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "vw_Ask_Question",
                    "F_QuestionId",
                    "*",
                    " and F_DeleteFlag=0 " + sb.ToString(),
                    "ORDER BY F_QuestionId desc",
                    filter.PageSize,
                    filter.PageIndex,
                    true,
                    out recordCount);
            var quesitemlist = questionItemBLL.GetModelList("");

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var items = "";
                string qid = dt.Rows[i]["F_QuestionId"].ToString();
                var quesitem = quesitemlist.Where(qi => qi.F_QuestionId == int.Parse(qid));
                if (quesitem.Count() > 0)
                {
                    foreach (var item in quesitem)
                    {
                        items += "；" + item.F_ItemName;
                    }
                }

                dt.Rows[i]["F_Content"] = items.Trim('；');
            }

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        public ActionResult GetQuestionModel(int id = 0)
        {
            if (id <= 0)
                return Error("参数不正确");
            var model = questionBLL.GetModel(id);
            if (model == null)
                return Error("当前数据不存在");
            return Success("获取成功", model);
        }
        public ActionResult CreateOrUpdateQuestion(QuesttionInput input)
        {
            DataTable dt = new DataTable();
            var model = new Model.T_Ask_Question();
            if (string.IsNullOrWhiteSpace(input.F_Title))
                return Error("请填写试题标题");
            //1问答题 2单选题 3多选题
            if (input.F_Type > 1)
            {
                //var questionItemList = questionItemBLL.DataTableToList(questionItemBLL.GetList($" F_QuestionId='{input.F_QuestionId}' ORDER BY F_Sort ").Tables[0]);
                #region 获取内容F_Content，格式：A.满意;B.一般;C.不满意;
                string[] arr1 = new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
                string[] arr2 = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T" };
                dt = new BLL.T_Ask_QuestionItems().GetList(" F_QuestionId=" + input.F_QuestionId + " ORDER BY F_Sort ").Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string vsort = "";
                    if (input.F_SortModel == 1)
                    {
                        vsort = arr2[i];
                    }
                    else
                    {
                        vsort = arr1[i];
                    }
                    input.F_Content += vsort + "." + dt.Rows[i]["F_ItemName"].ToString().Trim() + ";";
                }
                model.F_SortModel = input.F_SortModel;
                #endregion
            }
            else
            {
                model.F_SortModel = null;
            }
            if (input.F_QuestionId <= 0)
            {
                //model.F_SortModel = input.F_SortModel;
                model.F_QuestionId = CurrentUser.UserData.F_UserId;
                model.F_CategoryId = input.F_CategoryId;
                model.F_Type = input.F_Type;
                model.F_Title = input.F_Title;
                model.F_Content = input.F_Content;
                model.F_CreateOn = DateTime.Now;
                model.F_CreateBy = CurrentUser.UserData.F_UserId;
                model.F_ModifyOn = DateTime.Now;
                model.F_ModifyBy = CurrentUser.UserData.F_UserId;
                model.F_DeleteFlag = 0;
                if (questionBLL.Add(model) > 0)
                    return Success("添加成功");
                return Error("添加失败");
            }
            model = questionBLL.GetModel(input.F_QuestionId);
            //model.F_SortModel = input.F_SortModel;
            model.F_CategoryId = input.F_CategoryId;
            model.F_Title = input.F_Title;
            model.F_Type = input.F_Type;
            model.F_Content = input.F_Content;
            model.F_ModifyOn = DateTime.Now;
            model.F_ModifyBy = CurrentUser.UserData.F_UserId;
            if (questionBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        /// <summary>
        ///  删除试题列表(删除两表信息)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteQuestion(int id = 0)
        {
            if (questionBLL.Delete(id))
            {
                questionItemBLL.DeleteByQuestionId(id); ;
                return Success("删除成功"); ;
            }
            else
            {
                return Error("删除失败!");
            }
        }
        #endregion

        #region 试题管理 - 试题列表 -- 问题答案管理
        public ActionResult GetQuestionItemList(int pagesize = 10, int pageindex = 1, int id = 0)
        {
            //if (!Request.IsAuthenticated)
            //    return NoToken("未知错误，请重新登录");
            var sql = "";
            if (id > 0)
            {
                sql = " and F_QuestionId=" + id;
            }
            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
                    "T_Ask_QuestionItems",
                    "F_ItemId",
                    "*",
                    "  " + sql,
                    "ORDER BY F_Sort ",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }
        public ActionResult GetQuestionItemModel(int id = 0)
        {
            var model = questionItemBLL.GetModel(id);
            if (model == null)
                return Error("当前数据不存在");
            return Success("", model);
        }
        public ActionResult CreateOrUpdateQuestionItem(QuesttionItemInput input)
        {
            var model = new Model.T_Ask_QuestionItems();
            if (input.Id <= 0)
            {
                model.F_ItemName = input.Name;
                model.F_QuestionId = input.QuestionId;
                model.F_Remark = input.Remark;
                //model.F_IsAnswer = input.IsAnswer;
                //model.F_Sort = input.Sort;
                //model.F_SortModel = input.SortMode;
                if (questionItemBLL.Add(model) > 0)
                    return Success("添加成功");
                return Error("添加失败");
            }
            model = questionItemBLL.GetModel(input.Id);
            model.F_ItemName = input.Name;
            model.F_QuestionId = input.QuestionId;
            model.F_Remark = input.Remark;
            //model.F_IsAnswer = input.IsAnswer;
            //model.F_Sort = input.Sort;
            //model.F_SortModel = input.SortMode;
            if (questionItemBLL.Update(model))
                return Success("修改成功");
            return Error("修改失败");
        }
        public ActionResult DeleteQuestionItme(int id = 0)
        {
            if (questionItemBLL.Delete(id))
                return Success("删除成功");
            return Error("删除失败");
        }
        #endregion

        #region 问卷调查报告数据简单查询
        public ActionResult GetReport(string TaskID)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            DataTable dtnew = null;
            dtnew.Columns.Add("问题");
            dtnew.Columns.Add("选项");
            dtnew.Columns.Add("数量");
            //List<Model.T_Ask_Question> qrlist = new List<Model.T_Ask_Question>();
            DataSet ds = DbHelperSQL.Query("SELECT * FROM T_Ask_Question WHERE F_QuestionId IN (select ta.F_QuestionId from  T_Ask_PagerItems ta where ta.F_PagerId=(select F_PagerID from T_Call_OutTask where F_TaskID='" + TaskID + "') )");
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable dt = ds.Tables[0];
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string content = dt.Rows[i]["F_Content"].ToString();
                    string[] item = content.Split(';');
                    for (int j = 0; j < item.Length; j++)
                    {
                        if (item[j].Length > 0)
                        {
                            DataRow dr = dtnew.NewRow();
                            dr["问题"] = dt.Rows[i]["F_Title"].ToString();
                            dr["选项"] = item[j].ToString();
                            dtnew.Rows.Add(dr);
                        }
                    }

                }
            }
            res = Success("获取调查报表数据成功", dtnew);

            return res;
        }
        #endregion
    }
}