using AutoTurnOver.DB;
using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto;
using Bailun.ServiceFabric.Core;
using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;

namespace AutoTurnOver.Services
{
    public class PurchaseAdviseServices
    {
        /// <summary>
        /// 创建采购计划
        /// </summary>
        public static void Generate()
        {
            try
            {
                // 创建一个采购计划
                var mainID = purchase_advise.Add(new dc_auto_purchase_advise { create_time = DateTime.Now, no = purchase_advise.GenerateOrderNo() });
                if (mainID == null) throw new Exception("创建采购建议失败");

                purchase_advise.ImportDetailed(mainID.Value);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }





        /// <summary>
        /// 获取采购建议列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static List<dc_auto_purchase_advise> List(dc_auto_purchase_advise_search_dto m, int offset, int limit, ref int total)
        {
            return purchase_advise.List(m, offset, limit, ref total);
        }

        /// <summary>
        /// 获取采购建议明细列表
        /// </summary>
        /// <param name="m"></param>
        /// <param name="offset"></param>
        /// <param name="limit"></param>
        /// <param name="total"></param>
        /// <returns></returns>
        public static List<dc_auto_purchase_advise_detailed_dto> DetailList(dc_auto_purchase_advise_detailed_search_dto m, int offset, int limit, ref int total, string order = "", string sort = "")
        {
            return purchase_advise.DetailList(m, offset, limit, ref total, order, sort);
        }

        /// <summary>
        /// 设置采购数量
        /// </summary>
        /// <param name="id"></param>
        public static void SetQuantityActual(int id, int quantity_actual)
        {
            purchase_advise.SetQuantityActual(id, quantity_actual);
        }

        /// <summary>
        /// 批量设置采购数量
        /// </summary>
        /// <param name="id"></param>
        public static void BatchSetQuantityActual(List<BatchSetQuantityActualInputDto> datas)
        {
            purchase_advise.BatchSetQuantityActual(datas);
        }


        /// <summary>
        /// 查询历史采购建议
        /// </summary>
        /// <param name="id"></param>
        public static dc_auto_purchase_advise_detailed DetailInfo(string sku, string warehousecode, DateTime dateTime)
        {
            return purchase_advise.DetailInfo(sku, warehousecode, dateTime);
        }



        public static void Del(int id)
        {
            purchase_advise.Del(id);
        }

        private static object _push_lock = new object();
        /// <summary>
        /// 把最新一批的采购单推送到采购系统
        /// </summary>
        /// <param name="mainId"></param>
        public static void PushBuySys(List<dc_auto_purchase_advise_detailed_dto> datas, UserData user)
        {
            lock (_push_lock)
            {
                try
                {
                    //查询最近一个采购建议
                    // 
                    if (datas == null)
                    {
                        return;
                    }
                    List<string> planNos = new List<string>();
                    DateTime now = DateTime.Now;
                    // 查询未推送成功的采购建议的明细
                    var detailList = purchase_advise.BuyDetailList(datas.Select(s => s.id).ToList(), false);
                    foreach (var item in detailList.GroupBy(s => new { s.warehouse_code, s.warehouse_type }))
                    {

                        mPlanToPurchaseDto data = new mPlanToPurchaseDto
                        {
                            bp_sendtype = 1,
                            bp_send = item.Key.warehouse_type != "国内仓" ? 1 : 0,
                            bp_sendfromCode = item.Key.warehouse_type != "国内仓" ? "GZBLZZG" : item.Key.warehouse_code,
                            bp_sendtoCode = item.Key.warehouse_type != "国内仓" ? item.Key.warehouse_code : null,
                            sys_source = item.Any(s => s.type == 2) ? 2 : item.Any(s => s.type == 1) ? 1 : 3,
                            bi_buyplandetail = new List<bi_buyplandetail>(),
                            bp_remark = $"用户{user.UserName} 在 aims 操作推送"
                        };

                        data.bi_buyplandetail = item.Select(s => new bi_buyplandetail
                        {
                            bd_count = s.quantity_actual > 0 ? s.quantity_actual : s.quantity_final_advise,
                            bd_price = s.unit_price,
                            bd_sku = s.bailun_sku,
                            sys_source = s.type
                        }).ToList();

                        var result = ApiServices.PushBuyPlan(data);
                        if (result.IsSuccessed)
                        {
                            //把采购数量没有填的都补上 建议采购数
                            var sql = " update dc_auto_purchase_advise_detailed set quantity_actual=quantity_final_advise where quantity_actual<=0 and id in @ids ";
                            DynamicParameters parameters = new DynamicParameters();
                            parameters.Add("ids", item.Select(s => s.id).ToList());
                            if(result.fail_skus!=null && result.fail_skus.Count >= 1)
                            {
                                sql += " and bailun_sku not in @bailunSku ";
                                parameters.Add("bailunSku", result.fail_skus.ToList());
                            }
                            connectionHelper._connection.Execute(sql, parameters);

                            // 把相关的采购明细都标记成已推送
                            var sql2 = " update  dc_auto_purchase_advise_detailed set ispush=1,plan_nos=@plan_nos,push_user_name=@push_user_name where id in @ids ";
                            DynamicParameters parameters2 = new DynamicParameters();
                            parameters2.Add("ids", item.Select(s => s.id).ToArray());
                            parameters2.Add("plan_nos", result.planNo);
                            parameters2.Add("push_user_name", user.UserName);
                            if (result.fail_skus != null && result.fail_skus.Count >= 1)
                            {
                                sql2 += " and bailun_sku not in @bailunSku ";
                                parameters2.Add("bailunSku", result.fail_skus.ToList());
                            }
                            connectionHelper._connection.Execute(sql2, parameters2);
                        }
                        planNos.Add(result.planNo);

                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

        }


        /// <summary>
        /// 自动推送采购单
        /// </summary>
        public static void AutoPushBuySys()
        {
            // 生产jit采购建议
            var mainID = purchase_advise.ImportJITShortageDetailed(0);
            List<dc_auto_purchase_advise_detailed_dto> datas = new List<dc_auto_purchase_advise_detailed_dto>();
            try
            {


                // 推送 张莹霞 广州01 仓的数据
                var total = 0;
                datas.AddRange(PurchaseAdviseServices.DetailList(new dc_auto_purchase_advise_detailed_search_dto { main_id = mainID, end_date = DateTime.Now, start_date = DateTime.Now, ispush = false, purchase_user = "张莹霞", warehouse_code = "GZBLWH" }, 0, int.MaxValue, ref total));
                datas.AddRange(PurchaseAdviseServices.DetailList(new dc_auto_purchase_advise_detailed_search_dto { main_id = mainID, end_date = DateTime.Now, start_date = DateTime.Now, ispush = false, purchase_user = "张莹霞1", warehouse_code = "GZBLWH" }, 0, int.MaxValue, ref total));
                PurchaseAdviseServices.PushBuySys(datas, new UserData { UserName = "admin" });
            }
            catch (Exception ex)
            {
                report.AddError(new dc_task_error_log
                {
                    date = DateTime.Now,
                    message = ex.Message,
                    stack_trace = datas.ToJson(),
                    task_name = "AutoPushBuySys"
                });
                Console.WriteLine(ex.Message);

            }

        }

        /// <summary>
        /// 提取sku
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static List<string> ExtractSku(string message)
        {
            if (!message.Contains("SKU") && !message.Contains("sku"))
            {
                return null;
            }
            else
            {
                Regex skuRegex = new Regex(@"【[\s\S]+】");
                var skus = skuRegex.Matches(message);
                if (skus != null && skus.Count == 1)
                {
                    return skus[0].Value.Split(',').ToList();
                }
                else if (skus.Count > 1)
                {
                    report.AddError(new dc_task_error_log
                    {
                        date = DateTime.Now,
                        message = "异常中包含多个【】，识别异常",
                        stack_trace = message,
                        task_name = "AutoPushBuySys_ExtractSku"
                    });
                    return null;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}
