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



        #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.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.CreateDate = System.DateTime.Now;
            record.RecordDetailList = new List<RB_Finance_RecordDetail>();

            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("供应商账户信息不存在");
                }
                foreach (var orderGoodsItem in list)
                {
                    if (orderGoodsItem.CostMoney > 0)
                    {
                        var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                        newOrderGoods = orderGoodsItem;
                        newOrderGoods.FinanceType = 1;
                        result.Add(newOrderGoods);

                    }
                    if (orderGoodsItem.FreightCostMoney.HasValue && orderGoodsItem.FreightCostMoney.Value > 0)
                    {
                        var newOrderGoods = new RB_Goods_OrderDetail_Extend();
                        newOrderGoods = orderGoodsItem;
                        newOrderGoods.FinanceType = 2;
                        result.Add(newOrderGoods);
                    }
                    RB_Finance_RecordDetail financeRecordDetail = new RB_Finance_RecordDetail
                    {

                        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
                    };
                    record.RecordDetailList.Add(financeRecordDetail);
                }
                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.OrderNo
                });
                var financeObj = new
                {
                    CreateBy = Config.ExpendDirector,
                    IsPublic = demodel.IsPublic,//  supplierModel.ClientBankAccount.AccountType, //financeConfigurineModel.AccountType,
                    ClientType = supplierModel.ClientBankAccount.Type,
                    ClientID = supplierModel.BankAccountId,
                    CurrencyId = financeConfigurineModel.CurrencyId,
                    WBMoney = result.Sum(x => ((x.CostMoney ?? 0) * (x.Number ?? 0)) + (x.FreightCostMoney ?? 0)),
                    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
                };
                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);
                    if (addResult)
                    {
                        return ApiResult.Success("财务单据生成成功");

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

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

    }
}