using Dapper;
using SimpleCRM.Units;
using SimpleCRM.ViewDAO;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleCRM.Service
{
    public class DictionarysService
    {
        public static string CUSTOMER_CACHE_KEY = "SELECT * FROM T_CUSTOMER WHERE DELETEFLAG=0";
        public static string SALER_CACHE_KEY = "SELECT * FROM T_SALER WHERE ISLAYOFF=0";
        public static string PROVINCE_CACHE_KEY = "SELECT * FROM T_PROVINCE";
        public static string SALESDEPARTMENT_CACHE_KEY = "SELECT * FROM T_SALESDEPARTMENT";
        public ObservableCollection<Customer> GetAllCustomers()
        {
            string strSql = CUSTOMER_CACHE_KEY;
            return GetDictionaryDatas<Customer>(strSql);
        }

        public ObservableCollection<Saler> GetAllSalers()
        {
            string strSql = SALER_CACHE_KEY;
            return GetDictionaryDatas<Saler>(strSql);
        }

        public ObservableCollection<Province> GetAllProvinces()
        {
            string strSql = PROVINCE_CACHE_KEY;
            return GetDictionaryDatas<Province>(strSql);
        }

        public ObservableCollection<SalesDepartment> GetAllSalesDepartments()
        {
            string strSql = SALESDEPARTMENT_CACHE_KEY;
            return GetDictionaryDatas<SalesDepartment>(strSql);
        }

        private ObservableCollection<T> GetDictionaryDatas<T>(string strSql)
        {
            var items = CacheHelper.GetCacheItem<ObservableCollection<T>>(strSql, () =>
            {
                using (IDbConnection cnn = DbHelper.GetConnection())
                {
                    return new ObservableCollection<T>(cnn.Query<T>(strSql, new DynamicParameters()));
                }
            },
            new TimeSpan(0, 30, 0));//30分钟过期
            return items;
        }
    }
}
