using AutoTurnOver.Models;
using AutoTurnOver.Models.dc_base_purchase;
using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AutoTurnOver.Utility;
using AutoTurnOver.Models.Report;

namespace AutoTurnOver.DB
{

    /// <summary>
    ///  提货订单
    /// </summary>
    public class dc_auto_pick_up_goods_order_dao : connectionHelper
    {
        /// <summary>
        /// 生成提货订单
        /// </summary>
        public static void GenerateOrder(DateTime btime, DateTime etime)
        {
            var purchase_list = _connection.Query<dc_base_purchase_dto>(" select * from dc_base_purchase where create_time>=@btime and create_time<=@etime and buy_status!=-1 ", new
            {
                btime = btime.ToString("yyyy-MM-dd 00:00:00"),
                etime = etime.ToString("yyyy-MM-dd 23:59:59")
            }).ToList();

            var count = 1;
            foreach (var item in purchase_list.GroupBy(s => new { s.supplier_name, s.supplier_id }))
            {
                var dc_base_supplier_data = (_connection.QueryFirstOrDefault<dc_base_supplier>(" select * from dc_base_supplier where sup_value=@sup_value ", new { sup_value = item.Key.supplier_id }) ?? new dc_base_supplier());

                if (dc_base_supplier_data.isdaytakeinstore == 1)
                {
                   
                    foreach (var itemP in item.GroupBy(s => s.purchase_id))
                    {
                        
                        // 生成编号
                        var order_no = $"{item.Key.supplier_name}-{DateTime.Now.ToString("MM-dd")}-提-{GetNumberStr(count)}";


                        var order_data = new dc_auto_pick_up_goods_order()
                        {
                            create_date = DateTime.Now,
                            date = itemP.Max(s => s.create_time),
                            no = order_no,
                            order_1688_time = new DateTime(1991, 1, 1),
                            pay_time = item.Max(s => s.pay_time),
                            pick_up_goods_time = dc_base_supplier_data.laster_pockup_time ?? "",
                            purchase_id = itemP.Key,
                            warehouse_code = item.Max(v=>v.warehouse_code),
                            warehouse_name = item.Max(v=>v.warehouse_name),
                            suppliers_id  =item.Key.supplier_id??0,
                            suppliers_name = item.Key.supplier_name,
                            address = dc_base_supplier_data.companyaddress,
                            pick_up_tel = dc_base_supplier_data.contactphone,
                            pick_up_user  = dc_base_supplier_data.contactname
                        };

                        // 查询是否已经存在

                        var old_count = _connection.QueryFirstOrDefault<int>(" select * from dc_auto_pick_up_goods_order where purchase_id=@purchase_id ", new { order_data.purchase_id });
                        if (old_count >= 1)
                        {
                            continue;
                        }

                        var new_main_id = _connection.Insert(order_data) ?? 0;

                        foreach (var itemSku in itemP.AsQueryable())
                        {
                            _connection.Insert(new dc_auto_pick_up_goods_order_sku
                            {
                                amount = (itemSku.price ?? 0) * itemSku.count,
                                quantity = itemSku.count,
                                bailun_sku = itemSku.bailun_sku,
                                sku_name = itemSku.sku_name,
                                main_id = new_main_id,
                                price = (itemSku.price ?? 0)
                            });
                        }

                        var out_stock_list = _connection.Query<dc_mid_transit_dto>(" select * from dc_mid_transit where bailun_sku in @bailun_skus and warehouse_code=@warehouse_code ",new {
                            bailun_skus = itemP.Select(s=>s.bailun_sku).ToList(),
                            warehouse_code = order_data.warehouse_code
                        }).ToList();

                        try
                        {
                            ApiUtility.ApiPushSupplierUpSkuInfo(itemP.Select(s => new api_push_SupplierAimsUpSkuInfoDto
                            {
                                Address = order_data.address,
                                CheckGMV = (s.price ?? 0) * s.count,
                                CheckSale = s.count,
                                CheckTime = order_data.date,
                                LatestPickUpTime = order_data.pick_up_goods_time,
                                PickTime = order_data.create_date,
                                PickUpNo = order_data.no,
                                PickUpTel = order_data.pick_up_tel,
                                PickUpUser = order_data.pick_up_user,
                                Sku = s.bailun_sku,
                                Price = s.price,
                                SkuTitle = s.sku_name,
                                SupplierId = order_data.id,
                                SupplierName = order_data.suppliers_name,
                                WarehouseName = order_data.warehouse_name,
                                SupplierCheckSale = itemP.Sum(v => v.count),
                                DayOutStock = (out_stock_list.SingleOrDefault(v => v.bailun_sku == s.bailun_sku) ?? new dc_mid_transit_dto { }).quantity_out_stock
                            }).ToList());
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("提货单推送无库系统异常："+ex.Message);
                            Console.WriteLine("提货单推送无库系统异常："+ex.StackTrace);
                            _connection.Insert(new dc_task_error_log { 
                            date = DateTime.Now,
                            message = ex.Message,
                            task_name  = "提货单推送无库系统异常 - "+ order_data.purchase_id,
                            stack_trace  =ex.StackTrace
                            });
                        }
                       
                        count++;
                    }
                }


            }


        }

        public static string GetNumberStr(int val)
        {
            var val_str = val.ToString();
            for (int i = val_str.Length; i < 3; i++)
            {
                val_str = ("0" + val_str);
            }
            return val_str;
        }

        public static List<dc_auto_pick_up_goods_order_view_dto> SkuPage(dc_auto_return_goods_sku_search_dto m, int offset, int limit, ref int total)
        {
            var list = new List<dc_auto_pick_up_goods_order_view_dto>();

            try
            {
                var sql = @"select 
t2.`no` as 'no',
t2.`date` as 'date',
t2.pay_time,
t2.order_1688_time,
t2.pick_up_goods_time,
t2.purchase_id,
t2.warehouse_code,
t2.warehouse_name,
t1.bailun_sku,
t1.sku_name,
t1.price,
t1.quantity,
t1.amount
from dc_auto_pick_up_goods_order_sku as t1
left join dc_auto_pick_up_goods_order as t2 on t1.main_id = t2.id 
left join dc_base_warehouse as t3 on t2.warehouse_code = t3.warehouse_code
where 1 = 1 ";
                DynamicParameters parameters = new DynamicParameters();
                if (m.btime != null)
                {
                    sql += " and t2.date>=@btime ";
                    parameters.Add("btime", m.btime.Value.ToDayHome());
                }
                if (m.etime != null)
                {
                    sql += " and t2.date<=@etime ";
                    parameters.Add("etime", m.etime.Value.ToDayEnd());
                }
                if (!string.IsNullOrWhiteSpace(m.warehousetype))
                {
                    sql += " and t3.hq_type=@warehousetype";
                    parameters.Add("warehousetype", m.warehousetype);
                }
                if (!string.IsNullOrWhiteSpace(m.sku))
                {
                    sql += " and t1.bailun_sku=@bailun_sku";
                    parameters.Add("bailun_sku", m.sku);
                }
                if (m.warehousearea > 0)
                {
                    sql += " and t3.area_id=" + m.warehousearea;
                }
                if (m.warehouse_code != null)
                {
                    sql += $" and t1.warehouse_code=@warehouse_code ";
                    parameters.Add("warehouse_code", m.warehouse_code);
                }
                if (!string.IsNullOrWhiteSpace(m.supplier_name))
                {
                    sql += " and t1.suppliers_name =@suppliers_name ";
                    parameters.Add("suppliers_name", m.supplier_name);
                }
               

                total = _connection.QuerySingleOrDefault<int>("select count(0) from (" + sql + ") tb1", parameters);

                var obj = _connection.Query<dc_auto_pick_up_goods_order_view_dto>(sql + " limit " + offset + "," + limit, parameters);

                return obj.AsList();

            }
            catch (Exception ex)
            {
                return list;
            }
        }
    }
}
