using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models;
using Bailun.ServiceFabric.Core.Extension;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Microsoft.AspNetCore.Mvc;

namespace Bailun.DC.Web.Areas.Reports.Controllers
{
    /// <summary>
    /// 4千里的财务报表数据
    /// </summary>
    [Area("Reports")]
    public class Finance4KController : Base.BaseController
    {
        #region 月销售利润表

        public ActionResult MonthSaleProfit()
        {
            return View();
        }

        /// <summary>
        /// 月度销售利润统计
        /// </summary>
        /// <param name="start">开始月份</param>
        /// <param name="end">结束月份</param>
        /// <returns></returns>
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【4K月度新销售利润统计】->【查询】页面", 0)]
        public JsonResult ListMonthSaleProfit(string month)
        {
            var _service = new Services.FinanceReportServices();

            try
            {
                var obj = _service.ListMonthSaleProfit_4K(month, "");

                var list = obj;

                var listHead = new List<Tuple<string, string, int>>();
                listHead.Add(new Tuple<string, string, int>("营业收入", "incoming_operating", 1));
                listHead.Add(new Tuple<string, string, int>("SAAS套餐收入", "incoming_operating_saas", 0));
                listHead.Add(new Tuple<string, string, int>("测评收入", "incoming_operating_test", 0));
                listHead.Add(new Tuple<string, string, int>("DSP服务收入", "incoming_operating_dsp", 0));
                listHead.Add(new Tuple<string, string, int>("MH代理收入", "incoming_operating_mh", 0));
                listHead.Add(new Tuple<string, string, int>("代运营收入", "incoming_operating_tp", 0));
                listHead.Add(new Tuple<string, string, int>("粉丝系统服务收入", "incoming_operating_fansservice", 0));
                listHead.Add(new Tuple<string, string, int>("其他收入", "incoming_operating_other", 0));

                listHead.Add(new Tuple<string, string, int>("减：营业成本", "cost_operating", 1));
                listHead.Add(new Tuple<string, string, int>("IT人工成本", "cost_operating_it", 0));
                listHead.Add(new Tuple<string, string, int>("DSP渠道成本", "cost_operating_dspchannel", 0));
                listHead.Add(new Tuple<string, string, int>("DSP签约成本", "cost_operating_dspsign", 0));
                listHead.Add(new Tuple<string, string, int>("代运营成本", "cost_operating_tp", 0));
                listHead.Add(new Tuple<string, string, int>("MH客户成本", "cost_operating_mh", 0));
                listHead.Add(new Tuple<string, string, int>("营业税金及附加", "cost_operating_taxes", 0));


                listHead.Add(new Tuple<string, string, int>("销售费用", "cost_operating_sales", 0));
                listHead.Add(new Tuple<string, string, int>("管理费用", "cost_operating_manager", 0));
                listHead.Add(new Tuple<string, string, int>("财务费用", "cost_operating_finance", 0));
                listHead.Add(new Tuple<string, string, int>("其中：汇兑损益", "cost_operating_exchange", 0));
                listHead.Add(new Tuple<string, string, int>("资产减值损失", "cost_operating_assets_impairment", 0));

                listHead.Add(new Tuple<string, string, int>("加：公允价值变动收益（损失以“-”号填列）", "cost_operating_fair_value_change", 0));
                listHead.Add(new Tuple<string, string, int>("投资收益（损失以“-”号填列）", "cost_operating_investment", 0));
                listHead.Add(new Tuple<string, string, int>("其中:对联营企业和合营企业的投资收益", "cost_operating_investment_in", 0));


                listHead.Add(new Tuple<string, string, int>("营业利润（亏损以“-”号填列） ", "profit_operating", 1));
                listHead.Add(new Tuple<string, string, int>("加：营业外收入", "incoming_out_operating", 0));
                listHead.Add(new Tuple<string, string, int>("减：营业外支出", "cost_out_operating", 0));
                listHead.Add(new Tuple<string, string, int>("其中：非流动资产处置损失", "loss_ondisposal_noncurrent_assets", 0));

                listHead.Add(new Tuple<string, string, int>("利润总额（亏损总额以“-”号填列）", "profit", 1));
                listHead.Add(new Tuple<string, string, int>(" 减：所得税费用", "fee_income_tax", 0));

                listHead.Add(new Tuple<string, string, int>("净利润", "profit_retained", 1));

                var listCount = new List<dc_month_sales_profit_4k>();
                var listMonth = obj.GroupBy(a => a.month);
                foreach (var item in listMonth)
                {
                    var m = new dc_month_sales_profit_4k();
                    m.incoming_operating = item.Sum(a => a.incoming_operating);
                    m.incoming_operating_saas = item.Sum(a => a.incoming_operating_saas);
                    m.incoming_operating_test = item.Sum(a => a.incoming_operating_test);
                    m.incoming_operating_dsp = item.Sum(a => a.incoming_operating_dsp);
                    m.incoming_operating_mh = item.Sum(a => a.incoming_operating_mh);
                    m.incoming_operating_tp = item.Sum(a => a.incoming_operating_tp);
                    m.incoming_operating_fansservice = item.Sum(a => a.incoming_operating_fansservice);
                    m.incoming_operating_other = item.Sum(a => a.incoming_operating_other);

                    m.cost_operating = item.Sum(a => a.cost_operating);
                    m.cost_operating_it = item.Sum(a => a.cost_operating_it);
                    m.cost_operating_dspchannel = item.Sum(a => a.cost_operating_dspchannel);
                    m.cost_operating_dspsign = item.Sum(a => a.cost_operating_dspsign);
                    m.cost_operating_tp = item.Sum(a => a.cost_operating_tp);
                    m.cost_operating_mh = item.Sum(a => a.cost_operating_mh);
                    m.cost_operating_taxes = item.Sum(a => a.cost_operating_taxes);
                    m.cost_operating_sales = item.Sum(a => a.cost_operating_sales);
                    m.cost_operating_manager = item.Sum(a => a.cost_operating_manager);
                    m.cost_operating_finance = item.Sum(a => a.cost_operating_finance);
                    m.cost_operating_exchange = item.Sum(a => a.cost_operating_exchange);
                    m.cost_operating_assets_impairment = item.Sum(a => a.cost_operating_assets_impairment);
                    m.cost_operating_fair_value_change = item.Sum(a => a.cost_operating_fair_value_change);
                    m.cost_operating_investment = item.Sum(a => a.cost_operating_investment);
                    m.cost_operating_investment_in = item.Sum(a => a.cost_operating_investment_in);

                    m.profit_operating = item.Sum(a => a.profit_operating);
                    m.incoming_out_operating = item.Sum(a => a.incoming_out_operating);
                    m.cost_out_operating = item.Sum(a => a.cost_out_operating);
                    m.loss_ondisposal_noncurrent_assets = item.Sum(a => a.loss_ondisposal_noncurrent_assets);
                    m.profit = item.Sum(a => a.profit);
                    m.fee_income_tax = item.Sum(a => a.fee_income_tax);
                    m.profit_retained = item.Sum(a => a.profit_retained);


                    //营业收入=SAAS套餐收入+测评收入+DSP服务收入+MH代理收入+代运营收入+粉丝系统服务收入+其他收入
                    m.incoming_operating = m.incoming_operating_saas + m.incoming_operating_test + m.incoming_operating_dsp + m.incoming_operating_mh + m.incoming_operating_tp + m.incoming_operating_fansservice + m.incoming_operating_other;

                    //营业成本=IT人工成本+DSP渠道成本+DSP签约成本+代运营成本+MH客户成本
                    m.cost_operating = m.cost_operating_it + m.cost_operating_dspchannel + m.cost_operating_dspsign + m.cost_operating_tp + m.cost_operating_mh;

                    //营业利润=营业收入-营业成本-营业税金及附加-销售费用-管理费用-财务费用
                    m.profit_operating = m.incoming_operating - m.cost_operating - m.cost_operating_taxes - m.cost_operating_sales - m.cost_operating_manager - m.cost_operating_finance;

                    //利润总额=营业利润+营业外利润-营业务支出
                    m.profit = m.profit_operating + m.incoming_out_operating - m.cost_out_operating;

                    //净利润=利润总额-所得税费用
                    m.profit_retained = m.profit - m.fee_income_tax;

                    listCount.Add(m);
                }

                var objCount = listCount;

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = list.Where(a => a.isedit == 0).ToList(),
                    listEdit = list.Where(a => a.isedit == 1).ToList(),
                    head = listHead,
                    listCount = objCount
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message
                });
            }
        }

        /// <summary>
        /// 更新编辑项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveMonthSaleProfit(mMonthSaleProfit4K_Input m)
        {
            var user = HttpContextHelper.Current?.User;

            var _service = new Services.FinanceReportServices();

            var result = _service.UpdateMonthSaleProfit_4K(m, user != null ? user.GetUid() : 0, user != null ? user.GetUserName() : "");

            return Json(new
            {
                success = string.IsNullOrEmpty(result),
                msg = result
            });
        }


        #endregion

        #region 资产负债表

        public ActionResult BalanceSheet()
        {
            return View();
        }

        /// <summary>
        /// 资产负债表
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult BalanceSheetJson(DateTime start,DateTime end)
        {
            var _service = new Services.FinanceReportServices();

            try
            {
                var obj = _service.ListBalanceSheet4K(start,end);

                var list = obj;

                var listHead = new List<Tuple<string, string, int>>();
                listHead.Add(new Tuple<string, string, int>("资产", "", 3));
                listHead.Add(new Tuple<string, string, int>("流动资产：", "", 1));
                listHead.Add(new Tuple<string, string, int>("货币资金", "monetary_fund", 0));
                listHead.Add(new Tuple<string, string, int>("应收账款", "accounts_receivable", 0));
                listHead.Add(new Tuple<string, string, int>("预付款项", "prepayment", 0));
                listHead.Add(new Tuple<string, string, int>("应收利息", "fa_interest_receivable", 0));
                listHead.Add(new Tuple<string, string, int>("其他应收款", "other_accounts_receivable", 0));
                listHead.Add(new Tuple<string, string, int>("流动资产合计", "fa_count", 1));

                listHead.Add(new Tuple<string, string, int>("非流动资产", "", 1));
                listHead.Add(new Tuple<string, string, int>("固定资产", "fixed_assets", 0));
                listHead.Add(new Tuple<string, string, int>("非流动资产合计", "nca_count", 1));
                listHead.Add(new Tuple<string, string, int>("资产总计", "count_assets", 1));



                listHead.Add(new Tuple<string, string, int>("负债和所有者权益（或股东权益）", "", 3));
                listHead.Add(new Tuple<string, string, int>("流动负债：", "", 1));
                listHead.Add(new Tuple<string, string, int>("短期借款", "short_term_borrow", 0));
                listHead.Add(new Tuple<string, string, int>("应付账款", "accounts_payable", 0));
                listHead.Add(new Tuple<string, string, int>("预收款项", "advance_received", 0));
                listHead.Add(new Tuple<string, string, int>("应付职工薪酬", "payable_remuneration", 0));
                listHead.Add(new Tuple<string, string, int>("应交税费", "taxes_payable", 0));
                listHead.Add(new Tuple<string, string, int>("应付利息", "cl_payable_interest", 0));
                listHead.Add(new Tuple<string, string, int>("应付股利", "cl_dividends_payable", 0));
                listHead.Add(new Tuple<string, string, int>("其他应付款", "other_accounts_payable", 0));
                listHead.Add(new Tuple<string, string, int>("一年内到期的非流动负债", "cl_oneyear_noncurrent_liabilities", 0));
                listHead.Add(new Tuple<string, string, int>("其他流动负债", "cl_other_liabilities", 0));
                listHead.Add(new Tuple<string, string, int>("流动负债合计", "cl_count", 1));


                listHead.Add(new Tuple<string, string, int>("非流动负债：", "", 1));
                listHead.Add(new Tuple<string, string, int>("长期借款", "ncl_longterm_loan", 0));
                listHead.Add(new Tuple<string, string, int>("其他非流动负债 ", "ncl_other_liabilities", 0));
                listHead.Add(new Tuple<string, string, int>("非流动负债合计", "ncl_count", 1));
                listHead.Add(new Tuple<string, string, int>("负债合计", "count_liabilities", 1));


                listHead.Add(new Tuple<string, string, int>("所有者权益（或股东权益)：", "", 1));
                listHead.Add(new Tuple<string, string, int>("实收资本（或股本）", "oe_paicl_up_capital", 0));
                listHead.Add(new Tuple<string, string, int>("资本公积", "oe_capital_reserve", 0));
                listHead.Add(new Tuple<string, string, int>("盈余公积", "oe_surplus_public_accumulation", 0));
                listHead.Add(new Tuple<string, string, int>("未分配利润", "oe_undistributed_profit", 0));
                listHead.Add(new Tuple<string, string, int>("归属于母公司所有者权益合计", "oe_parentcompany_count", 1));
                listHead.Add(new Tuple<string, string, int>("少数股东权益", "oe_minority_equity", 0));
                listHead.Add(new Tuple<string, string, int>("所有者权益（或股东权益)合计", "oe_count", 1));
                listHead.Add(new Tuple<string, string, int>("负债和所有者权益(或股东权益)总计", "count_liabilities_and_oe", 1));


                var listCount = new List<dc_balance_sheet_4k>();
                var listMonth = obj.GroupBy(a => a.day);
                foreach (var item in listMonth)
                {
                    var m = new dc_balance_sheet_4k();
                    m.day = item.Key;
                    m.monetary_fund = item.Sum(a => a.monetary_fund);
                    m.accounts_receivable = item.Sum(a => a.accounts_receivable);
                    m.prepayment = item.Sum(a => a.prepayment);
                    m.fa_interest_receivable = item.Sum(a => a.fa_interest_receivable);
                    m.other_accounts_receivable = item.Sum(a => a.other_accounts_receivable);
                    m.fa_count = item.Sum(a => a.fa_count);
                    m.fixed_assets = item.Sum(a => a.fixed_assets);
                    m.nca_count = item.Sum(a => a.nca_count);

                    m.count_assets = item.Sum(a => a.count_assets);
                    m.short_term_borrow = item.Sum(a => a.short_term_borrow);
                    m.accounts_payable = item.Sum(a => a.accounts_payable);
                    m.advance_received = item.Sum(a => a.advance_received);
                    m.payable_remuneration = item.Sum(a => a.payable_remuneration);
                    m.taxes_payable = item.Sum(a => a.taxes_payable);
                    m.cl_payable_interest = item.Sum(a => a.cl_payable_interest);
                    m.cl_dividends_payable = item.Sum(a => a.cl_dividends_payable);
                    m.other_accounts_payable = item.Sum(a => a.other_accounts_payable);
                    m.cl_oneyear_noncurrent_liabilities = item.Sum(a => a.cl_oneyear_noncurrent_liabilities);
                    m.cl_other_liabilities = item.Sum(a => a.cl_other_liabilities);
                    m.cl_count = item.Sum(a => a.cl_count);
                    m.ncl_longterm_loan = item.Sum(a => a.ncl_longterm_loan);
                    m.ncl_other_liabilities = item.Sum(a => a.ncl_other_liabilities);
                    m.ncl_count = item.Sum(a => a.ncl_count);

                    m.count_liabilities = item.Sum(a => a.count_liabilities);
                    m.oe_paicl_up_capital = item.Sum(a => a.oe_paicl_up_capital);
                    m.oe_capital_reserve = item.Sum(a => a.oe_capital_reserve);
                    m.oe_surplus_public_accumulation = item.Sum(a => a.oe_surplus_public_accumulation);
                    m.oe_undistributed_profit = item.Sum(a => a.oe_undistributed_profit);
                    m.oe_parentcompany_count = item.Sum(a => a.oe_parentcompany_count);
                    m.oe_count = item.Sum(a => a.oe_count);

                    m.oe_minority_equity = item.Sum(a => a.oe_minority_equity);
                    m.count_liabilities_and_oe = item.Sum(a => a.count_liabilities_and_oe);

                    m.isedit = 2;

                    //流动资产合计=货币资金+应收账款+预付款项+应收利息+其他应收款
                    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;
                    listCount.Add(m);
                }

                var objCount = listCount;

                return Json(new
                {
                    success = true,
                    msg = "",
                    data = list.Where(a => a.isedit == 0).ToList(),
                    listEdit = list.Where(a => a.isedit == 1).ToList(),
                    head = listHead,
                    listCount = objCount
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message
                });
            }
        }


        /// <summary>
        /// 更新编辑项
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveBalanceSheet(mBalanceSheet4K_Input m)
        {
            var user = HttpContextHelper.Current?.User;

            var _service = new Services.FinanceReportServices();

            var result = _service.SaveBalanceSheet4K(m, user != null ? user.GetUid() : 0, user != null ? user.GetUserName() : "");

            return Json(new
            {
                success = string.IsNullOrEmpty(result),
                msg = result
            });
        }


        #endregion
    }
}
