using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
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.Satisfaction
{    
    /// <summary>
    /// 满意度管理
    /// </summary>
    public class QuestionAnswerController : BaseController
    {
        private BLL.T_Que_Question_Answer bllQue = new BLL.T_Que_Question_Answer();
        private BLL.T_Que_Question_Map bllQueMap = new BLL.T_Que_Question_Map();
        //private BLL.T_Wo_WorkOrder_Que_Map bllOrderQueMap = new BLL.T_Wo_WorkOrder_Que_Map();

        #region 题目和问答管理 - 满意度
        /// <summary>
        /// 题目列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList()
        {
            DataTable dt = new DataTable();
            int parentid = Utils.StrToInt(RequestString.GetQueryString("parentid"), 0);
            string title = RequestString.GetQueryString("title");
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            var sql = " and ISNULL(IsDelete,0) = 0 ";
            sql += " and ParendId = " + parentid + " ";
            if (!string.IsNullOrEmpty(title))
            {
                sql += " and Title like '%" + title.Trim() + "%' ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "dbo.T_Que_Question_Answer (NOLOCK)",
                "T_Que_Question_Answer.Id",
                "*",
                sql,
                "ORDER BY T_Que_Question_Answer.OrderBy,T_Que_Question_Answer.Id",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取部门
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public ActionResult GetInfo(int id = 0)
        {
            var dModel = bllQue.GetModel(id);
            if (dModel != null)
                return Success("获取成功", new
                {
                    Id = dModel.Id,
                    Title = dModel.Title,
                    ParendId = dModel.ParendId,
                    Score = dModel.Score,
                    OrderBy = dModel.OrderBy,
                    Remark = dModel.Remark
                });
            return Error("获取失败");
        }


        /// <summary>
        /// 添加题目和问题
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult Add(Que_QuestionInput input)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (string.IsNullOrEmpty(input.Title))
                return Error("名称不能为空");
            var model = new Model.T_Que_Question_Answer();
            //model.Id = input.Id;
            model.Title = input.Title;          //标题
            model.ParendId = input.ParendId;    //级别（父级子级）
            model.Layer = input.Layer;          //层数
            model.Score = input.Score;          //分数
            model.OrderBy = input.OrderBy;      //排序
            //model.IsDelete = input.IsDelete;  //是否删除
            model.Remark = input.Remark;        //备注
            long b = bllQue.Add(model);
            if (b > 0)
                return Success("添加成功");
            else
                return Error("添加失败");
        }

        /// <summary>
        /// 修改题目和问题
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public ActionResult Update(Que_QuestionInput input)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (input.Id <= 0)
                return Error("参数错误");
            if (string.IsNullOrEmpty(input.Title))
                return Error("名称不能为空");
            var model = bllQue.GetModel(input.Id);
            if (model == null)
                return Error("对象不存在");
            //model.Id = input.Id;
            model.Title = input.Title;          //标题
            model.ParendId = input.ParendId;    //级别（父级子级）
            model.Layer = input.Layer;          //层数
            model.Score = input.Score;          //分数
            model.OrderBy = input.OrderBy;      //排序
            //model.IsDelete = input.IsDelete;  //是否删除
            model.Remark = input.Remark;        //备注
            bool b = bllQue.Update(model);
            if (b)
                return Success("修改成功");
            else
                return Error("修改失败");
        }

        /// <summary>
        /// 删除题目和问题
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="parentid"></param>
        /// <returns></returns>
        public ActionResult Delete(string[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return Error("获取参数失败");
            StringBuilder sb = new StringBuilder();
            foreach (var item in ids)
            {
                sb.Append("" + item + ",");
            }
            #region 判断子栏目是否存在
            var sql = "";
            sql += " ISNULL(IsDelete,0) = 0 AND ParendId in (" + sb.ToString().Trim(',') + ") ";
            var list = bllQue.DataTableToList(bllQue.GetList(sql).Tables[0]);
            if (list.Count > 0)
                return Error("操作失败：问答存在，不能删除");
            #endregion
            string sqlwhereGoods = $" UPDATE dbo.T_Que_Question_Answer SET IsDelete = 1 WHERE ISNULL(IsDelete,0) = 0 AND Id IN ({sb.ToString().Trim(',')}) "; //删除
            int n = DbHelperSQL.ExecuteSql(sqlwhereGoods);
            if (n > 0)
                return Success("删除成功");
            else
                return Error("删除失败");
        }
        #endregion

        #region 试卷试题 和 问卷结果 - 满意度

        /// <summary>
        /// 试卷试题 - 满意度 - 下拉
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult GetQuestionPager()
        {
            var qlists = bllQue.DataTableToList(bllQue.GetList(" 1=1 AND IsDelete = 0 ").Tables[0]).OrderBy(x => x.OrderBy); ;
            var qlist = qlists.Where(x => x.ParendId == 0).ToList();
            var list = qlist.Select(q =>
            {
                return new
                {
                    id = q.Id,
                    title = q.Title,
                    //score = q.Score,
                    remark = q.Remark,
                    quesitems = qlists.Where(qq => qq.ParendId == q.Id).Select(qi =>
                    {
                        return new
                        {
                            id = qi.Id,
                            title = qi.Title,
                            score = qi.Score,
                            remark = qi.Remark,
                        };
                    })
                };
            });
            return Success("获取满意度问卷试题信息成功", list);
        }

        /// <summary>
        /// 获取 问卷结果 - 满意度
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult GetQuestionPagerResult(string workorderid)
        {
            if (string.IsNullOrEmpty(workorderid))
                return Error("参数错误");
            var listque_Map = bllQueMap.DataTableToList(bllQueMap.GetList(" 1=1 and WorkOrderId = '" + workorderid + "' ").Tables[0]);
            var qlists = bllQue.DataTableToList(bllQue.GetList(" 1=1 AND IsDelete = 0 ").Tables[0]).OrderBy(x => x.OrderBy);
            var qlist = qlists.Where(x => x.ParendId == 0).ToList();
            var list = qlist.Select(q =>
            {
                return new
                {
                    id = q.Id,
                    title = q.Title,
                    //score = q.Score,
                    remark = q.Remark,
                    quesitems = qlists.Where(qq => qq.ParendId == q.Id).Select(qi =>
                    {
                        return new
                        {
                            id = qi.Id,
                            title = qi.Title,
                            score = qi.Score,
                            ischeck = listque_Map.FirstOrDefault(x => x.QuestionIId == qi.Id) != null ? 1 : 0,
                            remark = qi.Remark,
                        };
                    })
                };
            });
            return Success("获取问答结果成功", list);
        }

        /// <summary>
        /// 回访工单（未回访，已回访,综合查询） - 满意度
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult GetWordOrderQuestionVisitList()
        {
            int userId = CurrentUser.UserData.F_UserId;
            int deptid = CurrentUser.UserData.F_DeptId;         //部门id
            string deptCode = CurrentUser.UserData.F_DeptCode;  //部门code
            int userRegionId = CurrentUser.UserData.RegionId;  //项目id

            string sql = " and ISNULL(IsDel,0) = 0 ";
            DataTable dt = new DataTable();

            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                if (ua != null)
                {
                    #region 权限限制           
                    // 部门信息
                    var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
                    int depType = 0, depRegion = 0;
                    if (modelDep != null)
                    {
                        depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                        depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
                    }
                    if (ua.F_RoleId != 17)
                    {
                        if (depType == 2)
                        {
                            if (depRegion == 1)
                            {
                                // 查看该区域工单
                                //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
                                sql += $" and IsUserSend = {userRegionId} ";
                            }
                            else if (depRegion == 2)
                            {
                                // 查看该项目工单
                                sql += $" and IsAdminSend = {userRegionId} ";
                            }
                        }
                        else if (depType == 3)
                        {
                            if (depRegion == 1)
                            {
                                // 查看该区域工单
                                //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
                                sql += $" and IsUserSend = {userRegionId} ";
                            }
                        }
                        else if (depType == 4)
                        {
                            if (depRegion == 2)
                            {
                                // 查看该项目工单
                                sql += $" and IsAdminSend = {userRegionId} ";
                            }
                            else if (depRegion == 9)
                            {
                                // 查看该部门工单（包括一级，二级）
                                string deptCodeNew = String.Empty;
                                int deptCodeIndex = 0;                                  //变量声明
                                string deptCodeN = deptCode.TrimEnd('|');      //去掉最后一个|
                                deptCodeIndex = deptCodeN.LastIndexOf("|");             //获得|的索引
                                deptCodeNew = deptCodeN.Substring(0, deptCodeIndex + 1);    //获得目标字符串（//去掉最后一个|后面的字符串）
                                                                                            //============== 部门权限条件 - 部门 ================
                                string arrUser = " select F_UserCode from T_Sys_UserAccount where F_DeptCode LIKE '" + deptCodeNew + "%' ";
                                sql += $" and WorkOrderID in (SELECT DISTINCT WorkOrderID FROM dbo.T_Wo_WorkOrderItem WHERE ToUser IN ({arrUser})) ";
                            }
                        }
                    }
                    #endregion
                }
            }
            string isreturnbak = HttpUtility.UrlDecode(RequestString.GetQueryString("isreturnbak"));
            string strid = HttpUtility.UrlDecode(RequestString.GetQueryString("id"));
            int strtype = RequestString.GetInt("type",0);
            //工单类型
            int gdlx = RequestString.GetInt("gdlx", 0);
            int strcallresultid = RequestString.GetInt("callresultid", 0);  //回访结果id
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            sql += " and State = 2 "; //已完成 
            //IsReturnBak：0未回访 1已回访工单
            if (!string.IsNullOrEmpty(isreturnbak))
            {
                sql += " and ISNULL(IsReturnBak,0) = '" + isreturnbak.Trim() + "' ";
            }
            if (strid.Trim() != "" && strid != "undefined")
            {
                sql += " and WorkOrderID = '" + strid.Trim() + "' ";
            }
            if (strtype>0)
            {
                sql += " and Type = " + strtype + " ";
            }
            if (gdlx > 0)
            {
                sql += " and TypeClass = " + gdlx + " ";
            }
            if (strcallresultid > 0)
            {
                sql += " and IsReturn = " + strcallresultid + " ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "dbo.T_Wo_WorkOrder (NOLOCK) ",
                "T_Wo_WorkOrder.ID",
                "dbo.GetDictionaryName(IsReturn) AS CallResult,(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsUserSend) AS areaname,(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsAdminSend) AS proname,(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsTimeOut) AS buildingname,dbo.GetDictionaryName(Type) as GDLYName,dbo.GetDictionaryName(TypeClass) as TypeClassName,dbo.GetUserName(ResponUser) as ResponUserName,(SELECT TOP 1 F_Remark FROM dbo.T_Sys_Department WHERE F_DeptId = Source) AS complaintTypeName,*",
                sql,
                "ORDER BY T_Wo_WorkOrder.ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            dt.Columns.Add("CBCount", typeof(int));
            foreach (DataRow dr in dt.Rows)
            {
                var list = new BLL.T_Wo_WorkOrderItem_New().GetList(" F_WoID='" + dr["ID"].ToString() + "' and IsDel=0 and Type=2 ").Tables[0];
                dr["CBCount"] = list.Rows.Count;
            }
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 导出工单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportVisitList()
        {
            int userId = CurrentUser.UserData.F_UserId;
            int deptid = CurrentUser.UserData.F_DeptId;         //部门id
            string deptCode = CurrentUser.UserData.F_DeptCode;  //部门code
            int userRegionId = CurrentUser.UserData.RegionId;  //项目id
            if (userId != 0)
            {
                Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                if (ua != null)
                {
                    string sql = " and ISNULL(IsDel,0) = 0 ";
                    DataTable dt = new DataTable();
                    string isreturnbak = HttpUtility.UrlDecode(RequestString.GetQueryString("isreturnbak"));
                    string strid = HttpUtility.UrlDecode(RequestString.GetQueryString("id"));
                    int strtype = RequestString.GetInt("type", 0);
                    string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                    string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

                    sql += " and State = 2 "; //已完成 

                    #region 权限限制 
                    //部门信息
                    var modelDep = new BLL.T_Sys_Department().GetModel(deptid);
                    int depType = 0, depRegion = 0;
                    if (modelDep != null)
                    {
                        depType = modelDep.F_Type ?? 0;  //部门操作权限：1接待部，2办理人员，3区域客服，4监管
                        depRegion = modelDep.F_Header ?? 0; //部门权限范围：9全部，1区域，2项目，3期
                    }
                    if (ua.F_RoleId != 17)
                    {
                        if (depType == 2)
                        {
                            if (depRegion == 1)
                            {
                                // 查看该区域工单
                                //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
                                sql += $" and IsUserSend = {userRegionId} ";
                            }
                            else if (depRegion == 2)
                            {
                                // 查看该项目工单
                                sql += $" and IsAdminSend = {userRegionId} ";
                            }
                        }
                        else if (depType == 3)
                        {
                            if (depRegion == 1)
                            {
                                // 查看该区域工单
                                //sql += $" and IsUserSend = (SELECT TOP 1 F_ParentId FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = {userRegionId}) ";
                                sql += $" and IsUserSend = {userRegionId} ";
                            }
                        }
                        else if (depType == 4)
                        {
                            if (depRegion == 2)
                            {
                                // 查看该项目工单
                                sql += $" and IsAdminSend = {userRegionId} ";
                            }
                            else if (depRegion == 9)
                            {
                                // 查看该部门工单（包括一级，二级）
                                string deptCodeNew = String.Empty;
                                int deptCodeIndex = 0;                                  //变量声明
                                string deptCodeN = deptCode.TrimEnd('|');      //去掉最后一个|
                                deptCodeIndex = deptCodeN.LastIndexOf("|");             //获得|的索引
                                deptCodeNew = deptCodeN.Substring(0, deptCodeIndex + 1);    //获得目标字符串（//去掉最后一个|后面的字符串）
                                                                                            //============== 部门权限条件 - 部门 ================
                                string arrUser = " select F_UserCode from T_Sys_UserAccount where F_DeptCode LIKE '" + deptCodeNew + "%' ";
                                sql += $" and WorkOrderID in (SELECT DISTINCT WorkOrderID FROM dbo.T_Wo_WorkOrderItem WHERE ToUser IN ({arrUser})) ";
                            }
                        }
                    }
                    #endregion

                    //IsReturnBak：0未回访 1已回访工单 0未回访 1已回访工单
                    if (!string.IsNullOrEmpty(isreturnbak))
                    {
                        sql += " and ISNULL(IsReturnBak,0) = '" + isreturnbak.Trim() + "' ";
                    }
                    if (strid.Trim() != "" && strid != "undefined")
                    {
                        sql += " and WorkOrderID = '" + strid.Trim() + "' ";
                    }
                    if (strtype > 0)
                    {
                        sql += " and Type = " + strtype + " ";
                    }
                    if (strstarttime.Trim() != "" && strstarttime != "undefined")
                    {
                        sql += " and datediff(day,CreateTime,'" + strstarttime + "')<=0 ";
                    }
                    if (strendtime.Trim() != "" && strendtime != "undefined")
                    {
                        sql += " and datediff(day,CreateTime,'" + strendtime + "')>=0   ";
                    }
                    string str = "SELECT [WorkOrderID] as '工单编号',(case [State] when 0 then '待处理' else '已处理' end) as '工单状态',Customer as '姓名',CustomerTel as '联系电话',(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsUserSend) AS '区域名称',(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsAdminSend) AS '项目名称',(SELECT F_RegionName FROM dbo.T_Cus_RegionCategory WHERE F_RegionId = dbo.T_Wo_WorkOrder.IsTimeOut) AS '楼号名称',Address as '房间号',dbo.GetDictionaryName(Type) as '工单来源',dbo.GetDictionaryName(TypeClass) as '工单类型',Detail as '接待描述',dbo.GetUserName(AuditUser) as '受理人',CreateUser as '坐席工号',CreateTime as '创建时间' FROM T_Wo_WorkOrder where 1=1 " + sql + "ORDER BY T_Wo_WorkOrder.ID desc";
                    dt = DbHelperSQL.Query(str).Tables[0];
                    //dt.Columns.Add("CBCount", typeof(int));
                    foreach (DataRow dr in dt.Rows)
                    {
                        dr["接待描述"] = Utils.DropHTML(dr["接待描述"].ToString());
                        //var list = new BLL.T_Wo_WorkOrderItem().GetList(" WorkOrderID='" + dr["WorkOrderID"].ToString() + "' and IsDel=0 and Type=2 and ','+ToUser+',' like ',%" + ua.F_UserCode + "%,' ").Tables[0];
                        //dr["CBCount"] = list.Rows.Count;
                    }
                    NPOIHelper npoi = new NPOIHelper();
                    if (npoi.ExportToExcel("工单列表", dt) == "")
                    {
                        return Success("导出成功");
                    }
                    else
                    {
                        return Error("导出失败");
                    }
                }
            }
            return Error("导出失败");
        }

        #endregion

    }
}