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 Mall.Model.Extend.Product;
using Mall.Model.Extend.MarketingCenter;
using Mall.Model.Entity.User;
using NPOI.SS.Formula.Functions;
using Google.Protobuf.WellKnownTypes;

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

        #region 微店提现

        /// <summary>
        /// 获取提现余额
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsWithdrawDepositBalance()
        {
            var userInfo = AppletUserInfo;

            var obj = smallShopsModule.GetSmallShopsWithdrawDepositBalance(userInfo);
            return ApiResult.Success("", obj);
        }

        /// <summary>
        /// 分销提现
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsWithdrawDeposit()
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            RB_SmallShops_Remit_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Remit_Extend>(req.msg.ToString());
            if ((demodel.AppliedMoney ?? 0) <= 0)
            {
                return ApiResult.ParamIsNull("提现金额不能小于0");
            }
            if (demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.WXZZ || demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.YYKZZ || demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.ZFBZZ)
            {
                if (string.IsNullOrEmpty(demodel.AccountName))
                {
                    return ApiResult.ParamIsNull("请输入账户名称");
                }
                if (string.IsNullOrEmpty(demodel.AccountNumber))
                {
                    return ApiResult.ParamIsNull("请输入账号");
                }
                if (demodel.WithdrawalWay == DistrbutorWithdrawWayEnum.YYKZZ)
                {
                    if (string.IsNullOrEmpty(demodel.BankName))
                    {
                        return ApiResult.ParamIsNull("请输入银行名称");
                    }
                }
            }

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            demodel.UserId = userInfo.UserId;
            demodel.AuditStatus = DistributorRemitAuditStatusEnum.Auditing;
            demodel.CreateDate = DateTime.Now;
            Random R = new Random();
            int Rstr = R.Next(111, 999);
            demodel.OrderNum = DateTime.Now.ToString("yyyyMMddHHmmssfff") + Rstr;
            string msg = smallShopsModule.SetSmallShopsWithdrawDeposit(demodel);
            if (msg == "")
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed(msg);
            }
        }

        #endregion

        #region 微店价格设置

        /// <summary>
        /// 获取店铺信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsGlobalPrice()
        {
            var userInfo = AppletUserInfo;
            var model = smallShopsModule.GetSmallShopsInfo_V2(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            if (model == null) { return ApiResult.Failed("微店不存在"); }
            if (model.AuditStatus != DistributorAuditStatusEnum.Audited) { return ApiResult.Failed("微店未审核通过"); }

            var bmodel = smallShopsModule.GetSmallShopsBaseInfo(userInfo.TenantId, userInfo.MallBaseId);
            if (bmodel == null) { return ApiResult.Failed("出错啦，请联系管理员"); }

            return ApiResult.Success("", new
            {
                model.Id,
                model.UpPrice,
                model.PriceType,
                bmodel.CustomMinPriceRate,
                bmodel.CustomMaxPriceRate,
                bmodel.CustomMinFixedPrice,
                bmodel.CustomMaxFixedPrice
            });
        }

        /// <summary>
        /// 设置微店全局价格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult SetSmallShopsGlobalPrice() 
        {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            decimal UpPrice = parms.GetDecimal("UpPrice");
            int PriceType = parms.GetInt("PriceType", 0);

            var model = smallShopsModule.GetSmallShopsInfo_V2(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            if (model == null) { return ApiResult.Failed("微店不存在"); }
            if (model.AuditStatus != DistributorAuditStatusEnum.Audited) { return ApiResult.Failed("微店未审核通过"); }

            var bmodel = smallShopsModule.GetSmallShopsBaseInfo(userInfo.TenantId, userInfo.MallBaseId);
            if (bmodel == null) { return ApiResult.Failed("出错啦，请联系管理员"); }

            if (PriceType == 1)
            {
                //百分比
                if (bmodel.CustomMinPriceRate <= UpPrice && UpPrice <= bmodel.CustomMaxPriceRate)
                {
                    //满足
                }
                else
                {
                    return ApiResult.Failed("未在价格区间里");
                }
            }
            else {
                //固定金额
                if (bmodel.CustomMinFixedPrice <= UpPrice && UpPrice <= bmodel.CustomMaxFixedPrice)
                {
                    //满足
                }
                else
                {
                    return ApiResult.Failed("未在价格区间里");
                }
            }

            bool flag = smallShopsModule.SetSmallShopsGlobalPrice(UpPrice, PriceType, model);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        /// <summary>
        /// 获取微店商品价格设置列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSmallShopsGoodsPricePageList() {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_SmallShops_Price_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Price_Extend>(req.msg.ToString());

            var model = smallShopsModule.GetSmallShopsInfo_V2(userInfo.UserId, userInfo.TenantId, userInfo.MallBaseId);
            if (model == null) { return ApiResult.Failed("微店不存在"); }
            if (model.AuditStatus != DistributorAuditStatusEnum.Audited) { return ApiResult.Failed("微店未审核通过"); }

            demodel.SmallShopsId = model.Id;
            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = smallShopsModule.GetSmallShopsGoodsPricePageList(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 GetSmallShopsChooseGoodsPageList() {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(req.msg.ToString());
            RB_SmallShops_Price_Extend demodel = JsonConvert.DeserializeObject<RB_SmallShops_Price_Extend>(req.msg.ToString());

            demodel.TenantId = userInfo.TenantId;
            demodel.MallBaseId = userInfo.MallBaseId;
            var list = smallShopsModule.GetSmallShopsChooseGoodsPageList(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 SetSmallShopsGoodsPrice() {
            var req = RequestParm;
            var userInfo = AppletUserInfo;
            JObject parms = JObject.Parse(req.msg.ToString());
            int GoodsId = parms.GetInt("GoodsId", 0);
            string PriceList = parms.GetStringValue("PriceList");
            if (GoodsId <= 0) {
                return ApiResult.ParamIsNull("请传递商品id");
            }
            if (string.IsNullOrEmpty(PriceList)) {
                return ApiResult.ParamIsNull("请传递价格配置");
            }
            List<RB_SmallShops_Price_Extend> SSPList = JsonConvert.DeserializeObject<List<RB_SmallShops_Price_Extend>>(PriceList);
            if (!SSPList.Any()) {
                return ApiResult.ParamIsNull("请传递价格配置");
            }

            bool flag = smallShopsModule.SetSmallShopsGoodsPrice(GoodsId, SSPList, userInfo);
            if (flag)
            {
                return ApiResult.Success();
            }
            else {
                return ApiResult.Failed();
            }
        }

        #endregion

    }
}