using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Edu.Common.API;
using Edu.Common.Plugin;
using Edu.Model.CacheModel;
using Edu.Model.ViewModel.Advertising;
using Edu.Module.Advertising;
using Edu.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Edu.WebApi.Controllers.Advertising
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class AdvertisingController : BaseController
    {
        /// <summary>
        /// 广告处理对象
        /// </summary>
        private readonly AdvertisingModule advertisingModule = AOP.AOPHelper.CreateAOPObject<AdvertisingModule>();


        #region 广告管理
        /// <summary>
        /// 新增修改广告基础信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        [HttpPost]
        public ApiResult SetAdvertising()
        {
            UserInfo userInfo = base.UserInfo;
            Rb_Advertising_Extend dmodel = new Rb_Advertising_Extend
            {
                IsFee = base.ParmJObj.GetInt("IsFee"),
                ChargeAmount = base.ParmJObj.GetDecimal("ChargeAmount"),
                PictureUrl = base.ParmJObj.GetStringValue("PictureUrl"),
                SamplePicturesUrl = base.ParmJObj.GetStringValue("SamplePicturesUrl"),
                Title = base.ParmJObj.GetStringValue("Title"),
                ID = base.ParmJObj.GetInt("ID", 0)
            };
            try
            {
                dmodel.LableList = Common.Plugin.JsonHelper.DeserializeObject<List<string>>(base.ParmJObj.GetStringValue("LableList"));
            }
            catch (Exception ex)
            {
                dmodel.LableList = new List<string>();
                Common.Plugin.LogHelper.Write(ex, "SetAdvertising");
            }
            if (dmodel.LableList != null && dmodel.LableList.Any())
            {
                dmodel.Lable = Common.Plugin.JsonHelper.Serialize(dmodel.LableList);
            }
            else
            {
                dmodel.Lable = "";
            }
            if (dmodel.IsFee == 1)
            {
                if (!dmodel.ChargeAmount.HasValue && dmodel.ChargeAmount <= 0)
                {
                    return ApiResult.ParamIsNull("请输入收费金额！");
                }
            }
            if (dmodel.ID == 0)
            {
                dmodel.CreateDate = System.DateTime.Now;
                dmodel.CreateBy = userInfo.Id;
                dmodel.Group_Id = userInfo.Group_Id;
            }
            bool flag = advertisingModule.SetAdvertising(dmodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 删除广告
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelAdvertising()
        {
            var BAID = base.ParmJObj.GetInt("BAID");
            if (BAID <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var flag = advertisingModule.DelAdvertising(BAID);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取广告列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAdvertisingList()
        {
            UserInfo userInfo = base.UserInfo;
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            int IsFee = base.ParmJObj.GetInt("IsFee", 0);
            string AdvName = base.ParmJObj.GetStringValue("AdvName");
            List<Rb_Advertising_Extend> list = advertisingModule.GetAdvertisingList(pmodel.PageIndex, pmodel.PageSize, out long count, AdvName, IsFee, userInfo.Group_Id);
            list.ForEach(x => x.LableList = !string.IsNullOrWhiteSpace(x.Lable) ? JsonConvert.DeserializeObject<List<string>>(x.Lable) : new List<string>());
            pmodel.Count = Convert.ToInt32(count.ToString());
            pmodel.PageData = list.Select(x => new
            {
                x.ID,
                x.Title,
                PictureUrl = x.PictureUrl ?? "",
                SamplePicturesUrl = x.SamplePicturesUrl ?? "",
                x.IsFee,
                x.ChargeAmount,
                x.AdvertisingCount,
                x.LableList
            });
            return ApiResult.Success("", pmodel);
        }

        /// <summary>
        /// 获取广告详情
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAdvertsingInfo()
        {
            int BAID = base.ParmJObj.GetInt("BAID", 0);
            if (BAID <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var model = advertisingModule.GetAdvertsingInfo(BAID);
            if (model != null)
            {
                List<string> LableList = new List<string>();
                if (!string.IsNullOrWhiteSpace(model.Lable))
                {
                    LableList = JsonConvert.DeserializeObject<List<string>>(model.Lable);
                }
                var obj = new
                {
                    model.ID,
                    model.Lable,
                    model.PictureUrl,
                    model.SamplePicturesUrl,
                    model.Status,
                    model.Title,
                    model.ChargeAmount,
                    model.IsFee,
                    model.Group_Id,
                    CreateDate = model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    model.CreateBy,
                    LableList
                };
                return ApiResult.Success("请求成功！", obj);
            }
            else
            {

                return ApiResult.Failed("请求失败，数据不存在！");
            }

        }

        /// <summary>
        /// 根据where 查询列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetAdvertsingListForComboBox()
        {
            UserInfo userInfo = base.UserInfo;
            string AdvName = base.ParmJObj.GetStringValue("AdvName");
            List<Rb_Advertising_Extend> list = advertisingModule.GetAdvertsingListForComboBox(AdvName, userInfo.Group_Id);
            var list1 = list.Select(x => new
            {
                x.ID,
                x.Title
            });
            return ApiResult.Success("", list1);
        }


        #endregion



        #region 制作广告
        /// <summary>
        /// 获取分页列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetPageList()
        {
            ResultPageModel pmodel = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.Msg.ToString());
            Rb_Advertising_Make_Extend model = JsonConvert.DeserializeObject<Rb_Advertising_Make_Extend>(RequestParm.Msg.ToString());
            UserInfo userInfo = base.UserInfo;
            model.UpdateBy = userInfo.Id;
            var data = advertisingModule.GetPageList(pmodel.PageIndex, pmodel.PageSize, model, out long count);
            var list = data.Select(x => new
            {
                x.ID,
                x.Title,
                x.Content,
                x.AdvertisingPicUrl,
                AdvertisingPicUrlStr = x.AdvertisingPicUrl ?? "",
                PictureUrl = x.PictureUrl ?? "",
                SamplePicturesUrl = x.SamplePicturesUrl ?? "",
                x.SecretKey,
                x.AdvertisingID
            }).ToList();
            pmodel.Count = int.Parse(count.ToString());
            pmodel.PageData = list;
            return ApiResult.Success("", data: pmodel);
        }

        /// <summary>
        /// 通过ID获取信息
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult Get()
        {
            UserInfo userInfo = base.UserInfo;

            int ID = base.ParmJObj.GetInt("ID");
            if (ID == 0)
            {
                return ApiResult.Failed("请求参数错误！");
            }
            Rb_Advertising_Make_Extend model = advertisingModule.GetList(new Rb_Advertising_Make_Extend { ID = ID }).FirstOrDefault();
            if (model != null)
            {
                var obj = new
                {
                    model.ID,
                    model.Title,
                    model.SecretKey,
                    model.Content,
                    AdvertisingPicUrlStr = model.AdvertisingPicUrl ?? "",
                    PictureUrl = model.PictureUrl ?? "",
                    SamplePicturesUrl = model.SamplePicturesUrl ?? "",
                    model.AdvertisingID
                };
                return ApiResult.Success("请求成功！", data: obj);
            }
            else
            {

                return ApiResult.Failed("请求失败，数据不存在！");
            }
        }


        /// <summary>
        /// 添加修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
      [HttpPost]
        public  ApiResult Set()
        {
            UserInfo userInfo = base.UserInfo;
            Rb_Advertising_Make_Extend model = JsonConvert.DeserializeObject<Rb_Advertising_Make_Extend>(RequestParm.Msg.ToString());

            string fileName = base.ParmJObj.GetStringValue("fileName");
            long fileSize = base.ParmJObj.GetLong("fileSize");

            if (model.AdvertisingID == 0)
            {
                return ApiResult.Failed("请关联广告！");
            }
            if (string.IsNullOrWhiteSpace(model.Content))
            {
                return ApiResult.Failed("请填写广告内容！");
            }
            model.School_Id = userInfo.School_Id;
            model.Group_Id = userInfo.Group_Id;

            model.UpdateBy = userInfo.Id;
            model.UpdateDate = System.DateTime.Now;
            model.Status = (int)Common.Enum.DateStateEnum.Normal;
            int ID = advertisingModule.Set(model, fileName, fileSize);
            if (ID > 0)
                return ApiResult.Success("保存成功", new { result = ID });
            else
                return ApiResult.Failed("请求失败！");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public  ApiResult Remove()
        {

            int ID = base.ParmJObj.GetInt("ID");
            UserInfo userInfo = base.UserInfo;

            bool flag = advertisingModule.Remove(ID, userInfo.Id);
            if (flag)
                return ApiResult.Success();
            else
                return ApiResult.Failed("请求失败！");
        }

        #endregion 
    }
}
