/* =============================================
-- Author:		<Author,,zhangkun>
-- Create date: <Create Date,,20200618>
-- 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.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 KGOrderController : BaseController
    {
        private readonly IBus_OrderDetailRepository bus_OrderDetailRepository;
        private readonly IBus_OrderRepository bus_OrderRepository;
        private readonly ISys_MarketingRepository bus_MarketingRepository;
        private readonly IBus_ProductRepository bus_productRepository;
        private readonly ICus_VipInfoRepository cus_vip_infoRepository;
        private readonly IBus_StockLogRepository bus_StockLogRepository;
        private readonly ICus_ScoreSetRepository cus_score_setRepository;
        private readonly IConfiguration config;
        private readonly OrderFunctionController busOrderFunctionController;
        public KGOrderController(OrderFunctionController _OrderFunctionController, ICus_ScoreSetRepository _cus_score_setRepository, IBus_StockLogRepository _bus_StockLogRepository, IBus_OrderRepository _bus_OrderRepository, IBus_OrderDetailRepository _bus_OrderDetailRepository, ISys_MarketingRepository _bus_MarketingRepository, IBus_ProductRepository _productRepository, ICus_VipInfoRepository _cus_vip_infoRepository, IConfiguration _configuration)
        {
            bus_OrderDetailRepository = _bus_OrderDetailRepository;
            bus_OrderRepository = _bus_OrderRepository;
            bus_MarketingRepository = _bus_MarketingRepository;
            bus_productRepository = _productRepository;
            cus_vip_infoRepository = _cus_vip_infoRepository;
            bus_StockLogRepository = _bus_StockLogRepository;
            cus_score_setRepository = _cus_score_setRepository;
            config = _configuration;
            busOrderFunctionController = _OrderFunctionController;
        }



        #region  库管操作  退回  分拣  发货

        /// <summary>
        /// 获取订单分页列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("/api/order/getorderlistbykgpage")]
        public async Task<IActionResult> GetOrderListByKGPage(OrderInput input)
        {

            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选


            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.GreaterThanOrEqual, FieldValue = "-2" });

            if (input.F_State > -2)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = input.F_State.ToString() });

            }
            else
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.NoEqual, FieldValue = "0" });
            }

            conModels.Add(new ConditionalCollections()
            {
                ConditionalList = new List<KeyValuePair<WhereType, SqlSugar.ConditionalModel>>()
{
                     new  KeyValuePair<WhereType, ConditionalModel>
                     ( WhereType.And ,    new ConditionalModel() { FieldName = "F_StockUser", ConditionalType = ConditionalType.Equal, FieldValue = UserLogin.UserId }),
                     new  KeyValuePair<WhereType, ConditionalModel>
                     (WhereType.Or,    new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = "3" })
}
            });

            if (!string.IsNullOrEmpty(input.F_ADFrom))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_ADFrom", ConditionalType = ConditionalType.Equal, FieldValue = input.F_ADFrom });
            }
            if (!string.IsNullOrEmpty(input.F_Type))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Type", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Type });
            }
            if (!string.IsNullOrEmpty(input.F_Id))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Id", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Id });
            }
            if (!string.IsNullOrEmpty(input.F_Customer))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Customer", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Customer });
            }
            if (!string.IsNullOrEmpty(input.F_CustomerPhone))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_CustomerPhone", ConditionalType = ConditionalType.Equal, FieldValue = input.F_CustomerPhone });
            }
            if (!string.IsNullOrEmpty(input.F_TrackingNo))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_TrackingNo", ConditionalType = ConditionalType.Equal, FieldValue = input.F_TrackingNo });
            }
            if (!string.IsNullOrEmpty(input.F_AddProvince))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddProvince", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddProvince });
            }
            if (!string.IsNullOrEmpty(input.F_AddCity))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddCity", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddCity });
            }
            if (!string.IsNullOrEmpty(input.F_AddArea))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddArea", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddArea });
            }
            if (!string.IsNullOrEmpty(input.F_AddTown))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTown", ConditionalType = ConditionalType.Equal, FieldValue = input.F_AddTown });
            }
            if (!string.IsNullOrEmpty(input.F_Express))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Express", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Express });
            }
            if (!string.IsNullOrEmpty(input.F_PayType))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_PayType", ConditionalType = ConditionalType.Equal, FieldValue = input.F_PayType });
            }
            if (!string.IsNullOrEmpty(input.F_Stock))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_Stock", ConditionalType = ConditionalType.Equal, FieldValue = input.F_Stock });
            }
            if (input.F_PayState > -1)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_PayState", ConditionalType = ConditionalType.Equal, FieldValue = input.F_PayState.ToString() });
            }
            if (input.SearchEndTime != null)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.LessThan, FieldValue = input.SearchEndTime.GetValueOrDefault().ToString("yyyy-MM-dd 23:59:59") });
            }
            if (input.SearchStartTime != null)
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_AddTime", ConditionalType = ConditionalType.GreaterThan, FieldValue = input.SearchStartTime.GetValueOrDefault().ToString("yyyy-MM-dd 00:00:01") });
            }




            #endregion
            RefAsync<int> recordCount = 0;
            PageData<T_Bus_Order> list = await bus_OrderRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = input.pageindex, PageSize = input.pagesize, PageCount = recordCount }, " F_AddTime DESC");
            PageData<OrderInput> returnobj = new PageData<OrderInput>() { Totals = list.Totals };
            List<OrderInput> returnlist = new List<OrderInput>();
            foreach (T_Bus_Order t in list.Rows)
            {
                OrderInput m = new OrderInput();
                ModelConvertHelper<OrderInput, T_Bus_Order>.ModeToModel(m, t);

                List<OrderDetailInput> orderDetailInputs = new List<OrderDetailInput>();
                #region 遍历订单商品
                List<T_Bus_OrderDetail> orderDetails = await bus_OrderDetailRepository.GetListALL(q => q.F_OrderId == t.F_Id);
                if (orderDetails != null)
                {
                    foreach (T_Bus_OrderDetail t1 in orderDetails)
                    {
                        OrderDetailInput m1 = new OrderDetailInput();
                        ModelConvertHelper<OrderDetailInput, T_Bus_OrderDetail>.ModeToModel(m1, t1);
                        orderDetailInputs.Add(m1);
                    }
                }
                #endregion
                m.OrderDetailList = orderDetailInputs;

                returnlist.Add(m);
            }
            returnobj.Rows = returnlist;


            return Success("成功", returnobj);


        }



        /// <summary>
        /// 订单二审 审完 走发货
        /// </summary>
        /// <param name="orderid">订单号</param>
        /// <param name="state">订单状态 -1无效 0暂存 1提交  2KF退回  3通过 4无货 5已分拣 6已发货</param>
        /// <param name="remark">客服备注</param>
        /// <returns></returns>
        [HttpPost("/api/order/checkorderbykg")]
        public async Task<IActionResult> CheckOrderKG(string orderid, int state, string remark)
        {
            //状态变化  积分变化  处理时间人变化  库存变化  备注
            T_Cus_VipInfo modelvip = new T_Cus_VipInfo();
            #region 验证参数 必填项  

            if (string.IsNullOrEmpty(orderid))
                return Error("请输入订单号");
            if (!(state == 4 || state == 5 || state == 6))
                return Error("操作类型不正确");

            #endregion


            T_Bus_Order modelOrder = await bus_OrderRepository.GetSingle(q => q.F_Id == orderid && new[] { 3, 4, 5 }.Contains(q.F_State));
            if (modelOrder == null)
            {
                 if (state ==5)
                    return Error("订单已分拣");
                return Error("订单已审核");
            }
            if (state == 5&& modelOrder.F_State == 5)
            {
                return Error("订单已分拣");
            }
            if (modelOrder.F_State == 3 || modelOrder.F_State == 4)
            {
                modelOrder.F_StockTime = DateTime.Now;
                modelOrder.F_StockUser = UserLogin.UserId.ObjToInt();
                modelOrder.F_StockUserName = UserLogin.UserName;
                modelOrder.F_CheckRemark = modelOrder.F_CheckRemark + remark;
            }

            if (state == 6)
            {
                modelOrder.F_SendTime = DateTime.Now;
                modelOrder.F_SendUser = UserLogin.UserId.ObjToInt();
                modelOrder.F_SendUserName = UserLogin.UserName;
            }

            modelOrder.F_State = state;


            if (await bus_OrderRepository.Update(modelOrder))
                return Success("订单成功审核！");
            return Error("订单审核失败,请汇报技术支持！");


        }




        #endregion





    }
}