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();

        #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);
                        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);
                    if (msg1 != "")
                    {
                        return ApiResult.Failed("提现：" + RemitId + "，失败");
                    }
                    return ApiResult.Success();
                }
            }
            else
            {
                return ApiResult.Failed("暂不支持该类型打款");
            }
        }

        #endregion
    }
}