using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Mall.Common.API;
using Mall.Model.Extend.User;
using Mall.Module.User;
using Mall.WebApi.Filter;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Mall.Common.Plugin;
using Mall.Common.Enum.User;
using Mall.CacheManager.User;
using Newtonsoft.Json.Linq;
using Mall.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Google.Protobuf.WellKnownTypes;
using Mall.Model.Entity.User;

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class SmallShopsController : BaseController
    {
        private readonly SmallShopsModule smallShopsModule = new SmallShopsModule();
        private readonly UserModule userModule = new UserModule();

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

        #region 微店管理
        /// <summary>
        /// 获取店铺分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_SmallShops_Info_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Info_Extend>(parms.msg.ToString());

            demodel.TenantId = parms.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = smallShopsModule.GetSmallShopsPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name,
                x.Logo,
                x.UserId,
                UserName = x.NickName,
                x.Commission,
                x.TotalCommission,
                x.Notice,
                x.AuditStatus,
                AuditStatusName = x.AuditStatus.GetEnumName(),
                AuditDate = x.AuditDate.HasValue ? x.AuditDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                x.Remark,
                x.TenantId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取店铺下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsDropDownList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_SmallShops_Info_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Info_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = smallShopsModule.GetSmallShopsDropDownList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.Name
            });
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 获取店铺信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsInfo()
        {
            var requestParm = RequestParm;
            var parms = JObject.Parse(requestParm.msg.ToString());
            int SmallShopsId = parms.GetInt("SmallShopsId", 0);
            if (SmallShopsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var model = smallShopsModule.GetSmallShopsInfo(SmallShopsId);
            if (model.TenantId != Convert.ToInt32(requestParm.uid))
            {
                return ApiResult.ParamIsNull("未查询到该微店信息");
            }
            if (model.MallBaseId != requestParm.MallBaseId)
            {
                return ApiResult.ParamIsNull("未查询到该微店信息");
            }
            return ApiResult.Success("", new
            {
                model.Id,
                model.Name,
                model.Logo,
                model.UserId,
                UserName = model.NickName,
                model.Commission,
                model.TotalCommission,
                model.Notice,
                model.AuditStatus,
                AuditStatusName = model.AuditStatus.GetEnumName(),
                AuditDate = model.AuditDate.HasValue ? model.AuditDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                model.Remark,
                CreateDate = model.CreateDate.HasValue ? model.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
        }

        /// <summary>
        /// 微店审核信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsAudit()
        {
            var req = RequestParm;
            JObject prams = JObject.Parse(req.msg.ToString());
            int SmallShopsId = prams.GetInt("SmallShopsId", 0);
            int Type = prams.GetInt("Type", 1);//类型  1审核通过   2审核拒绝  3修改备注  4删除
            string Remark = prams.GetStringValue("Remark");

            if (SmallShopsId <= 0)
            {
                return ApiResult.ParamIsNull();
            }
            var ssmodel = smallShopsModule.GetSmallShopsInfo(SmallShopsId);
            if (ssmodel == null)
            {
                return ApiResult.Failed("微店不存在");
            }
            if (ssmodel.TenantId != req.TenantId)
            {
                return ApiResult.ParamIsNull("未查询到该微店信息");
            }
            if (ssmodel.MallBaseId != req.MallBaseId)
            {
                return ApiResult.ParamIsNull("未查询到该微店信息");
            }
            if (Type == 1 || Type == 2)
            {
                if (ssmodel.AuditStatus != DistributorAuditStatusEnum.Auditing)
                {
                    return ApiResult.ParamIsNull("微店状态不正确");
                }
            }

            ssmodel.Remark = Remark;
            bool flag = smallShopsModule.SetSmallShopsAudit(ssmodel, Type);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 设置微店佣金
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsCommission()
        {
            var req = RequestParm;
            JObject parms = JObject.Parse(req.msg.ToString());
            int SmallShopsId = parms.GetInt("SmallShopsId", 0);
            decimal Commission = parms.GetDecimal("Commission");

            if (SmallShopsId <= 0)
            {
                return ApiResult.Failed();
            }

            bool flag = smallShopsModule.SetSmallShopsCommission(SmallShopsId, Commission, req.TenantId, req.MallBaseId, req.EmpId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        #endregion

        #region 微店提现

        /// <summary>
        /// 微店提现申请审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsRemitAudit()
        {
            var re = RequestParm;
            var parms = JObject.Parse(re.msg.ToString());
            int RemitId = parms.GetInt("RemitId", 0);
            int ErpEmpId = parms.GetInt("ErpEmpId", 0);//erp用户id
            int Type = parms.GetInt("Type", 0);//1审核通过  2打款  3驳回 
            string Remark = parms.GetStringValue("Remark");
            if (RemitId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分销提现id");
            }
            var model = smallShopsModule.GetSmallShopsRemitInfo(RemitId);
            if (model == null)
            {
                return ApiResult.Failed("该提现不存在，请核实后再试");
            }
            if (model.TenantId != Convert.ToInt32(re.uid))
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            if (model.MallBaseId != re.MallBaseId)
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            if (Type == 1)
            {
                if (model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.Auditing)
                {
                    return ApiResult.Failed("状态不对，请核实后再试");
                }
            }
            else if (Type == 2)
            {
                if (model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.ToPlayWith)
                {
                    return ApiResult.Failed("状态不对，请核实后再试");
                }
                //执行发放金额
                if (model.WithdrawalWay == DistrbutorWithdrawWayEnum.ZDDK)
                {
                    int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
                    if (IsNormalServer == 1)
                    {
                        var mallModel = userModule.GetMiniProgramExtend(re.MallBaseId);
                        var umodel = userModule.GetMemberUserInfo(model.UserId ?? 0);
                        var flag = App_Code.PayUtil.GetTransfersOrder(model.OrderNum, model.RemitMoney ?? 0, (model.UserId ?? 0).ToString(), umodel.OpenId, mallModel, _accessor);
                        if (flag)
                        {
                            string msg1 = smallShopsModule.SetSmallShopsRemitAudit(RemitId, Type, Remark, re.uid, re.MallBaseId, ErpEmpId);
                            if (msg1 != "")
                            {
                                LogHelper.Write("提现：" + RemitId + "，失败");
                            }

                            new MiniProgramMsgModule().SendWithdrawSucceedMsg(model.TenantId, model.MallBaseId, umodel.OpenId, (model.RemitMoney ?? 0).ToString(), (model.Fee ?? 0).ToString(), (model.WithdrawalWay.GetEnumName()), "已发放佣金，请注意查收");
                            return ApiResult.Success();
                        }
                        else
                        {
                            LogHelper.Write("企业付款失败RemitId:" + RemitId);
                            return ApiResult.Failed("支付失败");
                        }
                    }
                    else
                    {
                        string msg1 = smallShopsModule.SetSmallShopsRemitAudit(RemitId, Type, Remark, re.uid, re.MallBaseId, ErpEmpId);
                        if (msg1 != "")
                        {
                            return ApiResult.Failed("提现：" + RemitId + "，失败");
                        }
                        return ApiResult.Success();
                    }
                }
                else if (model.WithdrawalWay == DistrbutorWithdrawWayEnum.YETX) { 
                    //余额提现
                }
                else
                {
                    return ApiResult.Failed("暂不支持该类型打款");
                }
            }
            else if (Type == 3)
            {
                if (model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.Auditing && model.AuditStatus != Common.Enum.User.DistributorRemitAuditStatusEnum.ToPlayWith)
                {
                    return ApiResult.Failed("状态不对，请核实后再试");
                }
            }
            else
            {
                return ApiResult.Failed("暂不支持该类型");
            }

            string msg = smallShopsModule.SetSmallShopsRemitAudit(RemitId, Type, Remark, re.uid, re.MallBaseId, ErpEmpId);
            if (msg == "")
            {
                if (Type == 3)
                {
                    var umodel = userModule.GetMemberUserInfo(model.UserId ?? 0);
                    new MiniProgramMsgModule().SendWithdrawFailMsg(model.TenantId, model.MallBaseId, umodel.OpenId, (model.RemitMoney ?? 0).ToString(), "提现申请已被拒绝");
                }
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 微店自定义

        /// <summary>
        /// 新增分销商自定义
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorCustomInfo()
        {
            var requestParm = RequestParm;
            RB_SmallShops_Custom demodel = JsonConvert.DeserializeObject<RB_SmallShops_Custom>(requestParm.msg.ToString());
            if (string.IsNullOrWhiteSpace(demodel.HeadBackImage))
            {
                return ApiResult.ParamIsNull("请传递头部背景图片");
            }

            if (string.IsNullOrEmpty(demodel.WithdrawalText))
            {
                return ApiResult.ParamIsNull("请传递提现按钮文本");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawalColor))
            {
                return ApiResult.ParamIsNull("请传递提现按钮颜色");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawalTextColor))
            {
                return ApiResult.ParamIsNull("请传递按钮文字颜色");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawalImage))
            {
                return ApiResult.ParamIsNull("请传递提现图标");
            }
            if (string.IsNullOrEmpty(demodel.SmallShopOrderName))
            {
                return ApiResult.ParamIsNull("请传递店铺订单名称");
            }

            if (string.IsNullOrEmpty(demodel.SmallShopOrderImage))
            {
                return ApiResult.ParamIsNull("请传递店铺订单图片");
            }
            if (demodel.WithdrawalDetailName == null || string.IsNullOrWhiteSpace(demodel.WithdrawalDetailName))
            {
                return ApiResult.ParamIsNull("请传递提现明细");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawalDetailImage))
            {
                return ApiResult.ParamIsNull("请传递提现明细图片");
            }
            if (demodel.MyCustomerName == null || string.IsNullOrWhiteSpace(demodel.MyCustomerName))
            {
                return ApiResult.ParamIsNull("请传递我的客户");
            }
            if (string.IsNullOrEmpty(demodel.MyCustomerImage))
            {
                return ApiResult.ParamIsNull("请传递我的客户图片");
            }
            if (demodel.SmallShopQRCodeName == null || string.IsNullOrWhiteSpace(demodel.SmallShopQRCodeName))
            {
                return ApiResult.ParamIsNull("请传递店铺二维码");
            }
            if (string.IsNullOrEmpty(demodel.SmallShopQRCodeImage))
            {
                return ApiResult.ParamIsNull("请传递店铺二维码图片");
            }
            if (demodel.SmallShopSetUpName == null || string.IsNullOrWhiteSpace(demodel.SmallShopSetUpName))
            {
                return ApiResult.ParamIsNull("请传递店铺设置");
            }
            if (string.IsNullOrEmpty(demodel.SmallShopSetUpImage))
            {
                return ApiResult.ParamIsNull("请传递店铺设置图片");
            }
            if (demodel.LiveName == null || string.IsNullOrWhiteSpace(demodel.LiveName))
            {
                return ApiResult.ParamIsNull("请传递直播名称");
            }
            //
            if (string.IsNullOrEmpty(demodel.LiveImage))
            {
                return ApiResult.ParamIsNull("请传递直播图标");
            }
            if (string.IsNullOrEmpty(demodel.CommissionWithdrawnName))
            {
                return ApiResult.ParamIsNull("请传递已提现佣金描述");
            }
            if (string.IsNullOrEmpty(demodel.OutstandingCommissionName))
            {
                return ApiResult.ParamIsNull("请传递未结算佣金描述");
            }
            if (string.IsNullOrEmpty(demodel.WithdrawableName))
            {
                return ApiResult.ParamIsNull("请传递可提现佣金描述");
            }
            if (string.IsNullOrEmpty(demodel.CommissionTobePaidName))
            {
                return ApiResult.ParamIsNull("请传递待打款佣金描述");
            }
            if (string.IsNullOrEmpty(demodel.UserNotesName))
            {
                return ApiResult.ParamIsNull("请传递用户须知描述");
            }
            if (string.IsNullOrEmpty(demodel.UserNotes))
            {
                return ApiResult.ParamIsNull("请传递用户须知");
            }

            if (string.IsNullOrWhiteSpace(demodel.IWantToWithdrawName))
            {
                return ApiResult.Failed("请传递我要提现描述");
            }
            if (string.IsNullOrWhiteSpace(demodel.WithdrawalAmountName))
            {
                return ApiResult.Failed("请传递提现金额描述");
            }
            if (string.IsNullOrWhiteSpace(demodel.WithdrawalWayName))
            {
                return ApiResult.Failed("请传递提现方式描述");
            }

            if (demodel.Id == 0)
            {
                demodel.CreateDate = DateTime.Now;
               
            }
            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            demodel.UpdateDate = DateTime.Now;
            bool flag = smallShopsModule.SetSmallShopsCustomInfo(demodel);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取分销商自定义
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributorCustomInfo()
        {
            var requestParm = RequestParm;
            var model = smallShopsModule.GetSmallShopsCustomList(new Model.Entity.User.RB_SmallShops_Custom { TenantId = requestParm.TenantId, MallBaseId = requestParm.MallBaseId }).FirstOrDefault();
            if (model == null)
            {
                model = new Model.Entity.User.RB_SmallShops_Custom();
            }
            return ApiResult.Success("", new
            {
                model.Id,
                model.HeadBackImage,
                model.WithdrawalFilletPX,
                model.WithdrawalText,
                model.WithdrawalColor,
                model.WithdrawalTextColor,
                model.WithdrawalImage,
                model.SmallShopOrderName,
                model.SmallShopOrderImage,
                model.WithdrawalDetailName,
                model.WithdrawalDetailImage,
                model.MyCustomerName,
                model.MyCustomerImage,
                model.SmallShopQRCodeName,
                model.SmallShopQRCodeImage,
                model.SmallShopSetUpName,
                model.SmallShopSetUpImage,
                model.LiveName,
                model.LiveImage,
                model.CommissionWithdrawnName,
                model.OutstandingCommissionName,
                model.WithdrawableName,
                model.CommissionTobePaidName,
                model.UserNotesName,
                model.UserNotes,
                model.IWantToWithdrawName,
                model.WithdrawalAmountName,
                model.WithdrawalWayName,
                UpdateDate = model.UpdateDate.HasValue ? model.UpdateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",

            });
        }

        #endregion

        #region 微店提现

        /// <summary>
        /// 获取分销商提现分页列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsRemitPageList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(parms.msg.ToString());
            RB_SmallShops_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Remit_Extend>(parms.msg.ToString());

            demodel.TenantId = Convert.ToInt32(parms.uid);
            demodel.MallBaseId = parms.MallBaseId;
            var list = smallShopsModule.GetSmallShopsRemitPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.Id,
                x.OrderNum,
                x.UserId,
                x.UserName,
                x.Photo,
                x.Source,
                x.WithdrawalWay,
                WithdrawalWayName = x.WithdrawalWay.GetEnumName(),
                x.AccountName,
                x.AccountNumber,
                x.BankName,
                x.AppliedMoney,
                x.Fee,
                x.RemitMoney,
                x.AuditRemark,
                x.RemitRemark,
                x.RejectRemark,
                x.AuditStatus,
                AuditStatusName = x.AuditStatus.GetEnumName(),
                SourceName = x.Source.GetEnumName(),
                x.TenantId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                AuditDate = x.AuditDate.HasValue ? x.AuditDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                RemitDate = x.RemitDate.HasValue ? x.RemitDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
                RejectDate = x.RejectDate.HasValue ? x.RejectDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : "",
            });
            return ApiResult.Success("", pagelist);
        }
        #endregion
    }
}