using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MadRunFabric.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using CallCenterApi.IRepositories;
using MadRunFabric.Model.CallCenterApi;
using System.Security.Claims;
using MongoDB.Bson;

namespace CallCenterApi.Controllers
{
    /// <summary>
    /// 问卷
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class QuestionnaireController : BaseController
    {
        private readonly ILogger<QuestionnaireController> _logger;
        private readonly IAsk_QuestionListRepository _ask_auestionlistRepository;
        private readonly IAsk_QuestionPagerRepository _ask_questionpagerRepository;
        private readonly IAsk_QuestionRepository _ask_questionRepository;
        private readonly IAsk_QuestionItemsRepository _ask_questionitemsRepository;
        private readonly IMW_Autocall_Call_RecordRepository _mw_autocall_call_recordRepository;
        private readonly ICall_ClickOutTaskTelNumRepository _call_clickouttasktelnumRepository;
        public QuestionnaireController(ILogger<QuestionnaireController> logger,
            IAsk_QuestionListRepository ask_auestionlistRepository,
            IAsk_QuestionPagerRepository ask_questionpagerRepository,
            IAsk_QuestionRepository ask_questionRepository,
            IAsk_QuestionItemsRepository ask_questionitemsRepository,
            IMW_Autocall_Call_RecordRepository mw_autocall_call_recordRepository, 
            ICall_ClickOutTaskTelNumRepository call_clickouttasktelnumRepository
            )
        {
            _logger = logger;
            _ask_auestionlistRepository = ask_auestionlistRepository;
            _ask_questionpagerRepository = ask_questionpagerRepository;
            _ask_questionRepository = ask_questionRepository;
            _ask_questionitemsRepository = ask_questionitemsRepository;
            _mw_autocall_call_recordRepository = mw_autocall_call_recordRepository;
            _call_clickouttasktelnumRepository = call_clickouttasktelnumRepository;
        }

        #region 问卷管理
        /// <summary>
        /// 问卷列表 - 下拉
        /// </summary>
        /// <param name="usercode">坐席工号</param>
        /// <param name="calltype">呼叫方向</param>
        /// <param name="telephone">电话</param>
        /// <param name="stime">开始时间</param>
        /// <param name="etime">结束时间</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <returns></returns>
        [HttpGet("getpagelist")]
        public async Task<IActionResult> GetPageListAsync()
        {
            var list = await _ask_questionpagerRepository.Get(x=>x.isdelete == 0 && x.isopen == 1);
            return Success("获取成功", list);
        }

        /// <summary>
        /// 分页获取问卷列表
        /// </summary>
        /// <param name="usercode">坐席工号</param>
        /// <param name="calltype">呼叫方向</param>
        /// <param name="telephone">电话</param>
        /// <param name="stime">开始时间</param>
        /// <param name="etime">结束时间</param>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页记录数</param>
        /// <returns></returns>
        [HttpGet("getpagelistbypage")]
        public IActionResult GetPageListsByPageAsync(string keyword, string usercode, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _ask_questionpagerRepository.GetPageListsByPage(keyword, usercode, stime, etime, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 添加问卷
        /// </summary>
        /// <param name="title"></param>
        /// <param name="remark"></param>
        /// <param name="result"></param>
        /// <param name="starttext"></param>
        /// <param name="endtext"></param>
        /// <returns></returns>
        [HttpPost("addpage")]
        public async Task<IActionResult> AddPageAsync(string title, string remark, List<resultPageQuestion> result, string starttext, string endtext)
        {
            //public async Task<IActionResult> AddPageAsync(string title, string remark, List<resultPageQuestion> result, string starttext, string endtext)
            string userCode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string userName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            //var result = result1.ToList<resultPageQuestion>();
            //result.ForEach(x =>
            //{                
            //    x.qcscore = x.item.Sum(p => p.qcscore);
            //    x.score = x.item.Sum(p => p.score);
            //    x.item.ForEach(y =>
            //    {
            //        y.qcscore = y.item.Sum(p => p.qcscore);
            //        y.score = y.item.Sum(p => p.score);
            //    });
            //});                    

            #region modelPage 添加问卷
            var modelPage = new Ask_QuestionPager();
            modelPage.title = title;
            modelPage.totalnum = result.Count;  //题目数量
            modelPage.remark = remark;
            modelPage.starttext = starttext;    //问卷开场语
            modelPage.endtext = endtext;        //问卷结束语
            modelPage.createuser = userCode;
            modelPage.createusername = userName;
            #endregion
            string pageId = await _ask_questionpagerRepository.AddRetID(modelPage);
            if (string.IsNullOrEmpty(pageId))
                return Error("添加问卷失败");

            foreach (var itemQue in result)
            {
                #region modelQue 添加问卷题
                var modelQue = new Ask_Question();
                modelQue.pageid = pageId;
                modelQue.queguid = itemQue.queguid;
                modelQue.title = itemQue.quetitle;
                modelQue.type = itemQue.type;
                modelQue.isanswer = itemQue.isanswer;
                modelQue.sort = itemQue.sort;
                modelQue.content = string.Join(",", itemQue.itemList.ToList().Select(p => p.name));
                modelQue.remark = itemQue.remark;
                modelQue.createuser = userCode;
                modelQue.createusername = userName;
                #endregion
                string queId = await _ask_questionRepository.AddRetID(modelQue);

                foreach (var item in itemQue.itemList)
                {
                    #region 添加问卷题 选项
                    var modelItem = new Ask_QuestionItems();
                    modelItem.questionid = queId;
                    modelItem.queguid = item.queguid;
                    modelItem.itemsname = item.name;
                    modelItem.sort = modelItem.sort;
                    modelItem.remark = "";
                    modelItem.createuser = userCode;
                    modelItem.createusername = userName;
                    #endregion
                    string b3 = await _ask_questionitemsRepository.AddRetID(modelItem);
                }
            }
            return Success("保存成功");
        }

        /// <summary>
        /// 修改问卷
        /// </summary>
        /// <param name="pageid"></param>
        /// <param name="title"></param>
        /// <param name="remark"></param>
        /// <param name="result"></param>
        /// <param name="starttext"></param>
        /// <param name="endtext"></param>
        /// <returns></returns>
        [HttpPost("updatepage")]
        public async Task<IActionResult> UpdatePageAsync(string pageid, string title, string remark, List<resultPageQuestion> result, string starttext, string endtext)
        {
            string userCode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string userName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            var modelPage = (await _ask_questionpagerRepository.Get(p => p.id == pageid)).FirstOrDefault();
            #region modelPage 修改问卷
            if (modelPage != null)
            {
                modelPage.title = title;
                modelPage.totalnum = result.Count;  //题目数量
                modelPage.remark = remark;
                modelPage.starttext = starttext;    //问卷开场语
                modelPage.endtext = endtext;        //问卷结束语
                var b1 = await _ask_questionpagerRepository.UpdateOne(modelPage);
            }
            else
            {
                return Error("参数错误");
            }
            #endregion
            
            foreach (var itemQue in result)
            {
                #region modelQue 问卷题
                //var modelQue = new Ask_Question();
                var modelQue = (await _ask_questionRepository.Get(x => x.id == itemQue.queid)).FirstOrDefault();
                if (modelQue != null)
                {
                    //修改问卷题
                    modelQue.queguid = itemQue.queguid;
                    modelQue.title = itemQue.quetitle;
                    modelQue.type = itemQue.type;
                    modelQue.isanswer = itemQue.isanswer;
                    modelQue.sort = itemQue.sort;
                    modelQue.content = string.Join(",",itemQue.itemList.ToList().Select(p => p.name));
                    modelQue.remark = itemQue.remark;
                    await _ask_questionRepository.UpdateOne(modelQue);
                }
                else
                {
                    modelQue = new Ask_Question();
                    //添加问卷题
                    modelQue.pageid = pageid;
                    modelQue.queguid = itemQue.queguid;
                    modelQue.title = itemQue.quetitle;
                    modelQue.type = itemQue.type;
                    modelQue.sort = itemQue.sort;
                    modelQue.content = string.Join(",", itemQue.itemList.ToList().Select(p => p.name));
                    modelQue.remark = itemQue.remark;
                    modelQue.createuser = userCode;
                    modelQue.createusername = userName;
                    itemQue.queid = await _ask_questionRepository.AddRetID(modelQue);
                }
                #endregion

                foreach (var item in itemQue.itemList)
                {
                    #region 问卷题 选项
                    var modelItem = (await _ask_questionitemsRepository.Get(x => x.id == item.itemid)).FirstOrDefault();
                    if (modelItem != null)
                    {
                        //添加问卷题 选项
                        modelItem.queguid = item.queguid;
                        modelItem.itemsname = item.name;
                        modelItem.sort = modelItem.sort;
                        modelItem.remark = "";
                        await _ask_questionitemsRepository.UpdateOne(modelItem);
                    }
                    else
                    {
                        modelItem = new Ask_QuestionItems();
                        //添加问卷题 选项
                        modelItem.questionid = itemQue.queid;
                        modelItem.queguid = item.queguid;
                        modelItem.itemsname = item.name;
                        modelItem.sort = modelItem.sort;
                        modelItem.remark = "";
                        modelItem.createuser = userCode;
                        modelItem.createusername = userName;
                        await _ask_questionitemsRepository.AddRetID(modelItem);
                    }
                    #endregion
                }
            }

            return Success("保存成功");
        }

        /// <summary>
        /// 问卷详情
        /// </summary>
        /// <param name="pageid"></param>
        /// <returns></returns>
        [HttpGet("getpagedetails")]
        public async Task<IActionResult> GetPageDetailsAsync(string pageid)
        {
            //var modelPage = (await _ask_questionpagerRepository.Get(p => p.id == pageid)).FirstOrDefault();
            var modelPage = await _ask_questionpagerRepository.GetSingle(p => p.id == pageid);
            if (modelPage == null)
                return Error("参数错误");
            var listQuestion = (await _ask_questionRepository.Get(x => x.pageid == modelPage.id && x.isdelete == 0)).OrderBy(x => x.sort).ToList();
            var listOption = (await _ask_questionitemsRepository.Get(x => x.isdelete == 0)).OrderBy(x => x.sort).ToList();

            //foreach (var itemQue in listQue)
            //{
            //    var listOption_Item = listOption.Where(x => x.questionid == itemQue.id);
            //    foreach (var item in listOption_Item)
            //    {

            //    }
            //}

            var listQue = listQuestion.Where(q => q.pageid == modelPage.id).Select(q =>
            {
                var listOpt = listOption.Where(o => o.questionid == q.id).Select(o =>
                {
                    return new
                    {
                        o.id,
                        o.queguid,
                        o.itemsname,
                        o.remark,
                        o.sort,
                        o.createtime
                    };
                }).OrderBy(o => o.sort);

                return new
                {
                    q.id,
                    q.queguid,
                    q.type,
                    q.isanswer,
                    q.title,
                    q.content,
                    q.remark,
                    q.sort,
                    q.createtime,
                    item = listOpt
                };
            }).OrderBy(q => q.sort);

            var list = new
            {
                pageid = modelPage.id,
                title = modelPage.title,
                totalnum = modelPage.totalnum,
                remark = modelPage.remark,
                starttext = modelPage.starttext,
                endtext = modelPage.endtext,
                item = listQue
            };
            return Success("获取成功", list);
        }

        /// <summary>
        /// 删除问卷 by ids
        /// <summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deletepage")]
        public async Task<IActionResult> DeletePageAsync(string[] ids)
        {
            string userCode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    if (await DeletePageAsync(item, userCode))
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败");
                else
                    return Error("删除失败");
            }
            return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 循环删除 - 问卷，问卷题，问卷题选项 ------ 方法
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<bool> DeletePageAsync(string id, string usercode)
        {
            bool bl = false;
            //问卷
            var modelPage = await _ask_questionpagerRepository.GetSingle(x => x.id == id && x.isdelete == 0);
            if (modelPage != null)
            {
                //问卷题
                var listQuestion = (await _ask_questionRepository.Get(x => x.pageid == modelPage.id && x.isdelete == 0)).ToList();
                //问卷题 选项
                var listOption = (await _ask_questionitemsRepository.Get(x => x.isdelete == 0)).ToList();
                foreach (var itemQuestion in listQuestion)
                {
                    //问卷题 删除
                    itemQuestion.isdelete = 1;
                    itemQuestion.deleteuser = usercode;
                    itemQuestion.deletetime = DateTime.Now.ToLocalTime();
                    bool b2 = await _ask_questionRepository.UpdateOne(itemQuestion);
                    if (b2)
                    {
                        var listOpt = listOption.Where(x => x.questionid == itemQuestion.id);
                        foreach (var itemOption in listOpt)
                        {
                            ///问卷题 选项 删除
                            itemOption.isdelete = 1;
                            itemOption.deleteuser = usercode;
                            itemOption.deletetime = DateTime.Now.ToLocalTime();
                            bool b3 = await _ask_questionitemsRepository.UpdateOne(itemOption);
                        }
                    }
                }
                //问卷删除
                modelPage.isdelete = 1;
                modelPage.deleteuser = usercode;
                modelPage.deletetime = DateTime.Now.ToLocalTime();
                bl = await _ask_questionpagerRepository.UpdateOne(modelPage);
            }
            return bl;
        }

        /// <summary>
        /// 开启问卷
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("openpage")]
        public async Task<IActionResult> OpenPageAsync(string id)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            #endregion

            var model = await _ask_questionpagerRepository.GetSingle(x => x.id == id && x.isdelete == 0);
            if (model == null)
                return Error("参数错误");
            if (model.isopen == 1)
                return Error("已开启,无需再操作");

            model.isopen = 1;
            if (await _ask_questionpagerRepository.UpdateOne(model))
                return Success("开启成功");
            else
                return Error("开启失败");
        }

        /// <summary>
        /// 禁用问卷
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("closepage")]
        public async Task<IActionResult> ClosePageAsync(string id)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            #endregion

            var model = await _ask_questionpagerRepository.GetSingle(x => x.id == id && x.isdelete == 0);
            if (model == null)
                return Error("参数错误");
            if (model.isopen == 0)
                return Error("已禁用,无需再操作");

            model.isopen = 0;
            if (await _ask_questionpagerRepository.UpdateOne(model))
                return Success("操作成功");
            else
                return Error("操作失败");
        }

        #endregion

        #region 外呼问卷管理

        /// <summary>
        /// 获取外呼问卷列表
        /// </summary>
        /// <param name="keyword">关键词（电话）</param>
        /// <param name="calltype">呼叫方向</param>
        /// <param name="isqc_check">是否质检</param>
        /// <param name="stime">开始时间</param>
        /// <param name="etime">结束时间</param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getcallpagelistbypage")]
        public IActionResult GetCallPageListsByPageAsync(string keyword, int calltype, int isqc_check, string callresultid, string stime, string etime, int pageindex = 1, int pagesize = 10)
        {
            int recordCount = 0;
            var result = _ask_auestionlistRepository.GetCallPageListsByPageAsync(keyword, calltype, isqc_check, callresultid, stime, etime, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 回答问卷
        /// </summary>
        /// <param name="recordid">外呼记录id - 中间件</param>
        /// <param name="fullname">姓名</param>
        /// <param name="tel">电话</param>
        /// <param name="address">地址</param>
        /// <param name="pageid">问卷id</param>
        /// <param name="describe">话务结果描述</param>
        /// <param name="result">问卷回答结果 list</param>
        /// <param name="callresult">话务结果id</param>
        /// <returns></returns>
        [HttpPost("answerscallpage")]
        public async Task<IActionResult> AnswersCallPageAsync(string recordid, string fullname, string tel, string address, string pageid, string taskid, string describe, List<resultPageQuestion> result, string callresult)
        {
            //var result = result2.ToList<resultPageQuestion>();
            string userCode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string userName = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;

            #region 验证判断
            if (string.IsNullOrEmpty(recordid))
                return Error("话务参数不能为空");
            if (string.IsNullOrEmpty(fullname))
                return Error("姓名不能为空");
            if (string.IsNullOrEmpty(tel))
                return Error("电话不能为空");
            if(string.IsNullOrEmpty(pageid))
                return Error("问卷参数不能为空");
            //if (!(result.ToList().Count > 0))
            //    return Error("问卷内容不能为空");
            if(string.IsNullOrEmpty(callresult))
                return Error("呼叫结果不能为空");
            #endregion

            //var modelCall = (await _mw_autocall_call_recordRepository.Get(x => x.id == recordid)).FirstOrDefault();
            //更新电话呼叫结果
            var modelTaskTelNum = await _call_clickouttasktelnumRepository.GetSingle(x => x.id .Equals (recordid) );
            if (modelTaskTelNum != null)
            {
                modelTaskTelNum.hjjgname = callresult;
                modelTaskTelNum.hjjgtime = DateTime.Now;
                await _call_clickouttasktelnumRepository.Update(modelTaskTelNum );
            }

            var modelPage = (await _ask_questionpagerRepository.Get(x => x.id == pageid)).FirstOrDefault();
            if (modelPage == null)
                return Error("参数错误!");
            //if (modelTaskTelNum == null)
            //    return Error("参数错误!");

            #region model 添加回答问卷
            var model = new Ask_QuestionList();
            //电话用户
            model.recordid = recordid;
            model.fullname = fullname;
            model.mobile = tel;
            model.address = address;
            //问卷
            model.pageid = pageid;
            model.pagetitle = modelPage.title;
            model.describe = describe;
            model.pagecontent = modelPage.remark;
            model.result = result;
            //任务
            model.taskid = taskid;
            //话务状态
            model.callresult = callresult;
            //操作人
            model.createuser = userCode;
            model.createusername = userName;
            #endregion
            var b1 = await _ask_auestionlistRepository.AddRetID(model);
            if (!string.IsNullOrEmpty(b1))
            {
                modelTaskTelNum.quelistid = b1;
                await _call_clickouttasktelnumRepository.Update(modelTaskTelNum);
                return Success("保存成功");
            }
            return Error("添加失败");
        }
        
        /// <summary>
        /// 外呼问卷详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getcallpagedetails")]
        public async Task<IActionResult> GetCallPageDetailsAsync(string id)
        {
            var model = (await _ask_auestionlistRepository.Get(p => p.id == id)).FirstOrDefault();
            if (model == null)
                return Error("参数错误");            
            return Success("获取成功", model);
        }

        #endregion
    }
}
