/* =============================================
-- Author:		<Author,,zhangkun>
-- Create date: <Create Date,,20200709>
-- Description:	<Description,,订单合并相关操作）>
-- ============================================*/

using System;
using System.Collections.Generic;
using System.Common;
using System.Common.Helpers;
using System.Data;
using System.IRepositories;
using System.Linq;
using System.Linq.Expressions;
using System.Model;
using System.Repositories;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Utility.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure;
using Microsoft.Extensions.Configuration;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.Order
{
    [Route("api/[controller]")]
    public class OrderMergeController : BaseController
    {
        private readonly IBus_OrderDetailRepository bus_OrderDetailRepository;
        private readonly IBus_OrderRepository bus_OrderRepository;
        private readonly OrderFunctionController busOrcerFunctionController;
        private readonly IBus_ProductRepository bus_productRepository;
        private readonly ICus_VipInfoRepository cus_vip_infoRepository;
        private readonly IBus_OrderMergeRepository busOrderMergeRepository;
        private readonly ICus_ScoreSetRepository cus_score_setRepository;

        public OrderMergeController(ICus_ScoreSetRepository _cus_score_setRepository, IBus_OrderMergeRepository _busOrderMergeRepository, IBus_OrderRepository _bus_OrderRepository, IBus_OrderDetailRepository _bus_OrderDetailRepository, OrderFunctionController _orderController, IBus_ProductRepository _productRepository, ICus_VipInfoRepository _cus_vip_infoRepository)
        {
            bus_OrderDetailRepository = _bus_OrderDetailRepository;
            bus_OrderRepository = _bus_OrderRepository;
            busOrcerFunctionController = _orderController;
            bus_productRepository = _productRepository;
            cus_vip_infoRepository = _cus_vip_infoRepository;
            busOrderMergeRepository = _busOrderMergeRepository;
            cus_score_setRepository = _cus_score_setRepository;

        }

        #region 销售操作

        /// <summary>
        /// 创建合并订单申请
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("addordermerge")]
        public async Task<IActionResult> AddOrderMerge(OrderMergeInput input)
        {
            try
            {
                #region 验证参数 必填项  

                if (string.IsNullOrEmpty(input.F_OrderList))
                    return Error("请输入要合并的订单");
                string[] orderlist = input.F_OrderList.Split(',');
                if (orderlist.Length < 2)
                    return Error("合并订单至少有两个");
                //活动满减  免运费  活动满赠   活动优惠  
                if (string.IsNullOrEmpty(input.F_Type))
                    return Error("请选择合并类型");
                if (input.F_Type == "活动满赠")
                {
                    if (string.IsNullOrEmpty(input.F_Gift))
                        return Error("请选择赠品");
                }
                else
                {
                    if (string.IsNullOrEmpty(input.F_Gift))
                        input.F_Gift = "";
                    if (input.F_Money <= 0)
                        return Error("请输入有效金额");
                }
                //F_Remark、F_CheckRemak
                #endregion

                #region 验证逻辑
                foreach (string orderid in orderlist)
                {
                    //合并状态 -1无效 0暂存 1提交  2不予通过  3通过 
                    int exist = await busOrderMergeRepository.GetCount(q => q.F_OrderList.Contains(orderid) && new int[] { 0, 1, 3 }.Contains(q.F_State));
                    if (exist > 0)
                    {
                        return Error("此单号已参与合并中:" + orderid);
                    }
                    //订单状态 -1无效 0暂存 1提交  2KF退回  3通过 4无货 5已分拣 6已发货
                    exist = await bus_OrderRepository.GetCount(q => q.F_Id == orderid && new int[] { 1, 3, 4 }.Contains(q.F_State));
                    if (exist == 0)
                    {
                        return Error("提交订单后发货前才可合并，此单号状态无效:" + orderid);
                    }

                }
                #endregion

                T_Bus_OrderMerge modelOrderMerge = new T_Bus_OrderMerge();
                modelOrderMerge.F_AddUser = UserLogin.UserId.ObjToInt();
                modelOrderMerge.F_AddUserName = UserLogin.UserName;
                modelOrderMerge.F_State = input.F_State;
                modelOrderMerge.F_Money = input.F_Money;
                modelOrderMerge.F_Gift = input.F_Gift;
                modelOrderMerge.F_Type = input.F_Type;
                modelOrderMerge.F_OrderList = input.F_OrderList;
                if(!string.IsNullOrEmpty(input.F_Remark))
                  modelOrderMerge.F_Remark = input.F_Remark;
                modelOrderMerge.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                if (await busOrderMergeRepository.AddReturnCount(modelOrderMerge))
                {
                    if (input.F_State == 0)
                        return Success("订单合并已保存");
                    else if (input.F_State == 1)
                    { return Success("订单合并已提交审核"); }
                }
                return Error("订单合并失败,请重试！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }

        /// <summary>
        /// 修改合并订单 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("editordermerge")]
        public async Task<IActionResult> EditOrderMerge(OrderMergeInput input)
        {
            try
            {
                #region 验证参数 必填项  
                if (string.IsNullOrEmpty(input.F_Id))
                    return Error("缺失参数ID");
                if (string.IsNullOrEmpty(input.F_OrderList))
                    return Error("请输入要合并的订单");
                string[] orderlist = input.F_OrderList.Split(',');
                if (orderlist.Length < 2)
                    return Error("合并订单至少有两个");
                //活动满减  免运费  活动满赠   活动优惠  
                if (string.IsNullOrEmpty(input.F_Type))
                    return Error("请选择合并类型");
                if (input.F_Type == "活动满赠")
                {
                    if (string.IsNullOrEmpty(input.F_Gift))
                        return Error("请选择赠品");
                }
                else
                {
                    if (input.F_Money <= 0)
                        return Error("请数据金额");
                }
                //F_Remark、F_CheckRemak
                #endregion

                #region 验证逻辑
                foreach (string orderid in orderlist)
                {
                    //订单状态 -1无效 0暂存 1提交  2KF退回  3通过 4无货 5已分拣 6已发货
                    int exist = await bus_OrderRepository.GetCount(q => q.F_Id == orderid && new int[] { 1, 3, 4 }.Contains(q.F_State));
                    if (exist == 0)
                    {
                        return Error("此单号状态无效:" + orderid);
                    }

                }
                #endregion

                T_Bus_OrderMerge modelOrderMerge = await busOrderMergeRepository.GetSingle(q => q.F_Id == input.F_Id);
                if (modelOrderMerge.F_State == 3)
                { return Success("已审核不能修改"); }

                modelOrderMerge.F_AddUser = UserLogin.UserId.ObjToInt();
                modelOrderMerge.F_AddUserName = UserLogin.UserName;
                modelOrderMerge.F_State = input.F_State;
                modelOrderMerge.F_Money = input.F_Money;
                modelOrderMerge.F_Gift = input.F_Gift;
                modelOrderMerge.F_Type = input.F_Type;
                modelOrderMerge.F_OrderList = input.F_OrderList;
                modelOrderMerge.F_Remark = input.F_Remark == null ? "" : input.F_Remark;
                if (await busOrderMergeRepository.Update(modelOrderMerge))
                {
                    if (input.F_State == 0)
                        return Success("订单合并已保存");
                    else if (input.F_State == 1)
                    { return Success("订单合并已提交审核"); }
                }
                return Error("订单合并失败,请重试！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }

        /// <summary>
        /// 删除合并订单 
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("deleteordermerge")]
        public async Task<IActionResult> DeleteOrderMerge(string ids)
        {
            try
            {
                if (string.IsNullOrEmpty(ids))
                {
                    return Error("参数缺失：" + ids);
                }
                string[] idlist = ids.Split(',');

                if (await busOrderMergeRepository.Delete(q => idlist.Contains(q.F_Id)&&new[] { 0,1,2}.Contains(q.F_State)))
                {
                    return Success("删除成功");
                }
                return Error("删除失败,请重试！");
            }
            catch (Exception ex)
            { return Error(ex.Message); }

        }

        /// <summary>
        /// 根据分页获取列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getordermergebypage")]
        public async Task<IActionResult> GetOrderMergeByPage(OrderMergeInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_OrderMerge, bool>> eq = a => a.F_AddUser == UserLogin.UserId.ObjToInt();


            if (!string.IsNullOrEmpty(input.F_OrderList))
            {
                eq = eq.And(a => a.F_OrderList.Contains(input.F_OrderList));
            }
            if (!string.IsNullOrEmpty(input.F_Type))
            {
                eq = eq.And(a => a.F_Type == input.F_Type);
            }
            if (!string.IsNullOrEmpty(input.F_Id))
            {
                eq = eq.And(a => a.F_Id == input.F_Id);
            }
            if (input.F_State >-2)
            {
                eq = eq.And(a => a.F_State == input.F_State);
            }

            #endregion
            RefAsync<int> count = 0;
            PageData<T_Bus_OrderMerge> list = await busOrderMergeRepository.GetListByPage(eq, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = count }, " F_AddTime DESC");

            return Success("成功", list);

        }


        #endregion

        #region 客服操作


        /// <summary>
        /// 根据分页获取列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("getordermergebycheckpage")]
        public async Task<IActionResult> GetOrderMergeByCheckPage(OrderMergeInput input)
        {

            #region  拼接条件

            Expression<Func<T_Bus_OrderMerge, bool>> eq = a => (a.F_Checkuser == UserLogin.UserId.ObjToInt() || a.F_Checkuser == 0);

            if (!string.IsNullOrEmpty(input.F_OrderList))
            {
                eq = eq.And(a => a.F_OrderList.Contains(input.F_OrderList));
            }
            if (!string.IsNullOrEmpty(input.F_Type))
            {
                eq = eq.And(a => a.F_Type == input.F_Type);
            }
            if (input.F_State >= 0)
            {
                eq = eq.And(a => a.F_State == input.F_State);
            }

            #endregion
            RefAsync<int> count = 0;
            PageData<T_Bus_OrderMerge> list = await busOrderMergeRepository.GetListByPage(eq, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = count }, " F_AddTime DESC");

            return Success("成功", list);

        }

        /// <summary>
        /// 审核订单
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state">3审核通过，2审核不通过</param>
        /// <returns></returns>
        [HttpPost("checkordermerge")]
        public async Task<IActionResult> CheckOrderMerge(OrderMergeInput input)
        {
            try
            {
               
                string id = input.F_Id;
                int state = input.F_State;


                if (string.IsNullOrEmpty(id))
                    return Error("缺失参数ID");
                if (state != 2 && state != 3)
                {
                    return Error("参数不正确");
                }

                T_Bus_OrderMerge modelOrderMerge = await busOrderMergeRepository.GetSingle(q => q.F_Id == id);
                if (modelOrderMerge.F_State != 1)
                { return Success("未查到待审核合并"); }
                #region 验证逻辑
                foreach (string orderid in modelOrderMerge.F_OrderList.Split(','))
                {
                    //订单状态 -1无效 0暂存 1提交  2KF退回  3通过 4无货 5已分拣 6已发货
                    int exist = await bus_OrderRepository.GetCount(q => q.F_Id == orderid && new int[] { 1, 3, 4 }.Contains(q.F_State));
                    if (exist == 0)
                    {
                        return Error("此单号状态已失效:" + orderid);
                    }
                }
                #endregion


                modelOrderMerge.F_Checkuser = UserLogin.UserId.ObjToInt();
                modelOrderMerge.F_CheckuserName = UserLogin.UserName;
                modelOrderMerge.F_State = state;
                modelOrderMerge.F_CheckTime = DateTime.Now;
                modelOrderMerge.F_CheckRemak = input.F_CheckRemak;
                if (state == 3)
                {
                   
                    bool bl = true;
                    List<T_Bus_Order> modelorderlist = new List<T_Bus_Order>();
                    decimal totle = 0.00M;
                    foreach (string orderid in modelOrderMerge.F_OrderList.Split(','))
                    {
                        T_Cus_VipInfo modelvip = new T_Cus_VipInfo();
                        T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == orderid);

                        if (modelOrder == null)
                        {
                            bl = false;
                            break;
                        }
                        //待审核  审核
                        if (modelOrder.F_State == 1)
                        {
                            modelOrder.F_CheckTime = DateTime.Now;
                            modelOrder.F_CheckUser = UserLogin.UserId.ObjToInt();
                            modelOrder.F_CheckUserName = UserLogin.UserName;
                            modelOrder.F_CheckRemark = "订单合并";

                            #region 判断积分
                            bool blScore = false;
                            if (modelOrder.F_UseScore > 0)
                            {
                                //退回积分  查询批次号核算积分是否已经解冻
                                if (true)
                                {
                                    //log 或者解冻积分
                                    blScore = true;
                                }
                            }
                            else
                            {
                                blScore = true;
                            }
                            if (!blScore)
                            {
                                //积分处理失败  暂时不管不影响
                            }
                            #endregion

                            modelOrder.F_State = 3;
                            totle += modelOrder.F_ShouldPrice;
                            modelorderlist.Add(modelOrder);

                        }
                        if (modelOrder.F_State == 3)
                        {
                            totle += modelOrder.F_ShouldPrice;
                            modelorderlist.Add(modelOrder);
                        }
                    }
                    
                    if (!bl)
                    {
                        return Success("订单状态已经变化，无法合并");
                    }
                    else
                    {
                        T_Bus_OrderDetail modelDetail = null;
                        List<T_Bus_StockLog> modeStocklogs = null;
                        SetStockModel setStockModel = null;
                        int n = 0;
                        decimal totle2 = 0.00M;
                        foreach (T_Bus_Order m in modelorderlist)
                        {
                            if (n == 0&& modelOrderMerge.F_Gift != "")
                            {
                                T_Bus_Product productModel =await bus_productRepository.GetSingle(q=>q.F_ProductId== modelOrderMerge.F_Gift);
                                if (productModel == null)
                                    break;
                                modelDetail = new T_Bus_OrderDetail();
                                modelDetail.F_ProductName = productModel.F_ProductName;
                                modelDetail.F_ProductId = productModel.F_ProductId;
                                modelDetail.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                                modelDetail.F_OrderId = input.F_Id;
                                modelDetail.F_Count = 1;
                                modelDetail.F_Price = 0.00M;
                                modelDetail.F_DealPrice = 0.00M;
                                modelDetail.F_Sort = 0;
                                modelDetail.F_Remark = "合并订单："+ modelOrderMerge.F_Id;
                                modelDetail.F_AddUser = UserLogin.UserId.ObjToInt();
                                modelDetail.F_AddUserName = UserLogin.UserName;
                                modelDetail.F_TotlePrice = 0.00M;
                                modelDetail.F_Activity = 0;
                                modelDetail.F_AddTime = DateTime.Now;

                                #region 记录库存log
                                 modeStocklogs = new List<T_Bus_StockLog>();
                                T_Bus_StockLog modelStock = new T_Bus_StockLog();
                                modelStock.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                                modelStock.F_Action = 1;
                                modelStock.F_AddTime = DateTime.Now;
                                modelStock.F_FlowNum = m.F_FlowNum;
                                modelStock.F_BatchNum = 0;
                                modelStock.F_OrderId = m.F_Id;
                                modelStock.F_State = 0;
                                modelStock.F_UserId = m.F_AddUser;
                                modelStock.F_UserName = m.F_AddUserName;
                                modelStock.F_Stock = m.F_Stock;
                                modelStock.F_Status = 0;
                                modelStock.F_Num = -1;
                                modelStock.F_ProductId = productModel.F_ProductId;

                                modeStocklogs.Add(modelStock);
                                #endregion

                                #region  请求库存对象
                                List<StockChangeModel> stockChangeModels = new List<StockChangeModel>();
                                StockChangeModel stockChangeModel = new StockChangeModel();
                                stockChangeModel.sku = productModel.F_ProductId;
                                stockChangeModel.qty = -1;
                                stockChangeModels.Add(stockChangeModel);


                                setStockModel = new SetStockModel();

                                setStockModel.store = m.F_Stock;
                                setStockModel.dts = stockChangeModels;
                                setStockModel.masterid = m.F_FlowNum;
                                setStockModel.remark = "合并审核减库存";
                                #endregion

                               
                            }

                            if (modelOrderMerge.F_Money != 0)
                            {
                                if (n == modelorderlist.Count - 1)
                                { 
                                    m.F_MergeMoney = totle - totle2;
                                }
                                else
                                {
                                    m.F_MergeMoney = Math.Round( modelOrderMerge.F_Money * m.F_ShouldPrice / totle,2);
                                    totle2 += m.F_MergeMoney;
                                }
                                // modelOrderMerge.F_Money *m.F_ShouldPrice/totle
                            }
                            n++;
                        }
                        if (modelDetail != null)
                        {
                            ResultMessage modelMessage = await busOrcerFunctionController.ChangeStock(setStockModel, modeStocklogs);
                            if (modelMessage.Status)
                            {
                                //处理库存
                            }
                        }
                       await bus_OrderRepository.UpdateList(modelorderlist);
                    }

                }
                else if (state == 2)
                {

                }
                if (await busOrderMergeRepository.Update(modelOrderMerge))
                {
                    return Success("成功");
                }
                return Error("审核失败,请重试！");

            }
            catch (Exception ex)
            { return Error(ex.Message); }


        }

        #endregion







    }
}