using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Common.Plugin;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class UserVipController : BaseController
    {
        private readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="accessor"></param>
        public UserVipController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
        }

        private readonly UserVipModule userVipModule = new UserVipModule();


        #region VIP购买自定义页面设置

        /// <summary>
        /// 获取购买vip自定义页面设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetFXGradeCustom()
        {
            var parms = RequestParm;
            RB_Distributor_FXGradeCustom_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGradeCustom_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var model = userVipModule.GetGradeCustomList(demodel).FirstOrDefault();
            if (model == null)
            {
                model = new RB_Distributor_FXGradeCustom_Extend();
            }
            return ApiResult.Success("", model);
        }

        /// <summary>
        /// 新增修改购买vip自定义页面设置
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetFXGradeCustom()
        {
            var req = RequestParm;
            RB_Distributor_FXGradeCustom_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_FXGradeCustom_Extend>(req.msg.ToString());
            if (string.IsNullOrWhiteSpace(demodel.BottomRule))
            {
                return ApiResult.Failed("活动规则不能为空");
            }
            if (string.IsNullOrWhiteSpace(demodel.BackImage))
            {
                return ApiResult.Failed("背景图片不能为空");
            }
            if (string.IsNullOrWhiteSpace(demodel.VipICO))
            {
                return ApiResult.Failed("VIP图标不能为空");
            }
            if (string.IsNullOrWhiteSpace(demodel.BackColor))
            {
                return ApiResult.Failed("背景颜色不能为空");
            }


            if (demodel.Id == 0)
            {
                demodel.TenantId = Convert.ToInt32(req.uid);
                demodel.MallBaseId = req.MallBaseId;
                demodel.CreateDate = System.DateTime.Now;
            }
            demodel.Status = 0;
            demodel.UpdateDate = System.DateTime.Now;

            bool flag = userVipModule.AddOrUpdateFXGradeCustom(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }
        #endregion



        #region Vip购买记录
        /// <summary>
        /// 获取vip购买记录
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetVipBuyPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_Vip_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Vip_Buy_Extend>(parms.msg.ToString());
            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.PayState =1;
            var list = userVipModule.GetVipBuyPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);

            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderNo,
                x.UserName,
                x.Money,
                ExpiryDateStr = x.ExpiryDate.HasValue ? x.ExpiryDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.GradeName,
                x.PayState,
                x.PayWay,
                PayTimeStr = x.PayTime.HasValue ? x.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Remark
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion


        #region Vip购买返佣

        /// <summary>
        /// vip购买返佣分页列表
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetVipBuyCommissionPageList()
        {
            var requestParm = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(requestParm.msg.ToString());
            RB_Vip_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Vip_Buy_Extend>(requestParm.msg.ToString());

            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            var list = userVipModule.GetVipBuyCommissionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);

            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderNo,
                x.UserName,
                x.Money,
                x.GradeName,
                x.UserId,
                x.Remark,
                x.ReOrderId,
                x.ReOrderNum,
                PayTimeStr = x.PayTime.HasValue ? x.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                CommissionList = x.CommissionList.Select(z => new
                {
                    z.Id,
                    z.Grade,
                    z.GradeDescription,
                    z.Commission,
                    z.UserName
                })
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// vip购买返佣 Excel下载
        /// </summary>
        /// <param name="requestMsg"></param>
        /// <returns></returns>
        [HttpPost]
        public FileContentResult GetVipBuyCommissionPageListToExcel()
        {
            var requestParm = RequestParm;
            RB_Vip_Buy_Extend demodel = JsonConvert.DeserializeObject<RB_Vip_Buy_Extend>(requestParm.msg.ToString());

            string ExcelName = "分销订单" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            List<ExcelDataSource> slist = new List<ExcelDataSource>();
            ExcelDataSource header = new ExcelDataSource()
            {
                ExcelRows = new List<ExcelColumn>(30) {
                    new ExcelColumn(value: "序号") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "购买单号") { CellWidth = 25, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },                    
                    new ExcelColumn(value: "用户Id") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "用户名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "购买金额") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "等级名称") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "购买时间") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "关联订单号") { CellWidth = 25, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "返利级别") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "昵称") { CellWidth = 25, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                    new ExcelColumn(value: "佣金") { CellWidth = 15, HAlignmentEnum = HAlignmentEnum.CENTER, VAlignmentEnum = VAlignmentEnum.CENTER },
                }
            };
            slist.Add(header);

            try
            {
                demodel.TenantId = requestParm.TenantId;
                demodel.MallBaseId = requestParm.MallBaseId;
                var list = userVipModule.GetVipBuyCommissionPageList(1, 10000, out long count, demodel);
                int Num = 0;
                foreach (var item in list)
                {
                    Num++;
                    var ocList = item.CommissionList;
                    int OCCount = ocList.Count();
                    OCCount = OCCount == 0 ? 1 : OCCount;
                    ExcelDataSource datarow = new ExcelDataSource()
                    {
                        ExcelRows = new List<ExcelColumn>(30) {
                                new ExcelColumn(value:Num.ToString()){ Rowspan = OCCount},
                            },
                        ColumnHight = 30
                    };

                    datarow.ExcelRows.Add(new ExcelColumn(value: item.OrderNo) { Rowspan = OCCount });                    
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserId.ToString()) { Rowspan = OCCount });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.UserName) { Rowspan = OCCount });
                    datarow.ExcelRows.Add(new ExcelColumn(value: (item.Money).ToString()) { Rowspan = OCCount });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.GradeName) { Rowspan = OCCount });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.PayTime.HasValue ? item.PayTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") { Rowspan = OCCount });
                    datarow.ExcelRows.Add(new ExcelColumn(value: item.ReOrderNum ?? "") { Rowspan = OCCount });

                    bool IsOCFirst = true;
                    if (item.CommissionList.Any())
                    {
                        foreach (var qitem in item.CommissionList)
                        {
                            if (!IsOCFirst)
                            {
                                datarow = new ExcelDataSource()
                                {
                                    ExcelRows = new List<ExcelColumn>(30) {
                                            new ExcelColumn(value:Num.ToString()){ },
                                        },
                                    ColumnHight = 30
                                };
                                for (var i = 0; i < 6; i++)
                                {
                                    datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                                }
                            }
                            datarow.ExcelRows.Add(new ExcelColumn(value: qitem.GradeDescription) { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: qitem.UserName) { });
                            datarow.ExcelRows.Add(new ExcelColumn(value: (qitem.Commission ?? 0).ToString()) { });
                            slist.Add(datarow);
                            IsOCFirst = false;
                        }
                    }
                    else
                    {
                        datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                        datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                        datarow.ExcelRows.Add(new ExcelColumn(value: "") { });
                        slist.Add(datarow);
                    }
                }


                var byteData = ExcelTempLateHelper.ToExcelExtend(slist);

                return File(byteData, "application/octet-stream", ExcelName);
            }
            catch (Exception ex)
            {
                LogHelper.Write(ex, string.Format("GetVipBuyCommissionPageListToExcel: {0}", JsonHelper.Serialize(RequestParm)));
                var byteData1 = ExcelTempLateHelper.ToExcelExtend(slist);
                return File(byteData1, "application/octet-stream", ExcelName);
            }
        }

        #endregion
    }
}