using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using Dapper;
using Bailun.DC.Models;
using System.Threading;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

namespace Bailun.DC.BalanceSheet4K
{
    public class Services : BackgroundService
    {

        private Timer _timer;

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromMinutes(1));
            return Task.CompletedTask;
        }

        private void DoWork(object state)
        {
            try
            {
                var now = DateTime.Now;

                if (now.Day == 1 && now.Hour == 0 && now.Minute == 1)  //每个月的1日0点1分启动
                {
                    Console.WriteLine("开始启动 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    var start = DateTime.Parse(now.AddMonths(-1).ToShortDateString());

                    Init(start);

                    Console.WriteLine("任务运行完成 " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }


        /// <summary>
        /// 每月的第一天
        /// </summary>
        /// <param name="day"></param>
        public void Init(DateTime day)
        {
            var m = new dc_balance_sheet_4k { 
                day = day.AddMonths(1).AddDays(-1),
                cl_count = 0,
                cl_dividends_payable = 0,
                cl_oneyear_noncurrent_liabilities = 0,
                cl_other_liabilities = 0,
                cl_payable_interest = 0,
                count_assets = 0,
                count_liabilities = 0,
                count_liabilities_and_oe = 0,
                createtime = DateTime.Now,
                fa_count = 0,
                nca_count = 0,
                ncl_count = 0,
                oe_capital_reserve=0,
                oe_count = 0,
                oe_paicl_up_capital = 0,
                oe_parentcompany_count = 0,
                accounts_payable = 0,
                accounts_receivable = 0,
                advance_received = 0,
                fixed_assets = 0,
                fa_interest_receivable = 0,


                isedit=0,
                lastupdatetime = DateTime.Now,
                lastupdateuserid = 0,
                lastupdateusername = "admin",
                ncl_longterm_loan=0,
                ncl_other_liabilities = 0,


                monetary_fund = 0,
                oe_minority_equity = 0,
                oe_surplus_public_accumulation = 0,
                oe_undistributed_profit = 0,
                other_accounts_payable = 0,
                other_accounts_receivable = 0,

                payable_remuneration = 0,
                short_term_borrow = 0,
                prepayment = 0,
                taxes_payable = 0,

            };

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

                var sql = "";


                //货币资金
                sql = $@"select sum(balance_rmb) as balance_rmb from dc_bank_account_balance_new where statistical_time='{day.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd")}' and company_system_id=2;";
                m.monetary_fund = cn.QueryFirstOrDefault<decimal?>(sql)??0;


                //其他应收款
                sql = $@"select sum((a.amount - a.had_pay + (a.compensate)) * a.to_rmb_rate) from dc_daily_fee a where `cost_status`=4 and recoed_time='{day.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd")}' and company_name like '%四千里%'";
                m.other_accounts_receivable = cn.QueryFirstOrDefault<decimal?>(sql)??0;


                //固定资产
                sql = $@"select sum(amount_rmb) from dc_base_finance_fee where type_name='固定资产' and company_name like '%四千里%' and cost_status=4";
                m.fixed_assets = cn.QueryFirstOrDefault<decimal?>(sql) ?? 0;
            }

            //流动资产合计=货币资金+应收账款+预付款项+应收利息+其他应收款
            m.fa_count = m.monetary_fund + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.other_accounts_receivable; 

            //非流动资产合计=固定资产
            m.nca_count = m.fixed_assets;

            //资产总计=流动资产合计+非流动资产合计
            m.count_assets = m.fa_count + m.nca_count;

            //流动负债合计=短期借款+应付账款+预收款项+应付职工薪酬+应交税费+应付利息+应付股利+其他应付款+一年内到期的非流动负债+其他流动负债
            m.cl_count = m.short_term_borrow + m.accounts_payable + m.monetary_fund + m.advance_received + m.payable_remuneration + m.taxes_payable + m.cl_payable_interest + m.cl_dividends_payable + m.other_accounts_payable + m.cl_oneyear_noncurrent_liabilities + m.cl_other_liabilities;

            //非流动负债合计=长期借款+其他非流动负债
            m.ncl_count = m.ncl_longterm_loan + m.ncl_other_liabilities;

            //负债合计=流动负债合计+非流动负债合计
            m.count_liabilities = m.cl_count + m.ncl_count;

            //归属于母公司所有者权益合计=实收资本+资本公积+盈余公积+未分配利润
            m.oe_parentcompany_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

            //所有者权益合计= 少数股东权益
            m.oe_count = m.oe_minority_equity;

            //负债和所有者权益总计=负债合计+所有者权益合计
            m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;


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


                cn.Execute($"delete from dc_balance_sheet_4k where day='{day.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd")}' and isedit=0 ");

                var sql = $@"insert dc_balance_sheet_4k (day,cl_count,cl_dividends_payable,cl_oneyear_noncurrent_liabilities,cl_other_liabilities,cl_payable_interest,count_assets,count_liabilities,count_liabilities_and_oe,createtime,fa_count,nca_count,ncl_count,oe_capital_reserve,oe_count,oe_paicl_up_capital,oe_parentcompany_count,accounts_payable,accounts_receivable,advance_received,fixed_assets,fa_interest_receivable,isedit,lastupdatetime,lastupdateuserid,lastupdateusername,ncl_longterm_loan,ncl_other_liabilities,monetary_fund,oe_minority_equity,oe_surplus_public_accumulation,oe_undistributed_profit,other_accounts_payable,other_accounts_receivable,payable_remuneration,short_term_borrow,prepayment,taxes_payable) value ('{m.day.ToString("yyyy-MM-dd")}',{m.cl_count},{m.cl_dividends_payable},{m.cl_oneyear_noncurrent_liabilities},{m.cl_other_liabilities},{m.cl_payable_interest},{m.count_assets},{m.count_liabilities},{m.count_liabilities_and_oe},'{m.createtime.ToString("yyyy-MM-dd HH:mm:ss")}',{m.fa_count},{m.nca_count},{m.ncl_count},{m.oe_capital_reserve},{m.oe_count},{m.oe_paicl_up_capital},{m.oe_parentcompany_count},{m.accounts_payable},{m.accounts_receivable},{m.advance_received},{m.fixed_assets},{m.fa_interest_receivable},{m.isedit},'{m.lastupdatetime.ToString("yyyy-MM-dd HH:mm:ss")}',{m.lastupdateuserid},'{m.lastupdateusername}',{m.ncl_longterm_loan},{m.ncl_other_liabilities},{m.monetary_fund},{m.oe_minority_equity},{m.oe_surplus_public_accumulation},{m.oe_undistributed_profit},{m.other_accounts_payable},{m.other_accounts_receivable},{m.payable_remuneration},{m.short_term_borrow},{m.prepayment},{m.taxes_payable})";

                cn.Execute(sql);

            }

        }
    }
}
