using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Mall.Module.MarketingCenter;
using Mall.Common.API;
using Newtonsoft.Json;
using Mall.Model.Extend.MarketingCenter;
using Mall.Common.Plugin;
using Newtonsoft.Json.Linq;
using Mall.Model.Entity.MarketingCenter;
using Mall.Common.Enum.MarketingCenter;
using Microsoft.AspNetCore.Authorization;
using Dnc.Api.Throttle;

namespace Mall.WebApi.Controllers.MarketingCenter
{

    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class SurveyController : BaseController
    {
        /// <summary>
        /// 处理类对象
        /// </summary>
        private SurveyModule module = new SurveyModule();
        /// <summary>
        /// 处理类对象
        /// </summary>
        private Module.User.UserModule userModule = new Module.User.UserModule();

        #region 问卷活动调查
        /// <summary>
        /// 获取基础信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivitySurveyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_ActivitySurvey_Extend demodel = JsonConvert.DeserializeObject<RB_ActivitySurvey_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var data = module.GetActivitySurveyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            var list = data.Select(x => new { x.ID, x.PrizeType, x.Title, StartDateStr = x.StartDate.HasValue ? x.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", EndDateStr = x.EndDate.HasValue ? x.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", PrizeTypeStr = EnumHelper.GetEnumName(x.PrizeType), x.PrizeAddress, x.Description, x.SurveyNum }).ToList();
            pagelist.count = int.Parse(count.ToString());
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 通过id获取信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetActivitySurvey()
        {
            var parms = RequestParm;
            JObject parm = JObject.Parse(parms.msg.ToString());
            int ID = parm.GetInt("ID");
            RB_ActivitySurvey_Extend model = module.GetActivitySurveyList(new RB_ActivitySurvey_Extend { ID = ID, MallBaseId = parms.MallBaseId, TenantId = UserInfo.TenantId }).FirstOrDefault();
            if (model != null)
            {
                return ApiResult.Success("请求成功", new { model.ID, model.Title, StartDate = model.StartDate.HasValue ? model.StartDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", EndDate = model.EndDate.HasValue ? model.EndDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "", model.SurveyNum, model.Description, model.PrizeAddress, model.PrizeType });
            }
            return ApiResult.Failed("活动信息不存在");
        }

        /// <summary>
        /// 通过id获取信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelActivitySurvey()
        {
            var parms = RequestParm;
            JObject parm = JObject.Parse(parms.msg.ToString());
            int ID = parm.GetInt("ID");
            RB_ActivitySurvey_Extend model = module.GetActivitySurveyList(new RB_ActivitySurvey_Extend { ID = ID, MallBaseId = parms.MallBaseId, TenantId = UserInfo.TenantId }).FirstOrDefault();
            if (model != null)
            {
                if (model.State == Common.Enum.DateStateEnum.Delete)
                {
                    return ApiResult.Failed("已删除请勿重复删除");
                }
                model.SurveyList = new List<Rb_Survey_Extend>();
                model.SurveyList = module.GetSurveyList(new Rb_Survey_Extend { ActivitySurveyId = model.ID, MallBaseId = parms.MallBaseId, TenantId = UserInfo.TenantId });


                var surveyOptionsList = new List<Rb_SurveyOptions_Extend>();
                if (model.SurveyList != null && model.SurveyList.Any())
                {
                    surveyOptionsList = module.GetSurveyOptionsList(new Rb_SurveyOptions_Extend { SurveyIDs = string.Join(",", model.SurveyList.Select(x => x.ID)) });
                }
                foreach (var item in model.SurveyList)
                {
                    item.SurveyOptionsList = new List<Rb_SurveyOptions_Extend>();

                    item.SurveyOptionsList = (surveyOptionsList != null && surveyOptionsList.Any()) ? surveyOptionsList.Where(x => x.SurveyID == item.ID).ToList() : new List<Rb_SurveyOptions_Extend>();
                }

                bool result = module.DelActivitySurvey(model);
                return ApiResult.Success("删除成功");
            }
            return ApiResult.Failed("活动信息不存在");
        }

        /// <summary>
        /// 添加修改调查信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetActivitySurvey()
        {
            var parms = RequestParm;
            RB_ActivitySurvey_Extend model = JsonConvert.DeserializeObject<RB_ActivitySurvey_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(model.Title))
            {
                return ApiResult.Failed("请填写名称");
            }
            if (model.SurveyNum == 0)
            {
                return ApiResult.Failed("问卷调查份数不能为0");
            }
            if (model.ID == 0)
            {
                model.TenantId = UserInfo.TenantId;
                model.MallBaseId = parms.MallBaseId;
                model.CreateDate = DateTime.Now;
            }
            model.UpdateDate = DateTime.Now;
            model.State = Common.Enum.DateStateEnum.Normal;
            bool flag = module.SetActivitySurvey(model);
            if (flag)
                return ApiResult.Success();
            else
                return ApiResult.Failed("请求失败");
        }

        /// <summary>
        /// 获取活动奖品地址类型枚举列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPrizeTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(PrizeTypeEnum));
            return ApiResult.Success("", list.Select(x => new { Id = x.Value, Name = x.Key }));
        }

        #endregion
        #region 问卷调查
        /// <summary>
        /// 获取基础信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            Rb_Survey_Extend demodel = JsonConvert.DeserializeObject<Rb_Survey_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var data = module.GetPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            var list = data.Select(x => new { x.ID, x.SurveyType,x.IsRequired, x.FormType, x.Title, x.IsShow, x.Sort, SurveyTypeStr = EnumHelper.GetEnumName(x.SurveyType), FormTypeStr = EnumHelper.GetEnumName(x.FormType) }).ToList();
            pagelist.count = int.Parse(count.ToString());
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 通过id获取信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSurvey()
        {
            var parms = RequestParm;
            JObject parm = JObject.Parse(parms.msg.ToString());
            int SurveyID = parm.GetInt("SurveyID");
            Rb_Survey_Extend model = module.GetEntity(SurveyID).RefMapperTo<Rb_Survey_Extend>();
            if (model != null)
            {
                model.SurveyOptionsList = new List<Rb_SurveyOptions_Extend>();

                model.SurveyOptionsList = module.GetSurveyOptionsList(new Rb_SurveyOptions_Extend { SurveyID = model.ID });

                return ApiResult.Success("请求成功", model);
            }
            return ApiResult.Failed("未找到此调查信息");
        }

        /// <summary>
        /// 通过id获取信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelSurvey()
        {
            var parms = RequestParm;
            JObject parm = JObject.Parse(parms.msg.ToString());
            int SurveyID = parm.GetInt("SurveyID");
            Rb_Survey_Extend model = module.GetEntity(SurveyID).RefMapperTo<Rb_Survey_Extend>();
            if (model != null)
            {
                if (model.State == Common.Enum.DateStateEnum.Delete)
                {
                    return ApiResult.Failed("已删除请勿重复删除");
                }
                model.SurveyOptionsList = new List<Rb_SurveyOptions_Extend>();

                model.SurveyOptionsList = module.GetSurveyOptionsList(new Rb_SurveyOptions_Extend { SurveyID = model.ID });

                bool result = module.DelSurvey(model);
                return ApiResult.Success("删除成功");
            }
            return ApiResult.Failed("未找到此调查信息");
        }

        /// <summary>
        /// 添加修改调查信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSurvey()
        {
            var parms = RequestParm;
            Rb_Survey_Extend model = JsonConvert.DeserializeObject<Rb_Survey_Extend>(parms.msg.ToString());
            if (string.IsNullOrEmpty(model.Title))
            {
                return ApiResult.Failed("请填写名称！");
            }
            if (model.SurveyType == SurveyTypeEnum.MultiSelect || model.SurveyType == SurveyTypeEnum.TheRadio)
            {
                if (model.SurveyOptionsList == null || !model.SurveyOptionsList.Any())
                {
                    return ApiResult.Failed("请填写选项");
                }
                else
                {
                    model.SurveyOptionsList.ForEach(x => x.State = Common.Enum.DateStateEnum.Normal);
                }
            }
            if (model.ID == 0)
            {
                model.TenantId = UserInfo.TenantId;
                model.MallBaseId = parms.MallBaseId;
                model.CreateDate = DateTime.Now;
            }
            model.UpdateDate = DateTime.Now;
            model.State = Common.Enum.DateStateEnum.Normal;
            bool flag = module.SetSurvey(model);
            if (flag)
                return ApiResult.Success();
            else
                return ApiResult.Failed("请求失败");
        }

        /// <summary>
        /// 获取调查选项类型枚举列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSurveyTypeEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(SurveyTypeEnum));
            return ApiResult.Success("", list.Select(x => new { Id = x.Value, Name = x.Key }));
        }


        /// <summary>
        /// 获取调查类型枚举列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFormTypeEnumEnumList()
        {
            var list = EnumHelper.GetEnumList(typeof(FormTypeEnum));
            return ApiResult.Success("", list.Select(x => new { Id = x.Value, Name = x.Key }));
        }
        #endregion


        #region 问卷调查详情
        /// <summary>
        /// 通过id获取信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous] [RateValve(Policy = Policy.Ip, Limit = 10, Duration = 60)]
        public ApiResult GetGuestSurveyDetails()
        {
            var parms = RequestParm;
            JObject parm = JObject.Parse(parms.msg.ToString());
            int SurveyID = parm.GetInt("SurveyID");
            Rb_GuestSurvey_Extend model = module.GetGuestSurveyEntity(SurveyID).RefMapperTo<Rb_GuestSurvey_Extend>();
            if (model != null)
            {
                model.SurveyOptionsList = new List<Rb_GuestSurveyDetails>();
                model.SurveyOptionsList = module.GetGuestSurveyDetailsList(new Rb_GuestSurveyDetails { GuestSurveyId = SurveyID });
                //调查问卷信息
                var surverList = module.GetSurveyList(new Rb_Survey_Extend { SurveyIDs = string.Join(",", model.SurveyOptionsList.Select(x => x.SurveyId)), MallBaseId = parms.MallBaseId, TenantId = parms.TenantId });
                var surveyOptionsList = module.GetSurveyOptionsList(new Rb_SurveyOptions_Extend { SurveyIDs = string.Join(",", model.SurveyOptionsList.Select(x => x.SurveyId)) });
                foreach (var item in surverList)
                {
                    item.CreateDate = model.CreateDate;
                    item.SurveyOptionsList = new List<Rb_SurveyOptions_Extend>();
                    item.SurveyOptionsList = surveyOptionsList.Where(x => x.SurveyID == item.ID).OrderBy(x => x.Sort).ToList();
                    item.SurveyOptionsList.ForEach(x => x.IsCheck = "0");

                    if (item.SurveyType == SurveyTypeEnum.MultiSelect || item.SurveyType == SurveyTypeEnum.TheRadio)
                    {
                        foreach (var surveyOptionsItem in item.SurveyOptionsList)
                        {
                            var surverOptionsIds = model.SurveyOptionsList.FirstOrDefault(x => x.SurveyId == item.ID);
                            if (surverOptionsIds != null && !string.IsNullOrWhiteSpace(surverOptionsIds.SurveyOptionIds))
                            {
                                foreach (var OptionId in surverOptionsIds.SurveyOptionIds.Split(','))
                                {
                                    if (OptionId == surveyOptionsItem.ID.ToString())
                                    {
                                        surveyOptionsItem.IsCheck = "1";
                                    }
                                }
                            }
                            item.TextContent = "";
                            item.ScoreNum = 0;
                        }
                    }
                    else if (item.SurveyType == SurveyTypeEnum.Score)
                    {
                        var surverOptionsIds = model.SurveyOptionsList.FirstOrDefault(x => x.SurveyId == item.ID);
                        item.ScoreNum = surverOptionsIds.ScoreNum;
                        item.TextContent = "";
                    }
                    else
                    {
                        var surverOptionsIds = model.SurveyOptionsList.FirstOrDefault(x => x.SurveyId == item.ID);
                        item.TextContent = surverOptionsIds.TextContent;
                        item.ScoreNum = 0;

                    }
                }

                var userModel = userModule.GetMemberUserInfo(model.UserId ?? 0);
                if (userModel == null)
                {
                    userModel = new Model.Extend.User.RB_Member_User_Extend();
                }
                var obj = new
                {
                    userModel.Name,
                    userModel.Photo,
                    CreateDateStr = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
                };
                return ApiResult.Success("请求成功！", new { surverList= surverList.Where(x=>x.FormType==FormTypeEnum.Survey), baseList = surverList.Where(x => x.FormType == FormTypeEnum.Base), obj });
            }
            return ApiResult.Failed("未找到调查信息！");
        }

        #endregion

        #region 问卷调查列表
        /// <summary>
        /// 获取基础信息列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetResultPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            Rb_GuestSurvey_Extend demodel = JsonConvert.DeserializeObject<Rb_GuestSurvey_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var data = module.GetResultPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            var list = data.Select(x => new { x.ID, x.ActiveSurveyName, x.AliasName, CreateDateStr = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",x.Photo }).ToList();
            pagelist.count = int.Parse(count.ToString());
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }



        #endregion


    }
}
