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

namespace Mall.WebApi.Controllers.User
{
    [Route("api/[controller]/[action]")]
    [ApiExceptionFilter]
    [ApiController]
    [EnableCors("AllowCors")]
    public class SupplierController : BaseController
    {
        private readonly SupplierModule supplierModule = new SupplierModule();
        /// <summary>
        /// 订单
        /// </summary>
        private readonly OrderModule orderModule = new OrderModule();

        /// <summary>
        /// 财务
        /// </summary>
        private readonly FinanceModule financeModule = new FinanceModule();



        #region 供应商管理
        [HttpPost]
        public ApiResult GetSupplierList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Supplier_Extend demodel = JsonConvert.DeserializeObject<RB_Supplier_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = supplierModule.GetPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.ID,
                x.CreateDate,
                x.Name,
                x.Mobile,
                x.Address,
                IntroducerName = x.MemberUserName,
                CardNum = x.ClientBankAccount != null ? x.ClientBankAccount.CardNum : "",
                OpenBankName = x.ClientBankAccount != null ? x.ClientBankAccount.OpenBankName : "",
                AccountAlias = x.ClientBankAccount != null ? x.ClientBankAccount.AccountAlias : "",
                AccountHolder = x.ClientBankAccount != null ? x.ClientBankAccount.AccountHolder : "",
                BackId = x.ClientBankAccount != null ? x.ClientBankAccount.ID : 0,
                x.SupplierCommissionList,
                AccountClassifyStr = x.ClientBankAccount != null ? (x.ClientBankAccount?.AccountClassify == 2 ? "银行" : (x.ClientBankAccount?.AccountClassify == 3 ? "虚拟账户" : (x.ClientBankAccount?.AccountClassify == 4 ? "微信支付宝" : (x.ClientBankAccount?.AccountClassify == 1 ? "平台" : "")))) : "",

            });
            return ApiResult.Success("", pagelist);
        }


        /// <summary>
        /// 添加修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>

        [HttpPost]
        public ApiResult SetSupplier()
        {
            var parms = RequestParm;
            RB_Supplier_Extend demodel = JsonConvert.DeserializeObject<RB_Supplier_Extend>(RequestParm.msg.ToString());

            if (string.IsNullOrEmpty(demodel.Name))
            {
                return ApiResult.Failed("请填写供应商名称");
            }

            if (string.IsNullOrEmpty(demodel.Mobile))
            {
                return ApiResult.Failed("请填写联系电话");
            }
            if (demodel.Introducer > 0)
            {
                if (demodel.SupplierCommissionList == null || !demodel.SupplierCommissionList.Any())
                {
                    return ApiResult.Failed("请输入供应商返佣比例");
                }
            }
            //if (string.IsNullOrEmpty(demodel.ClientBankAccount.OpenBankName))
            //{
            //    return ApiResult.Failed("请填写开户行！");
            //}
            //if (string.IsNullOrEmpty(demodel.ClientBankAccount.AccountHolder))
            //{
            //    return ApiResult.Failed("请填写开户人！");
            //}
            //if (string.IsNullOrEmpty(demodel.ClientBankAccount.CardNum))
            //{
            //    return ApiResult.Failed("请填写卡号！");
            //}
            //if (supplierModule.ExistsClientAccount(demodel.ClientBankAccount.ID, demodel.ClientBankAccount.CardNum, 2, Convert.ToInt32(Config.RB_Branch_Id)))
            //{
            //    return ApiResult.Failed("卡号重复！");
            //}
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.CreateDate = DateTime.Now;
            demodel.ClientBankAccount.CreateDate = DateTime.Now;
            demodel.ClientBankAccount.RB_Branch_Id = Convert.ToInt32(Config.RB_Branch_Id);
            demodel.ClientBankAccount.RB_Group_Id = 2;
            demodel.ClientBankAccount.Type = Common.Enum.Finance.ClientTypeEnum.Other;

            demodel.ClientBankAccount.CreateBy = Convert.ToInt32(Config.NetworkDirector);

            if (demodel.ID > 0)
            {
                demodel.BankAccountId = demodel.ClientBankAccount.ID;
                demodel.UpdateDate = System.DateTime.Now;
            }
            bool flag = supplierModule.AddOrUpdateSupplier(demodel);
            if (flag)
                return ApiResult.Success();
            else
                return ApiResult.Failed("请求失败！");
        }



        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSupplierDetail()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Supplier_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsModel = supplierModule.GetList(query).FirstOrDefault();
            if (oldLogisticsModel == null)
            {
                oldLogisticsModel = new RB_Supplier_Extend();

            }
            return ApiResult.Success("", oldLogisticsModel);
        }



        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult DelDiscountCoupon()
        {
            var parms = RequestParm;
            JObject parmsJob = JObject.Parse(RequestParm.msg.ToString());
            int Id = parmsJob.GetInt("Id", 0);
            int BackId = parmsJob.GetInt("BackId", 0);
            if (Id <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            if (BackId <= 0)
            {
                return ApiResult.Failed("请传递参数");
            }
            bool flag = supplierModule.RemoveSupplier(Id, BackId);
            if (flag)
            {
                return ApiResult.Success();
            }
            else
            {
                return ApiResult.Failed();
            }
        }



        /// <summary>
        /// 获取供应商下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetSupplierAllList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Supplier_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            var oldLogisticsList = supplierModule.GetList(query);
            return ApiResult.Success("", oldLogisticsList);
        }

        /// <summary>
        /// 获取分销商下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public ApiResult GetDistributorInfoList()
        {
            var parms = RequestParm;
            var query = JsonConvert.DeserializeObject<RB_Distributor_Info_Extend>(RequestParm.msg.ToString());
            query.TenantId = UserInfo.TenantId;
            query.MallBaseId = parms.MallBaseId;
            query.AuditStatus = Common.Enum.User.DistributorAuditStatusEnum.Audited;
            var oldLogisticsList = orderModule.GetDistributorInfoList(query);
            if (oldLogisticsList != null && oldLogisticsList.Any())
            {
                oldLogisticsList.ForEach(x => x.Name = (string.IsNullOrWhiteSpace(x.Name) ? x.MemberUserName : x.Name));
            }
            return ApiResult.Success("", oldLogisticsList);
        }

        #endregion


        #region 供应商采购商品信息
        /// <summary>
        /// 供应商商品信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult GetSupplierGoodsList()
        {
            var parms = RequestParm;
            ResultPageModel pagelist = JsonConvert.DeserializeObject<ResultPageModel>(RequestParm.msg.ToString());
            RB_Goods_OrderDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderDetail_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            var list = orderModule.GetSupplierOrderPageList(pagelist.pageIndex, pagelist.pageSize, out long count, demodel);
            pagelist.count = Convert.ToInt32(count);
            pagelist.pageData = list.Select(x => new
            {
                x.SupplierId,
                x.OrderNo,
                x.GoodsName,
                x.Original_Price,
                x.CostMoney,
                x.FreightCostMoney,
                x.CostFinanceId,
                x.FreightFinanceId,
                x.Id,
                x.OrderId
            });
            return ApiResult.Success("", pagelist);
        }



        //生成财务单据

        /// <summary>
        /// 供应商商品生成财务单据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ApiResult PayCostFinance()
        {
            var parms = RequestParm;
            RB_Goods_OrderDetail_Extend demodel = JsonConvert.DeserializeObject<RB_Goods_OrderDetail_Extend>(RequestParm.msg.ToString());
            demodel.TenantId = UserInfo.TenantId;
            demodel.MallBaseId = parms.MallBaseId;
            demodel.IsFinance = 2;
            var list = orderModule.GetSupplierOrderList(demodel);
            var result = new List<RB_Goods_OrderDetail_Extend>();
            RB_Finance_Record_Extend record = new RB_Finance_Record_Extend();
            record.MallBaseId = demodel.MallBaseId;
            record.TenantId = demodel.TenantId;
            record.Type = 2;
            record.IsFinanceAll = demodel.IsSelectAll;
            record.CreateDate = System.DateTime.Now;
            record.RecordDetailList = new List<RB_Finance_RecordDetail_Extend>();

            if (list != null && list.Any())
            {
                //先查询规则
                var financeConfigurineModel = financeModule.GetFinanceConfigurineList(new Model.Extend.Finance.RB_Finance_Configurine_Extend { Type = 2, MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId }).FirstOrDefault();
                //查询供应商的财务信息
                var supplierModel = supplierModule.GetList(new RB_Supplier_Extend { MallBaseId = demodel.MallBaseId, TenantId = demodel.TenantId, ID = demodel.SupplierId }).FirstOrDefault();

                if (supplierModel == null)
                {
                    return ApiResult.Failed("供应商信息不存在");
                }
                if (supplierModel.ClientBankAccount == null)
                {
                    return ApiResult.Failed("供应商账户信息不存在");
                }

                List<object> ECList = new List<object>();//电商关联订单
                foreach (var orderGoodsItem in list)
                {
                    decimal OrderDetailPaid = (orderGoodsItem.PaidCostMoney ?? 0);
                    if (demodel.IsSelectAll == 0 || demodel.IsSelectAll == 1)
                    {
                        if (orderGoodsItem.CostMoney > 0 && orderGoodsItem.CostFinanceId <= 0)
                        {
                            //var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                            //newOrderGoods = orderGoodsItem;
                            //newOrderGoods.FinanceType = 1;
                            var newOrderGoods = new RB_Goods_OrderDetail_Extend
                            {
                                FinanceType = 1,
                                Final_Price = orderGoodsItem.Final_Price,
                                Number = orderGoodsItem.Number,
                                FreightMoney = orderGoodsItem.FreightMoney,
                                GoodsName = orderGoodsItem.GoodsName,
                                OrderNo = orderGoodsItem.OrderNo,
                                Id = orderGoodsItem.Id,
                                CostMoney = orderGoodsItem.CostMoney,
                                FreightCostMoney = orderGoodsItem.FreightCostMoney
                            };
                            OrderDetailPaid += ((orderGoodsItem.CostMoney ?? 0) * (orderGoodsItem.Number ?? 0));
                            result.Add(newOrderGoods);
                        }
                    }
                    if (demodel.IsSelectAll == 0 || demodel.IsSelectAll == 2)
                    {
                        if (orderGoodsItem.FreightCostMoney.HasValue && orderGoodsItem.FreightCostMoney.Value > 0 && orderGoodsItem.FreightFinanceId <= 0)
                        {
                            //var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                            //newOrderGoods = orderGoodsItem;
                            //newOrderGoods.FinanceType = 2;
                            var newOrderGoods = new RB_Goods_OrderDetail_Extend
                            {
                                FinanceType = 2,
                                Final_Price = orderGoodsItem.Final_Price,
                                Number = 1,
                                FreightMoney = orderGoodsItem.FreightMoney,
                                GoodsName = orderGoodsItem.GoodsName,
                                OrderNo = orderGoodsItem.OrderNo,
                                Id = orderGoodsItem.Id,
                                CostMoney = orderGoodsItem.CostMoney,
                                FreightCostMoney = orderGoodsItem.FreightCostMoney
                            };
                            OrderDetailPaid += (orderGoodsItem.FreightCostMoney ?? 0);
                            result.Add(newOrderGoods);
                        }
                    }
                    RB_Finance_RecordDetail_Extend financeRecordDetail = new RB_Finance_RecordDetail_Extend
                    {

                        ID = 0,
                        RecordId = 0,
                        Type = record.Type,
                        TenantId = record.TenantId,
                        MallBaseId = record.MallBaseId,
                        FinanceId = 0,
                        CreateDate = record.CreateDate,
                        Name = orderGoodsItem.GoodsName,
                        OrderId = orderGoodsItem.OrderId ?? 0,
                        OrderDetailId = orderGoodsItem.Id,
                        GoodsPrice = ((orderGoodsItem.CostMoney ?? 0) * (orderGoodsItem.Number ?? 0)),
                        FreightMoney = orderGoodsItem.FreightCostMoney,
                        Unit_Price = orderGoodsItem.CostMoney,
                        Number = orderGoodsItem.Number,
                        OrderDetailPaid = OrderDetailPaid,
                    };
                    record.RecordDetailList.Add(financeRecordDetail);

                    ECList.Add(new
                    {
                        ECOrderId = orderGoodsItem.OrderId,
                        ECOrderDetailId = orderGoodsItem.Id
                    });
                }
                ECList = ECList.Distinct().ToList();
                var detailList = result.Select(x => new
                {
                    CostTypeId = x.FinanceType == 1 ? financeConfigurineModel.CBCostTypeId : financeConfigurineModel.ExpensesCostTypeId,
                    Number = x.FinanceType == 1 ? x.Number : 1,
                    OriginalMoney = x.FinanceType == 1 ? ((x.CostMoney ?? 0) * (x.Number ?? 0)) : x.FreightCostMoney,
                    UnitPrice = x.FinanceType == 1 ? ((x.CostMoney ?? 0)) : x.FreightCostMoney,
                    Remark = x.GoodsName + x.Specification + x.OrderNo
                });

                decimal totalMonry = 0;
                if (demodel.IsSelectAll == 0)
                {
                    totalMonry = (result.Where(x => x.FinanceType == 1).Sum(x => ((x.CostMoney ?? 0) * (x.Number ?? 0)))) + (result.Where(x => x.FinanceType == 2).Sum(x => x.FreightCostMoney ?? 0));
                }
                else if (demodel.IsSelectAll == 1)
                {
                    totalMonry = result.Where(x => x.FinanceType == 1).Sum(x => ((x.CostMoney ?? 0) * (x.Number ?? 0)));
                }
                else if (demodel.IsSelectAll == 2)
                {
                    totalMonry = result.Where(x => x.FinanceType == 2).Sum(x => (x.FreightCostMoney ?? 0));
                }
                var financeObj = new
                {
                    CreateBy = demodel.FinanceCreateBy == 0 ? Config.ExpendDirector : demodel.FinanceCreateBy.ToString(),
                    IsPublic = demodel.IsPublic,//  supplierModel.ClientBankAccount.AccountType, //financeConfigurineModel.AccountType,
                    ClientType = supplierModel.ClientBankAccount.Type,
                    ClientID = supplierModel.BankAccountId,
                    CurrencyId = financeConfigurineModel.CurrencyId,
                    WBMoney = totalMonry,
                    RB_Branch_Id = Config.ExpendBranchId,
                    PayDate = System.DateTime.Now.ToString("yyyy-MM-dd"),
                    TemplateId = financeConfigurineModel.WorkFlowId,
                    OrderSource = 16,
                    OtherType = 13,
                    Remark = System.DateTime.Now.ToString("yyyy年MM月dd日") + "生成财务单据",
                    detailList,
                    RB_Depart_Id = Config.ExpendDepartment,
                    ECOrderList = ECList
                };
                string sign = EncryptionHelper.AesEncrypt(JsonHelper.Serialize(financeObj), Config.FinanceKey);
                var resultInfo = new
                {
                    msg = sign,
                };

                string apiResult = Mall.Common.Plugin.HttpHelper.HttpPost(Config.PaymentFinanceApi, JsonHelper.Serialize(resultInfo), "");
                JObject parmsJob = JObject.Parse(apiResult);
                string resultCode = parmsJob.GetStringValue("resultCode");
                int frid = parmsJob.GetInt("data", 0);
                if (resultCode == "1" && frid > 0)//新增记录
                {
                    record.FinanceId = frid;
                    bool addResult = financeModule.SetFinanceRecord(record, result);
                    if (addResult)
                    {
                        return ApiResult.Success("财务单据生成成功");

                    }
                    else
                    {
                        return ApiResult.Failed("财务单据生成失败");
                    }
                }
                else
                {
                    return ApiResult.Failed(parmsJob.GetStringValue("message"));
                }
            }

            return ApiResult.Success("");
        }
        #endregion




        #region 获取付款对象的列表


        [HttpPost]
        public ApiResult GetClientBankAccountList()
        {
            var parms = RequestParm;
            Model.Extend.Finance.RB_ClientBankAccount_Extend demodel = JsonConvert.DeserializeObject<Model.Extend.Finance.RB_ClientBankAccount_Extend>(RequestParm.msg.ToString());
            demodel.RB_Group_Id = 2;
            demodel.RB_Branch_Id = -1;
            demodel.Type = Common.Enum.Finance.ClientTypeEnum.Other;
            var list = supplierModule.GetClientBankAccountList(demodel);

            var result = list.Select(x => new
            {
                x.ID,
                x.OpenBankName,
                x.AccountAlias,
                x.AccountClassify,
                x.AccountHolder,
                x.AccountType,
                x.BankId,
                x.CardNum,
                x.RB_Branch_Id,
                x.RB_Group_Id
            });
            return ApiResult.Success("", result);
        }
        #endregion
    }
}