using System;
using System.Collections.Generic;
using System.Text;
using Dapper;
using MySql.Data.MySqlClient;
using Bailun.DC.Common;
using Bailun.DC.Models;


namespace Bailun.DC.Services
{
    public class BalanceSheetServices
    {
        /// <summary>
        /// 获取资产负债表导入表格的汇总金额
        /// </summary>
        /// <param name="type">金额类型</param>
        /// <param name="day">统计日期</param>
        /// <returns></returns>
        public decimal GetCount(string type, DateTime day)
        {
            var sql = $"select sum(amount) amount from dc_balance_sheet_subdetail where type='{type}' and day='{day.ToString("yyyy-MM-dd")}'";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                return cn.QueryFirstOrDefault<decimal?>(sql)??0;

            }

        }

        /// <summary>
        /// 获取资产负债表导入表格的列表
        /// </summary>
        /// <param name="type"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        public List<dc_balance_sheet_subdetail> List(string type, DateTime day,BtTableParameter parameter,ref int total)
        {
            var sql = $"select * from dc_balance_sheet_subdetail where type='{type}' and day='{day.ToString("yyyy-MM-dd")}'";

            using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
            {
                if (cn.State == System.Data.ConnectionState.Closed)
                {
                    cn.Open();
                }

                var obj = cn.Page<dc_balance_sheet_subdetail>(parameter.pageIndex,parameter.limit,sql,ref total).AsList();

                return obj;
            }
        }

        /// <summary>
        /// 新增资产负债表导入表格数据
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public int Add(dc_balance_sheet_subdetail m)
        {
            try
            {
                using (var cn = new MySqlConnection(Common.GlobalConfig.ConnectionString))
                {
                    if (cn.State == System.Data.ConnectionState.Closed)
                    {
                        cn.Open();
                    }

                    var result = cn.Insert<dc_balance_sheet_subdetail>(m);

                    return result ?? 0;
                }
            }
            catch (Exception ex)
            {

                return 0;
            }
            
        }

        public int AddRang(List<dc_balance_sheet_subdetail> list)
        {
            var result = 0;
            foreach (var item in list)
            {
                result += Add(item);
            }

            return result;
        }

    }
}
