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 Newtonsoft.Json.Linq;
using Mall.Common;
using Mall.Module.Finance;
using Mall.Model.Extend.Finance;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Mall.Model.Extend.Product;
using Mall.Module.Product;
using Microsoft.AspNetCore.Http;

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

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

        private readonly UserModule userModule = new UserModule();
        private readonly OrderModule orderModule = new OrderModule();
        private readonly SmallShopsModule smallShopsModule = new SmallShopsModule();

        #region erp查询分销情况

        /// <summary>
        /// 用户返佣列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributionCommissionPageList(object request)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(request.ToString());
            string msg = EncryptionHelper.AesDecrypt(requestParm.msg.ToString(), Config.FinanceKey);
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(msg);
            RB_Member_User_Extend demodel = JsonConvert.DeserializeObject<RB_Member_User_Extend>(msg);

            demodel.TenantId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["TenantId"]);
            demodel.MallBaseId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["MallBaseId"]);
            demodel.IsDistributor = 1;
            var list = userModule.GetDistributionCommissionPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list;
            return ApiResult.Success("", pagelist);
        }

        /// <summary>
        /// 用户订单返佣列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetDistributionOrderCommissionPageList(object request)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(request.ToString());
            string msg = EncryptionHelper.AesDecrypt(requestParm.msg.ToString(), Config.FinanceKey);
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(msg);
            RB_Goods_OrderCommission_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderCommission_Extend>(msg);
            if ((demodel.UserId ?? 0) <= 0) {
                return ApiResult.ParamIsNull("请传递用户id");
            }
            demodel.TenantId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["TenantId"]);
            demodel.MallBaseId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["MallBaseId"]);
            var list = orderModule.GetERPDistributionOrdersPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.OrderId,
                x.OrderNo,
                x.Grade,
                x.GradeDescription,
                DetailList = x.OrderDetailList.Select(y => new {
                    y.Id,
                    y.CoverImagePath,
                    y.OrderType,
                    OrderTypeName = y.OrderType.GetEnumName(),
                    y.GoodsName,
                    SpecificationList = JsonConvert.DeserializeObject<List<string>>(y.Specification),
                    y.ProductCode,
                    y.Final_Price,
                    y.Number
                }),
                x.UserId,
                x.UserName,
                x.Mobile,
                x.Remark,
                x.Commission,
                x.CommissionState,
                x.TenantId,
                x.MallBaseId,
                CreateDate = x.CreateDate.HasValue ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            });
            return ApiResult.Success("", pagelist);
        }

        #endregion

        #region erp打款回调

        /// <summary>
        /// 分销提现申请审核
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetDistributorRemit(object request)
        {
            JObject parms1 = JObject.Parse(request.ToString());
            string msg = EncryptionHelper.AesDecrypt(parms1.GetStringValue("msg"), Config.FinanceKey);

            var parms = JObject.Parse(msg.ToString());
            int RemitId = parms.GetInt("RemitId", 0);
            string Remark = parms.GetStringValue("Remark");
            int TenantId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["TenantId"]);
            int MallBaseId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["MallBaseId"]);
            if (RemitId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分销提现id");
            }
            var model = userModule.GetDistributorEntity(RemitId);
            if (model == null)
            {
                return ApiResult.Failed("该提现不存在，请核实后再试");
            }
            if (model.TenantId != Convert.ToInt32(TenantId))
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            if (model.MallBaseId != MallBaseId)
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            
            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(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 = userModule.SetDistributorRemitAudit(RemitId, 2, Remark, TenantId.ToString(), MallBaseId, 0);
                        if (msg1 != "")
                        {
                            LogHelper.Write("提现：" + RemitId + "，失败");
                        }
                        return ApiResult.Success();
                    }
                    else
                    {
                        userModule.SetDistributorRemitRemark(RemitId, "ERP打款失败，请手动操作打款");
                        return ApiResult.Failed("支付失败");
                    }
                }
                else
                {
                    string msg1 = userModule.SetDistributorRemitAudit(RemitId, 2, Remark, TenantId.ToString(), MallBaseId, 0);
                    if (msg1 != "")
                    {
                        return ApiResult.Failed("提现：" + RemitId + "，失败");
                    }
                    return ApiResult.Success();
                }
            }
            else if (model.WithdrawalWay == DistrbutorWithdrawWayEnum.YETX)
            {
                string msg1 = userModule.SetDistributorRemitAudit(RemitId, 2, Remark, TenantId.ToString(), MallBaseId, 0);
                if (msg1 != "")
                {
                    return ApiResult.Failed("提现：" + RemitId + "，失败");
                }
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed("暂不支持该类型打款");
            }
        }

        #endregion

        #region erp微店打款

        /// <summary>
        /// 微店打款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsRemitAudit(object request)
        {
            JObject parms1 = JObject.Parse(request.ToString());
            string msg = EncryptionHelper.AesDecrypt(parms1.GetStringValue("msg"), Config.FinanceKey);

            var parms = JObject.Parse(msg.ToString());
            int RemitId = parms.GetInt("RemitId", 0);
            string Remark = parms.GetStringValue("Remark");
            int TenantId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["TenantId"]);
            int MallBaseId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["MallBaseId"]);
            if (RemitId <= 0)
            {
                return ApiResult.ParamIsNull("请传递分销提现id");
            }
            var model = smallShopsModule.GetSmallShopsRemitInfo(RemitId);
            if (model == null)
            {
                return ApiResult.Failed("该提现不存在，请核实后再试");
            }
            if (model.TenantId != Convert.ToInt32(TenantId))
            {
                return ApiResult.Failed("未查询到提现信息");
            }
            if (model.MallBaseId != MallBaseId)
            {
                return ApiResult.Failed("未查询到提现信息");
            }

            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(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, 2, Remark, TenantId.ToString(), MallBaseId, 0);
                        if (msg1 != "")
                        {
                            LogHelper.Write("提现：" + RemitId + "，失败");
                        }
                        return ApiResult.Success();
                    }
                    else
                    {
                        smallShopsModule.SetSmallShopsRemitRemark(RemitId, "ERP财务审核打款失败，请手动操作打款");
                        return ApiResult.Failed("支付失败");
                    }
                }
                else
                {
                    string msg1 = smallShopsModule.SetSmallShopsRemitAudit(RemitId, 2, Remark, TenantId.ToString(), MallBaseId, 0);
                    if (msg1 != "")
                    {
                        return ApiResult.Failed("提现：" + RemitId + "，失败");
                    }
                    return ApiResult.Success();
                }
            }
            else if (model.WithdrawalWay == DistrbutorWithdrawWayEnum.YETX) {
                string msg1 = smallShopsModule.SetSmallShopsRemitAudit(RemitId, 2, Remark, TenantId.ToString(), MallBaseId, 0);
                if (msg1 != "")
                {
                    return ApiResult.Failed("提现：" + RemitId + "，失败");
                }
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed("暂不支持该类型打款");
            }
        }

        #endregion

        #region 推荐账单
        /// <summary>
        /// 账单打款
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetRecommendOrdersBillRemit(object request)
        {
            JObject parms1 = JObject.Parse(request.ToString());
            string rmsg = EncryptionHelper.AesDecrypt(parms1.GetStringValue("msg"), Config.FinanceKey);
            int TenantId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["TenantId"]);
            int MallBaseId = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("FinanceSetting")["MallBaseId"]);
            var parms = JObject.Parse(rmsg.ToString());
            int BillId = parms.GetInt("BillId", 0);            
            if (BillId <= 0)
            {
                return ApiResult.ParamIsNull();
            }

            var bmodel = userModule.GetBillModel(BillId);
            if (bmodel == null) { return ApiResult.Failed("账单不存在"); }
            if (bmodel.BillState != 1) { return ApiResult.Failed("账单状态不正确"); }

            int IsNormalServer = Convert.ToInt32(new ConfigurationBuilder().Add(new JsonConfigurationSource { Path = "appsettings.json" }).Build().GetSection("IsNormalServer").Value);
            if (IsNormalServer == 1)
            {
                var mallModel = userModule.GetMiniProgramExtend(MallBaseId);
                var umodel = userModule.GetMemberUserInfo(bmodel.UserId ?? 0);
                var flag = App_Code.PayUtil.GetTransfersOrder((bmodel.Periods ?? "") + bmodel.Id, bmodel.Money ?? 0, (bmodel.UserId ?? 0).ToString(), umodel.OpenId, mallModel, _accessor, "赞羊供应商佣金打款");
                if (flag)
                {
                    string msg = userModule.SetRecommendOrdersBillRemit(BillId, TenantId, MallBaseId, 0, "单据审核通过，已自动打款");
                    if (msg != "")
                    {
                        LogHelper.Write("企业付款失败 账单BillId:" + BillId);
                    }

                    new MiniProgramMsgModule().SendWithdrawSucceedMsg(TenantId, MallBaseId, umodel.OpenId, (bmodel.Money ?? 0).ToString(), "0", "自动打款", "已发放供应商佣金，请注意查收");
                    return ApiResult.Success();
                }
                else
                {
                    LogHelper.Write("企业付款失败 账单BillId:" + BillId);
                    return ApiResult.Failed("支付失败");
                }
            }
            else
            {
                string msg = userModule.SetRecommendOrdersBillRemit(BillId, TenantId, MallBaseId, 0, "单据审核通过，已自动打款");
                if (msg == "")
                {
                    return ApiResult.Success();
                }
                else
                {
                    return ApiResult.Failed(msg);
                }
            }
        }

        /// <summary>
        /// 获取账单明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetRecommendOrdersBillDetailList(object request)
        {
            var requestParm = JsonConvert.DeserializeObject<RequestParm>(request.ToString());
            RB_Distributor_BillDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Distributor_BillDetail_Extend>(requestParm.msg.ToString());

            demodel.TenantId = requestParm.TenantId;
            demodel.MallBaseId = requestParm.MallBaseId;
            if ((demodel.BillId ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("请传递账单id");
            }
            var Robj = userModule.GetRecommendOrdersBillDetailList(demodel);
            return ApiResult.Success("", Robj);
        }
        #endregion
    }
}