using System;
using System.Collections.Generic;
using System.Common;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.Marketing
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class MarketingController : BaseController
    {

        private readonly ISys_MarketingRepository _sys_marketing_Repository;
        private readonly IBus_ProductRepository _productRepository;
        private readonly ICus_VipLabelInfoRepository _cus_vip_labelinfoRepository;
        public MarketingController(ISys_MarketingRepository sys_marketing_Repository, IBus_ProductRepository productRepository, ICus_VipLabelInfoRepository cus_vip_labelinfoRepository)
        {
            _sys_marketing_Repository = sys_marketing_Repository;
            _productRepository = productRepository;
            _cus_vip_labelinfoRepository = cus_vip_labelinfoRepository;
        }
     
        /// <summary>
        /// 添加营销政策
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddMark(MarketingInput input)
        {
            if (string.IsNullOrEmpty(input.F_Name ))
                return Error("请输入名称");
            if (input .F_Type <=0)
                return Error("请选择营销方式");
            if (string.IsNullOrEmpty(input.F_StartTime))
                return Error("请选择活动开始时间");
            if (string.IsNullOrEmpty(input.F_EndTime))
                return Error("请选择活动结束时间");
            var model = new T_Sys_Marketing ();
            model = Transformation(model,input);
         //   model.F_CreateUser = "8000";
           model.F_CreateTime = DateTime.Now;
              model.F_CreateUser = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
           var res = await _sys_marketing_Repository.Add(model);
            if (res > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }
        /// <summary>
        /// 修改营销政策
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(MarketingInput input)
        {
            if (input.F_ID <= 0)
                return Error("请选择正确的营销政策");
            if (string.IsNullOrEmpty(input.F_Name))
                return Error("请输入名称");
            if (input.F_Type <= 0)
                return Error("请选择营销方式");
            if (string.IsNullOrEmpty(input.F_StartTime))
                return Error("请选择活动开始时间");
            if (string.IsNullOrEmpty(input.F_EndTime))
                return Error("请选择活动结束时间");
            var model = await _sys_marketing_Repository.GetSingle(x => x.F_ID == input.F_ID);
            if (model == null)
                return Error("操作失败");
            model = Transformation(model,input);
            model.F_UpdateTime = DateTime.Now;
           // model.F_UpdateUser = "8000";
          model.F_UpdateUser  = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var  b = await _sys_marketing_Repository.Update(model);
            if (b)
                return Success("修改成功");
            return Error("修改失败");
        }
        /// <summary>
        /// 删除营销政策
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    //var model = await _sys_marketing_Repository.GetSingle(x => x.F_ID == item);
                    //model.F_IsDelete  = (int)EnumUserCountState.Delete;
                    //model.F_DeleteTime  = DateTime.Now.ToLocalTime();
                    //model.F_DeleteUser  = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_marketing_Repository.Delete(q=>q.F_ID== item).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 获取营销政策列表
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListMark(string keyword, string name, string  commodity, string gift, string starttime, string endtime,
       string  process ,  string  type="1",  int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_IsDelete", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (!string.IsNullOrEmpty(name))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Name", ConditionalType = ConditionalType.Like, FieldValue = name });
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_PromotionRules", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_Describe", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_PromotionMethod", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                         new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_ActivityMode", ConditionalType = ConditionalType.Like, FieldValue = keyword })
                    }
                });
            }
            if (!string.IsNullOrEmpty(commodity))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Commodit", ConditionalType = ConditionalType.Like, FieldValue = commodity });
            }
            if (!string.IsNullOrEmpty(gift))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Gift", ConditionalType = ConditionalType.Like, FieldValue = gift });
            }
            if (!string.IsNullOrEmpty(starttime))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_StartTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = starttime });
            }
            if (!string.IsNullOrEmpty(endtime))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_EndTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = endtime });
            }
            if (!string.IsNullOrEmpty(process))
            {
                if (process=="0")
                {
                    conModels.Add(new ConditionalModel() { FieldName = "F_StartTime", ConditionalType = ConditionalType.GreaterThan, FieldValue = DateTime .Now .ToString () });
                }
                else if (process == "1")
                {
                    conModels.Add(new ConditionalModel() { FieldName = "F_StartTime", ConditionalType = ConditionalType.LessThanOrEqual, FieldValue = DateTime.Now.ToString() });
                    conModels.Add(new ConditionalModel() { FieldName = "F_EndTime", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = DateTime.Now.ToString() });
                }
                else
                {
                    conModels.Add(new ConditionalModel() { FieldName = "F_EndTime", ConditionalType = ConditionalType.LessThan, FieldValue = DateTime.Now.ToString() });
                }
                //conModels.Add(new ConditionalModel() { FieldName = "F_Process", ConditionalType = ConditionalType.Equal , FieldValue = process });
            }
            #endregion
            conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Like, FieldValue = type });
            int recordCount = 0;
            var list = await _sys_marketing_Repository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount });
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = await ConvertAsync(list),
                total = list.Totals ,
            };

            return  Content(obj.ToJson());
        }
        /// <summary>
        /// 获取营销政策详情
        /// </summary>
        /// <param name="id">id</param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public async Task<IActionResult> GetDetailsAsync(int id)
        {
            if (id <= 0)
                return Error("参数错误");

            var model = await _sys_marketing_Repository.GetSingle(x => x.F_ID == id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", await Convert(model) );
        }
        #region 私有方法
        /// <summary>
        /// Input转Model
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private T_Sys_Marketing Transformation(T_Sys_Marketing model, MarketingInput input)
        {
         
            model.F_Name = input.F_Name;//政策名称（活动名称）
            model.F_PromotionRules = input.F_PromotionRules;//催销规则（赠送方式，促销方式）
            model.F_Describe = input.F_Describe;//活动描述
            model.F_Commodity = input.F_Commodity;//商品
            model.F_Money = input.F_Money;//商品活动金额
            model.F_Gift = input.F_Gift;//赠品
            model.F_StartTime = DateTime.Parse(input.F_StartTime);//开始时间
            model.F_EndTime = DateTime.Parse(input.F_EndTime);//结束时间
            model.F_ActivityMode = input.F_ActivityMode;//活动方式
            model.F_Tag = input.F_Tag;//商品标签（暂留）
            #region 满赠营销政策
            model.F_Member = input.F_Member;//适用会员
            #endregion
            #region 满减活动政策
            model.F_AmountRange = input.F_AmountRange;//金额区间
            #endregion
            
            if (DateTime.Now > DateTime.Parse(input.F_StartTime))
            {
                if (DateTime.Now > DateTime.Parse(input.F_EndTime))
                    model.F_Process = 2;
                else
                    model.F_Process = 1;
            }
            else
            {
                model.F_Process = 0;
            }
            model.F_Type = input.F_Type;
            model.F_IsDelete = 0;
            return model;
        }
        private async Task <MarketingInput> Convert(T_Sys_Marketing it)
        {
            MarketingInput marketing = new MarketingInput();
            marketing.F_ID = it.F_ID;
            marketing.F_Name = it.F_Name; /// 政策名称（活动名称）
            marketing.F_PromotionRules = it.F_PromotionRules; //催销规则（赠送方式，促销方式）
            marketing.F_Commodity = it.F_Commodity; //商品
            marketing.F_Describe = it.F_Describe; //描述
            marketing.F_Gift = it.F_Gift; //赠品ID
            marketing.F_GiftName ="";
            if (!string.IsNullOrEmpty(it.F_Gift))
            {
                try
                {
                    string[] split = it.F_Gift.Split(',');
                    if (split != null)
                        foreach (var iv in split)
                        {
                            var data = await _productRepository.GetSingle(x => x.F_ProductId ==iv);
                            if (data != null)
                            {
                                if (marketing.F_GiftName == "")
                                    marketing.F_GiftName = data.F_ProductName; //赠品名称
                                else
                                    marketing.F_GiftName += ","+ data.F_ProductName;
                            }
                               
                        }

                }
                catch
                {
                    marketing.F_GiftName = ""; /// 赠品名称
                }
            }
            marketing.F_Money = it.F_Money; //金额
            marketing.F_StartTime = it.F_StartTime.ToString(); //开始时间
            marketing.F_EndTime = it.F_EndTime.ToString(); //结束时间
            marketing.F_Member = it.F_Member; //适用会员
            if (!string.IsNullOrEmpty(it.F_Member))
            {
                try
                {
                    var data = await _cus_vip_labelinfoRepository.GetSingle(x => x.F_ID == int.Parse(marketing.F_Member));
                    if (data != null)
                        marketing.F_MemberName = data.F_Name; /// 会员名称
                }
                catch
                {
                    marketing.F_MemberName = ""; /// 会员名称
                }
            }
            marketing.F_CreateTime = it.F_CreateTime; //创建时间
            marketing.F_CreateUser = it.F_CreateUser; //创建人
            marketing.F_UpdateTime = it.F_UpdateTime; //修改时间
            marketing.F_UpdateUser = it.F_UpdateUser; //修改人

            marketing.F_PromotionMethod = it.F_PromotionMethod; //促销方式
            marketing.F_AmountRange = it.F_AmountRange; //金额区间
            marketing.F_ActivityMode = it.F_ActivityMode; //活动方式
            if (DateTime.Now > it.F_StartTime)
            {
                if (it.F_Process == 0&& DateTime.Now < it.F_EndTime)
                {
                    it.F_Process = 1;
                    bool b = await _sys_marketing_Repository.Update(it);
                }
                if (DateTime.Now > it.F_EndTime && it.F_Process != 2)
                {
                    it.F_Process = 2;
                    bool b = await _sys_marketing_Repository.Update(it);
                }
            }
            marketing.F_Process = it.F_Process; //进程
            marketing.F_Type = it.F_Type; //营销方式
            return marketing;
        }
        /// model转input
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<List<MarketingInput>> ConvertAsync(PageData<T_Sys_Marketing> model)
        {
            List<MarketingInput> input = new List<MarketingInput>();
            if (model != null)
            {

                foreach (var it in model.Rows)
                {
                    MarketingInput marketing = new MarketingInput();
                    marketing = await  Convert(it);
                    input.Add(marketing);
                }
            }
            return input;
        }
        #endregion
    }
}