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)
        {
            return purchase_advise.DetailList(m, offset, limit, ref total);
        }

        /// <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 dc_auto_purchase_advise_detailed DetailInfo(string sku, string warehousecode, DateTime dateTime)
        {
            return purchase_advise.DetailInfo(sku, warehousecode, dateTime);
        }

        /// <summary>
        /// 把最新一批的采购单推送到采购系统
        /// </summary>
        /// <param name="mainId"></param>
        public static void PushBuySys(List<dc_auto_purchase_advise_detailed_dto> datas,int type)
        {
            MySqlConnection conn = connectionHelper._connection;
            conn.Open();
            IDbTransaction transaction = conn.BeginTransaction();
            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 => s.warehouse_code))
                {

                    mPlanToPurchaseDto data = new mPlanToPurchaseDto
                    {
                        bp_sendtype = 1,
                        bp_sendfromCode = item.Key,
                        type = type,
                        bi_buyplandetail = new List<bi_buyplandetail>()
                    };

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

                    var result = ApiServices.PushBuyPlan(data);
                    if (result.IsSuccessed)
                    {
                        // 把相关的采购明细都标记成已推送
                        conn.Execute(" update  dc_auto_purchase_advise_detailed set ispush=1 where id in @ids ",new { ids = item.Select(s=>s.id).ToArray() });
                    }
                    planNos.Add(result.planNo);
                    
                }

                conn.Execute(" update dc_auto_purchase_advise set buy_sys_plan_no=@buy_sys_plan_no,push_time=@push_time ", new { buy_sys_plan_no = string.Join(",", planNos), push_time = now }, transaction);

                transaction.Commit();
            }
            catch (Exception)
            {

                transaction.Rollback();
                conn.Close();
                throw;
            }
        }

    }
}
