using AutoTurnOver.Models;
using Bailun.ServiceFabric;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AutoTurnOver.DB
{
    public class dc_task_download_dao : connectionHelper
    {
        public static void PushData<T>(dc_task_download data, UserData user)
        {
            data.create_date = DateTime.Now;
            data.create_user = user.UserName;
            data.end_date  = new DateTime(1991,1,1);
            data.start_date  = new DateTime(1991,1,1);
            data.status  = (int)dc_task_download_status.待执行;
            data.result_file_url = "";
            data.error_message = "";
            data.error_stack_trace = "";

            var parList = new List<string>();
            var par = data.parameter.ToObject<T>();
            Type dataType = par.GetType();
            PropertyInfo[] properts = dataType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            if (properts.Any())
            {
                foreach (PropertyInfo item in properts)
                {
                    var descriptionData = ((DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute)));
                    if(descriptionData!=null && !string.IsNullOrWhiteSpace(descriptionData.Description))
                    {
                        var obj = item.GetValue(par);
                        if (obj != null && !string.IsNullOrWhiteSpace(obj.ToString()))
                        {
                            var val = obj.ToString();
                            val = RenderVal(descriptionData.Description, val);
                            parList.Add($"[{descriptionData.Description}]={val}");
                        }
                    }
                    
                }
            }

            if(parList!=null&& parList.Count >= 1)
            {
                data.parameter_show = string.Join(",", parList);
            }
            else
            {
                data.parameter_show = "";
            }
          _connection.Insert(data);
        }

        /// <summary>
        /// 渲染参数
        /// </summary>
        /// <param name="description"></param>
        /// <param name="val"></param>
        public static string RenderVal(string description,string val) {
            if (description == "仓库国家")
            {
                return _connection.QueryFirstOrDefault<string>(" select area_name from dc_base_warehouse where area_id=@area_id limit 1  ",new { area_id  = val});
            }
            return val;
        }



    }
}
