using DeviceRepair.DataAccess.Data;
using DeviceRepair.Models;
using DeviceRepair.Models.History;
using DeviceRepair.Models.Preserve;
using DeviceRepair.Utils;
using NLog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace DeviceRepair.DataAccess.SysCommon
{
    public class SysConfigDa : BaseDa
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();
        
        public SysConfigDa(IDictionary<string, string> apiParams) : base(apiParams)
        {

        }

        /// <summary>
        /// 获取全部配置信息
        /// </summary>
        /// <returns></returns>
        public DataSet GetDatas()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                List<SysConfigInfo> Datas = devMain.Queryable<SysConfigInfo>()?.ToList();
                DataTable table = Datas.ToDataTable();
                dsDatas.Tables.Add(table);
                return dsDatas;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 批量编辑配置
        /// </summary>
        /// <param name="Datas"></param>
        /// <returns></returns>
        public APIResponseData EditConfigs(DataTable Datas)
        {
            try
            {
                if (Datas == null || Datas.Rows.Count == 0)
                {
                    throw new ArgumentException($"未能获取到待修改的配置信息！");
                }

                List<SysConfigInfo> Items = DTOHelper<SysConfigInfo>.DataTableToList(Datas)?.ToList();
                if (Items.Count != devMain.Updateable(Items).UpdateColumns(x => new { x.Value }).ExecuteCommand())
                {
                    throw new Exception("修改的配置信息出错！");
                }

                return new APIResponseData { Code = 1 };
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
    }
}
