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

namespace AutoTurnOver.Services
{
    /// <summary>
    /// 采购平均指标计算
    /// </summary>
    public class PurchaseAverageTargetServices
    {
        /// <summary>
        /// 取数基数
        /// </summary>
        public static int _seed_count = 5;

        public static void Calculation()
        {
            MySqlConnection conn = connectionHelper._connection;

            var task_log = new dc_task_log
            {
                StartTime = DateTime.Now,
                Type = 1,
                Count = 0
            };

            var taskID = conn.Insert(task_log);
            task_log.ID = taskID.Value;

            try
            {

                // 获取最近2天发送变化的SKU 用于计算
                var chageSkuList = AveragePurchase.GetChangeSku(30);
                foreach (var skuItem in chageSkuList)
                {
                    dc_average_purchase data = new dc_average_purchase()
                    {
                        bailun_sku = skuItem.bailun_sku,
                        supplier_id = skuItem.supplier_id ?? 0,
                        warehouse_code = skuItem.warehouse_code
                    };



                    // 查询相关采购单
                    var purchaseList = AveragePurchase.GetPurchaseList(skuItem, _seed_count).ToList();

                   
                    //查出来的采购单数量
                    var purchase_order_count = purchaseList.Select(s => s.purchase_id).Distinct().Count();

                    //有相关采购单 (要至少有3个单，才算平均数)
                    if (purchaseList != null && purchase_order_count >= 3)
                    {
                        data.supplier_name = purchaseList[0].supplier_name;

                        //计算平均价格
                        data.price = purchaseList.Sum(s => s.price ?? 0) / purchaseList.Count;

                        // 计算平均到货天数
                        // 计算总交期
                        int delivery_days = 0;
                        // 查询相关的到货记录
                        var arrivalList = AveragePurchase.GetArrivalList(purchaseList.Select(s => s.purchase_id), skuItem.bailun_sku);
                        foreach (var itemArrivalList in arrivalList.GroupBy(s => s.purchase_id))
                        {
                            var tempPurchase = purchaseList.SingleOrDefault(s => s.purchase_id == itemArrivalList.Key);

                            if (tempPurchase.pay_type == 1)
                            {
                                delivery_days += (int)Math.Ceiling((itemArrivalList.Min(s => s.update_time) - tempPurchase.pay_time).Value.TotalHours / 24);
                            }
                            else
                            {
                                delivery_days += (int)Math.Ceiling((itemArrivalList.Min(s => s.update_time) - tempPurchase.confirm_time).Value.TotalHours / 24);
                            }
                        }

                        // 平均采购交期
                        var temp_delivery_days = delivery_days / purchaseList.Count;
                        //够5个单才算平均值给系统用
                        // 如果是海外仓暂时不算，否则算出来30几天的平均值，影响计划单交期调整的推进
                        if (purchase_order_count >= 5  && skuItem.hq_type=="国内仓")
                        {
                            data.delivery_days = temp_delivery_days;
                        }
                        else
                        {
                            // 不够5个单不算这个值
                            data.delivery_days = -1;
                        }
                        data.virtual_delivery_days = temp_delivery_days;
                        data.payment_type = purchaseList.Any(s => s.pay_type == 1) ? 1 : 2;




                        //写入数据库
                        AveragePurchase.Save(data, conn);

                        task_log.Count++;
                    }
                    else
                    {
                        // 不够3个单，不该有平均数
                        data.delivery_days = -1; 
                        data.supplier_name = ""; 
                        AveragePurchase.Save(data, conn);
                    }

                    var purchaseWList = AveragePurchase.GetPurchaseListByWode(skuItem, _seed_count).ToList();

                    if (purchaseWList != null && purchaseWList.Count() >= 1)
                    {
                        dc_average_warehouse dataWarehouse = new dc_average_warehouse()
                        {
                            bailun_sku = skuItem.bailun_sku,
                            warehouse_code = skuItem.warehouse_code
                        };
                        // 计算平均入库天数
                        // 查询相关的入库记录
                        var inboundList = AveragePurchase.GetInboundList(purchaseWList.Select(s => s.purchase_id), skuItem.bailun_sku);
                        if (inboundList != null && inboundList.Count() >= 1)
                        {
                            dataWarehouse.inbound_days = (int)inboundList.Sum(s => Math.Ceiling((s.update_time - s.arrival_time).TotalHours / 24)) / inboundList.Count();
                        }
                        else
                        {
                            dataWarehouse.inbound_days = 0;
                        }

                        // 计算平均海运调拨天数
                        // 查询最近5次海运（已完成）记录
                        var transport1List = AveragePurchase.GetTransportList(skuItem.bailun_sku, skuItem.warehouse_code, "海运", _seed_count);
                        if (transport1List != null && transport1List.Count() >= 1)
                        {
                            dataWarehouse.transfer_type_1_days = (decimal)transport1List.Sum(s => (s.inbound_time - s.bale_time).TotalDays) / transport1List.Count();
                        }


                        // 计算平均空运调拨天数
                        // 查询最近5次空运（已完成）记录
                        var transport2List = AveragePurchase.GetTransportList(skuItem.bailun_sku, skuItem.warehouse_code, "空运", _seed_count);
                        if (transport2List != null && transport2List.Count() >= 1)
                        {
                            dataWarehouse.transfer_type_2_days = (decimal)transport2List.Sum(s => (s.inbound_time - s.bale_time).TotalDays) / transport2List.Count();
                        }

                        //头程天数
                        var transport3List = AveragePurchase.GetTransportList(skuItem.bailun_sku, skuItem.warehouse_code, "", _seed_count);
                        // 大于两条记录，才计算平均值，否则没有意义
                        if (transport3List != null && transport3List.Count() >= 2)
                        {
                            dataWarehouse.transfer_bale_delivery = (decimal)transport3List.Sum(s => (s.delivery_time - s.bale_time).TotalDays) / transport3List.Count();
                            dataWarehouse.transfer_delivery = (decimal)transport3List.Sum(s => (s.arrival_time - s.verify_time).TotalDays) / transport3List.Count();
                            dataWarehouse.abroad_inbound_delivery = (decimal)transport3List.Sum(s => (s.inbound_time - s.arrival_time).TotalDays) / transport3List.Count();
                        }

                        AveragePurchase.Save(dataWarehouse, conn);
                    }


                }

                task_log.CompleteTime = DateTime.Now;
            }
            catch (Exception ex)
            {
                task_log.ErrorMsg = ex.Message;
            }

            conn.Update(task_log);
        }

        public static IEnumerable<dc_average_purchase> GetListByWCode(string sku, string warehouse_code)
        {
            return AveragePurchase.GetListByWCode(sku, warehouse_code);
        }

        public static IEnumerable<dc_average_purchase> GetList(string supplier_ids, string bailun_skus)
        {
            return AveragePurchase.GetList(supplier_ids, bailun_skus);
        }

        public static dc_average_warehouse GetWarehouse(string sku, string warehouse_code)
        {
            return AveragePurchase.GetWarehouse(sku, warehouse_code);
        }



    }


}
