/* =============================================
-- 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 Microsoft.Extensions.Logging;
using NPOI.SS.Formula.Atp;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;
using Utility;

namespace TVShoppingCallCenter_ZLJ.Controllers.Order
{
    [Route("api/[controller]")]
    public class OrderFunctionController : 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 ISys_DictionaryValueRepository dictionaryValueRepository;
        private readonly ILogger<OrderFunctionController> _logger;
        public OrderFunctionController(ILogger<OrderFunctionController> logger,ISys_DictionaryValueRepository _dictionaryValueRepository,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)
        {
            _logger = logger;
            dictionaryValueRepository = _dictionaryValueRepository;
            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;
        }


        /// <summary>
        /// state=1 提交锁库存 减库存减积分   
        /// </summary>
        /// <param name="modelOrder"></param>
        /// <param name="state"></param>
        /// <param name="score"></param>
        /// <returns></returns>
        internal async Task<string> ChangeStockOne(T_Bus_Order modelOrder,int state,List< T_Bus_OrderDetail> modelDetailList)
        {
            bool blstock = false;
            bool blScore = false;
            string msg = "";
            T_Cus_VipInfo modelvip = null;
            #region 变更积分
                        
            if (modelOrder.F_UseScore > 0)
            {
                //退回积分  查询批次号核算积分是否已经退回
                modelvip = await cus_vip_infoRepository.GetSingle(q => q.F_ID == modelOrder.F_VipId);
                modelvip.F_Score = modelvip.F_Score + modelOrder.F_UseScore;
                if (await cus_vip_infoRepository.Update(modelvip))
                {
                    //log 或者冻结转作废
                    blScore = true;
                }
                else { return ("积分处理失败"); }
            }


            #endregion
            #region 退回库存
            List<StockChangeModel> stockChangeModels = new List<StockChangeModel>();
            List<T_Bus_StockLog> newstockLogList = new List<T_Bus_StockLog>();
            if (state == 1) 
            {
                if (modelDetailList.Count <= 0)
                    return "提交商品详情不能为空";
                foreach (T_Bus_OrderDetail productstock in modelDetailList)
                {
                    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 = modelOrder.F_FlowNum;
                    modelStock.F_BatchNum = modelDetailList.Count;
                    modelStock.F_OrderId = modelOrder.F_Id;
                    modelStock.F_State = 0;
                    modelStock.F_UserId = modelOrder.F_AddUser;
                    modelStock.F_UserName = modelOrder.F_AddUserName;
                    modelStock.F_Stock = modelOrder.F_Stock;
                    modelStock.F_Status = 0;

                    modelStock.F_Num = -productstock.F_Count;
                    modelStock.F_ProductId = productstock.F_ProductId;

                    newstockLogList.Add(modelStock);

                    StockChangeModel stockChangeModel = new StockChangeModel();
                    stockChangeModel.sku = productstock.F_ProductId;
                    stockChangeModel.qty = modelStock.F_Num;
                    stockChangeModels.Add(stockChangeModel);
                }
                
            }
            else
            {
                List<T_Bus_StockLog> stockLogList = await bus_StockLogRepository.GetListALL(q => q.F_OrderId == modelOrder.F_Id && q.F_FlowNum == modelOrder.F_FlowNum);
                if (stockLogList != null && stockLogList.Count > 0)
                {
                    foreach (T_Bus_StockLog modelStock in stockLogList)
                    {
                        modelStock.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                        modelStock.F_Action = 2;
                        modelStock.F_AddTime = DateTime.Now;
                        modelStock.F_Num = -modelStock.F_Num;
                        modelStock.F_State = 0;
                        if (state == 0)
                        {
                            modelStock.F_UserId =modelOrder.F_AddUser;
                            modelStock.F_UserName = modelOrder.F_AddUserName;
                        }
                        else
                        {
                            modelStock.F_UserId = modelOrder.F_CheckUser;
                            modelStock.F_UserName = modelOrder.F_CheckUserName;

                        }
                        modelStock.F_Status = 0;
                        newstockLogList.Add(modelStock);
                        //拼装请求亿博士接口

                        StockChangeModel stockChangeModel = new StockChangeModel();
                        stockChangeModel.sku = modelStock.F_ProductId;
                        stockChangeModel.qty = modelStock.F_Num;
                        stockChangeModels.Add(stockChangeModel);
                    }
                }
                else
                {
                    return "没有提交扣库存记录";
                }
            }

            //添加库存记录
            if (await bus_StockLogRepository.AddMany(newstockLogList))
            {
                //请求亿博士接口
                SetStockModel setStockModel = new SetStockModel();
                //modelset.store            
                //modelset.dts
                //modelset.masterid
                //modelset.remark
                //modelset.ms
                setStockModel.store = modelOrder.F_Stock;
                setStockModel.dts = stockChangeModels;
                //long masterlong =long.Parse(modelOrder.F_FlowNum.Replace("U", "").Replace("R", "") + DateTime.Now.ToString("ddHHmmss"));
                setStockModel.masterid = modelOrder.F_FlowNum+ state;
                if(state==1)
                setStockModel.remark = "销售提交锁库存";
                else if (state == 0)
                    setStockModel.remark = "销售撤回加库存";
                else if (state == 2)
                    setStockModel.remark = "审核不通过加库存";
                //更新库存记录   
                ResultMessage ModelResultMessage = await ChangeStock(setStockModel, newstockLogList);
                blstock = ModelResultMessage.Status;
                msg = ModelResultMessage.Msg;
            }
            if (!blstock)
            {
                if (blScore)
                {
                    modelvip.F_Score = modelvip.F_Score + modelOrder.F_UseScore;
                    if (await cus_vip_infoRepository.Update(modelvip))
                    { 
                        return ("库存可能不足//积分回滚") + msg; 
                    }
                    else 
                    {
                        return ("回滚") + msg;
                    }
                }
                return ("对接亿博士库存失败"+ msg);
            }
            #endregion
            return "1";
        }
        internal async Task<ResultMessage> ChangeStock(SetStockModel modelset1, List<T_Bus_StockLog> modelStockLogs)
        {
            //modelset.store            
            //modelset.dts
            //modelset.masterid
            //modelset.remark
            //modelset.ms
            SetStockModel modelset = new SetStockModel();
            modelset.store = modelset1.store.Contains("新乡")? config["eBoss:stock1"].ToString() : config["eBoss:stock"].ToString();
            modelset.dts = modelset1.dts;
            modelset.masterid = modelset1.masterid;
            modelset.remark = modelset1.remark;

            modelset.appid = config["eBoss:appid"].ToString();
            modelset.appkey = config["eBoss:appkey"].ToString();
            modelset.billdate = DateTime.Now.ToString("yyyyMMdd");
            string url = config["eBoss:url"].ToString();
            string ret = await HttpHelper.HttpGetAsync(url + modelset.ToJson());//"\"success\": true";
            //ret.ToJson();
            
            foreach (T_Bus_StockLog stocklog in modelStockLogs)
            {
                stocklog.F_Result = ret;
                if (ret.Contains("\"success\": true"))
                {
                    LogDefault.Error("成功"+ret);
                    stocklog.F_State = 1;
                }
                else
                {
                    LogDefault.Error("失败" + ret);
                    stocklog.F_State = 2;
                }

            }
            await bus_StockLogRepository.UpdateList(modelStockLogs);//不计较更新成功失败
                                                                    //string ret = await HttpHelper.HttpGetAsync(url + "{\"appid\":\""+ appid + "\",\"appkey\":\""+ appkey + "\",\"method\":\"eboss.drp.adj.add\",\"masterid\":\""+ masterid + "\",\"billdate\":\"" + billdate + "\",\"adjtype\":\"正常调整\",\"store\":\"WLZZ0001\",\"remark\":\"备注测试备注测试备注测试备注测试备注测试备注测试备注测试备注测试备注测试\",\"createid\":\"000\",\"dts\":[{\"sku\":\"010801001\",\"qty\":1},{\"sku\":\"010801002\",\"qty\":2}],\"ms\":[{\"sku\":\"010801001\",\"mastercode\":\"code1\",\"mastercode2\":\"code2\"},{\"sku\":\"010801002\",\"mastercode\":\"code3\",\"mastercode2\":\"code4\"}]}");


            return  new ResultMessage() { Code = 0, Status = ret.Contains("\"success\": true"), Msg = ret };
        }

        #region 对接亿博士

        /// <summary>
        /// 获取相应商品库存
        /// </summary>
        /// <param name="sku">010801001  不传则为全部商品</param>
        /// <param name="stock">WLZZ0001  不传则为全部仓库</param>
        /// <returns></returns>
        [HttpPost("getStock")]
        public async Task<List<EBossStock>> GetStock(string sku, string stock, int pageindex = 1, int pagesize = 10)
        {
            try
            {
                stock = stock.Contains("新乡") ? config["eBoss:stock1"].ToString() : config["eBoss:stock"].ToString();
                string url = config["eBoss:url"].ToString();
                string appid = config["eBoss:appid"].ToString();
                string appkey = config["eBoss:appkey"].ToString();
                string ret = await HttpHelper.HttpGetAsync(url + "{\"appid\":\"" + appid + "\",\"appkey\":\"" + appkey + "\",\"method\":\"eboss.drp.stock.get\",\"pageno\":\"" + pageindex + "\",\"pagesize\":\"" + pagesize + "\",\"sku\":\"" + sku + "\",\"store\":\"" + stock + "\",\"modifybeg\":\"20000202\",\"modifyend\":\"20250505\"}");
                GetStock obj = ret.ToObject<GetStock>();
                return obj.stocks;
            }
            catch (Exception ex)
            {
                return null;
            }

        }



        /// <summary>
        /// 物理调整单
        /// </summary>
        /// <param name="modelset1"></param>
        /// <returns></returns>
        [HttpPost("setStock")]
        public async Task<IActionResult> SetStock([FromBody]SetStockModel modelset1)
        {
            //modelset.store            
            //modelset.dts
            //modelset.masterid
            //modelset.remark
            //modelset.ms
            SetStockModel modelset = new SetStockModel();
            modelset.store = modelset1.store;
            modelset.dts = modelset1.dts;
            modelset.masterid = modelset1.masterid;
            modelset.remark = modelset1.remark;

            modelset.appid = config["eBoss:appid"].ToString();
            modelset.appkey = config["eBoss:appkey"].ToString();
            modelset.billdate = DateTime.Now.ToString("yyyyMMdd");
            string url = config["eBoss:url"].ToString();
            string ret = await HttpHelper.HttpGetAsync(url + modelset.ToJson());
            ret.ToJson();
            //string ret = await HttpHelper.HttpGetAsync(url + "{\"appid\":\""+ appid + "\",\"appkey\":\""+ appkey + "\",\"method\":\"eboss.drp.adj.add\",\"masterid\":\""+ masterid + "\",\"billdate\":\"" + billdate + "\",\"adjtype\":\"正常调整\",\"store\":\"WLZZ0001\",\"remark\":\"备注测试备注测试备注测试备注测试备注测试备注测试备注测试备注测试备注测试\",\"createid\":\"000\",\"dts\":[{\"sku\":\"010801001\",\"qty\":1},{\"sku\":\"010801002\",\"qty\":2}],\"ms\":[{\"sku\":\"010801001\",\"mastercode\":\"code1\",\"mastercode2\":\"code2\"},{\"sku\":\"010801002\",\"mastercode\":\"code3\",\"mastercode2\":\"code4\"}]}");
            return Success("", ret.Contains("\"success\": true"));
        }


        #endregion


        #region 日循环  创建生日订单
        /// <summary>
        /// 创建生日订单 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [NonAction]
        public async Task<string> AddBirthDayOrder()
        {
            int n1 = 0;
            int n2 = 0;
            try
            {

                OrderInput input = new OrderInput();
                List<T_Cus_VipInfo> modelvipList = await cus_vip_infoRepository.GetListALL(q => (q.F_GiftYear == (DateTime.Now.Year - 1).ToString() || q.F_GiftYear == (DateTime.Now.Year - 2).ToString()) && q.F_Birthday > DateTime.Now.AddDays(-15) && q.F_Birthday < DateTime.Now.AddDays(7));
                List<T_Sys_DictionaryValue> dicStockList = await dictionaryValueRepository.GetListALL(q => q.F_ParentCode.ToUpper() == "STOCK");
                //遍历需要发生日礼物的人  发一个更新一个 比较安全
                if (modelvipList != null && modelvipList.Count > 0 && dicStockList != null && dicStockList.Count > 0)
                {
                    foreach (T_Cus_VipInfo modelvip in modelvipList)
                    {
                        n1++;
                        //modelvipListUpdate.Add(modelvip)
                        List<T_Bus_Order> OldOrderList = await bus_OrderRepository.GetListALL(q => q.F_State > 3 && (q.F_CustomerPhone == modelvip.F_Mobile || q.F_CustomerPhone == modelvip.F_Mobile1 || q.F_CustomerPhone == modelvip.F_Mobile || q.F_CustomerPhone == modelvip.F_Mobile), q => q.F_AddTime, SqlSugar.OrderByType.Desc);
                        T_Bus_Order modelOrder = new T_Bus_Order();
                        if (OldOrderList != null && OldOrderList.Count > 0)
                        {
                            modelOrder = OldOrderList[0];

                        }
                        else
                        {
                            modelOrder.F_Customer = modelvip.F_Name;
                            modelOrder.F_CustomerPhone = modelvip.F_Mobile;
                            modelOrder.F_Addressee = modelvip.F_Name;
                            modelOrder.F_AddPhone = modelvip.F_Mobile;
                            modelOrder.F_AddProvince = modelvip.F_Province;
                            modelOrder.F_AddCity = modelvip.F_City;
                            modelOrder.F_AddArea = modelvip.F_Area;
                            modelOrder.F_AddTown = modelvip.F_Town;
                            modelOrder.F_AddDes = "生日单";
                            modelOrder.F_Address = modelvip.F_Address;
                            modelOrder.F_PostalCode = modelvip.F_Postcode;
                            modelOrder.F_Express = "中通快递";
                            modelOrder.F_Belong = modelvip.F_Saleperson.ObjToInt();
                            modelOrder.F_BelongName = "ID:" + modelvip.F_Saleperson;
                        }

                        #region 订单属性
                        //必填
                        modelOrder.F_ADFrom = "生日单";
                        modelOrder.F_Type = "系统单";
                        modelOrder.F_Id = "BJ" + modelvip.F_Saleperson + "T" + DateTimeConvert.ToTimetag(DateTime.Now);
                        modelOrder.F_VipId = modelvip.F_ID;
                        modelOrder.F_UseActivity = "生日单";
                        //选填 快递属性
                        modelOrder.F_TrackingNo = "";

                        modelOrder.F_ExpressFee = 0;

                        modelOrder.F_PayType = "系统免单";

                        modelOrder.F_Remark = "生日单";

                        modelOrder.F_RealPrice = 0.00M;
                        modelOrder.F_UseScore = 0.00M;
                        //选填 关联属性
                        modelOrder.F_Status = 0;


                        //必须属性 系统生成
                        modelOrder.F_AddTime = DateTime.Now;
                        modelOrder.F_AddUser = 0;
                        modelOrder.F_AddUserName = "系统";


                        #endregion

                        #region
                        //未删除的赠品
                        List<T_Bus_Product> modelProductList = await bus_productRepository.GetListALL(b => b.F_ClassId == 3 && b.F_IsDelete == 1 && b.F_IsSale == 0);
                        if (modelProductList == null || modelProductList.Count == 0)
                            return "==error==没有设置生日赠品";
                        int n = 1;

                        List<T_Bus_OrderDetail> modelDetailList = new List<T_Bus_OrderDetail>();
                        foreach (T_Bus_Product modelProduct in modelProductList)
                        {
                            T_Bus_OrderDetail modelDetail = new T_Bus_OrderDetail();
                            modelDetail.F_ProductName = modelProduct.F_ProductName;
                            modelDetail.F_ProductId = modelProduct.F_ProductId;
                            modelDetail.F_Id = Guid.NewGuid().ToString().Replace("-", "");
                            modelDetail.F_OrderId = modelOrder.F_Id;
                            modelDetail.F_Count = 1;
                            modelDetail.F_Price = modelProduct.F_MemberPrice;
                            modelDetail.F_DealPrice = 0.00M;
                            modelDetail.F_Remark = "生日赠品-活动";

                            modelDetail.F_Sort = n;
                            modelDetail.F_AddTime = DateTime.Now;

                            modelDetail.F_AddUser = 0;
                            modelDetail.F_AddUserName = "系统";
                            modelDetailList.Add(modelDetail);
                            n++;
                        }
                        modelOrder.F_TotlePrice = 0.00M;
                        modelOrder.F_ActivityMoney = 0.00M;
                        modelOrder.F_ShouldPrice = 0.00M;
                        modelOrder.F_PayState = 1;
                        modelOrder.F_Score = 0.00M;
                        #endregion


                        #region 直接提交  锁库存log  锁积分log


                        modelOrder.F_SubmitTime = DateTime.Now;
                        modelOrder.F_State = 1;
                        modelOrder.F_Stock = dicStockList[0].F_Value;

                        modelOrder.F_FlowNum = DateTime.Now.ToString("yyMMddHHmmss") + "U" + modelOrder.F_AddUser + "R" + new Random().Next(9);
                        string strStock = await ChangeStockOne(modelOrder, 1, modelDetailList);
                        if (strStock != "1")
                        {
                            if (dicStockList.Count > 1)
                            {
                                modelOrder.F_Stock = dicStockList[1].F_Value;
                                modelOrder.F_FlowNum = DateTime.Now.ToString("yyMMddHHmmss") + "U" + modelOrder.F_AddUser + "R" + new Random().Next(9);
                                strStock = await ChangeStockOne(modelOrder, 1, modelDetailList);
                                if (strStock != "1")
                                {
                                    modelOrder.F_State = 0;
                                    modelOrder.F_SubmitTime = null;
                                }
                            }
                        }
                        #endregion

                        if (await bus_OrderRepository.AddReturnCount(modelOrder))
                        {
                            n2++;
                            if (await bus_OrderDetailRepository.AddMany(modelDetailList))
                            {
                                continue;
                            }
                            else
                            {
                                _logger.LogError("TODO系统订单详情添加失败库存已减：" + modelOrder.F_Id);
                                break;
                            }
                        }
                        else
                        {
                            _logger.LogError("TODO系统订单添加失败库存已减" + modelDetailList.ToJson());
                            break;
                        }
                    }
                }
                else
                { }
            }

            catch (Exception ex)
            {
                return "==error==" + ex.Message;
            }
            return $"==1==执行{n1}成功{n2}";
        }
        #endregion
    }
}