using AutoTurnOver.DB;
using AutoTurnOver.Models;
using AutoTurnOver.Models.ApiDto;
using Dapper;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

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 = GenerateOrderNo() });
                if (mainID == null) throw new Exception("创建采购建议失败");

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

        }

        /// <summary>
        /// 生成一个流水号
        /// </summary>
        public static string GenerateOrderNo()
        {
            var now = DateTime.Now;
            string dataStr = now.ToString("yyyyMMdd");
            //查找当前最大的订单号
            var maxNo = purchase_advise.MaxNo();

            //取出订单号的流水部分
            if (string.IsNullOrWhiteSpace(maxNo))
                return dataStr + "001";

            return dataStr + GetIntStr(int.Parse(maxNo.Substring(8, 3)) + 1);
        }

        /// <summary>
        /// 把流水号装换成4位数字符串形式
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string GetIntStr(int num)
        {
            var intLength = num.ToString().Length;
            var intStr = num.ToString();
            for (int i = intLength; i < 3; i++)
            {
                intStr = "0" + intStr;
            }
            return intStr;
        }

        /// <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)
                        {
                            //把采购数量没有填的都补上 建议采购数
                            connectionHelper._connection.Execute(" update dc_auto_purchase_advise_detailed set quantity_actual=quantity_final_advise where quantity_actual<=0 and id in @ids ", new { ids = item.Select(s => s.id).ToList() });

                            // 把相关的采购明细都标记成已推送
                            connectionHelper._connection.Execute(" update  dc_auto_purchase_advise_detailed set ispush=1,plan_nos=@plan_nos,push_user_name=@push_user_name where id in @ids ", new { ids = item.Select(s => s.id).ToArray(), plan_nos = result.planNo, push_user_name = user.UserName });
                        }
                        planNos.Add(result.planNo);

                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

        }

    }
}
