using AutoTurnOver.Models;
using Dapper;
using System;
using System.Collections.Generic;
using System.Text;

namespace AutoTurnOver.DB
{
    public class dc_base_prod_order_dao : connectionHelper
    {
        public static void SynchroData()
        {
            var task_name = "SynchroProdData_v3";
            var conn = _connection;
            // 查询最后一次成功抓取的记录
            var last_task_synchro_log = conn.QuerySingleOrDefault<task_synchro_log>(" select  * from task_synchro_log where task_name=@task_name and status=1 order by end_time desc limit 1 ", new { task_name = task_name });

            var new_task_synchro_log = new task_synchro_log
            {
                create_date = DateTime.Now,
                end_time = DateTime.Now.AddMinutes(-3),
                status = 0,
                task_name = task_name
            };

            if (last_task_synchro_log != null)
            {
                new_task_synchro_log.start_time = last_task_synchro_log.end_time.AddMinutes(-1);
            }
            else
            {
                new_task_synchro_log.start_time = new DateTime(2020, 05, 14);
            }

            if((new_task_synchro_log.end_time- new_task_synchro_log.start_time).TotalDays > 90)
            {
                new_task_synchro_log.end_time = new_task_synchro_log.start_time.AddDays(89);
            }

            // 如果抓今天的数据，跨度不能太大
            if((new_task_synchro_log.end_time - new_task_synchro_log.start_time).TotalHours > 50 && new_task_synchro_log.end_time.ToString("yyyy-MM-dd")==DateTime.Now.ToString("yyyy-MM-dd"))
            {
                new_task_synchro_log.end_time = DateTime.Now.AddHours(-48);
            }

            new_task_synchro_log.id = conn.Insert(new_task_synchro_log) ?? 0;
            int count = 0;


            var page = 1;
            var rows = 1000;
            while (true)
            {
                var datas = ApiUtility.GetProdOrder(new Models.ApiDto.api_prod_order_request_dto { btime = new_task_synchro_log.start_time, etime = new_task_synchro_log.end_time, page = page, rows = rows });
                if (datas == null || datas.Count <= 0)
                {
                    break;
                }
                page++;

                foreach (var item in datas)
                {
                    if (string.IsNullOrWhiteSpace(item.purchase_no))
                    {
                        continue;
                    }
                    var db_data = new dc_base_prod_order()
                    {
                        gmt_modified_date = DateTime.Now,
                        is_delete = item.order_status == 1 ? 1 : 0,
                        prod_sys_id = item.sys_id,
                        purchase_no = item.purchase_no,
                        prod_sys_no = item.prod_order_no,
                        prod_last_update_date = item.last_update_date,
                        gmt_create_date = DateTime.Now
                    };
                    if ((!string.IsNullOrWhiteSpace(item.pack_code)) && item.pack_product_quantity > 0)
                    {
                        db_data.order_quantity = (item.product_quantity ?? 0) / item.pack_product_quantity.Value;
                        db_data.distribution_quantity = (item.product_distribution_quantity ?? 0) / item.pack_product_quantity.Value;
                        db_data.prod_quantity = (item.product_prod_quantity ?? 0) / item.pack_product_quantity.Value;
                        //  编码要看这俩编码哪一个能匹配上采购单的编码了
                        db_data.bailun_sku = item.pack_code;
                        // 如果通过订单编码查到了数据，则用订单编码
                        var pu_count = _connection.QueryFirstOrDefault<int?>(" select id from dc_base_purchase_details where purchase_id=@purchase_id and bailun_sku=@bailun_sku ",new {
                            purchase_id = db_data.purchase_no,
                            bailun_sku = item.pack_order_code
                        }) ??0;
                        if (pu_count > 0)
                        {
                            db_data.bailun_sku = item.pack_order_code;
                        }
                    }
                    else
                    {
                       
                        db_data.order_quantity = item.product_quantity ?? 0;
                        db_data.distribution_quantity = item.product_distribution_quantity ?? 0;
                        db_data.prod_quantity = item.product_prod_quantity ?? 0;
                        db_data.bailun_sku = item.product_sku_code;
                        // 如果通过订单编码查到了数据，则用订单编码
                        var pu_count = _connection.QueryFirstOrDefault<int?>(" select id from dc_base_purchase_details where purchase_id=@purchase_id and bailun_sku=@bailun_sku ", new
                        {
                            purchase_id = db_data.purchase_no,
                            bailun_sku = item.product_order_code
                        }) ?? 0;
                        if (pu_count > 0)
                        {
                            db_data.bailun_sku = item.product_order_code;
                        }
                    }

                   
                    if (string.IsNullOrWhiteSpace(db_data.bailun_sku))
                    {
                        continue;
                    }
                    var old_data = MyMySqlConnection._connection.QueryFirstOrDefault<dc_base_prod_order>(" select * from dc_base_prod_order where `purchase_no`=@purchase_no and  bailun_sku=@bailun_sku ", new
                    {
                        purchase_no = db_data.purchase_no,
                        bailun_sku = db_data.bailun_sku,
                    });
                    if (old_data != null)
                    {
                        db_data.distribution_quantity = Math.Min(db_data.distribution_quantity, old_data.distribution_quantity);
                        db_data.prod_quantity = Math.Min(db_data.prod_quantity, old_data.prod_quantity);
                        db_data.id = old_data.id;
                        SetStatus(db_data);
                        conn.Update(db_data);
                    }
                    else
                    {
                        SetStatus(db_data);
                        conn.Insert(db_data);
                    }

                    #region 计算状态
                   
                    #endregion

                    count++;
                }

            }


            new_task_synchro_log.count = count;
            new_task_synchro_log.status = 1;
            conn.Update(new_task_synchro_log);
        }

        public static void SetStatus(dc_base_prod_order db_data)
        {
            if (db_data.order_quantity <= db_data.prod_quantity)
            {
                db_data.status = "生产完成";
            }
            else
            {
                var status = "";

                if (db_data.order_quantity <= db_data.distribution_quantity)
                {
                    status += " 完全分配 ";
                }
                else if (db_data.distribution_quantity > 0)
                {
                    status += " 部分分配 ";
                }
                else
                {
                    status += " 未分配 ";
                }

                if (db_data.prod_quantity > 0)
                {
                    status += " 部分生产 ";
                }
                db_data.status = status;
            }
        }
    }
}
