using Caliburn.Micro;
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 CustomerService
    {
        public ObservableCollection<Customer> GetCustomers(string conditon)
        {
            var items = new ObservableCollection<Customer>();
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                items = new ObservableCollection<Customer>(cnn.Query<Customer>("SELECT * FROM T_Customer WHERE DELETEFLAG=0 ORDER BY ID DESC", new DynamicParameters()));
            }
            return items;
        }

        public int AddCustomer(Customer item)
        {
            int id = 0;
            var oMaps = new Dictionary<string, object>();
            oMaps.Add("Name", item.Name);
            oMaps.Add("Address", item.Address);
            oMaps.Add("Tel", item.Tel);
            oMaps.Add("CreateTime", item.CreateTime);
            oMaps.Add("Remark", item.Remark);
            string fields = string.Join(",", oMaps.Keys);
            string valueDefineds = string.Join(",", oMaps.Keys.Select(key => string.Format("@{0}", key)));
            string strSql = string.Format("INSERT INTO T_Customer({0}) VALUES({1})", fields, valueDefineds);
            var dynamicParams = new DynamicParameters();
            oMaps.Apply(param => dynamicParams.Add(param.Key, param.Value));

            string strSelectOrderID = "select max(ID) from T_Customer";
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                cnn.Execute(strSql, dynamicParams);
                id = cnn.ExecuteScalar<int>(strSelectOrderID, null);
            }
            return id;
        }

        public int UpdateCustomer(Customer item)
        {
            var oMaps = new Dictionary<string, object>();
            oMaps.Add("Name", item.Name);
            oMaps.Add("Address", item.Address);
            oMaps.Add("Tel", item.Tel);
            oMaps.Add("CreateTime", item.CreateTime);
            oMaps.Add("Remark", item.Remark);
            string fields = string.Join(",", oMaps.Keys.Select(f => string.Format(@"{0}=@{0}", f)));
            string strSql = string.Format("UPDATE T_Customer SET {0} WHERE ID=@ID", fields);
            oMaps.Add("ID", item.ID);
            var dynamicParams = new DynamicParameters();
            oMaps.Apply(param => dynamicParams.Add(param.Key, param.Value));
            using (IDbConnection cnn = DbHelper.GetConnection())
            {
                cnn.Execute(strSql, dynamicParams);
            }
            return 0;
        }
    }
}
