using AutoTurnOver.Models;
using System;
using System.Collections.Generic;
using System.Text;
using AutoTurnOver.DB;
using System.Data;
using System.IO;
using AutoTurnOver.Utility;
using System.Linq;
using Dapper;

namespace AutoTurnOver.Services
{
    /// <summary>
    /// 子母sku
    /// </summary>
    public class MotherSkuServices
    {
        public List<dc_base_mother_sku_dto> Page(dc_base_mother_sku_search_dto search, int offset, int limit, ref int total)
        {
            return dc_base_mother_sku_dao.Page(search, offset, limit, ref total);
        }
        public List<dc_base_mother_sku_log_dto> LogPage(dc_base_mother_sku_log_search_dto search, int offset, int limit, ref int total)
        {
            return dc_base_mother_sku_dao.LogPage(search, offset, limit, ref total);
        }
        public void Save(dc_base_mother_sku data, UserData user)
        {
            dc_base_mother_sku_dao.Save(data, user);
        }
        public void UpdateStatus(update_status_input_dto data, UserData user)
        {
            dc_base_mother_sku_dao.UpdateStatus(data, user);
        }
        public void RemoveMap(remove_map_input_dto data, UserData user)
        {
            dc_base_mother_sku_dao.RemoveMap(data, user);
        }
        public void SetMainMap(remove_map_input_dto data, UserData user)
        {
            dc_base_mother_sku_dao.SetMainMap(data, user);
        }

        public void BatchSet(batch_set_input_dto input_data, UserData user)
        {
            dc_base_mother_sku_dao.BatchSet(input_data, user);
        }

        public List<dc_base_mother_sku_dto> SearchSku(string name)
        {
            return dc_base_mother_sku_dao.SearchSku(name);
        }

        public DataTable Import(Stream fileInfo, UserData user)
        {
            var conn = MyMySqlConnection._connection;
            var data_set = EPPlusHelper.ReadExcel(fileInfo);
            var table = data_set.Tables[0];
            if (!table.Columns.Contains("导入结果")) table.Columns.Add("导入结果");
            if (!table.Columns.Contains("导入异常")) table.Columns.Add("导入异常");

            var warehouse_list = DB.common.ListWareHouse(null, null);

            DateTime now = DateTime.Now;

            int index = 1;
            foreach (DataRow row in table.Rows)
            {
                index++;
                try
                {
                    var mother_bailun_sku = row["母SKU"].ToString();
                    var month_warehouse_code = row["母仓库编码"].ToString();
                    var bailun_sku = row["子SKU"].ToString();
                    var warehouse_code = row["子仓库编码"].ToString();
                    var is_main = row["是否主sku"].ToString();

                    if (string.IsNullOrWhiteSpace(mother_bailun_sku)) throw new Exception("母SKU必填");
                    if (string.IsNullOrWhiteSpace(month_warehouse_code)) throw new Exception("母warehouse_code必填");
                    if (string.IsNullOrWhiteSpace(bailun_sku)) throw new Exception("SKU必填");
                    if (string.IsNullOrWhiteSpace(warehouse_code)) throw new Exception("warehouse_code必填");
                    var m_warehouse_data = warehouse_list.SingleOrDefault(s => s.warehouse_code.Equals(month_warehouse_code, StringComparison.OrdinalIgnoreCase));
                    if (m_warehouse_data == null) { throw new Exception("母仓库在系统中找不到"); }

                    var warehouse_data = warehouse_list.SingleOrDefault(s => s.warehouse_code.Equals(warehouse_code, StringComparison.OrdinalIgnoreCase));
                    if (warehouse_data == null) { throw new Exception("仓库在系统中找不到"); }
                    var warehouse_name = warehouse_data.warehouse_name;

                    var trun_data_id = (conn.QueryFirstOrDefault<int?>("select id from dc_auto_turnover where bailun_sku=@bailun_sku and warehouse_code=@warehouse_code", new
                    {
                        bailun_sku = bailun_sku,
                        warehouse_code = warehouse_code
                    }) ?? 0);
                    if (trun_data_id <= 0)
                    {
                        throw new Exception("子sku不存在");
                    }

                    try
                    {
                        dc_base_mother_sku_dao.Save(new dc_base_mother_sku()
                        {
                            warehouse_code = month_warehouse_code,
                            sku = mother_bailun_sku,
                        }, user);


                    }
                    catch (Exception)
                    {

                    }

                    dc_base_mother_sku_dao.BatchSet(new batch_set_input_dto
                    {
                        mother_id = conn.QueryFirstOrDefault<int?>("select id from dc_base_mother_sku where sku_warehouse_code=@sku_warehouse_code", new
                        {
                            sku_warehouse_code = $"M-{mother_bailun_sku}{month_warehouse_code}"
                        }) ?? 0,
                        ids = new List<int> {
                       trun_data_id
                        },
                        is_main = (is_main=="是"?1:0)
                    }, user);


                    row["导入结果"] = "成功";
                    row["导入异常"] = "";
                }
                catch (Exception ex)
                {
                    row["导入结果"] = "失败";
                    row["导入异常"] = ex.Message;
                }
            }
            return table;
        }
    }
}
