using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models;
using Bailun.DC.Models.Report;
using Bailun.ServiceFabric.Authorize;
using Bailun.ServiceFabric.Core.Extension;
using Bailun.ServiceFabric.Core.Extension.HttpContext;
using Bailun.ServiceFabric.Extension;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

namespace Bailun.DC.Web.Areas.Reports.Controllers
{
    [Area("Reports")]
    public class FinanceController : Base.BaseController
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public FinanceController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        #region 资产负债表

        public IActionResult Index()
        {
            return View();
        }

        public ActionResult Index2()
        {

            return View();
        }

        /// <summary>
        /// 获取资产负债表数据
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【资产负债表】->【查询】页面", 0)]
        public JsonResult IndexJson(int type, int paycompanyvalue, DateTime? day)
        {
            var date = DateTime.Now;

            if (type == 2) //按周
            {
                if(day.HasValue)  //Add by Allan at 20210429，按周也可以选择日期进行查看
                {
                    date = day.Value;
                }
                else
                {
                    date = date.AddDays(-1);
                }


                if (date.DayOfWeek == DayOfWeek.Saturday)
                {
                    date = date.AddDays(-4);
                }
                else if (date.DayOfWeek == DayOfWeek.Sunday)
                {
                    date = date.AddDays(-5);
                }
                else if (date.DayOfWeek == DayOfWeek.Friday)
                {
                    date = date.AddDays(-3);
                }
                else if (date.DayOfWeek == DayOfWeek.Thursday)
                {
                    date = date.AddDays(-2);
                }
                else if (date.DayOfWeek == DayOfWeek.Wednesday)
                {
                    date = date.AddDays(-1);
                }
                else if (date.DayOfWeek == DayOfWeek.Monday)
                {
                    date = date.AddDays(-6);
                }
            }
            else if (type == 3) //按月
            {
                if(day.HasValue)  //Add by Allan at 20210429，for 月份也可选择日期进行查看
                {
                    date = day.Value;
                }

                if (date.AddDays(1).ToString("yyyy-MM") == date.ToString("yyyy-MM"))
                {
                    date = DateTime.Parse(date.ToString("yyyy-MM") + "-01").AddDays(-1);
                }
            }
            else if (type == 1)
            {
                date = day.Value;
            }

            var list = new Services.FinanceReportServices().GetBalanceSheet(type, date, paycompanyvalue);

            foreach (var m in list)
            {
                m.cl_count = m.cl_count ?? 0;
                m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                m.cl_notes_payable = m.cl_notes_payable ?? 0;
                m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                m.cl_payable_interest = m.cl_payable_interest ?? 0;
                m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                m.count_assets = m.count_assets ?? 0;
                m.count_liabilities = m.count_liabilities ?? 0;
                m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                m.fa_count = m.fa_count ?? 0;
                m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                m.fa_other_assets = m.fa_other_assets ?? 0;
                m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                m.nca_count = m.nca_count ?? 0;
                m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                m.nca_engineering_material = m.nca_engineering_material ?? 0;


                m.nca_goodwill = m.nca_goodwill ?? 0;
                m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                m.nca_investment_property = m.nca_investment_property ?? 0;
                m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                m.nca_other_assets = m.nca_other_assets ?? 0;
                m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                m.ncl_count = m.ncl_count ?? 0;
                m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;


                m.ncl_special_payable = m.ncl_special_payable ?? 0;
                m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                m.oe_count = m.oe_count ?? 0;
                m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                m.bank_account_balance = m.bank_account_balance ?? 0;
                m.withdraw_amount = m.withdraw_amount ?? 0;
                m.platform_balance = m.platform_balance ?? 0;
                m.logistics_prepayment = m.logistics_prepayment ?? 0;
                m.finished_prepayment = m.finished_prepayment ?? 0;
                m.semi_prepayment = m.semi_prepayment ?? 0;

                m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                m.semi_transfer_amount = m.semi_transfer_amount ?? 0;
                m.semi_prod_inventory_amount = m.semi_prod_inventory_amount ?? 0;


                m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;


                m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;


                m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                m.semi_accounts_payable = m.semi_accounts_payable ?? 0;


                //m.amount_borrowed = m.amount_borrowed;   //借支金额

                //Add by Allan at 2019-01-30 16:04
                m.prepayment = Math.Abs(m.prepayment);

                //Add by Allan at 20200608, 自产采购在途
                m.purchase_pro_amount = m.purchase_pro_amount ?? 0;

                //流动资产合计
                m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                //非流动资产合计
                m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                //资产总计
                m.count_assets = m.fa_count + m.nca_count;

                //流动负债合计
                m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                //所有者权益（或股东权益）合计
                m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                //负债和所有者权益（或股东权益）总计
                m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;


                //add by Allan at 20200109,for 标识是否周日或者月末
                if (type == 2) //按周
                {
                    if (m.statistical_time.DayOfWeek == DayOfWeek.Tuesday)  //周二
                    {
                        m.ismark = 1;
                    }
                }
                else if (type == 3)  //按月
                {
                    if (m.statistical_time.AddDays(1).ToString("yyyy-MM") != m.statistical_time.ToString("yyyy-MM"))
                    {
                        m.ismark = 2;
                    }
                }
            }


            return Json(new
            {
                success = list.Count > 0,
                msg = list.Count == 0 ? "暂无数据" : "",
                data = list,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportIndex", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        public ActionResult ExportIndex(int type, DateTime? day, int paycompanyvalue)
        {
            var date = DateTime.Now;

            if (type == 2) //按周
            {
                if (day.HasValue)  //Add by Allan at 20210429，按周也可以选择日期进行查看
                {
                    date = day.Value;
                }
                else
                {
                    date = date.AddDays(-1);
                }

                if (date.DayOfWeek == DayOfWeek.Saturday)
                {
                    date = date.AddDays(-4);
                }
                else if (date.DayOfWeek == DayOfWeek.Sunday)
                {
                    date = date.AddDays(-5);
                }
                else if (date.DayOfWeek == DayOfWeek.Friday)
                {
                    date = date.AddDays(-3);
                }
                else if (date.DayOfWeek == DayOfWeek.Thursday)
                {
                    date = date.AddDays(-2);
                }
                else if (date.DayOfWeek == DayOfWeek.Wednesday)
                {
                    date = date.AddDays(-1);
                }
                else if (date.DayOfWeek == DayOfWeek.Monday)
                {
                    date = date.AddDays(-6);
                }
            }
            else if (type == 3) //按月
            {
                if (day.HasValue)  //Add by Allan at 20210429，for 月份也可选择日期进行查看
                {
                    date = day.Value;
                }

                if (date.AddDays(1).ToString("yyyy-MM") == date.ToString("yyyy-MM"))
                {
                    date = DateTime.Parse(date.ToString("yyyy-MM") + "-01").AddDays(-1);
                }
            }

            var list = new Services.FinanceReportServices().GetBalanceSheet(type, date, paycompanyvalue);

            foreach (var m in list)
            {
                m.cl_count = m.cl_count ?? 0;
                m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                m.cl_notes_payable = m.cl_notes_payable ?? 0;
                m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                m.cl_payable_interest = m.cl_payable_interest ?? 0;
                m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                m.count_assets = m.count_assets ?? 0;
                m.count_liabilities = m.count_liabilities ?? 0;
                m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                m.fa_count = m.fa_count ?? 0;
                m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                m.fa_other_assets = m.fa_other_assets ?? 0;
                m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                m.nca_count = m.nca_count ?? 0;
                m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                m.nca_engineering_material = m.nca_engineering_material ?? 0;


                m.nca_goodwill = m.nca_goodwill ?? 0;
                m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                m.nca_investment_property = m.nca_investment_property ?? 0;
                m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                m.nca_other_assets = m.nca_other_assets ?? 0;
                m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                m.ncl_count = m.ncl_count ?? 0;
                m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;


                m.ncl_special_payable = m.ncl_special_payable ?? 0;
                m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                m.oe_count = m.oe_count ?? 0;
                m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                m.bank_account_balance = m.bank_account_balance ?? 0;
                m.withdraw_amount = m.withdraw_amount ?? 0;
                m.platform_balance = m.platform_balance ?? 0;
                m.logistics_prepayment = m.logistics_prepayment ?? 0;
                m.finished_prepayment = -(m.finished_prepayment ?? 0);
                m.semi_prepayment = -(m.semi_prepayment ?? 0);

                m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                m.semi_transfer_amount = m.semi_transfer_amount ?? 0;

                m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;

                m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                m.semi_accounts_payable = m.semi_accounts_payable ?? 0;

                m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;

                m.purchase_pro_amount = m.purchase_pro_amount ?? 0;

                //Add by Allan at 2019-01-30 16:04
                m.prepayment = Math.Abs(m.prepayment);

                //流动资产合计
                m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                //非流动资产合计
                m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                //资产总计
                m.count_assets = m.fa_count + m.nca_count;

                //流动负债合计
                m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                //所有者权益（或股东权益）合计
                m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                //负债和所有者权益（或股东权益）总计
                m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;
            }

            var colNames = new List<string>() { "数值" };
            colNames.AddRange(list.Select(p => p.statistical_time.ToString("yyyy-MM-dd")));

            var listresult = new List<string>();

            for (var i = 0; i < list.Count; i++)
            {
                var m0 = list[i];

                var listProperties = m0.GetType().GetProperties();
                var rowindex = 0;
                for (var o = 0; o < listProperties.Length; o++)
                {
                    var descriptionName = "";
                    var v = (DescriptionAttribute[])listProperties[o].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (v.Length > 0)
                    {
                        descriptionName = v[0].Description;
                    }

                    if (descriptionName == "")
                    {
                        continue;
                    }

                    var value = listProperties[o].GetValue(m0, null).ToString();

                    if (i == 0)  //添加字段名称
                    {
                        listresult.Add(descriptionName);
                    }

                    var temp = listresult[rowindex] + "|" + value;
                    listresult[rowindex] = temp;
                    rowindex++;
                }
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "资产负债表 " + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listresult, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 更新资产负债表
        /// </summary>
        /// <param name="id"></param>
        /// <param name="c">更新字段</param>
        /// <param name="val">值</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult BalanceSheet(int id, string c, decimal val)
        {
            if (id <= 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "id必须大于0。"
                });
            }

            var result = new Services.FinanceReportServices().UpdateBalanceSheet(id, c, val);

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

            });
        }

        /// <summary>
        /// 资产负债表任务启动情况
        /// </summary>
        /// <returns></returns>
        public ActionResult BalanceSheetTask()
        {
            return View();
        }

        /// <summary>
        /// 资产负债表任务可视化数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【资产负债表】->【任务运行情况】->【查询】页面", 0)]
        public JsonResult BalanceSheetTaskJson(DateTime day)
        {
            if (day > DateTime.Now.AddDays(-1))
            {
                return Json(new
                {
                    success = false,
                    msg = "只统计到" + DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") + "的数据"

                });
            }

            var list = new Services.FinanceReportServices().ListBalanceSheetTask(day);

            return Json(new
            {
                success = true,
                msg = "",
                list = list
            });
        }


        /// <summary>
        /// 供应商应付款详情
        /// </summary>
        /// <param name="date">日期</param>
        /// <returns></returns>
        public ActionResult LogisticWaitPayDetail(DateTime date)
        {
            var m = new Services.FinanceReportServices().GetLogisticsWaitPay(date);

            if (m == null)
            {
                m = new dc_daily_lg_waitpay()
                {
                    day = date,
                };
            }

            ViewBag.m = m;

            return View();
        }

        /// <summary>
        /// 更新供应商应付款
        /// </summary>
        /// <param name="id">供应商应付款id</param>
        /// <param name="type">更改类型，1：修改发生调整额，2：修改付款调整额，3：修改发生额</param>
        /// <param name="amount">金额</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult UpdateLogisticWaitPay(int id, int type, decimal amount)
        {
            var user = HttpContextHelper.Current?.User;

            var result = new Services.FinanceReportServices().UpdateLogisticsWaitPay(id, type, amount, (user != null ? user.GetUid() : 0), (user != null ? user.GetUserName() : ""));

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

        /// <summary>
        /// 更新物流供应商的付款额
        /// </summary>
        /// <param name="day">日期</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult UpdateLogisticPayed(DateTime day)
        {
            var _service = new Services.FinanceReportServices();

            var result = "";

            while (day.AddDays(1) < DateTime.Now)
            {
                result += _service.UpdateLogisticPayed(day);
                day = day.AddDays(1);
            }

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

        #endregion


        #region 新资产负债表 at 20201207 -- 需求from唐衍芬

        /// <summary>
        /// 资产负债表（新）
        /// </summary>
        /// <returns></returns>
        public ActionResult BalanceSheetNew()
        {

            return View();
        }


        /// <summary>
        /// 资产负债表（新）
        /// </summary>
        /// <param name="type">统计时间类型，1：日，2：周，3：月</param>
        /// <param name="day">日期</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult BalanceSheetNewJson(int type,DateTime? day, int paycompanyvalue=0)
        {
            #region 注释

            /*
             var _service = new Services.BalanceSheetServices();

            //基础和编辑的合并数据
            var list = _service.ListBalanceSheetNew(type, start,end, paycompanyvalue,1);
            FormatBalanceSheet(list,type);


            //编辑的数据
            var listEdit = _service.ListBalanceSheetNew(type, start,end, paycompanyvalue,2);
            FormatBalanceSheet(listEdit,type);

            //原始数据
            var listBase = _service.ListBalanceSheetNew(type, start,end, paycompanyvalue, 0);
            FormatBalanceSheet(listBase,type);


            var listHead = new List<Tuple<string, string, int>>();

            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>("其他应收款", "other_accounts_receivable", 0));
            listHead.Add(new Tuple<string, string, int>("存货", "inventory_amount", 0));
            listHead.Add(new Tuple<string, string, int>("其他流动资产", "fa_other_assets", 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>("长期股权投资", "nca_longterm_equity_investment", 0));
            listHead.Add(new Tuple<string, string, int>("固定资产", "fixed_assets", 0));
            listHead.Add(new Tuple<string, string, int>("无形资产", "nca_intangible_assets", 0));
            listHead.Add(new Tuple<string, string, int>("长期待摊费用", "nca_longterm_unamortized_expenses", 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>("流动负债：", "", 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>("应付利息", "fa_interest_receivable", 0));
            listHead.Add(new Tuple<string, string, int>("应付股利", "fa_dividends_receivable", 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_anticipation_liabilities", 0));
            listHead.Add(new Tuple<string, string, int>("递延所得税负债", "ncl_deferred_income_tax_liabilities", 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_count", 1));
            listHead.Add(new Tuple<string, string, int>("负债及股东权益合计", "count_liabilities_and_oe", 1));

            var listCount = new List<dc_balance_sheet_new_result>();
            foreach(var item in listBase)
            {
                var objEdit = listEdit.Where(a => a.statistical_time == item.statistical_time && a.company_value == item.company_value).FirstOrDefault();
                if(objEdit==null)
                {
                    listCount.Add(item);
                }
                else
                {
                    var m = new dc_balance_sheet_new_result {
                        monetary_fund = item.monetary_fund+objEdit.monetary_fund,
                        accounts_receivable = item.accounts_receivable + objEdit.accounts_receivable,
                        prepayment = item.prepayment + objEdit.prepayment,
                        other_accounts_receivable = item.other_accounts_receivable + objEdit.other_accounts_receivable,
                        inventory_amount = item.inventory_amount + objEdit.inventory_amount,
                        fa_other_assets = item.fa_other_assets + objEdit.fa_other_assets,
                        fa_count = item.fa_count + objEdit.fa_count,

                        nca_longterm_equity_investment = item.nca_longterm_equity_investment + objEdit.nca_longterm_equity_investment,
                        fixed_assets= item.fixed_assets + objEdit.fixed_assets,
                        nca_intangible_assets = item.nca_intangible_assets + objEdit.nca_intangible_assets,
                        nca_longterm_unamortized_expenses = item.nca_longterm_unamortized_expenses + objEdit.nca_longterm_unamortized_expenses,
                        nca_count = item.nca_count + objEdit.nca_count,

                        count_assets = item.count_assets + objEdit.count_assets,

                        short_term_borrow = item.short_term_borrow + objEdit.short_term_borrow,
                        accounts_payable = item.accounts_payable + objEdit.accounts_payable,
                        advance_received = item.advance_received + objEdit.advance_received,
                        payable_remuneration = item.payable_remuneration + objEdit.payable_remuneration,
                        taxes_payable = item.taxes_payable + objEdit.taxes_payable,
                        fa_interest_receivable = item.fa_interest_receivable + objEdit.fa_interest_receivable,
                        fa_dividends_receivable = item.fa_dividends_receivable + objEdit.fa_dividends_receivable,
                        other_accounts_payable = item.other_accounts_payable + objEdit.other_accounts_payable,
                        cl_oneyear_noncurrent_liabilities = item.cl_oneyear_noncurrent_liabilities + objEdit.cl_oneyear_noncurrent_liabilities,
                        cl_other_liabilities = item.cl_other_liabilities + objEdit.cl_other_liabilities,
                        cl_count = item.cl_count + objEdit.cl_count,

                        ncl_longterm_loan = item.ncl_longterm_loan + objEdit.ncl_longterm_loan,
                        ncl_anticipation_liabilities = item.ncl_anticipation_liabilities + objEdit.ncl_anticipation_liabilities,
                        ncl_deferred_income_tax_liabilities = item.ncl_deferred_income_tax_liabilities + objEdit.ncl_deferred_income_tax_liabilities,
                        ncl_other_liabilities = item.ncl_other_liabilities + objEdit.ncl_other_liabilities,
                        ncl_count = item.ncl_count + objEdit.ncl_count,
                        count_liabilities = item.count_liabilities + objEdit.count_liabilities,

                        oe_paicl_up_capital = item.oe_paicl_up_capital + objEdit.oe_paicl_up_capital,
                        oe_capital_reserve = item.oe_capital_reserve + objEdit.oe_capital_reserve,
                        oe_surplus_public_accumulation = item.oe_surplus_public_accumulation + objEdit.oe_surplus_public_accumulation,
                        oe_undistributed_profit = item.oe_undistributed_profit + objEdit.oe_undistributed_profit,
                        oe_count = item.oe_count + objEdit.oe_count,
                        count_liabilities_and_oe = item.count_liabilities_and_oe + objEdit.count_liabilities_and_oe,

                        statistical_time = item.statistical_time,
                        company_name = item.company_name,
                        company_value = item.company_value

                    };

                    listCount.Add(m);
                    
                }
            }

            return Json(new
            {
                success = list.Count > 0,
                msg = listBase.Count == 0 ? "暂无数据" : "",
                data = listBase,
                listEdit = listEdit,
                listCount = listCount ,//list,
                head = listHead,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportIndex", HttpContextHelper.Current.User.GetUserName()),
            });
             */

            #endregion

            var date = DateTime.Now;

            if (type == 2) //按周
            {
                date = date.AddDays(-1);

                if (date.DayOfWeek == DayOfWeek.Saturday)
                {
                    date = date.AddDays(-4);
                }
                else if (date.DayOfWeek == DayOfWeek.Sunday)
                {
                    date = date.AddDays(-5);
                }
                else if (date.DayOfWeek == DayOfWeek.Friday)
                {
                    date = date.AddDays(-3);
                }
                else if (date.DayOfWeek == DayOfWeek.Thursday)
                {
                    date = date.AddDays(-2);
                }
                else if (date.DayOfWeek == DayOfWeek.Wednesday)
                {
                    date = date.AddDays(-1);
                }
                else if (date.DayOfWeek == DayOfWeek.Monday)
                {
                    date = date.AddDays(-6);
                }
            }
            else if (type == 3) //按月
            {
                if (date.AddDays(1).ToString("yyyy-MM") == date.ToString("yyyy-MM"))
                {
                    date = DateTime.Parse(date.ToString("yyyy-MM") + "-01").AddDays(-1);
                }
            }
            else if (type == 1)
            {
                date = day.Value;
            }

            var list = new Services.BalanceSheetServices().GetBalanceSheetNew(type, date, paycompanyvalue);

            foreach (var m in list)
            {
                m.cl_count = m.cl_count ?? 0;
                m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                m.cl_notes_payable = m.cl_notes_payable ?? 0;
                m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                m.cl_payable_interest = m.cl_payable_interest ?? 0;
                m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                m.count_assets = m.count_assets ?? 0;
                m.count_liabilities = m.count_liabilities ?? 0;
                m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                m.fa_count = m.fa_count ?? 0;
                m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                m.fa_other_assets = m.fa_other_assets ?? 0;
                m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                m.nca_count = m.nca_count ?? 0;
                m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                m.nca_engineering_material = m.nca_engineering_material ?? 0;


                m.nca_goodwill = m.nca_goodwill ?? 0;
                m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                m.nca_investment_property = m.nca_investment_property ?? 0;
                m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                m.nca_other_assets = m.nca_other_assets ?? 0;
                m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                m.ncl_count = m.ncl_count ?? 0;
                m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;


                m.ncl_special_payable = m.ncl_special_payable ?? 0;
                m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                m.oe_count = m.oe_count ?? 0;
                m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                m.bank_account_balance = m.bank_account_balance ?? 0;
                m.withdraw_amount = m.withdraw_amount ?? 0;
                m.platform_balance = m.platform_balance ?? 0;
                m.logistics_prepayment = m.logistics_prepayment ?? 0;
                m.finished_prepayment = m.finished_prepayment ?? 0;
                m.semi_prepayment = m.semi_prepayment ?? 0;

                m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                m.semi_transfer_amount = m.semi_transfer_amount ?? 0;
                m.semi_prod_inventory_amount = m.semi_prod_inventory_amount ?? 0;


                m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;


                m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;


                m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                m.semi_accounts_payable = m.semi_accounts_payable ?? 0;

                //Add by Allan at 20210410
                m.accounts_receivable_update = m.accounts_receivable_update ?? 0;
                m.accounts_receivable_import = m.accounts_receivable_import ?? 0;
                m.other_accounts_receivable_import = m.other_accounts_receivable_import ?? 0;
                m.other_accounts_payable_import = m.other_accounts_payable_import ?? 0;
                m.fixed_assets_import = m.fixed_assets_import ?? 0;
                m.nca_deferred_tax_assets_import = m.nca_deferred_tax_assets_import ?? 0;
                m.not_fba_hc_inventory_amount = m.not_fba_hc_inventory_amount ?? 0;


                //m.amount_borrowed = m.amount_borrowed;   //借支金额

                //Add by Allan at 2019-01-30 16:04
                m.prepayment = Math.Abs(m.prepayment??0);

                //Add by Allan at 20200608, 自产采购在途
                m.purchase_pro_amount = m.purchase_pro_amount ?? 0;

                //流动资产合计
                m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                //非流动资产合计
                m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                //资产总计
                m.count_assets = m.fa_count + m.nca_count;

                //流动负债合计
                m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                //所有者权益（或股东权益）合计
                m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                //负债和所有者权益（或股东权益）总计
                m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;


                //add by Allan at 20200109,for 标识是否周日或者月末
                if (type == 2) //按周
                {
                    if (m.statistical_time.DayOfWeek == DayOfWeek.Tuesday)  //周二
                    {
                        m.ismark = 1;
                    }
                }
                else if (type == 3)  //按月
                {
                    if (m.statistical_time.AddDays(1).ToString("yyyy-MM") != m.statistical_time.ToString("yyyy-MM"))
                    {
                        m.ismark = 2;
                    }
                }
            }


            return Json(new
            {
                success = list.Count > 0,
                msg = list.Count == 0 ? "暂无数据" : "",
                data = list,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportIndex", HttpContextHelper.Current.User.GetUserName()),
            });

        }

        public ActionResult ExportBalanceSheetNew(int type, DateTime? day, int paycompanyvalue)
        {
            var date = DateTime.Now;

            if (type == 2) //按周
            {
                if (date.DayOfWeek == DayOfWeek.Saturday)
                {
                    date = date.AddDays(-1);
                }
                else if (date.DayOfWeek == DayOfWeek.Sunday)
                {
                    date = date.AddDays(-2);
                }
                else
                {
                    date = date.AddDays(-2 - (int)date.DayOfWeek);
                }
            }
            else if (type == 3) //按月
            {
                if (date.AddDays(1).ToString("yyyy-MM") == date.ToString("yyyy-MM"))
                {
                    date = DateTime.Parse(date.ToString("yyyy-MM") + "-01").AddDays(-1);
                }
            }

            var list = new Services.BalanceSheetServices().GetBalanceSheetNew(type, date, paycompanyvalue);

            foreach (var m in list)
            {
                m.cl_count = m.cl_count ?? 0;
                m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                m.cl_notes_payable = m.cl_notes_payable ?? 0;
                m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                m.cl_payable_interest = m.cl_payable_interest ?? 0;
                m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                m.count_assets = m.count_assets ?? 0;
                m.count_liabilities = m.count_liabilities ?? 0;
                m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                m.fa_count = m.fa_count ?? 0;
                m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                m.fa_other_assets = m.fa_other_assets ?? 0;
                m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                m.nca_count = m.nca_count ?? 0;
                m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                m.nca_engineering_material = m.nca_engineering_material ?? 0;


                m.nca_goodwill = m.nca_goodwill ?? 0;
                m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                m.nca_investment_property = m.nca_investment_property ?? 0;
                m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                m.nca_other_assets = m.nca_other_assets ?? 0;
                m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                m.ncl_count = m.ncl_count ?? 0;
                m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;


                m.ncl_special_payable = m.ncl_special_payable ?? 0;
                m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                m.oe_count = m.oe_count ?? 0;
                m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                m.bank_account_balance = m.bank_account_balance ?? 0;
                m.withdraw_amount = m.withdraw_amount ?? 0;
                m.platform_balance = m.platform_balance ?? 0;
                m.logistics_prepayment = m.logistics_prepayment ?? 0;
                m.finished_prepayment = -(m.finished_prepayment ?? 0);
                m.semi_prepayment = -(m.semi_prepayment ?? 0);

                m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                m.semi_transfer_amount = m.semi_transfer_amount ?? 0;

                m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;

                m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                m.semi_accounts_payable = m.semi_accounts_payable ?? 0;

                m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;

                m.purchase_pro_amount = m.purchase_pro_amount ?? 0;

                //Add by Allan at 20210410
                m.accounts_receivable_update = m.accounts_receivable_update ?? 0;
                m.accounts_receivable_import = m.accounts_receivable_import ?? 0;
                m.other_accounts_receivable_import = m.other_accounts_receivable_import ?? 0;
                m.other_accounts_payable_import = m.other_accounts_payable_import ?? 0;
                m.fixed_assets_import = m.fixed_assets_import ?? 0;
                m.nca_deferred_tax_assets_import = m.nca_deferred_tax_assets_import ?? 0;
                m.not_fba_hc_inventory_amount = m.not_fba_hc_inventory_amount ?? 0;


                //Add by Allan at 2019-01-30 16:04
                m.prepayment = Math.Abs(m.prepayment??0);

                //流动资产合计
                m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                //非流动资产合计
                m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                //资产总计
                m.count_assets = m.fa_count + m.nca_count;

                //流动负债合计
                m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                //所有者权益（或股东权益）合计
                m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                //负债和所有者权益（或股东权益）总计
                m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;
            }

            var colNames = new List<string>() { "数值" };
            colNames.AddRange(list.Select(p => p.statistical_time.ToString("yyyy-MM-dd")));

            var listresult = new List<string>();

            for (var i = 0; i < list.Count; i++)
            {
                var m0 = list[i];

                var listProperties = m0.GetType().GetProperties();
                var rowindex = 0;
                for (var o = 0; o < listProperties.Length; o++)
                {
                    var descriptionName = "";
                    var v = (DescriptionAttribute[])listProperties[o].GetCustomAttributes(typeof(DescriptionAttribute), false);
                    if (v.Length > 0)
                    {
                        descriptionName = v[0].Description;
                    }

                    if (descriptionName == "")
                    {
                        continue;
                    }

                    var value = listProperties[o].GetValue(m0, null).ToString();

                    if (i == 0)  //添加字段名称
                    {
                        listresult.Add(descriptionName);
                    }

                    var temp = listresult[rowindex] + "|" + value;
                    listresult[rowindex] = temp;
                    rowindex++;
                }
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "资产负债表 " + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listresult, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        private void FormatBalanceSheet(List<dc_balance_sheet_new_result> list,int type)
        {
            foreach (var m in list)
            {
                m.cl_count = m.cl_count ?? 0;
                m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                m.cl_notes_payable = m.cl_notes_payable ?? 0;
                m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                m.cl_payable_interest = m.cl_payable_interest ?? 0;
                m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                m.count_assets = m.count_assets ?? 0;
                m.count_liabilities = m.count_liabilities ?? 0;
                m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                m.fa_count = m.fa_count ?? 0;
                m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                m.fa_other_assets = m.fa_other_assets ?? 0;
                m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                m.nca_count = m.nca_count ?? 0;
                m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                m.nca_engineering_material = m.nca_engineering_material ?? 0;


                m.nca_goodwill = m.nca_goodwill ?? 0;
                m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                m.nca_investment_property = m.nca_investment_property ?? 0;
                m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                m.nca_other_assets = m.nca_other_assets ?? 0;
                m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                m.ncl_count = m.ncl_count ?? 0;
                m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;


                m.ncl_special_payable = m.ncl_special_payable ?? 0;
                m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                m.oe_count = m.oe_count ?? 0;
                m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                m.bank_account_balance = m.bank_account_balance ?? 0;
                m.withdraw_amount = m.withdraw_amount ?? 0;
                m.platform_balance = m.platform_balance ?? 0;
                m.logistics_prepayment = m.logistics_prepayment ?? 0;
                m.finished_prepayment = m.finished_prepayment ?? 0;
                m.semi_prepayment = m.semi_prepayment ?? 0;

                m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                m.semi_transfer_amount = m.semi_transfer_amount ?? 0;
                m.semi_prod_inventory_amount = m.semi_prod_inventory_amount ?? 0;


                m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;


                m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;


                m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                m.semi_accounts_payable = m.semi_accounts_payable ?? 0;


                //m.amount_borrowed = m.amount_borrowed;   //借支金额

                //Add by Allan at 2019-01-30 16:04
                m.prepayment = Math.Abs(m.prepayment ?? 0);

                //Add by Allan at 20200608, 自产采购在途
                m.purchase_pro_amount = m.purchase_pro_amount ?? 0;

                //流动资产合计
                m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                //非流动资产合计
                m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                //资产总计
                m.count_assets = m.fa_count + m.nca_count;

                //流动负债合计
                m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                //所有者权益（或股东权益）合计
                m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                //负债和所有者权益（或股东权益）总计
                m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;


                //add by Allan at 20200109,for 标识是否周日或者月末
                if (type == 2) //按周
                {
                    if (m.statistical_time.DayOfWeek == DayOfWeek.Tuesday)  //周二
                    {
                        m.ismark = 1;
                    }
                }
                else if (type == 3)  //按月
                {
                    if (m.statistical_time.AddDays(1).ToString("yyyy-MM") != m.statistical_time.ToString("yyyy-MM"))
                    {
                        m.ismark = 2;
                    }
                }
            }
        }


        #endregion


        /// <summary>
        /// 管理成本报表页面
        /// </summary>
        /// <returns></returns>
        public IActionResult AdministrativeCost()
        {
            var lastmonth = DateTime.Now;
            var day = DateTime.Now;

            var start = DateTime.Parse(lastmonth.Year + "-" + lastmonth.Month + "-01");
            var end = start.AddMonths(1).AddDays(-1);

            ViewBag.start = start;
            ViewBag.end = end;

            return View();
        }

        /// <summary>
        /// 管理成本报表数据
        /// </summary>
        /// <param name="t"></param>
        /// <param name="PayName"></param>
        /// <param name="ismanager">是否管理成本</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【管理成本报表】->【查询】页面", 0)]
        public JsonResult AdministrativeCostJson(int t, DateTime start,DateTime end,int? paycompanyid,int? ismanager)
        {
            var url = ConfigHelper.GetByName("FeeUrl")+"?o=0";
            var cwurl = ConfigHelper.GetByName("cwUrl") + "?";
            
            url += "&startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");
            cwurl += "BeginRepayTime="+start.ToString("yyyy-MM-dd")+ "&EndRepayTime="+end.ToString("yyyy-MM-dd");

            if (paycompanyid.HasValue)
            {
                url += "&companyValue=" + paycompanyid.Value;
                cwurl += "&CompanyVal=" + paycompanyid.Value;
            }


            //利息支出
            var listInterest = new Services.FinanceReportServices().ListInterestExpense(cwurl);

            //Edit by Allan at 20191217 for 更改数据源
            //var list = new Services.FinanceReportServices().ListFinanceManageCost(start,end,"","","",paycompanyid); //new Services.FinanceReportServices().ListOtherCost(url);  

            var list = new Services.FinanceReportServices().ListFinanceFee(start,end,"","","",paycompanyid,ismanager);

            //手续费  Add by Allan at 20200514
            var listHandleFee = new Services.FinanceReportServices().ListFinanceHandleFee(start, end, paycompanyid,"");

            var listValue = new List<Tuple<string, List<decimal>>>();
            var listCol = new List<string>();
            var listColVal = new List<int>();

            if (list.Count > 0)
            {
                //var list4K = new List<int>() { 72, 67, 58, 54, 78 };
                if (t == 2)  //按付款主体
                {
                    listCol = list.GroupBy(a => a.company_name).Select(p => p.Key).OrderBy(a=>a).ToList();

                    //对四千里主体的数据进行合并处理，四千里的主体包括：香港四千里数据科技有限公司(72),深圳市四千里数据科技有限公司(67),4Kmiles tec Limited(58),广州四千里数据科技有限公司(54)
                    
                    //if (list.Where(a => list4K.Contains(a.company_value)).Count() > 0)
                    //{
                    //    listCol.Remove("香港四千里数据科技有限公司");
                    //    listCol.Remove("深圳市四千里数据科技有限公司");
                    //    listCol.Remove("4Kmiles tec Limited");
                    //    listCol.Remove("广州四千里数据科技有限公司");
                    //    listCol.Remove("（英国）4kmiles technologies ltd");

                    //    listCol.Add("四千里主体");
                    //}
                }
                else  //按部门
                {
                    listCol = list.GroupBy(a => a.department_name).Select(p => p.Key).ToList();
                }

                for (var i=0;i< listCol.Count;i++)
                {
                    foreach (var item in list)
                    {
                        if (t == 2)  //按付款主体
                        {
                            if (item.company_name == listCol[i])
                            {
                                var obj = listValue.Where(a => a.Item1 == item.type_name).FirstOrDefault();

                                if (obj == null)
                                {
                                    var listItems = new List<decimal>();
                                    while (listItems.Count < listCol.Count)
                                    {
                                        listItems.Add(0.00M);
                                    }

                                    listItems[i] = item.amount_rmb??0;
                                    listValue.Add(new Tuple<string, List<decimal>>(item.type_name, listItems));
                                }
                                else
                                {
                                    obj.Item2[i] += item.amount_rmb??0;
                                }
                            }
                        }
                        else
                        {
                            if (item.department_name == listCol[i])
                            {
                                var obj = listValue.Where(a => a.Item1 == item.type_name).FirstOrDefault();

                                if (obj == null)
                                {
                                    var listItems = new List<decimal>();
                                    while (listItems.Count < listCol.Count)
                                    {
                                        listItems.Add(0.00M);
                                    }

                                    listItems[i] = item.amount_rmb??0;
                                    listValue.Add(new Tuple<string, List<decimal>>(item.type_name, listItems));
                                }
                                else
                                {
                                    obj.Item2[i] += item.amount_rmb??0;
                                }
                            }
                        }
                    }
                }

                var listCount = new List<decimal>();

                //利息支出
                if (listInterest.Count > 0)
                {
                    var obj = listValue.Where(a => a.Item1 == "利息支出").FirstOrDefault();
                    var index_Interest = -1;


                    if (t == 2)  //按付款主体
                    {
                        var gogirlindex = -1; //广州歌戈儿生活科技有限公司
                        var gogirlindexarr = new List<int>();   //广州歌戈儿 相关付款主体
                        var clothindex = -1;
                        for (var i = 0; i<listCol.Count; i++)
                        {
                            if (listCol[i] == "广州电子服装仓")
                            {
                                clothindex = i;
                            }

                            if (listCol[i] == "广州百伦供应链科技有限公司")
                            {
                                index_Interest = i;
                            }

                            if (listCol[i] == "广州歌戈儿生活科技有限公司")
                            {
                                gogirlindex = i;
                            }
                            else if (listCol[i].Contains("歌戈儿"))
                            {
                                gogirlindexarr.Add(i);
                            }
                        }

                        //广州电子服装仓
                        var clothVal = 0.00M;
                        var objCloth = listInterest.Where(a => a.CompanyVal != 1);
                        if (objCloth.Count() > 0)
                        {
                            clothVal = objCloth.Sum(a => a.RepayInterestRMB);
                        }

                        //广州百伦
                        var gzblVal = 0.00M;
                        var objGZBL = listInterest.Where(a => a.CompanyVal == 1);
                        if (objGZBL.Count() > 0)
                        {
                            gzblVal = objGZBL.Sum(a => a.RepayInterestRMB);
                        }

                        if (clothVal > 0 && clothindex == -1)
                        {
                            listCol.Add("广州电子服装仓");
                            clothindex = listCol.Count - 1;

                            foreach (var item in listValue)
                            {
                                item.Item2.Add(0);
                            }

                        }
                        if(gzblVal>0 && index_Interest==-1)
                        {
                            listCol.Add("广州百伦供应链科技有限公司");
                            index_Interest = listCol.Count - 1;

                            foreach (var item in listValue)
                            {
                                item.Item2.Add(0);
                            }
                        }

                        if (obj == null)
                        {
                            var _list = new List<decimal>();
                            for (var j = 0; j < listCol.Count; j++)
                            {
                                if (j == clothindex)
                                {
                                    _list.Add(clothVal);
                                }
                                else if (j == index_Interest)
                                {
                                    _list.Add(gzblVal);
                                }
                                else
                                {
                                    _list.Add(0);
                                }
                            }

                            listValue.Add(new Tuple<string, List<decimal>>("利息支出", _list));
                        }
                        else
                        {
                            obj.Item2[clothindex] = clothVal;
                            obj.Item2[index_Interest] = gzblVal;
                        }

                        //Add by Allan at 201907091500
                        //合并广州歌戈儿相关付款主体到 广州歌戈儿生活科技有限公司
                        if (gogirlindexarr.Count > 0)
                        {
                            //降序排序，方便下面的删除操作，从数据后面开始删除
                            gogirlindexarr = gogirlindexarr.OrderByDescending(a => a).ToList();

                            if (gogirlindex > -1)
                            {
                                //附加数据到 广州歌戈儿生活科技有限公司
                                foreach (var item in listValue)
                                {
                                    foreach (var index in gogirlindexarr)
                                    {
                                        item.Item2[gogirlindex] += item.Item2[index];
                                    }
                                }

                                //按索引删除 值集合里面的值
                                foreach (var item in listValue)
                                {
                                    foreach (var index in gogirlindexarr)
                                    {
                                        item.Item2.RemoveAt(index);
                                    }
                                }

                                //按索引删除 列头
                                foreach (var index in gogirlindexarr)
                                {
                                    listCol.RemoveAt(index);
                                }
                            }
                            else
                            {
                                listCol.Add("广州歌戈儿生活科技有限公司");

                                //增加一列
                                foreach (var item in listValue)
                                {
                                    item.Item2.Add(0);
                                }

                                foreach (var index in gogirlindexarr)
                                {
                                    foreach (var item in listValue)
                                    {
                                        item.Item2[item.Item2.Count-1]+=item.Item2[index];
                                    }
                                }

                                //按索引删除 值集合里面的值
                                foreach (var item in listValue)
                                {
                                    foreach (var index in gogirlindexarr)
                                    {
                                        item.Item2.RemoveAt(index);
                                    }
                                }

                                //按索引删除 列头
                                foreach (var index in gogirlindexarr)
                                {
                                    listCol.RemoveAt(index);
                                }
                            }
                        }
                        //End Add
                    }
                    else  //按部门
                    {
                        for (var i = 0; i < listCol.Count; i++)
                        {
                            if (listCol[i] == "财务部")
                            {
                                index_Interest = i;
                            }
                        }

                        var val = listInterest.Sum(a => a.RepayInterestRMB);

                        if (index_Interest == -1 && val > 0)
                        {
                            listCol.Add("财务部");
                            index_Interest = listCol.Count - 1;

                            foreach (var item in listValue)
                            {
                                item.Item2.Add(0);
                            }
                        }

                        if (obj == null)
                        {
                            var _list = new List<decimal>();
                            for (var j = 0; j < listCol.Count; j++)
                            {

                                if (j == index_Interest)
                                {
                                    _list.Add(val);
                                }
                                else
                                {
                                    _list.Add(0);
                                }
                            }

                            listValue.Add(new Tuple<string, List<decimal>>("利息支出", _list));
                        }
                        else
                        {
                            obj.Item2[index_Interest] = val;
                        }
                    }
                }

                
                //手续费支出
                if (listHandleFee.Count > 0)
                {
                    var obj = listValue.Where(a => a.Item1 == "手续费支出").FirstOrDefault();

                    if (obj == null)
                    {
                        var _list = new List<decimal>();
                        for (var j = 0; j < listCol.Count; j++)
                        {
                            _list.Add(0);
                        }

                        listValue.Add(new Tuple<string, List<decimal>>("手续费支出", _list));

                        obj = listValue.Where(a => a.Item1 == "手续费支出").FirstOrDefault();
                    }

                    if (t == 2)  //按付款主体
                    {
                        var gogirlindex_h = -1; //广州歌戈儿生活科技有限公司
                        var gogirlindexarr_h = new List<int>();   //广州歌戈儿 相关付款主体
                        for (var i = 0; i < listCol.Count; i++)
                        {

                            var objHandleFee = new decimal(0);
                            
                            if (listCol[i].Contains("歌戈儿"))
                            {
                                objHandleFee = listHandleFee.Where(a => a.subject_name_from.Contains("歌戈儿"))?.Sum(a => a.pay_money_rMB) ?? 0;
                            }
                            else
                            {
                                objHandleFee = listHandleFee.Where(a => a.subject_name_from == listCol[i])?.Sum(a => a.pay_money_rMB) ?? 0;
                            }

                            obj.Item2[i] += objHandleFee;
                        }
                        
                        
                        //Add by Allan at 201907091500
                        //合并广州歌戈儿相关付款主体到 广州歌戈儿生活科技有限公司
                        if (gogirlindexarr_h.Count > 0)
                        {
                            //降序排序，方便下面的删除操作，从数据后面开始删除
                            gogirlindexarr_h = gogirlindexarr_h.OrderByDescending(a => a).ToList();

                            if (gogirlindex_h > -1)
                            {
                                //附加数据到 广州歌戈儿生活科技有限公司
                                foreach (var item in listValue)
                                {
                                    foreach (var index in gogirlindexarr_h)
                                    {
                                        item.Item2[gogirlindex_h] += item.Item2[index];
                                    }
                                }

                                //按索引删除 值集合里面的值
                                foreach (var item in listValue)
                                {
                                    foreach (var index in gogirlindexarr_h)
                                    {
                                        item.Item2.RemoveAt(index);
                                    }
                                }

                                //按索引删除 列头
                                foreach (var index in gogirlindexarr_h)
                                {
                                    listCol.RemoveAt(index);
                                }
                            }
                            else
                            {
                                listCol.Add("广州歌戈儿生活科技有限公司");

                                //增加一列
                                foreach (var item in listValue)
                                {
                                    item.Item2.Add(0);
                                }

                                foreach (var index in gogirlindexarr_h)
                                {
                                    foreach (var item in listValue)
                                    {
                                        item.Item2[item.Item2.Count - 1] += item.Item2[index];
                                    }
                                }

                                //按索引删除 值集合里面的值
                                foreach (var item in listValue)
                                {
                                    foreach (var index in gogirlindexarr_h)
                                    {
                                        item.Item2.RemoveAt(index);
                                    }
                                }

                                //按索引删除 列头
                                foreach (var index in gogirlindexarr_h)
                                {
                                    listCol.RemoveAt(index);
                                }
                            }
                        }
                        //End Add
                        

                    }
                    else  //按部门
                    {
                        var index_Interest_h = 0;

                        for (var i = 0; i < listCol.Count; i++)
                        {
                            if (listCol[i] == "财务部")
                            {
                                index_Interest_h = i;
                            }
                        }

                        var val = listHandleFee.Sum(a => a.pay_money_rMB);

                        if (index_Interest_h == -1 && val > 0)
                        {
                            listCol.Add("财务部");
                            index_Interest_h = listCol.Count - 1;

                            foreach (var item in listValue)
                            {
                                item.Item2.Add(0);
                            }
                        }

                        if (obj == null)
                        {
                            var _list = new List<decimal>();
                            for (var j = 0; j < listCol.Count; j++)
                            {

                                if (j == index_Interest_h)
                                {
                                    _list.Add(val);
                                }
                                else
                                {
                                    _list.Add(0);
                                }
                            }

                            listValue.Add(new Tuple<string, List<decimal>>("手续费支出", _list));
                        }
                        else
                        {
                            obj.Item2[index_Interest_h] = val;
                        }
                    }
                }

                foreach (var item in listValue)
                {
                    for (var i = 0; i < item.Item2.Count; i++)
                    {
                        var v = item.Item2[i];

                        item.Item2[i] = Math.Round(v, 2);

                        if (listCount.Count() > i)
                        {
                            listCount[i] += item.Item2[i];
                        }
                        else
                        {
                            listCount.Add(item.Item2[i]);
                        }
                    }

                    item.Item2.Add(item.Item2.Sum());
                }
                listValue.Add(new Tuple<string, List<decimal>>("总计", listCount));
            }
            
            return Json(new {
                success = list.Count>0,
                msg = list.Count>0?"":"成本接口返回了空记录。",
                col = listCol,
                list = listValue,
                amount = Math.Round(list.Sum(a=>a.amount_rmb??0)+ listInterest.Sum(a=>a.RepayInterestRMB)+ listHandleFee.Sum(a => a.pay_money_rMB), 2),
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportListInterestExpense", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        [HttpPost]
        public JsonResult AdministrativeCostChildrenJson(int t, DateTime start, DateTime end, int? paycompanyid, string categoryname, string heads)
        {
            var url = ConfigHelper.GetByName("FeeUrl") + "?o=0";

            url += "&startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");

            if (paycompanyid.HasValue)
            {
                url += "&companyValue=" + paycompanyid.Value;
            }

            if (!string.IsNullOrEmpty(categoryname))
            {
                url += "&feeSuperType=" + categoryname;
            }

            var list = new Services.FinanceReportServices().ListFinanceManageCost(start, end, categoryname,"","", paycompanyid);//new Services.FinanceReportServices().ListOtherCost(url);
            var listValue = new List<Tuple<string, List<decimal>>>();
            var listCol = heads.Split("|").ToList();

            if (list.Count > 0)
            {
                
                for (var i = 0; i < listCol.Count; i++)
                {
                    foreach (var item in list)
                    {
                        if (t == 2)  //按付款主体
                        {
                            if (item.company_name == listCol[i])
                            {
                                var obj = listValue.Where(a => a.Item1 == item.fee_sub_type).FirstOrDefault();

                                if (obj == null)
                                {
                                    var listItems = new List<decimal>();
                                    while (listItems.Count < listCol.Count)
                                    {
                                        listItems.Add(0.00M);
                                    }

                                    listItems[i] = item.amount_rmb;
                                    listValue.Add(new Tuple<string, List<decimal>>(item.fee_sub_type, listItems));
                                }
                                else
                                {
                                    obj.Item2[i] += item.amount_rmb;
                                }
                            }
                        }
                        else
                        {
                            if (item.department_name == listCol[i])
                            {
                                var obj = listValue.Where(a => a.Item1 == item.fee_sub_type).FirstOrDefault();

                                if (obj == null)
                                {
                                    var listItems = new List<decimal>();
                                    while (listItems.Count < listCol.Count)
                                    {
                                        listItems.Add(0.00M);
                                    }

                                    listItems[i] = item.amount_rmb;
                                    listValue.Add(new Tuple<string, List<decimal>>(item.fee_sub_type, listItems));
                                }
                                else
                                {
                                    obj.Item2[i] += item.amount_rmb;
                                }
                            }
                        }
                    }
                }
            }

            return Json(new
            {
                success = list.Count > 0,
                msg = list.Count > 0 ? "" : "管理成本接口返回了空记录。",
                col = listCol,
                list = listValue
            });
        }

        public ActionResult ListAdministrativeCost(DateTime start,DateTime end,int? paycompanyid,string headname,string categoryname,int type,int issub,int? ismanager)
        {
            ViewBag.start = start;
            ViewBag.end = end;
            ViewBag.paycompanyid = paycompanyid??-1;
            ViewBag.headname = headname;
            ViewBag.categoryname = categoryname;
            ViewBag.type = type;
            ViewBag.isSub = issub;
            ViewBag.ismanager = ismanager.HasValue?ismanager.Value.ToString() : "";

            return View();
        }

        /// <summary>
        /// 获取管理成本明细列表
        /// </summary>
        /// <param name="paycompanyid">付款主体id</param>
        /// <param name="headname">列头名称</param>
        /// <param name="categoryname"></param>
        /// <param name="subname"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public string ListAdministrativeCostJson(DateTime start, DateTime end, int? paycompanyid, string headname, string categoryname, int type, int issub,int? ismanager)
        {
            var user = HttpContextHelper.Current?.User;

            //var url = ConfigHelper.GetByName("FeeUrl") + "?o=0";

            //url += "&startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");

            //if (paycompanyid.HasValue && paycompanyid.Value>0)
            //{
            //    url += "&companyValue=" + paycompanyid.Value;
            //}

            if (!string.IsNullOrEmpty(headname))
            {
                if (type == 1)
                {
                    //url += "&departmentName=" + headname;
                }
                else
                {
                    if (headname == "四千里主体")  //四千里
                    {
                        paycompanyid = 54;
                    }
                    else
                    {
                        var val = -1;
                        var objPayCompany = new Services.FinanceReportServices().GetPayCompanyByName(headname);

                        if (objPayCompany != null)
                        {
                            paycompanyid = objPayCompany.company_value;
                        }
                    }
                    
                }

            }

            //if (!string.IsNullOrEmpty(categoryname))
            //{
            //    if (issub == 0)
            //    {
            //        url += "&feeSuperType=" + categoryname;
            //    }
            //    else
            //    {
            //        url += "&feeSubType=" + categoryname;
            //    }

            //}

            //var obj = new Services.FinanceReportServices().ListOtherCost(url);

            var obj = new Services.FinanceReportServices().ListFinanceFee(start, end, (issub == 0 ? categoryname : ""), (issub != 0 ? categoryname : ""), (type==1?headname:""), paycompanyid, ismanager);


            if (obj.Count > 0)
            {
                var m = new Models.dc_base_finance_fee {
                    cost_no = "",
                    company_name = "",
                    amount = obj.Sum(a => (a.amount??0)),
                    amount_rmb = obj.Sum(a => (a.amount_rmb??0)),
                    dic = "",
                    department_name = "",
                    accounting_subject_name = "",
                    type_name = "合计",
                };

                obj.Add(m);
            }

            var list = obj.Select(a => new {
                amount = (a.amount??0).ToString("###,###.##"),
                amountRmb = (a.amount_rmb??0).ToString("###,###.##"),
                companyName = a.company_name,
                currency = a.dic,
                departmentName = a.department_name,
                feeSubType = a.kind_name,
                a.accounting_subject_name,
                feeSuperType = a.type_name,
                no = a.cost_no,
                manageCostType = a.accounting_subject_name,
                cost_form = a.cost_form>2?(a.is_lend.Value==1?3:4):a.cost_form,
                receiveUnit = a.bank_company,
                reason = string.IsNullOrEmpty(a.cost_reason)?a.cost_remark:a.cost_reason,
                payTime = a.pay_time.HasValue?a.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                uid = user != null ? user.GetUid() : 0
            }).ToList();
            

            return JsonConvert.SerializeObject(new { total = list.Count, rows = list ,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportAdministrativeCost", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        public ActionResult ListInterestExpense(DateTime start, DateTime end, int? paycompanyid, string headname, string categoryname, int type, int issub)
        {
            if (type == 2)
            {
                var objCompany = new Services.FinanceReportServices().GetPayCompanyByName(headname);
                ViewBag.paycompanyid = objCompany!=null?objCompany.company_value:-1;
            }
            else
            {
                ViewBag.paycompanyid = paycompanyid ?? -1;
            }

            ViewBag.start = start;
            ViewBag.end = end;
            
            ViewBag.headname = headname;
            ViewBag.categoryname = categoryname;
            ViewBag.type = type;
            ViewBag.isSub = issub;

            return View();
        }


        public ActionResult ListFinanceHandleFee(DateTime start, DateTime end, int? paycompanyid,string headname)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            ViewBag.paycompanyid = paycompanyid.HasValue ? paycompanyid.Value.ToString() : "";
            ViewBag.headname = headname;

            return View();
        }

        /// <summary>
        /// 手续费明细
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public JsonResult ListFinanceHandleFeeJson(DateTime start, DateTime end, int? paycompanyid,string headname)
        {
            var total = 0;

            var obj = new Services.FinanceReportServices().ListFinanceHandleFee(start, end, paycompanyid,headname);

            var totalRmb = 0M;

            if (obj.Count > 0)
            {
                totalRmb = obj.Sum(a => a.pay_money_rMB);
            }

            var list = obj.Select(a => new { 
                a.subject_name_from,

                a.bank_card_from,
                a.bank_card_to,
                a.bank_card_user_from,
                a.bank_card_user_to,
                a.bank_name_from,
                a.bank_name_to,
                
                a.casher_transaction_type,  //出纳单交易类型 -1转账支出 -2替人代付 2找人代付 3提现收入 -4还款支出 4借款收入
                a.create_time,      //创建时间
                a.remark,           //备注

                a.source,           //来源 0账户互转 1财务出纳 2提现收入 3币种金额互转 4调账 5供应商退回 6手续费 7借贷
                a.trade_category,   //交易类别 0常规转账 1银行手续费
                a.trade_type,       //交易类型 1付款 2 收款
                a.trad_code,        //交易号
                a.pay_money_rMB,    //手续费  
            });

            return Json(new { 
                success = true,
                msg = "",
                data = list,
                total = totalRmb
            });
        }

        /// <summary>
        /// 导出手续费明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult ExportListFinanceHandleFee(DateTime start, DateTime end, int? paycompanyid)
        {

            return View();

        }

        /// <summary>
        /// 获取利息支出明细列表
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="headname"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string ListInterestExpenseJson(DateTime start, DateTime end, int? paycompanyid, string headname, int type)
        {
            var cwurl = ConfigHelper.GetByName("cwUrl") + "?BeginRepayTime=" + start.ToString("yyyy-MM-dd") + "&EndRepayTime=" + end.ToString("yyyy-MM-dd");

            var listInterest = new List<Models.Api.mInterestExpense>();

            if (paycompanyid.HasValue && paycompanyid.Value>0 && paycompanyid.Value==1)
            {
                cwurl += "&CompanyVal=" + paycompanyid.Value;
            }

            if ((type == 1 && headname == "财务部") || type==2)
            {
                //利息支出
                listInterest = new Services.FinanceReportServices().ListInterestExpense(cwurl);

                if (paycompanyid.HasValue && paycompanyid.Value > 0 && paycompanyid.Value != 1)  //如果不是广州百伦的，则汇总显示为电子仓的
                {
                    listInterest = listInterest.Where(a => a.CompanyVal != 1).ToList();
                }
            }
            
            if (listInterest.Count > 0)
            {
                listInterest.Add(new Models.Api.mInterestExpense {
                    Company = "总计",
                    RepayInterest = listInterest.Sum(a=>a.RepayInterest),
                    RepayInterestRMB = listInterest.Sum(a=>a.RepayInterestRMB),
                    //ActualRepayTime = DateTime.Now,
                });
            }

            var list = listInterest.Select(a => new
            {
                ActualRepayTime = a.ActualRepayTime.HasValue?a.ActualRepayTime.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                a.BankCard,
                a.BankCardUser,
                a.BankName,
                a.Company,
                a.Creditor,
                RepayInterest = a.RepayInterest.ToString("N2"),
                RepayInterestRMB = a.RepayInterestRMB.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new { total = list.Count(), rows = list,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportAdministrativeCost", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        public ActionResult ExportListInterestExpense(DateTime start, DateTime end, int? paycompanyid, string headname, string categoryname, int type, int issub)
        {
            var cwurl = ConfigHelper.GetByName("cwUrl") + "?BeginRepayTime=" + start.ToString("yyyy-MM-dd") + "&EndRepayTime=" + end.ToString("yyyy-MM-dd");

            var listInterest = new List<Models.Api.mInterestExpense>();

            if (paycompanyid.HasValue && paycompanyid.Value > 0 && paycompanyid.Value == 1)
            {
                cwurl += "&CompanyVal=" + paycompanyid.Value;
            }

            if ((type == 1 && headname == "财务部") || type == 2)
            {
                //利息支出
                listInterest = new Services.FinanceReportServices().ListInterestExpense(cwurl);

                if (paycompanyid.HasValue && paycompanyid.Value > 0 && paycompanyid.Value != 1)  //如果不是广州百伦的，则汇总显示为电子仓的
                {
                    listInterest = listInterest.Where(a => a.CompanyVal != 1).ToList();
                }
            }

            var colNames = new List<string> {"借入公司主体名称","借款帐号","借款银行名称", "借款银行持卡人", "债权方",
                                             "本期归还利息", "本期归还利息RMB","实际还款时间" };

            var list = new List<string>();
            foreach (var item in listInterest)
            {
                list.Add(item.Company + "|" + item.BankCard + "|" + item.BankCardUser + "|" + item.BankName + "|" + item.Creditor + "|" +
                    item.RepayInterest + "|" + item.RepayInterestRMB+"|"+(item.ActualRepayTime.HasValue?item.ActualRepayTime.Value.ToString("yyyy-MM-dd"):"")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = categoryname + "+" + headname + " 利息支出明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 导出分类管理成品明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="headname"></param>
        /// <param name="categoryname"></param>
        /// <param name="type"></param>
        /// <param name="issub"></param>
        /// <returns></returns>
        public ActionResult ExportListAdministrativeCost(DateTime start, DateTime end, int? paycompanyid, string headname, string categoryname, int type, int issub,int? ismanager)
        {
            //var url = ConfigHelper.GetByName("FeeUrl") + "?o=0";

            //url += "&startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");

            //if (paycompanyid.HasValue && paycompanyid.Value > 0)
            //{
            //    url += "&companyValue=" + paycompanyid.Value;
            //}

            //if (!string.IsNullOrEmpty(headname))
            //{
            //    if (type == 1)
            //    {
            //        url += "&departmentName=" + headname;
            //    }
            //    else
            //    {
            //        url += "&companyValue=" + headname;
            //    }

            //}

            //if (!string.IsNullOrEmpty(categoryname))
            //{
            //    if (issub == 0)
            //    {
            //        url += "&feeSuperType=" + categoryname;
            //    }
            //    else
            //    {
            //        url += "&feeSubType=" + categoryname;
            //    }

            //}


            if (!string.IsNullOrEmpty(headname))
            {
                if (type == 1)
                {
                    //url += "&departmentName=" + headname;
                }
                else
                {
                    var objPayCompany = new Services.FinanceReportServices().GetPayCompanyByName(headname);

                    if (objPayCompany != null)
                    {
                        paycompanyid = objPayCompany.company_value;
                    }
                }

            }

            //if (!string.IsNullOrEmpty(categoryname))
            //{
            //    if (issub == 0)
            //    {
            //        url += "&feeSuperType=" + categoryname;
            //    }
            //    else
            //    {
            //        url += "&feeSubType=" + categoryname;
            //    }

            //}

            //var obj = new Services.FinanceReportServices().ListOtherCost(url);

            var obj = new Services.FinanceReportServices().ListFinanceFee(start, end, (issub == 0 ? categoryname : ""), (issub != 0 ? categoryname : ""), (type == 1 ? headname : ""), paycompanyid, ismanager);


            var colNames = new List<string> {"费用单号","一级部门","付款主体名称","费用类别", "会计科目",
                                            "金额","币种", "人民币金额","收款单位","收款理由","付款时间","备注" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.cost_no + "|" + item.department_name + "|" + item.company_name + "|" + item.type_name + "|" + item.accounting_subject_name + "|" +
                    item.amount + "|" + item.dic + "|" + item.amount_rmb + "|" + item.bank_company + "|" + (string.IsNullOrEmpty(item.cost_reason) ? item.cost_remark : item.cost_reason) + "|" + item.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss"+"|"+item.mor_remark)
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = categoryname+"+"+headname+ " 付现流水明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 导出管理成本明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public IActionResult ExportAdministrativeCost(DateTime start, DateTime end, int? paycompanyid,int? ismanager)
        {
            //var url = ConfigHelper.GetByName("FeeUrl") + "?o=0";

            //url += "&startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");

            //if (paycompanyid.HasValue && paycompanyid.Value > 0)
            //{
            //    url += "&companyValue=" + paycompanyid.Value;
            //}


            //var obj = new Services.FinanceReportServices().ListOtherCost(url);

            //var obj = new Services.FinanceReportServices().ListFinanceManageCost(start, end, "", "", "", paycompanyid);

            var obj = new Services.FinanceReportServices().ListFinanceFee(start, end, "", "", "", paycompanyid, ismanager); 

            var colNames = new List<string> {"费用单号","部门名称","付款主体名称","费用类别", "会计科目",
                                            "金额","币种", "人民币金额","收款单位","收款理由","付款时间",
                                            "备注" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.cost_no + "|" + item.department_name + "|" + item.company_name + "|" + item.type_name + "|" + item.accounting_subject_name + "|" +
                    item.amount + "|" + item.dic + "|" + item.amount_rmb + "|" + item.bank_company + "|" + (string.IsNullOrEmpty(item.cost_reason) ? item.cost_remark : item.cost_reason) + "|" + item.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss" + "|" + item.mor_remark)
                    );
            }

            //利息


            //手续费支出

            var guid = Guid.NewGuid().ToString();
            var filename = "付现流水明细"+DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\"+DateTime.Now.ToString("yyyy-MM-dd")+"\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        #region 资产负债表-子表
        public ActionResult MonetaryFund(DateTime date, int paycompanyid)
        {
            var m = new Services.FinanceReportServices().GetMonetaryFundCount(date, paycompanyid);

            ViewBag.m = m;
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }

        /// <summary>
        /// 提现在途明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult WithDrawOnWay(DateTime date, int paycompanyid)
        {
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            //var list = _services.ListWithDrawOnWay(date, paycompanyid);

            ViewBag.PayCompanyName = paycompany != null ? paycompany.company_name : "";
            //ViewBag.list = list;
            ViewBag.date = date.ToString("yyyy-MM-dd HH:mm:ss");
            ViewBag.companyid = paycompanyid;
            return View();
        }

        public string WithDrawOnWayJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var obj = _services.ListWithDrawOnWay(request,date, paycompanyid,ref total);

            var list = obj.Select(a => new {
                sale_platform = a.sale_platform,
                platform = a.platform,
                pay_account = a.pay_account,
                bank_name = a.bank_name,
                bank_card_user = a.bank_card_user,
                amount_rmb = a.amount_rmb.ToString("N2"),
                statistical_time = a.statistical_time.ToString("yyyy-MM-dd HH:mm:ss")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        /// <summary>
        /// 导出提现在途明细
        /// </summary>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult WithDrawOnWayExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() {
                offset = 0,
                limit = 100000
            };

            var obj = _services.ListWithDrawOnWay(request, date, paycompanyid, ref total);

            var colNames = new List<string> {"销售平台名称","支付平台名称","银行帐号", "银行名称", "持卡人",
                                             "帐号余额", "日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.sale_platform + "|" + item.platform + "|" + item.pay_account + "|" + item.bank_name + "|" + item.bank_card_user + "|" +
                    item.amount_rmb.ToString("N2") + "|" + item.statistical_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 平台提现在途明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        /// <summary>
        /// 第三方帐号余额明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult PlatformBalance(DateTime date, int paycompanyid)
        {
            //var _services = new Services.FinanceReportServices();
            //var paycompany = _services.GetPayCompany(paycompanyid);
            

            //ViewBag.PayCompanyName = paycompany != null ? paycompany.company_name : "";

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        public string PlatformBalanceJson(BtTableParameter request,DateTime date,int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPlatFormBalance(request,date, paycompanyid,ref total);

            var list = obj.Select(a => new {
                platformname = a.platformname,
                a.account,
                amount = a.amount.ToString("N2"),
                userable_amount = a.userable_amount.ToString("N2"),
                freeze_amount = a.freeze_amount.ToString("N2"),
                a.currency,
                amount_rmb = a.amount_rmb.ToString("N2"),
                userable_amount_rmb = a.userable_amount_rmb.ToString("N2"),
                freeze_amount_rmb = a.freeze_amount_rmb.ToString("N2"),
                puttime = a.puttime.ToString("yyyy-MM-dd"),
                day = a.day.ToString("yyyy-MM-dd")
            });
            
            return JsonConvert.SerializeObject(new { total=total,rows=list});
        }

        /// <summary>
        /// 导出第三方帐号余额明细
        /// </summary>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult PlatformBalanceExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter(){offset = 0,limit = 100000};

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPlatFormBalance(request, date, paycompanyid, ref total);

            var colNames = new List<string> {"平台名称","帐号名称","总余额（原币）", "可用余额（原币）", "冻结余额（原币）",
                                             "币种", "总余额（人民币）","可用余额（人民币）","冻结余额（人民币）","放款日期","统计日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.platformname + "|" + item.account + "|" + item.amount.ToString("N2") + "|" + item.userable_amount.ToString("N2") + "|" + item.freeze_amount.ToString("N2") + "|" +
                    item.currency + "|" + item.amount_rmb.ToString("N2")+"|"+item.userable_amount_rmb.ToString("N2")+"|"+item.freeze_amount_rmb.ToString("N2")+"|"+ item.puttime.ToString("yyyy-MM-dd")+"|"+ item.day.ToString("yyyy-MM-dd")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 第三方帐号余额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 银行余额明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult BankBalance(DateTime date, int paycompanyid)
        {

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        public string BankBalanceJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            int total = 0;
            var _services = new Services.FinanceReportServices();

            //var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListBankBalance(request,date, paycompanyid,ref total);
            var list = obj.Select(a => new {
                a.company_name,
                a.bank_name,
                a.bank_card,
                a.bank_card_user,
                balance_rmb = a.balance_rmb.ToString("N2"),
                statistical_time = a.statistical_time.ToString("yyyy-MM-dd"),
                
            });

            return JsonConvert.SerializeObject(new {total=total,rows=list});
        }

        public ActionResult BankBalanceExport(DateTime date, int paycompanyid)
        {
            int total = 0;
            var _services = new Services.FinanceReportServices();

            var request = new BtTableParameter()
            {
                offset = 0,
                limit = 100000
            };

            var obj = _services.ListBankBalance(request, date, paycompanyid, ref total);
            
            var colNames = new List<string> {"付款主体","银行名称","银行卡号","持卡人", "帐号余额", "日期"};

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.company_name+"|"+item.bank_name + "|'" + item.bank_card + "|" + item.bank_card_user + "|" + item.balance_rmb.ToString("N2") + "|" + item.statistical_time.ToString("yyyy-MM-dd")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 银行余额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 获取存货FBA和非FBA的分别库存数
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult InventoryBalanceCount(DateTime date, int paycompanyid)
        {
            var m = new Services.FinanceReportServices().ListInventoryBalanceCount(date, paycompanyid);
            ViewBag.m = m;
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        /// <summary>
        /// 获取存货明细
        /// </summary>
        /// <param name="date">日期</param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult InventoryBalance(DateTime date, int paycompanyid, int t)
        {

            ViewBag.t = t;
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }

        /// <summary>
        /// 库存在库明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public string InventoryBalanceJson(BtTableParameter request, DateTime date, int paycompanyid, int t)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListInventoryBalance(request,date, paycompanyid, t,ref total);

            var list = obj.Select(a => new {
                company_name = paycompany!=null? paycompany.company_name:"",
                warehouse_name = a.warehouse_name,
                balance_rmb = a.balance_rmb.ToString("N2"),
                statistical_time = a.statistical_time.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult InventoryBalanceExport(DateTime date, int paycompanyid, int t)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);

            var obj = _services.ListInventoryBalance(request, date, paycompanyid, t, ref total);

            //var list = obj.Select(a => new {
            //    company_name = paycompany != null ? paycompany.company_name : "",
            //    warehouse_name = a.warehouse_name,
            //    balance_rmb = a.balance_rmb.ToString("N2"),
            //    statistical_time = a.statistical_time.ToString("yyyy-MM-dd")
            //});

            var colNames = new List<string> {"仓库名称","存货余额","日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.warehouse_name + "|" + item.balance_rmb.ToString("N2") + "|" + item.statistical_time.ToString("yyyy-MM-dd"));
            }

            var typename = "";
            if (t == 0) //FBA在库明细
            {
                typename = "FBA仓在库明细";
            }
            else if (t == 1) //非FBA在库明细
            {
                typename = "非FBA仓在库明细";
            }
            else if (t == 3) //FBA在途明细
            {
                typename = "FBA仓在途明细";
            }
            else if (t == 4) //非FBA在途明细
            {
                typename = "非FBA仓在途明细";
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + typename + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 半成品库存明细
        /// </summary>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid">付款主体</param>
        /// <returns></returns>
        public ActionResult SemiFinishStock(DateTime date, int paycompanyid)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }


        /// <summary>
        /// 半成品库存明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public string SemiFinishStockJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListSemiFinishDailyStock(request, date, paycompanyid, ref total);

            var list = obj.Select(a => new {
                a.warehouse_name,
                a.sku_code,
                a.stock_quantity,
                inventory_amount = a.inventory_amount.ToString("N2"),
                day = a.day.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult SemiTransferStock(DateTime date, int paycompanyid)
        {

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        /// <summary>
        /// 半成品在途库存
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid">付款主体id</param>
        /// <returns></returns>
        public string SemiTransferStockJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListSemiTransferStock(request, date, paycompanyid, ref total);

            var list = obj.Select(a => new {
                a.warehouse_name,
                a.sku_code,
                a.transfer_quantity,
                inventory_amount = (a.transfer_quantity*a.unit_price).ToString("N2"),
                day = a.day.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }


        public ActionResult SemiFinishStockExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListSemiFinishDailyStock(request, date, paycompanyid, ref total);

            //var list = obj.Select(a => new {
            //    a.warehouse_name,
            //    a.sku_code,
            //    a.stock_quantity,
            //    inventory_amount = a.inventory_amount.ToString("N2"),
            //    update_time = a.update_time.ToString("yyyy-MM-dd HH:mm:ss")
            //});

            var colNames = new List<string> { "仓库名称", "Sku编码", "库存数量","库存金额","更新日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.warehouse_name + "|" + item.sku_code + "|" + item.stock_quantity+"|"+ item.inventory_amount.ToString("N5")+"|"+item.day.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + "半成品在库明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        public ActionResult SemiTransferStockExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListSemiTransferStock(request, date, paycompanyid, ref total);

            var colNames = new List<string> { "仓库名称", "Sku编码", "库存数量", "库存金额", "更新日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.warehouse_name + "|" + item.sku_code + "|" + item.transfer_quantity + "|" + (item.unit_price*item.transfer_quantity).ToString("N2") + "|" + item.day.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + "半成品在途明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 半成品生产库存
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult SemiProductionStock(DateTime date, int paycompanyid)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }

        /// <summary>
        /// 半成品生产库存
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public string SemiProductionStockJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var paycompany = _services.GetPayCompany(paycompanyid);

            var obj = _services.ListProductionStock(request, date, paycompanyid, ref total);

            var list = obj.Select(a => new {
                a.warehouse_name,
                a.material_code,
                a.material_name,
                a.jit_prod_stock,
                a.plan_prod_stock,
                a.new_price,
                record_time = a.record_time.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });

        }

        /// <summary>
        /// 导出半成品生产库存
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult SemiProductionStockExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListProductionStock(request, date, paycompanyid, ref total);

            var colNames = new List<string> { "仓库名称", "Sku编码", "Sku名称", "jit库存", "计划单库存","最新报价","统计日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.warehouse_name + "|" + item.material_code + "|" + item.material_name + "|" + item.jit_prod_stock + "|" + item.plan_prod_stock + "|" + item.new_price + "|" + item.record_time.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + "生产库存明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 自产采购在途
        /// </summary>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid">付款主体id</param>
        /// <returns></returns>
        public ActionResult ListProductOnway(DateTime date, int paycompanyid)
        {
            ViewBag.date = date.ToString("yyyy-MM-dd");
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        /// <summary>
        /// 自产采购在途数据
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public string ListProductOnwayJson(BtTableParameter request, DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListProductOnway(request, date, ref total);

            var list = obj.Select(a => new {
                a.warehouse_name,
                a.warehouse_code,
                a.bailun_sku,
                a.buyer_name,
                a.quantity_purchase,
                a.unit_price,
                amount = a.quantity_purchase*a.unit_price,
                record_time = a.record_time.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        /// <summary>
        /// 自产采购在途数据导出
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public ActionResult ListProductOnwayExport(DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListProductOnway(new BtTableParameter { limit=0}, date, ref total);

            var colNames = new List<string> { "统计日期", "Sku编码", "仓库名称", "在途数量", "采购价", "总金额","采购员名称" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.record_time.ToString("yyyy-MM-dd") + "|" + item.bailun_sku + "|" + item.warehouse_name + "|" + item.quantity_purchase + "|" + item.unit_price + "|"+ (item.quantity_purchase*item.unit_price) + "|" + item.buyer_name);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + "自产采购在途" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 自产采购发货在途
        /// </summary>
        /// <param name="date">日期</param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult ListSelfProductShippingOnway(DateTime date, int paycompanyid)
        {
            ViewBag.date = date.ToString("yyyy-MM-dd");
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }

        /// <summary>
        /// 自产采购在途数据
        /// </summary>
        /// <param name="request">分页信息</param>
        /// <param name="date">统计日期</param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public string ListSelfProductShippingOnwayJson(BtTableParameter request, DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListSelfProductShippingOnway(request, date, ref total);

            var list = obj.Select(a => new {
                a.purchase_id,
                a.bailun_sku,
                a.buyer_name,
                a.count,
                a.price,
                amount = a.count * a.price,
                record_time = a.day.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        /// <summary>
        /// 自产采购在途数据导出
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public ActionResult ListSelfProductShippingOnwayExport(DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListSelfProductShippingOnway(new BtTableParameter { limit = 0 }, date, ref total);

            var colNames = new List<string> { "统计日期", "采购单号", "Sku编码", "发货在途数量", "采购价", "总金额", "采购员名称" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.day.ToString("yyyy-MM-dd") + "|" + item.purchase_id + "|" + item.bailun_sku + "|" + item.count + "|" + item.price + "|" + (item.count * item.price) + "|" + item.buyer_name);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + "自产采购发货在途" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        /// <summary>
        /// 短期借款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult ShortBorrow(DateTime date, int paycompanyid)
        {

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        public string ShortBorrowJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListShorBorrow(request,date, paycompanyid,ref total);

            var list = obj.Select(a => new {
                a.company_name,
                a.bank_card,
                a.bank_name,
                a.bank_card_user,
                a.creditor,
                balance_rmb = a.balance_rmb.ToString("N2"),
                statistical_time = a.statistical_time.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult ExportShortBorrow(DateTime date, int paycompanyid)
        {

            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListShorBorrow(new BtTableParameter { offset=1,limit=0}, date, paycompanyid, ref total);


            var colNames = new List<string> {"借入公司主体名称","借款帐号","借款银行名称", "借款银行持卡人", "债权方",
                                             "借款余额", "日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.company_name + "|" + item.bank_card + "|" + item.bank_name + "|" + item.bank_card_user + "|" + item.creditor + "|" +
                    item.balance_rmb + "|" + item.statistical_time.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd")  + " 短期借款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        public ActionResult PrePayCount(DateTime date, int paycompanyid)
        {
            var _services = new Services.FinanceReportServices();
            var list = _services.ListPrePayCount(date, paycompanyid, 1);

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            ViewBag.list = list;
            return View();
        }

        /// <summary>
        /// 商品供应商 预付款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult PrePay(DateTime date, int paycompanyid,int finish)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            ViewBag.finish = finish;
            return View();
        }

        public string PrePayJson(BtTableParameter request,DateTime date, int paycompanyid,int? finish)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            //var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePay(request,date, paycompanyid,1,finish,ref total);

            var list = obj.Select(a => new {
                a.supplier_name,
                is_finish = (a.is_finish == 0 ? "半成品" : "成品"),
                a.pay_company_name,
                start_amount = a.start_amount.ToString("N2"),
                putting_amount = ((a.putting_amount + a.express_amount + a.adjust_amount - a.return_amount - a.return_express).ToString("N2")),
                pay_amount = (a.pay_amount - a.receive_amount).ToString("N2"),
                end_amount = a.end_amount.ToString("N2"),
                day = a.day.Value.ToString("yyyy-MM-dd"),
            });

            return JsonConvert.SerializeObject(new { total=total,rows = list });
        }

        public ActionResult PrePayExport(DateTime date, int paycompanyid, int? finish)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter()
            {
                offset = 0,
                limit = 100000
            };
            var obj = _services.ListPrePay(request, date, paycompanyid, 1, finish, ref total);

            var colNames = new List<string> {"供应商名称","是否成品","公司主体", "期初金额", "借方发生额",
                                             "贷方发生额", "期末金额","日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.supplier_name + "|" + (item.is_finish == 0 ? "半成品" : "成品") + "|" + item.pay_company_name + "|" + item.start_amount.ToString("N2") + "|" + ((item.putting_amount + item.express_amount + item.adjust_amount - item.return_amount - item.return_express).ToString("N2")) + "|" +
                    (item.pay_amount - item.receive_amount).ToString("N2") + "|" + item.end_amount.ToString("N2")+"|"+ item.day.Value.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") +((finish??0)==1?"成品":"半成品") + " 商品供应商预付款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }

        /// <summary>
        /// 物流供应商 预付款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult PrePayLogistics(DateTime date, int paycompanyid)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        public string PrePayLogisticsJson(BtTableParameter request,DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            //var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePayLogistics(request, date, paycompanyid, 1, ref total);

            var list = obj.Select(a => new {
                a.supplier_name,
                a.pay_company_name,
                start_amount = a.start_amount.ToString("N2"),
                borrow_amount = a.borrow_amount.ToString("N2"),
                loan_amount = a.loan_amount.ToString("N2"),
                end_amount = a.end_amount.ToString("N2"),
                day = a.day.Value.ToString("yyyy-MM-dd"),
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult PrePayLogisticsExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter()
            {
                offset = 0,
                limit = 100000
            };

            var obj = _services.ListPrePayLogistics(request, date, paycompanyid, 1, ref total);
            var colNames = new List<string> {"供应商名称","公司主体", "期初金额", "借方发生额","贷方发生额", "期末金额","日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.supplier_name + "|" + item.pay_company_name + "|" + item.start_amount.ToString("N2") + "|" + item.borrow_amount.ToString("N2") + "|" +item.loan_amount.ToString("N2")+"|"+item.end_amount.ToString("N2")+"|"+item.day.Value.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 物流供应商预付款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 应付款统计
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult CopeWithCount(DateTime date, int paycompanyid)
        {
            var _services = new Services.FinanceReportServices();
            var list = _services.ListPrePayCount(date, paycompanyid, 0);

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            ViewBag.list = list;
            return View();
        }

        /// <summary>
        /// 应付款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult CopeWith(DateTime date, int paycompanyid,int finish)
        {

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            ViewBag.finish = finish;
            return View();
        }

        public string CopeWithJson(BtTableParameter request,DateTime date, int paycompanyid,int? finish)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePay(request,date, paycompanyid, 0, finish, ref total);

            var list = obj.Select(a=>new {
                supplier_name = a.supplier_name,
                is_finish = (a.is_finish == 0 ? "半成品" : "成品"),
                a.pay_company_name,
                start_amount = a.start_amount.ToString("N2"),
                putting_amount = (a.putting_amount + a.express_amount + a.adjust_amount - a.return_amount - a.return_express).ToString("N2"),
                pay_amount = (a.pay_amount - a.receive_amount).ToString("N2"),
                end_amount = a.end_amount.ToString("N2"),
                day = a.day.Value.ToString("yyyy-MM-dd"),
            });
            return JsonConvert.SerializeObject(new { total=total,rows=list});
        }

        public ActionResult CopeWithPayCompany(DateTime date,int paycompanyid,int? finish)
        {
            ViewBag.date = date.ToString("yyyy-MM-dd");
            ViewBag.paycompanyid = paycompanyid;
            ViewBag.finish = finish ?? 0;

            return View();
        }

        public string CopeWithPayCompanyJson(BtTableParameter parameter, DateTime date, int paycompanyid, int? finish)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var paycompany = _services.GetPayCompany(paycompanyid);

            var obj = _services.ListPrePayGroup(parameter, date, paycompanyid, 0, finish, ref total);

            var list = obj.Select(a => new {
                a.pay_company_name,
                putting_amount = (a.putting_amount + a.express_amount + a.adjust_amount - a.return_amount - a.return_express).ToString("N2"),
                pay_amount = (a.pay_amount - a.receive_amount).ToString("N2"),
                day = a.day.Value.ToString("yyyy-MM-dd"),
            });
            return JsonConvert.SerializeObject(new { total = total, rows = list });

        }


        public ActionResult CopeWithExport(DateTime date, int paycompanyid, int? finish)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() {offset = 0,limit = 100000};
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePay(request, date, paycompanyid, 0, finish, ref total);

            var colNames = new List<string> {"供应商名称","是否成品","公司主体", "期初金额", "借方发生额",
                                             "贷方发生额", "期末金额","统计日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.supplier_name + "|" + (item.is_finish == 0 ? "半成品" : "成品") + "|" + item.pay_company_name + "|" + item.start_amount.ToString("N2") + "|" + ((item.putting_amount + item.express_amount + item.adjust_amount - item.return_amount - item.return_express).ToString("N2")) + "|" +
                    (item.pay_amount - item.receive_amount).ToString("N2") + "|" + item.end_amount.ToString("N2") + "|" + item.day.Value.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + ((finish ?? 0) == 1 ? "成品" : "半成品") + " 商品供应商应付款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }

        /// <summary>
        /// 物流供应商应付款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult CopeWithLogistics(DateTime date, int paycompanyid)
        {

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        /// <summary>
        /// 物流供应商应付账款
        /// </summary>
        /// <param name="request"></param>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public string CopeWithLogisticsJson(BtTableParameter request, DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePayLogistics(request, date, paycompanyid, 0, ref total);
            
            var list = obj.Select(a => new {
                a.supplier_name,
                a.pay_company_name,
                start_amount = a.start_amount.ToString("N2"),
                borrow_amount = a.borrow_amount.ToString("N2"),
                loan_amount = a.loan_amount.ToString("N2"),
                end_amount = a.end_amount.ToString("N2"),
                day = a.day.Value.ToString("yyyy-MM-dd"),
            });
            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult CopeWithLogisticsExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePayLogistics(request, date, paycompanyid, 0, ref total);
            
            var colNames = new List<string> { "供应商名称", "公司主体", "期初金额", "借方发生额", "贷方发生额", "期末金额", "日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.supplier_name + "|" + item.pay_company_name + "|" + item.start_amount.ToString("N2") + "|" + item.borrow_amount.ToString("N2") + "|" + item.loan_amount.ToString("N2") + "|" + item.end_amount.ToString("N2") + "|" + item.day.Value.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 物流供应商应付款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        /// <summary>
        /// 其他应收款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult OtherReceivable(DateTime date, int paycompanyid)
        {

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        public string OtherReceivableJson(BtTableParameter request,DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListOtherCost(request,date, paycompanyid, 1,ref total);

            var list = obj.Select(a => new {
                company_name = (paycompany==null?"":paycompany.company_name),
                a.borrower_or_payer,
                start_amount = a.start_amount.ToString("N2"),
                debit_amount = a.debit_amount.ToString("N2"),
                credit_amount = a.credit_amount.ToString("N2"),
                end_amount = a.end_amount.ToString("N2"),
                day = a.day.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult OtherReceivableExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListOtherCost(request, date, paycompanyid, 1, ref total);

            //var list = obj.Select(a => new {
            //    company_name = (paycompany == null ? "" : paycompany.company_name),
            //    a.borrower_or_payer,
            //    start_amount = a.start_amount.ToString("N2"),
            //    debit_amount = a.debit_amount.ToString("N2"),
            //    credit_amount = a.credit_amount.ToString("N2"),
            //    end_amount = a.end_amount.ToString("N2"),
            //    day = a.day.ToString("yyyy-MM-dd")
            //});

            var colNames = new List<string> { "借款方", "期初金额", "借方发生额", "贷方发生额", "期末金额", "统计日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.borrower_or_payer + "|" + item.start_amount.ToString("N2") + "|" + item.debit_amount.ToString("N2") + "|" + item.credit_amount.ToString("N2") + "|" + item.end_amount.ToString("N2") + "|" + item.day.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 其他应收款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 其他应付款明细
        /// </summary>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <returns></returns>
        public ActionResult OtherPayable(DateTime date, int paycompanyid)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        public string OtherPayableJson(BtTableParameter request,DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListOtherCost(request,date, paycompanyid, 2,ref total);
            var list = obj.Select(a => new {
                company_name = paycompany!=null?paycompany.company_name:"",
                a.borrower_or_payer,
                start_amount = a.start_amount.ToString("N2"),
                debit_amount = a.debit_amount.ToString("N2"),
                credit_amount = a.credit_amount.ToString("N2"),
                end_amount = a.end_amount.ToString("N2"),
                day = a.day.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list });
        }

        public ActionResult OtherPayableExport(DateTime date, int paycompanyid)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListOtherCost(request, date, paycompanyid, 2, ref total);
            
            var colNames = new List<string> { "公司主体","还款方","期初金额", "借方发生额", "贷方发生额", "期末金额", "日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.company_name+"|"+ item.borrower_or_payer + "|" + item.start_amount.ToString("N2") + "|" + item.debit_amount.ToString("N2") + "|" + item.credit_amount.ToString("N2") + "|" + item.end_amount.ToString("N2") + "|" + item.day.ToString("yyyy-MM-dd"));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 其他应付款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 固定资产一级明细
        /// </summary>
        /// <returns></returns>
        public ActionResult ListFixedAssets(DateTime date,int paycompanyid)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }

        /// <summary>
        /// 固定资产一级明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="date"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="companyvalue"></param>
        /// <returns></returns>
        public string ListFixedAssetsJson(BtTableParameter request, DateTime date, int paycompanyid,int? companyvalue)
        {
            var total = 0;

            var obj = new Services.FinanceReportServices().ListFixedAssets(request, date, paycompanyid, companyvalue, ref total);

            var countM = new dc_fixed_assets_detail();
            if (obj.Count > 0)
            {
                countM = (new dc_fixed_assets_detail
                {
                    company_name = "合计：",
                    debit_amount = obj.Sum(a => a.debit_amount.Value),
                    credit_amount = obj.Sum(a => a.credit_amount.Value),
                });
            }
            
            var list = obj.Select(a => new {
                day = a.day.HasValue?a.day.Value.ToString("yyyy-MM-dd"):"",
                company_value = a.company_value.HasValue?a.company_value.Value+"":"",
                a.company_name,
                start_amount = a.start_amount.HasValue?a.start_amount.Value.ToString("N2"):"",
                debit_amount = a.debit_amount.HasValue?a.debit_amount.Value.ToString("N2"):"",
                credit_amount = a.credit_amount.HasValue ? a.credit_amount.Value.ToString("N2"):"",
                end_amount = a.end_amount.HasValue?a.end_amount.Value.ToString("N2"):"",
            });

            return JsonConvert.SerializeObject(new { total=total,rows = list, count_row = new {
                countM.company_name,
                debit_amount = countM.debit_amount.HasValue?countM.debit_amount.Value.ToString("N2"):"0",
                credit_amount = countM.credit_amount.HasValue?countM.credit_amount.Value.ToString("N2"):"0"
            } });
        }

        public ActionResult ListFixedAssetsExport(DateTime date, int paycompanyid, int? companyvalue)
        {
            var total = 0;
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var obj = new Services.FinanceReportServices().ListFixedAssets(request, date, paycompanyid, companyvalue, ref total);

            var colNames = new List<string> { "采购公司", "期初金额", "借方发生额", "贷方发生额", "期末金额", "统计日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.company_name + "|" + (item.start_amount.HasValue ? item.start_amount.Value.ToString("N2") : "") + "|" + (item.debit_amount.HasValue ? item.debit_amount.Value.ToString("N2") : "") + "|" + (item.credit_amount.HasValue ? item.credit_amount.Value.ToString("N2") : "") + "|" + (item.end_amount.HasValue ? item.end_amount.Value.ToString("N2") : "") + "|" + (item.day.HasValue ? item.day.Value.ToString("yyyy-MM-dd") : ""));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 固定资产明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 固定资产二级明细
        /// </summary>
        /// <param name="companyvalue"></param>
        /// <returns></returns>
        public ActionResult ListFixedAssetsDetails(int companyvalue,DateTime date)
        {

            ViewBag.date = date;
            ViewBag.companyvalue = companyvalue;
            return View();
        }

        /// <summary>
        /// 固定资产二级明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="companyvalue"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string ListFixedAssetsDetailsJson(BtTableParameter request, int? companyvalue, DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListFixedAssetsDetails(request, date, companyvalue, ref total);

            var countM = new mFixedAssetsDetail();
            if (obj.Count>0)
            {
                countM = (new mFixedAssetsDetail {
                    buyno = "合计：",
                    amount = obj.Sum(a=>a.amount.Value)
                });

            }

            var list = obj.Select(a => new
            {
                a.buyno,
                pay_time = a.pay_time.HasValue?a.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                a.skuname,
                amount = a.amount.HasValue?a.amount.Value.ToString("N2"):"",
                creditamount = 0,
                day = a.day.HasValue?a.day.Value.ToString("yyyy-MM-dd"):""
            }).ToList();



            return JsonConvert.SerializeObject(new { total=total,rows=list,count_row=new {
                buyno = countM.buyno,
                amount = countM.amount.HasValue?countM.amount.Value.ToString("N2"):"0",
            }
            });
        }

        public ActionResult ListFixedAssetsDetailsExport(int? companyvalue, DateTime date)
        {
            var total = 0;
            var request = new BtTableParameter() { offset = 0, limit = 100000 };
            var obj = new Services.FinanceReportServices().ListFixedAssetsDetails(request, date, companyvalue, ref total);

            var colNames = new List<string> { "其他采购单号", "出纳付款时间", "采购物品", "本期借方发生额", "本期贷方发生额", "统计日期" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.buyno + "|" + (item.pay_time.HasValue ? item.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss") : "") + "|" + (item.skuname) + "|" + (item.amount.HasValue ? item.amount.Value.ToString("N2") : "") + "|" + "0" + "|" + (item.day.HasValue ? item.day.Value.ToString("yyyy-MM-dd") : ""));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 固定资产二级明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 借支金额
        /// </summary>
        /// <param name="companyvalue"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public ActionResult ListBorrowAmount(int companyvalue, DateTime date)
        {
            ViewBag.date = date;
            ViewBag.companyvalue = companyvalue;
            return View();
        }

        /// <summary>
        /// 借支金额
        /// </summary>
        /// <param name="request"></param>
        /// <param name="companyvalue"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string ListBorrowAmountJson(BtTableParameter request, int? companyvalue, DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListBorrowAmount(request, date, companyvalue, ref total);

            var objCount = new Services.FinanceReportServices().ListBorrowAmountCount(date, companyvalue);

            var list = obj.Select(a => new {
                a.id,
                a.cost_no,
                cost_form = Enum.GetName(typeof(Enum_cost_form),a.cost_form.Value),
                a.company_name,
                a.type_name,
                a.kind_name,
                a.create_username,
                create_time = a.create_time.HasValue?a.create_time.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                amount = (a.amount - a.had_pay + (a.compensate??0)) * a.to_rmb_rate,
                recoed_time = a.recoed_time.Value.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    cost_no = "总计",
                    amount = objCount.amount,
                }
            });

        }

        public ActionResult ListBorrowAmountExport(int? companyvalue, DateTime date)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListBorrowAmount(new BtTableParameter {offset=0,limit=0}, date, companyvalue, ref total);

            var list = obj.Select(a => new {
                a.id,
                a.cost_no,
                cost_form = Enum.GetName(typeof(Enum_cost_form), a.cost_form.Value),
                a.company_name,
                a.type_name,
                a.kind_name,
                a.create_username,
                create_time = a.create_time.HasValue?a.create_time.Value.ToString("yyyy-MM-dd HH:mm:ss"):"",
                amount = (a.amount - a.had_pay + (a.compensate ?? 0)) * a.to_rmb_rate,
                recoed_time = a.recoed_time.Value.ToString("yyyy-MM-dd")
            });

            var colNames = new List<string> { "费用单号", "费用类型", "付款主体", "费用大类", "费用小类", "创建人", "创建时间", "待还金额", "记录日期" };

            var listval = new List<string>();
            foreach (var item in list)
            {
                listval.Add(item.cost_no + "|" + item.cost_form + "|" + item.company_name + "|" + item.type_name + "|" + item.kind_name + "|" + item.create_username + "|" + item.create_time+"|"+item.amount+"|"+item.recoed_time);
            }

            var guid = Guid.NewGuid().ToString();
            var filename = date.ToString("yyyy-MM-dd") + " 借款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listval, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }


        /// <summary>
        /// 应收账款
        /// </summary>
        /// <param name="paycompanyid">付款主体id</param>
        /// <param name="date">日期</param>
        /// <returns></returns>
        public ActionResult ReceivablesCount(int paycompanyid, DateTime date)
        {
            var m = new Services.FinanceReportServices().ReceivablesCount(date);
            ViewBag.m = m;
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }


        public ActionResult ListReceivablesPlatform(int paycompanyid, DateTime date)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

        /// <summary>
        /// 应收账款平台金额明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string ListReceivablesPlatformJson(BtTableParameter request, int paycompanyid, DateTime date)
        {
            var total = 0;

            var obj = new Services.FinanceReportServices().ListReceivables(request, date, ref total);

            var objCount = new Services.FinanceReportServices().ReceivablesCount(date);

            var list = obj.Select(a => new {
                a.id,
                amount_end = a.amount_end.ToString("N2"),
                a.platform,
                day = a.day.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    platform = "总计",
                    amount_end = objCount.Item1,
                }
            });

        }

        public ActionResult ListReceivablesBorrow(int paycompanyid, DateTime date)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }


        /// <summary>
        /// 应收账款借支单金额明细
        /// </summary>
        /// <param name="request"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public string ListReceivablesBorrowJson(BtTableParameter request, int paycompanyid, DateTime date)
        {
            var total = 0;

            var obj = new Services.FinanceReportServices().ListBorrow(request, date, ref total);

            var objCount = new Services.FinanceReportServices().ReceivablesCount(date);

            var list = obj.Select(a => new {
                a.id,
                a.cost_no,
                a.company_name,
                a.create_username,
                amount = (a.amount??0).ToString("N2"),
                recoed_time = a.recoed_time.Value.ToString("yyyy-MM-dd")
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    cost_no = "总计",
                    amount = objCount.Item2,
                }
            });

        }


        /// <summary>
        /// 资产负债表环比图表
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult Index2Chart()
        {
            ViewBag.start = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
            ViewBag.end = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

            
            return View();
        }
        
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【资产负债表】->【环比报表】->【查询】页面", 0)]
        public JsonResult FinanceDebtChainChartJson(DateTime start, DateTime end)
        {
            try
            {
                var obj = new Services.FinanceReportServices().ListBalanceSheet(start, end);

                var s = new List<string>() { "货币资金", "1.平台提现在途", "2.第三方平台余额", "3.银行帐号余额", "交易性金融资金", "应收票据", "应收账款", "1.借支金额", "预付款项", "1.预付成品供应商", "2.预付半成品供应商", "3.预付物流供应商", "应收利息", "应收股利", "其他应收款", "存货", "1.存货FBA仓在库", "2.存货非FBA仓在库", "3.存货FBA仓在途(非调拨计划)", "4.存货FBA仓在途(调拨计划)",
                                         "5.存货非FBA仓在途(非调拨计划)","6.存货非FBA在途(调拨计划)","7.存货半成品在库","7.1百伦半成品在库","7.2哈倪曼半成品在库","7.3生产库存","8.存货半成品在途","8.1百伦半成品在途","8.2哈倪曼半成品在途","9.自产采购发货在途","一年内到期的非流动资产","其他流动资产","流动资产合计","可供出售金融资产","持有至到期投资","长期应收款","长期股权投资","投资性房地产","固定资产","在建工程",
                                         "工程物资","固定资产清理","生产性生物资产","油气资产","无形资产","开发支出","商誉","长期待摊费用","递延所得税资产","其他非流动资产","非流动资产合计","资产合计","短期借款","交易性金融负债","应付票据","应付账款","1.成品供应商","2.应付半成品供应商","3.应付物流供应商","预收款项",
                                         "应付职工薪酬","应交税费","应付利息","应付股利","其他应付款","一年内到期的非流动负债","其他流动负债","流动负债合计","长期借款","应付债券","长期应付款","专项应付款","预计负债","递延所得税负债","其他非流动负债","非流动负债合计","负债合计","实收资本(股本)","资本公积","减:库存股",
                                         "盈余公积","未分配利润","所有者权益(或股东权益)","负债和所有者权益(或股东权益)合计"
                };

                var val = new List<string>();

                var listval = new List<mFinanceDebtChain>();

                foreach (var m in obj)
                {
                    m.cl_count = m.cl_count ?? 0;
                    m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                    m.cl_notes_payable = m.cl_notes_payable ?? 0;
                    m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                    m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                    m.cl_payable_interest = m.cl_payable_interest ?? 0;
                    m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                    m.count_assets = m.count_assets ?? 0;
                    m.count_liabilities = m.count_liabilities ?? 0;
                    m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                    m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                    m.fa_count = m.fa_count ?? 0;
                    m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                    m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                    m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                    m.fa_other_assets = m.fa_other_assets ?? 0;
                    m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                    m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                    m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                    m.nca_count = m.nca_count ?? 0;
                    m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                    m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                    m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                    m.nca_engineering_material = m.nca_engineering_material ?? 0;
                    m.semi_prod_inventory_amount = m.semi_prod_inventory_amount ?? 0;

                    m.nca_goodwill = m.nca_goodwill ?? 0;
                    m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                    m.nca_investment_property = m.nca_investment_property ?? 0;
                    m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                    m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                    m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                    m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                    m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                    m.nca_other_assets = m.nca_other_assets ?? 0;
                    m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                    m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                    m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                    m.ncl_count = m.ncl_count ?? 0;
                    m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                    m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                    m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;


                    m.ncl_special_payable = m.ncl_special_payable ?? 0;
                    m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                    m.oe_count = m.oe_count ?? 0;
                    m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                    m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                    m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                    m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                    m.bank_account_balance = m.bank_account_balance ?? 0;
                    m.withdraw_amount = m.withdraw_amount ?? 0;
                    m.platform_balance = m.platform_balance ?? 0;
                    m.logistics_prepayment = m.logistics_prepayment ?? 0;
                    m.finished_prepayment = m.finished_prepayment ?? 0;
                    m.semi_prepayment = m.semi_prepayment ?? 0;

                    m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                    m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                    m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                    m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                    m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                    m.semi_transfer_amount = m.semi_transfer_amount ?? 0;


                    m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                    m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                    m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                    m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                    m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                    m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;


                    m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                    m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                    m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                    m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;


                    m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                    m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                    m.semi_accounts_payable = m.semi_accounts_payable ?? 0;

                    m.purchase_pro_amount = m.purchase_pro_amount ?? 0;  //自产采购发货在途

                    //m.amount_borrowed = m.amount_borrowed;   //借支金额


                    //Add by Allan at 2019-01-30 16:04
                    m.prepayment = Math.Abs(m.prepayment);

                    //流动资产合计
                    m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                    //非流动资产合计
                    m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                    //资产总计
                    m.count_assets = m.fa_count + m.nca_count;

                    //流动负债合计
                    m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                    //所有者权益（或股东权益）合计
                    m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                    //负债和所有者权益（或股东权益）总计
                    m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;
                }

                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[0], start = obj[0].monetary_fund, end = obj[1].monetary_fund, diff = (obj[0].monetary_fund == 0 ? 0 : (obj[1].monetary_fund - obj[0].monetary_fund) / obj[0].monetary_fund * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[1], start = obj[0].withdraw_amount.Value, end = obj[1].withdraw_amount.Value, diff = (obj[0].withdraw_amount == 0 ? 0 : (obj[1].withdraw_amount - obj[0].withdraw_amount) / obj[0].withdraw_amount * 100).Value.ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[2], start = obj[0].platform_balance.Value, end = obj[1].platform_balance.Value, diff = (obj[0].platform_balance == 0 ? 0 : (obj[1].platform_balance - obj[0].platform_balance) / obj[0].platform_balance * 100).Value.ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[3], start = obj[0].bank_account_balance.Value, end = obj[1].bank_account_balance.Value, diff = (obj[0].bank_account_balance.Value == 0 ? 0 : (obj[1].bank_account_balance.Value - obj[0].bank_account_balance.Value) / obj[0].bank_account_balance.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[4], start = obj[0].fa_trading_finan_asset.Value, end = obj[1].fa_trading_finan_asset.Value, diff = (obj[0].fa_trading_finan_asset.Value == 0 ? 0 : (obj[1].fa_trading_finan_asset.Value - obj[0].fa_trading_finan_asset.Value) / obj[0].fa_trading_finan_asset.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[5], start = obj[0].fa_bill_receivable.Value, end = obj[1].fa_bill_receivable.Value, diff = (obj[0].fa_bill_receivable.Value == 0 ? 0 : (obj[1].fa_bill_receivable.Value - obj[0].fa_bill_receivable.Value) / obj[0].fa_bill_receivable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[6], start = obj[0].accounts_receivable, end = obj[1].accounts_receivable, diff = (obj[0].accounts_receivable == 0 ? 0 : (obj[1].accounts_receivable - obj[0].accounts_receivable) / obj[0].accounts_receivable * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[7], start = obj[0].amount_borrowed, end = obj[1].amount_borrowed, diff = (obj[0].amount_borrowed == 0 ? 0 : (obj[1].amount_borrowed - obj[0].amount_borrowed) / obj[0].amount_borrowed * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[8], start = obj[0].prepayment, end = obj[1].prepayment, diff = (obj[0].prepayment == 0 ? 0 : (obj[1].prepayment - obj[0].prepayment) / obj[0].prepayment * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[9], start = obj[0].finished_prepayment.Value, end = obj[1].finished_prepayment.Value, diff = (obj[0].finished_prepayment.Value == 0 ? 0 : (obj[1].finished_prepayment.Value - obj[0].finished_prepayment.Value) / obj[0].finished_prepayment.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[10], start = obj[0].semi_prepayment.Value, end = obj[1].semi_prepayment.Value, diff = (obj[0].semi_prepayment.Value == 0 ? 0 : (obj[1].semi_prepayment.Value - obj[0].semi_prepayment.Value) / obj[0].semi_prepayment.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[11], start = obj[0].logistics_prepayment.Value, end = obj[1].logistics_prepayment.Value, diff = (obj[0].logistics_prepayment.Value == 0 ? 0 : (obj[1].logistics_prepayment.Value - obj[0].logistics_prepayment.Value) / obj[0].logistics_prepayment.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[12], start = obj[0].fa_interest_receivable.Value, end = obj[1].fa_interest_receivable.Value, diff = (obj[0].fa_interest_receivable.Value == 0 ? 0 : (obj[1].fa_interest_receivable.Value - obj[0].fa_interest_receivable.Value) / obj[0].fa_interest_receivable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[13], start = obj[0].fa_dividends_receivable.Value, end = obj[1].fa_dividends_receivable.Value, diff = (obj[0].fa_dividends_receivable.Value == 0 ? 0 : (obj[1].fa_dividends_receivable.Value - obj[0].fa_dividends_receivable.Value) / obj[0].fa_dividends_receivable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[14], start = obj[0].other_accounts_receivable, end = obj[1].other_accounts_receivable, diff = (obj[0].other_accounts_receivable == 0 ? 0 : (obj[1].other_accounts_receivable - obj[0].other_accounts_receivable) / obj[0].other_accounts_receivable * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[15], start = obj[0].inventory_amount, end = obj[1].inventory_amount, diff = (obj[0].inventory_amount == 0 ? 0 : (obj[1].inventory_amount - obj[0].inventory_amount) / obj[0].inventory_amount * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[16], start = obj[0].fba_inventory_amount.Value, end = obj[1].fba_inventory_amount.Value, diff = (obj[0].fba_inventory_amount.Value == 0 ? 0 : (obj[1].fba_inventory_amount.Value - obj[0].fba_inventory_amount.Value) / obj[0].fba_inventory_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[17], start = obj[0].not_fba_inventory_amount.Value, end = obj[1].not_fba_inventory_amount.Value, diff = (obj[0].not_fba_inventory_amount.Value == 0 ? 0 : (obj[1].not_fba_inventory_amount.Value - obj[0].not_fba_inventory_amount.Value) / obj[0].not_fba_inventory_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[18], start = obj[0].fba_transfer_allot_amount.Value, end = obj[1].fba_transfer_allot_amount.Value, diff = (obj[0].fba_transfer_allot_amount.Value == 0 ? 0 : (obj[1].fba_transfer_allot_amount.Value - obj[0].fba_transfer_allot_amount.Value) / obj[0].fba_transfer_allot_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[19], start = obj[0].fba_transfer_plan_amount.Value, end = obj[1].fba_transfer_plan_amount.Value, diff = (obj[0].fba_transfer_plan_amount.Value == 0 ? 0 : (obj[1].fba_transfer_plan_amount.Value - obj[0].fba_transfer_plan_amount.Value) / obj[0].fba_transfer_plan_amount.Value * 100).ToString("N2") });


                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[20], start = obj[0].not_fba_transfer_allot_amount.Value, end = obj[1].not_fba_transfer_allot_amount.Value, diff = (obj[0].not_fba_transfer_allot_amount.Value == 0 ? 0 : (obj[1].not_fba_transfer_allot_amount.Value - obj[0].not_fba_transfer_allot_amount.Value) / obj[0].not_fba_transfer_allot_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[21], start = obj[0].not_fba_transfer_plan_amount.Value, end = obj[1].not_fba_transfer_plan_amount.Value, diff = (obj[0].not_fba_transfer_plan_amount.Value == 0 ? 0 : (obj[1].not_fba_transfer_plan_amount.Value - obj[0].not_fba_transfer_plan_amount.Value) / obj[0].not_fba_transfer_plan_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[22], start = obj[0].semi_inventory_amount.Value, end = obj[1].semi_inventory_amount.Value, diff = (obj[0].semi_inventory_amount.Value == 0 ? 0 : (obj[1].semi_inventory_amount.Value - obj[0].semi_inventory_amount.Value) / obj[0].semi_inventory_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[23], start = obj[0].semi_bailun_inventory_amount.Value, end = obj[1].semi_bailun_inventory_amount.Value, diff = (obj[0].semi_bailun_inventory_amount.Value == 0 ? 0 : (obj[1].semi_bailun_inventory_amount.Value - obj[0].semi_bailun_inventory_amount.Value) / obj[0].semi_bailun_inventory_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[24], start = obj[0].semi_hani_inventory_amount.Value, end = obj[1].semi_hani_inventory_amount.Value, diff = (obj[0].semi_hani_inventory_amount.Value == 0 ? 0 : (obj[1].semi_hani_inventory_amount.Value - obj[0].semi_hani_inventory_amount.Value) / obj[0].semi_hani_inventory_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[25], start = obj[0].semi_prod_inventory_amount.Value, end = obj[1].semi_prod_inventory_amount.Value, diff = (obj[0].semi_prod_inventory_amount.Value == 0 ? 0 : (obj[1].semi_prod_inventory_amount.Value - obj[0].semi_prod_inventory_amount.Value) / obj[0].semi_prod_inventory_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[26], start = obj[0].semi_transfer_amount.Value, end = obj[1].semi_transfer_amount.Value, diff = (obj[0].semi_transfer_amount.Value == 0 ? 0 : (obj[1].semi_transfer_amount.Value - obj[0].semi_transfer_amount.Value) / obj[0].semi_transfer_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[27], start = obj[0].semi_bailun_transfer_amount.Value, end = obj[1].semi_bailun_transfer_amount.Value, diff = (obj[0].semi_bailun_transfer_amount.Value == 0 ? 0 : (obj[1].semi_bailun_transfer_amount.Value - obj[0].semi_bailun_transfer_amount.Value) / obj[0].semi_bailun_transfer_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[28], start = obj[0].semi_hani_transfer_amount.Value, end = obj[1].semi_hani_transfer_amount.Value, diff = (obj[0].semi_hani_transfer_amount.Value == 0 ? 0 : (obj[1].semi_hani_transfer_amount.Value - obj[0].semi_hani_transfer_amount.Value) / obj[0].semi_hani_transfer_amount.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[29], start = obj[0].purchase_pro_amount.Value, end = obj[1].purchase_pro_amount.Value, diff = (obj[0].purchase_pro_amount.Value == 0 ? 0 : (obj[1].purchase_pro_amount.Value - obj[0].purchase_pro_amount.Value) / obj[0].purchase_pro_amount.Value * 100).ToString("N2") });

                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[30], start = obj[0].fa_oneyear_noncurrent_assets.Value, end = obj[1].fa_oneyear_noncurrent_assets.Value, diff = (obj[0].fa_oneyear_noncurrent_assets.Value == 0 ? 0 : (obj[1].fa_oneyear_noncurrent_assets.Value - obj[0].fa_oneyear_noncurrent_assets.Value) / obj[0].fa_oneyear_noncurrent_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[31], start = obj[0].fa_other_assets.Value, end = obj[1].fa_other_assets.Value, diff = (obj[0].fa_other_assets.Value == 0 ? 0 : (obj[1].fa_other_assets.Value - obj[0].fa_other_assets.Value) / obj[0].fa_other_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[32], start = obj[0].fa_count.Value, end = obj[1].fa_count.Value, diff = (obj[0].fa_count.Value == 0 ? 0 : (obj[1].fa_count.Value - obj[0].fa_count.Value) / obj[0].fa_count.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[33], start = obj[0].nca_avai_for_sale_fassets.Value, end = obj[1].nca_avai_for_sale_fassets.Value, diff = (obj[0].nca_avai_for_sale_fassets.Value == 0 ? 0 : (obj[1].nca_avai_for_sale_fassets.Value - obj[0].nca_avai_for_sale_fassets.Value) / obj[0].nca_avai_for_sale_fassets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[34], start = obj[0].nca_heldon_investment.Value, end = obj[1].nca_heldon_investment.Value, diff = (obj[0].nca_heldon_investment.Value == 0 ? 0 : (obj[1].nca_heldon_investment.Value - obj[0].nca_heldon_investment.Value) / obj[0].nca_heldon_investment.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[35], start = obj[0].nca_longterm_receivable.Value, end = obj[1].nca_longterm_receivable.Value, diff = (obj[0].nca_longterm_receivable.Value == 0 ? 0 : (obj[1].nca_longterm_receivable.Value - obj[0].nca_longterm_receivable.Value) / obj[0].nca_longterm_receivable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[36], start = obj[0].nca_longterm_equity_investment.Value, end = obj[1].nca_longterm_equity_investment.Value, diff = (obj[0].nca_longterm_equity_investment.Value == 0 ? 0 : (obj[1].nca_longterm_equity_investment.Value - obj[0].nca_longterm_equity_investment.Value) / obj[0].nca_longterm_equity_investment.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[37], start = obj[0].nca_investment_property.Value, end = obj[1].nca_investment_property.Value, diff = (obj[0].nca_investment_property.Value == 0 ? 0 : (obj[1].nca_investment_property.Value - obj[0].nca_investment_property.Value) / obj[0].nca_investment_property.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[38], start = obj[0].fixed_assets, end = obj[1].fixed_assets, diff = (obj[0].fixed_assets == 0 ? 0 : (obj[1].fixed_assets - obj[0].fixed_assets) / obj[0].fixed_assets * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[39], start = obj[0].nca_construction_in_process.Value, end = obj[1].nca_construction_in_process.Value, diff = (obj[0].nca_construction_in_process.Value == 0 ? 0 : (obj[1].nca_construction_in_process.Value - obj[0].nca_construction_in_process.Value) / obj[0].nca_construction_in_process.Value * 100).ToString("N2") });


                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[40], start = obj[0].nca_engineering_material.Value, end = obj[1].nca_engineering_material.Value, diff = (obj[0].nca_engineering_material.Value == 0 ? 0 : (obj[1].nca_engineering_material.Value - obj[0].nca_engineering_material.Value) / obj[0].nca_engineering_material.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[41], start = obj[0].nca_disposal_of_fixed_assets.Value, end = obj[1].nca_disposal_of_fixed_assets.Value, diff = (obj[0].nca_disposal_of_fixed_assets.Value == 0 ? 0 : (obj[1].nca_disposal_of_fixed_assets.Value - obj[0].nca_disposal_of_fixed_assets.Value) / obj[0].nca_disposal_of_fixed_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[42], start = obj[0].nca_productive_biological_asset.Value, end = obj[1].nca_productive_biological_asset.Value, diff = (obj[0].nca_productive_biological_asset.Value == 0 ? 0 : (obj[1].nca_productive_biological_asset.Value - obj[0].nca_productive_biological_asset.Value) / obj[0].monetary_fund * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[43], start = obj[0].nca_oil_and_gas_assets.Value, end = obj[1].nca_oil_and_gas_assets.Value, diff = (obj[0].nca_oil_and_gas_assets.Value == 0 ? 0 : (obj[1].nca_oil_and_gas_assets.Value - obj[0].nca_oil_and_gas_assets.Value) / obj[0].nca_oil_and_gas_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[44], start = obj[0].nca_intangible_assets.Value, end = obj[1].nca_intangible_assets.Value, diff = (obj[0].nca_intangible_assets.Value == 0 ? 0 : (obj[1].nca_intangible_assets.Value - obj[0].nca_intangible_assets.Value) / obj[0].nca_intangible_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[45], start = obj[0].nca_development_expenditure.Value, end = obj[1].nca_development_expenditure.Value, diff = (obj[0].nca_development_expenditure.Value == 0 ? 0 : (obj[1].nca_development_expenditure.Value - obj[0].nca_development_expenditure.Value) / obj[0].nca_development_expenditure.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[46], start = obj[0].nca_goodwill.Value, end = obj[1].nca_goodwill.Value, diff = (obj[0].nca_goodwill.Value == 0 ? 0 : (obj[1].nca_goodwill.Value - obj[0].nca_goodwill.Value) / obj[0].nca_goodwill.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[47], start = obj[0].nca_longterm_unamortized_expenses.Value, end = obj[1].nca_longterm_unamortized_expenses.Value, diff = (obj[0].nca_longterm_unamortized_expenses.Value == 0 ? 0 : (obj[1].nca_longterm_unamortized_expenses.Value - obj[0].nca_longterm_unamortized_expenses.Value) / obj[0].nca_longterm_unamortized_expenses.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[48], start = obj[0].nca_deferred_tax_assets.Value, end = obj[1].nca_deferred_tax_assets.Value, diff = (obj[0].nca_deferred_tax_assets.Value == 0 ? 0 : (obj[1].nca_deferred_tax_assets.Value - obj[0].nca_deferred_tax_assets.Value) / obj[0].nca_deferred_tax_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[49], start = obj[0].nca_other_assets.Value, end = obj[1].nca_other_assets.Value, diff = (obj[0].nca_other_assets.Value == 0 ? 0 : (obj[1].nca_other_assets.Value - obj[0].nca_other_assets.Value) / obj[0].nca_other_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[50], start = obj[0].nca_count.Value, end = obj[1].nca_count.Value, diff = (obj[0].nca_count.Value == 0 ? 0 : (obj[1].nca_count.Value - obj[0].nca_count.Value) / obj[0].nca_count.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[51], start = obj[0].count_assets.Value, end = obj[1].count_assets.Value, diff = (obj[0].count_assets.Value == 0 ? 0 : (obj[1].count_assets.Value - obj[0].count_assets.Value) / obj[0].count_assets.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[52], start = obj[0].short_term_borrow, end = obj[1].short_term_borrow, diff = (obj[0].short_term_borrow == 0 ? 0 : (obj[1].short_term_borrow - obj[0].short_term_borrow) / obj[0].short_term_borrow * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[53], start = obj[0].cl_trading_financ_liabilities.Value, end = obj[1].cl_trading_financ_liabilities.Value, diff = (obj[0].cl_trading_financ_liabilities.Value == 0 ? 0 : (obj[1].cl_trading_financ_liabilities.Value - obj[0].cl_trading_financ_liabilities.Value) / obj[0].cl_trading_financ_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[54], start = obj[0].cl_notes_payable.Value, end = obj[1].cl_notes_payable.Value, diff = (obj[0].cl_notes_payable.Value == 0 ? 0 : (obj[1].cl_notes_payable.Value - obj[0].cl_notes_payable.Value) / obj[0].cl_notes_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[55], start = obj[0].accounts_payable, end = obj[1].accounts_payable, diff = (obj[0].accounts_payable == 0 ? 0 : (obj[1].accounts_payable - obj[0].accounts_payable) / obj[0].accounts_payable * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[56], start = obj[0].finished_accounts_payable.Value, end = obj[1].finished_accounts_payable.Value, diff = (obj[0].finished_accounts_payable.Value == 0 ? 0 : (obj[1].finished_accounts_payable.Value - obj[0].finished_accounts_payable.Value) / obj[0].finished_accounts_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[57], start = obj[0].semi_accounts_payable.Value, end = obj[1].semi_accounts_payable.Value, diff = (obj[0].semi_accounts_payable.Value == 0 ? 0 : (obj[1].semi_accounts_payable.Value - obj[0].semi_accounts_payable.Value) / obj[0].semi_accounts_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[58], start = obj[0].logistics_accounts_payable.Value, end = obj[1].logistics_accounts_payable.Value, diff = (obj[0].logistics_accounts_payable.Value == 0 ? 0 : (obj[1].logistics_accounts_payable.Value - obj[0].logistics_accounts_payable.Value) / obj[0].logistics_accounts_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[59], start = obj[0].advance_received, end = obj[1].advance_received, diff = (obj[0].advance_received == 0 ? 0 : (obj[1].advance_received - obj[0].advance_received) / obj[0].advance_received * 100).ToString("N2") });



                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[60], start = obj[0].payable_remuneration, end = obj[1].payable_remuneration, diff = (obj[0].payable_remuneration == 0 ? 0 : (obj[1].payable_remuneration - obj[0].payable_remuneration) / obj[0].payable_remuneration * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[61], start = obj[0].taxes_payable, end = obj[1].taxes_payable, diff = (obj[0].taxes_payable == 0 ? 0 : (obj[1].taxes_payable - obj[0].taxes_payable) / obj[0].taxes_payable * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[62], start = obj[0].cl_payable_interest.Value, end = obj[1].cl_payable_interest.Value, diff = (obj[0].cl_payable_interest.Value == 0 ? 0 : (obj[1].cl_payable_interest.Value - obj[0].cl_payable_interest.Value) / obj[0].cl_payable_interest.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[63], start = obj[0].cl_dividends_payable.Value, end = obj[1].cl_dividends_payable.Value, diff = (obj[0].cl_dividends_payable.Value == 0 ? 0 : (obj[1].cl_dividends_payable.Value - obj[0].cl_dividends_payable.Value) / obj[0].cl_dividends_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[64], start = obj[0].other_accounts_payable, end = obj[1].other_accounts_payable, diff = (obj[0].other_accounts_payable == 0 ? 0 : (obj[1].other_accounts_payable - obj[0].other_accounts_payable) / obj[0].other_accounts_payable * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[65], start = obj[0].cl_oneyear_noncurrent_liabilities.Value, end = obj[1].cl_oneyear_noncurrent_liabilities.Value, diff = (obj[0].cl_oneyear_noncurrent_liabilities.Value == 0 ? 0 : (obj[1].cl_oneyear_noncurrent_liabilities.Value - obj[0].cl_oneyear_noncurrent_liabilities.Value) / obj[0].cl_oneyear_noncurrent_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[66], start = obj[0].cl_other_liabilities.Value, end = obj[1].cl_other_liabilities.Value, diff = (obj[0].cl_other_liabilities.Value == 0 ? 0 : (obj[1].cl_other_liabilities.Value - obj[0].cl_other_liabilities.Value) / obj[0].cl_other_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[67], start = obj[0].cl_count.Value, end = obj[1].cl_count.Value, diff = (obj[0].cl_count.Value == 0 ? 0 : (obj[1].cl_count.Value - obj[0].cl_count.Value) / obj[0].cl_count.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[68], start = obj[0].ncl_longterm_loan.Value, end = obj[1].ncl_longterm_loan.Value, diff = (obj[0].ncl_longterm_loan.Value == 0 ? 0 : (obj[1].ncl_longterm_loan.Value - obj[0].ncl_longterm_loan.Value) / obj[0].ncl_longterm_loan.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[69], start = obj[0].ncl_bonds_payable.Value, end = obj[1].ncl_bonds_payable.Value, diff = (obj[0].ncl_bonds_payable.Value == 0 ? 0 : (obj[1].ncl_bonds_payable.Value - obj[0].ncl_bonds_payable.Value) / obj[0].ncl_bonds_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[70], start = obj[0].long_term_accounts_payable, end = obj[1].long_term_accounts_payable, diff = (obj[0].long_term_accounts_payable == 0 ? 0 : (obj[1].long_term_accounts_payable - obj[0].long_term_accounts_payable) / obj[0].long_term_accounts_payable * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[71], start = obj[0].ncl_special_payable.Value, end = obj[1].ncl_special_payable.Value, diff = (obj[0].ncl_special_payable.Value == 0 ? 0 : (obj[1].ncl_special_payable.Value - obj[0].ncl_special_payable.Value) / obj[0].ncl_special_payable.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[72], start = obj[0].ncl_anticipation_liabilities.Value, end = obj[1].ncl_anticipation_liabilities.Value, diff = (obj[0].ncl_anticipation_liabilities.Value == 0 ? 0 : (obj[1].ncl_anticipation_liabilities.Value - obj[0].ncl_anticipation_liabilities.Value) / obj[0].ncl_anticipation_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[73], start = obj[0].ncl_deferred_income_tax_liabilities.Value, end = obj[1].ncl_deferred_income_tax_liabilities.Value, diff = (obj[0].ncl_deferred_income_tax_liabilities.Value == 0 ? 0 : (obj[1].ncl_deferred_income_tax_liabilities.Value - obj[0].ncl_deferred_income_tax_liabilities.Value) / obj[0].ncl_deferred_income_tax_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[74], start = obj[0].ncl_other_liabilities.Value, end = obj[1].ncl_other_liabilities.Value, diff = (obj[0].ncl_other_liabilities.Value == 0 ? 0 : (obj[1].ncl_other_liabilities.Value - obj[0].ncl_other_liabilities.Value) / obj[0].ncl_other_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[75], start = obj[0].ncl_count.Value, end = obj[1].ncl_count.Value, diff = (obj[0].ncl_count.Value == 0 ? 0 : (obj[1].ncl_count.Value - obj[0].ncl_count.Value) / obj[0].ncl_count.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[76], start = obj[0].count_liabilities.Value, end = obj[1].count_liabilities.Value, diff = (obj[0].count_liabilities.Value == 0 ? 0 : (obj[1].count_liabilities.Value - obj[0].count_liabilities.Value) / obj[0].count_liabilities.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[77], start = obj[0].oe_paicl_up_capital.Value, end = obj[1].oe_paicl_up_capital.Value, diff = (obj[0].oe_paicl_up_capital.Value == 0 ? 0 : (obj[1].oe_paicl_up_capital.Value - obj[0].oe_paicl_up_capital.Value) / obj[0].oe_paicl_up_capital.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[78], start = obj[0].oe_capital_reserve.Value, end = obj[1].oe_capital_reserve.Value, diff = (obj[0].oe_capital_reserve.Value == 0 ? 0 : (obj[1].oe_capital_reserve.Value - obj[0].oe_capital_reserve.Value) / obj[0].oe_capital_reserve.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[79], start = obj[0].oe_inventory_amount.Value, end = obj[1].oe_inventory_amount.Value, diff = (obj[0].oe_inventory_amount.Value == 0 ? 0 : (obj[1].oe_inventory_amount.Value - obj[0].oe_inventory_amount.Value) / obj[0].oe_inventory_amount.Value * 100).ToString("N2") });



                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[80], start = obj[0].oe_surplus_public_accumulation.Value, end = obj[1].oe_surplus_public_accumulation.Value, diff = (obj[0].oe_surplus_public_accumulation.Value == 0 ? 0 : (obj[1].oe_surplus_public_accumulation.Value - obj[0].oe_surplus_public_accumulation.Value) / obj[0].oe_surplus_public_accumulation.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[81], start = obj[0].oe_undistributed_profit.Value, end = obj[1].oe_undistributed_profit.Value, diff = (obj[0].oe_undistributed_profit.Value == 0 ? 0 : (obj[1].oe_undistributed_profit.Value - obj[0].oe_undistributed_profit.Value) / obj[0].oe_undistributed_profit.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[82], start = obj[0].oe_count.Value, end = obj[1].oe_count.Value, diff = (obj[0].oe_count.Value == 0 ? 0 : (obj[1].oe_count.Value - obj[0].oe_count.Value) / obj[0].oe_count.Value * 100).ToString("N2") });
                listval.Add(new mFinanceDebtChain { onelevelname = "", sencondlevelname = s[83], start = obj[0].count_liabilities_and_oe.Value, end = obj[1].count_liabilities_and_oe.Value, diff = (obj[0].count_liabilities_and_oe.Value == 0 ? 0 : (obj[1].count_liabilities_and_oe.Value - obj[0].count_liabilities_and_oe.Value) / obj[0].count_liabilities_and_oe.Value * 100).ToString("N2") });
                

                var listPro = new List<string>();
                for (var i = 0; i < s.Count; i++)
                {
                    listval[i].diffval = listval[i].end - listval[i].start;

                    if (i >= 0 && i < 33)
                    {
                        listval[i].onelevelname=("流动资产");
                    }
                    else if (i >= 33 && i < 51)
                    {
                        listval[i].onelevelname=("非流动资产");
                    }
                    else if (i >= 51 && i < 52)
                    {
                        listval[i].onelevelname=("资产合计");
                    }
                    else if (i >= 52 && i < 68)
                    {
                        listval[i].onelevelname=("流动负债");
                    }
                    else if (i >= 68 && i < 76)
                    {
                        listval[i].onelevelname=("非流动负债");
                    }
                    else if (i >= 76 && i < 77)
                    {
                        listval[i].onelevelname=("负债合计");
                    }
                    else if (i >= 77 && i < 83)
                    {
                        listval[i].onelevelname=("所有者权益(或股东权益)");
                    }
                    else if (i >= 83 && i < 84)
                    {
                        listval[i].onelevelname=("所有者权益(或股东权益)合计");
                    }
                }


                return Json(new
                {
                    success = true,
                    msg = "",
                    data = listval.Select(a=> new {
                        start = a.start.ToString("N2"),
                        end = a.end.ToString("N2"),
                        a.diff,
                        diffval = a.diffval.ToString("N2"),
                        a.onelevelname,
                        a.sencondlevelname,
                    
                    }),
                    start = start.ToString("yyyy-MM-dd"),
                    end = end.ToString("yyyy-MM-dd")
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message
                });
            }

        }

        public ActionResult ExportFinanceDebtChainChart(DateTime start, DateTime end)
        {
            try
            {
                var obj = new Services.FinanceReportServices().ListBalanceSheet(start, end);

                var s = new List<string>() { "货币资金", "1.平台提现在途", "2.第三方平台余额", "3.银行帐号余额", "交易性金融资金", "应收票据", "应收账款", "1.借支金额", "预付款项", "1.预付成品供应商", "2.预付半成品供应商", "3.预付物流供应商", "应收利息", "应收股利", "其他应收款", "存货", "1.存货FBA仓在库", "2.存货非FBA仓在库", "3.存货FBA仓在途(非调拨计划)", "4.存货FBA仓在途(调拨计划)",
                                         "5.存货非FBA仓在途(非调拨计划)","6.存货非FBA在途(调拨计划)","7.存货半成品在库","7.1百伦半成品在库","7.2哈倪曼半成品在库","7.3生产库存","8.存货半成品在途","8.1百伦半成品在途","8.2哈倪曼半成品在途","9.自产采购发货在途","一年内到期的非流动资产","其他流动资产","流动资产合计","可供出售金融资产","持有至到期投资","长期应收款","长期股权投资","投资性房地产","固定资产","在建工程",
                                         "工程物资","固定资产清理","生产性生物资产","油气资产","无形资产","开发支出","商誉","长期待摊费用","递延所得税资产","其他非流动资产","非流动资产合计","资产合计","短期借款","交易性金融负债","应付票据","应付账款","1.成品供应商","2.应付半成品供应商","3.应付物流供应商","预收款项",
                                         "应付职工薪酬","应交税费","应付利息","应付股利","其他应付款","一年内到期的非流动负债","其他流动负债","流动负债合计","长期借款","应付债券","长期应付款","专项应付款","预计负债","递延所得税负债","其他非流动负债","非流动负债合计","负债合计","实收资本(股本)","资本公积","减:库存股",
                                         "盈余公积","未分配利润","所有者权益(或股东权益)","负债和所有者权益(或股东权益)合计"
                };

                var val = new List<string>();

                foreach (var m in obj)
                {
                    m.cl_count = m.cl_count ?? 0;
                    m.cl_dividends_payable = m.cl_dividends_payable ?? 0;
                    m.cl_notes_payable = m.cl_notes_payable ?? 0;
                    m.cl_oneyear_noncurrent_liabilities = m.cl_oneyear_noncurrent_liabilities ?? 0;
                    m.cl_other_liabilities = m.cl_other_liabilities ?? 0;
                    m.cl_payable_interest = m.cl_payable_interest ?? 0;
                    m.cl_trading_financ_liabilities = m.cl_trading_financ_liabilities ?? 0;
                    m.count_assets = m.count_assets ?? 0;
                    m.count_liabilities = m.count_liabilities ?? 0;
                    m.count_liabilities_and_oe = m.count_liabilities_and_oe ?? 0;
                    m.fa_bill_receivable = m.fa_bill_receivable ?? 0;

                    m.fa_count = m.fa_count ?? 0;
                    m.fa_dividends_receivable = m.fa_dividends_receivable ?? 0;
                    m.fa_interest_receivable = m.fa_interest_receivable ?? 0;
                    m.fa_oneyear_noncurrent_assets = m.fa_oneyear_noncurrent_assets ?? 0;
                    m.fa_other_assets = m.fa_other_assets ?? 0;
                    m.fa_trading_finan_asset = m.fa_trading_finan_asset ?? 0;
                    m.nca_avai_for_sale_fassets = m.nca_avai_for_sale_fassets ?? 0;
                    m.nca_construction_in_process = m.nca_construction_in_process ?? 0;
                    m.nca_count = m.nca_count ?? 0;
                    m.nca_deferred_tax_assets = m.nca_deferred_tax_assets ?? 0;
                    m.nca_development_expenditure = m.nca_development_expenditure ?? 0;
                    m.nca_disposal_of_fixed_assets = m.nca_disposal_of_fixed_assets ?? 0;
                    m.nca_engineering_material = m.nca_engineering_material ?? 0;


                    m.nca_goodwill = m.nca_goodwill ?? 0;
                    m.nca_heldon_investment = m.nca_heldon_investment ?? 0;
                    m.nca_investment_property = m.nca_investment_property ?? 0;
                    m.nca_longterm_equity_investment = m.nca_longterm_equity_investment ?? 0;
                    m.nca_longterm_receivable = m.nca_longterm_receivable ?? 0;
                    m.nca_longterm_unamortized_expenses = m.nca_longterm_unamortized_expenses ?? 0;
                    m.nca_oil_and_gas_assets = m.nca_oil_and_gas_assets ?? 0;
                    m.nca_intangible_assets = m.nca_intangible_assets ?? 0;
                    m.nca_other_assets = m.nca_other_assets ?? 0;
                    m.nca_productive_biological_asset = m.nca_productive_biological_asset ?? 0;
                    m.ncl_anticipation_liabilities = m.ncl_anticipation_liabilities ?? 0;
                    m.ncl_bonds_payable = m.ncl_bonds_payable ?? 0;
                    m.ncl_count = m.ncl_count ?? 0;
                    m.ncl_deferred_income_tax_liabilities = m.ncl_deferred_income_tax_liabilities ?? 0;
                    m.ncl_longterm_loan = m.ncl_longterm_loan ?? 0;
                    m.ncl_other_liabilities = m.ncl_other_liabilities ?? 0;
                    m.semi_prod_inventory_amount = m.semi_prod_inventory_amount ?? 0;

                    m.ncl_special_payable = m.ncl_special_payable ?? 0;
                    m.oe_capital_reserve = m.oe_capital_reserve ?? 0;
                    m.oe_count = m.oe_count ?? 0;
                    m.oe_inventory_amount = m.oe_inventory_amount ?? 0;
                    m.oe_paicl_up_capital = m.oe_paicl_up_capital ?? 0;
                    m.oe_surplus_public_accumulation = m.oe_surplus_public_accumulation ?? 0;
                    m.oe_undistributed_profit = m.oe_undistributed_profit ?? 0;

                    m.bank_account_balance = m.bank_account_balance ?? 0;
                    m.withdraw_amount = m.withdraw_amount ?? 0;
                    m.platform_balance = m.platform_balance ?? 0;
                    m.logistics_prepayment = m.logistics_prepayment ?? 0;
                    m.finished_prepayment = m.finished_prepayment ?? 0;
                    m.semi_prepayment = m.semi_prepayment ?? 0;

                    m.fba_inventory_amount = m.fba_inventory_amount ?? 0;
                    m.not_fba_inventory_amount = m.not_fba_inventory_amount ?? 0;
                    m.fba_transfer_amount = m.fba_transfer_amount ?? 0;
                    m.not_fba_transfer_amount = m.not_fba_transfer_amount ?? 0;
                    m.semi_inventory_amount = m.semi_inventory_amount ?? 0;
                    m.semi_transfer_amount = m.semi_transfer_amount ?? 0;


                    m.fba_transfer_allot_amount = m.fba_transfer_allot_amount ?? 0;
                    m.not_fba_transfer_allot_amount = m.not_fba_transfer_allot_amount ?? 0;
                    m.fba_transfer_plan_amount = m.fba_transfer_plan_amount ?? 0;
                    m.not_fba_transfer_plan_amount = m.not_fba_transfer_plan_amount ?? 0;
                    m.fba_purchase_amount = m.fba_purchase_amount ?? 0;
                    m.not_fba_purchase_amount = m.not_fba_purchase_amount ?? 0;


                    m.semi_bailun_inventory_amount = m.semi_bailun_inventory_amount ?? 0;
                    m.semi_hani_inventory_amount = m.semi_hani_inventory_amount ?? 0;
                    m.semi_bailun_transfer_amount = m.semi_bailun_transfer_amount ?? 0;
                    m.semi_hani_transfer_amount = m.semi_hani_transfer_amount ?? 0;


                    m.logistics_accounts_payable = m.logistics_accounts_payable ?? 0;
                    m.finished_accounts_payable = m.finished_accounts_payable ?? 0;
                    m.semi_accounts_payable = m.semi_accounts_payable ?? 0;


                    m.purchase_pro_amount = m.purchase_pro_amount ?? 0;

                    //m.amount_borrowed = m.amount_borrowed;   //借支金额


                    //Add by Allan at 2019-01-30 16:04
                    m.prepayment = Math.Abs(m.prepayment);

                    //流动资产合计
                    m.fa_count = m.monetary_fund + m.fa_trading_finan_asset + m.fa_bill_receivable + m.accounts_receivable + m.prepayment + m.fa_interest_receivable + m.fa_dividends_receivable + m.other_accounts_receivable + m.inventory_amount + m.fa_oneyear_noncurrent_assets + m.fa_other_assets;

                    //非流动资产合计
                    m.nca_count = m.nca_avai_for_sale_fassets + m.nca_heldon_investment + m.nca_longterm_receivable + m.nca_longterm_equity_investment + m.nca_investment_property + m.fixed_assets + m.nca_construction_in_process + m.nca_engineering_material + m.nca_disposal_of_fixed_assets + m.nca_productive_biological_asset + m.nca_oil_and_gas_assets + m.nca_intangible_assets + m.nca_development_expenditure + m.nca_goodwill + m.nca_longterm_unamortized_expenses + m.nca_deferred_tax_assets + m.nca_other_assets;

                    //资产总计
                    m.count_assets = m.fa_count + m.nca_count;

                    //流动负债合计
                    m.cl_count = m.short_term_borrow + m.cl_trading_financ_liabilities + m.cl_notes_payable + m.accounts_payable + 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_bonds_payable + m.long_term_accounts_payable + m.ncl_special_payable + m.ncl_anticipation_liabilities + m.ncl_deferred_income_tax_liabilities + m.ncl_other_liabilities;

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

                    //所有者权益（或股东权益）合计
                    m.oe_count = m.oe_paicl_up_capital + m.oe_capital_reserve + m.oe_inventory_amount + m.oe_surplus_public_accumulation + m.oe_undistributed_profit;

                    //负债和所有者权益（或股东权益）总计
                    m.count_liabilities_and_oe = m.count_liabilities + m.oe_count;
                }

                

                var colNames = new List<string> { "一级项目", "二级项目", start.ToString("yyyy-MM-dd"), end.ToString("yyyy-MM-dd"),"环比%","差异值" };

                var list = new List<string>();

                list.Add(s[0]+"|"+obj[0].monetary_fund.ToString("N2")+"|"+obj[1].monetary_fund.ToString("N2") + "|"+(obj[0].monetary_fund == 0 ? 0 : (obj[1].monetary_fund - obj[0].monetary_fund) / obj[0].monetary_fund * 100).ToString("N2"));
                list.Add(s[1] + "|" + obj[0].withdraw_amount.Value.ToString("N2") + "|" + obj[1].withdraw_amount.Value.ToString("N2") + "|" + (obj[0].withdraw_amount.Value == 0 ? 0 : (obj[1].withdraw_amount.Value - obj[0].withdraw_amount.Value) / obj[0].withdraw_amount.Value * 100).ToString("N2"));
                list.Add(s[2]+"|"+obj[0].platform_balance.Value.ToString("N2")+"|"+obj[1].platform_balance.Value.ToString("N2") + "|"+(obj[0].platform_balance.Value == 0 ? 0 : (obj[1].platform_balance.Value - obj[0].platform_balance.Value) / obj[0].platform_balance.Value * 100).ToString("N2"));
                list.Add(s[3]+"|"+obj[0].bank_account_balance.Value.ToString("N2")+"|"+obj[1].bank_account_balance.Value.ToString("N2") + "|"+(obj[0].bank_account_balance.Value == 0 ? 0 : (obj[1].bank_account_balance.Value - obj[0].bank_account_balance.Value) / obj[0].bank_account_balance.Value * 100).ToString("N2"));
                list.Add(s[4]+"|"+obj[0].fa_trading_finan_asset.Value.ToString("N2")+"|"+obj[1].fa_trading_finan_asset.Value.ToString("N2") + "|"+(obj[0].fa_trading_finan_asset.Value == 0 ? 0 : (obj[1].fa_trading_finan_asset.Value - obj[0].fa_trading_finan_asset.Value) / obj[0].fa_trading_finan_asset.Value * 100).ToString("N2"));
                list.Add(s[5]+"|"+obj[0].fa_bill_receivable.Value.ToString("N2")+"|"+obj[1].fa_bill_receivable.Value.ToString("N2") + "|"+(obj[0].fa_bill_receivable.Value == 0 ? 0 : (obj[1].fa_bill_receivable.Value - obj[0].fa_bill_receivable.Value) / obj[0].fa_bill_receivable.Value * 100).ToString("N2"));
                list.Add(s[6]+"|"+obj[0].accounts_receivable.ToString("N2")+"|"+obj[1].accounts_receivable.ToString("N2") + "|"+(obj[0].accounts_receivable == 0 ? 0 : (obj[1].accounts_receivable - obj[0].accounts_receivable) / obj[0].accounts_receivable * 100).ToString("N2"));
                list.Add(s[7]+"|"+obj[0].amount_borrowed.ToString("N2")+"|"+obj[1].amount_borrowed.ToString("N2") + "|"+(obj[0].amount_borrowed == 0 ? 0 : (obj[1].amount_borrowed - obj[0].amount_borrowed) / obj[0].amount_borrowed * 100).ToString("N2"));
                list.Add(s[8]+"|"+obj[0].prepayment.ToString("N2")+"|"+obj[1].prepayment.ToString("N2") + "|"+(obj[0].prepayment == 0 ? 0 : (obj[1].prepayment - obj[0].prepayment) / obj[0].prepayment * 100).ToString("N2"));
                list.Add(s[9]+"|"+obj[0].finished_prepayment.Value.ToString("N2")+"|"+obj[1].finished_prepayment.Value.ToString("N2") + "|"+(obj[0].finished_prepayment.Value == 0 ? 0 : (obj[1].finished_prepayment.Value - obj[0].finished_prepayment.Value) / obj[0].finished_prepayment.Value * 100).ToString("N2"));
                list.Add(s[10]+"|"+obj[0].semi_prepayment.Value.ToString("N2")+"|"+obj[1].semi_prepayment.Value.ToString("N2") + "|"+(obj[0].semi_prepayment.Value == 0 ? 0 : (obj[1].semi_prepayment.Value - obj[0].semi_prepayment.Value) / obj[0].semi_prepayment.Value * 100).ToString("N2"));
                list.Add(s[11]+"|"+obj[0].logistics_prepayment.Value.ToString("N2")+"|"+obj[1].logistics_prepayment.Value.ToString("N2") + "|"+(obj[0].logistics_prepayment.Value == 0 ? 0 : (obj[1].logistics_prepayment.Value - obj[0].logistics_prepayment.Value) / obj[0].logistics_prepayment.Value * 100).ToString("N2"));
                list.Add(s[12]+"|"+obj[0].fa_interest_receivable.Value.ToString("N2")+"|"+obj[1].fa_interest_receivable.Value.ToString("N2") + "|"+(obj[0].fa_interest_receivable.Value == 0 ? 0 : (obj[1].fa_interest_receivable.Value - obj[0].fa_interest_receivable.Value) / obj[0].fa_interest_receivable.Value * 100).ToString("N2"));
                list.Add(s[13]+"|"+obj[0].fa_dividends_receivable.Value.ToString("N2")+"|"+obj[1].fa_dividends_receivable.Value.ToString("N2") + "|"+(obj[0].fa_dividends_receivable.Value == 0 ? 0 : (obj[1].fa_dividends_receivable.Value - obj[0].fa_dividends_receivable.Value) / obj[0].fa_dividends_receivable.Value * 100).ToString("N2"));
                list.Add(s[14]+"|"+obj[0].other_accounts_receivable.ToString("N2")+"|"+obj[1].other_accounts_receivable.ToString("N2") + "|"+(obj[0].other_accounts_receivable == 0 ? 0 : (obj[1].other_accounts_receivable - obj[0].other_accounts_receivable) / obj[0].other_accounts_receivable * 100).ToString("N2"));
                list.Add(s[15]+"|"+obj[0].inventory_amount.ToString("N2")+"|"+obj[1].inventory_amount.ToString("N2") + "|"+(obj[0].inventory_amount == 0 ? 0 : (obj[1].inventory_amount - obj[0].inventory_amount) / obj[0].inventory_amount * 100).ToString("N2"));
                list.Add(s[16]+"|"+obj[0].fba_inventory_amount.Value.ToString("N2")+"|"+obj[1].fba_inventory_amount.Value.ToString("N2") + "|"+(obj[0].fba_inventory_amount.Value == 0 ? 0 : (obj[1].fba_inventory_amount.Value - obj[0].fba_inventory_amount.Value) / obj[0].fba_inventory_amount.Value * 100).ToString("N2"));
                list.Add(s[17]+"|"+obj[0].not_fba_inventory_amount.Value.ToString("N2")+"|"+obj[1].not_fba_inventory_amount.Value.ToString("N2") + "|"+(obj[0].not_fba_inventory_amount.Value == 0 ? 0 : (obj[1].not_fba_inventory_amount.Value - obj[0].not_fba_inventory_amount.Value) / obj[0].not_fba_inventory_amount.Value * 100).ToString("N2"));
                list.Add(s[18]+"|"+obj[0].fba_transfer_allot_amount.Value.ToString("N2")+"|"+obj[1].fba_transfer_allot_amount.Value.ToString("N2") + "|"+(obj[0].fba_transfer_allot_amount.Value == 0 ? 0 : (obj[1].fba_transfer_allot_amount.Value - obj[0].fba_transfer_allot_amount.Value) / obj[0].fba_transfer_allot_amount.Value * 100).ToString("N2"));
                list.Add(s[19]+"|"+obj[0].fba_transfer_plan_amount.Value.ToString("N2")+"|"+obj[1].fba_transfer_plan_amount.Value.ToString("N2") + "|"+(obj[0].fba_transfer_plan_amount.Value == 0 ? 0 : (obj[1].fba_transfer_plan_amount.Value - obj[0].fba_transfer_plan_amount.Value) / obj[0].fba_transfer_plan_amount.Value * 100).ToString("N2"));


                list.Add(s[20]+"|"+obj[0].not_fba_transfer_allot_amount.Value.ToString("N2")+"|"+obj[1].not_fba_transfer_allot_amount.Value.ToString("N2") + "|"+(obj[0].not_fba_transfer_allot_amount.Value == 0 ? 0 : (obj[1].not_fba_transfer_allot_amount.Value - obj[0].not_fba_transfer_allot_amount.Value) / obj[0].not_fba_transfer_allot_amount.Value * 100).ToString("N2"));
                list.Add(s[21]+"|"+obj[0].not_fba_transfer_plan_amount.Value.ToString("N2")+"|"+obj[1].not_fba_transfer_plan_amount.Value.ToString("N2") + "|"+(obj[0].not_fba_transfer_plan_amount.Value == 0 ? 0 : (obj[1].not_fba_transfer_plan_amount.Value - obj[0].not_fba_transfer_plan_amount.Value) / obj[0].not_fba_transfer_plan_amount.Value * 100).ToString("N2"));
                list.Add(s[22]+"|"+obj[0].semi_inventory_amount.Value.ToString("N2")+"|"+obj[1].semi_inventory_amount.Value.ToString("N2") + "|"+(obj[0].semi_inventory_amount.Value == 0 ? 0 : (obj[1].semi_inventory_amount.Value - obj[0].semi_inventory_amount.Value) / obj[0].semi_inventory_amount.Value * 100).ToString("N2"));
                list.Add(s[23]+"|"+obj[0].semi_bailun_inventory_amount.Value.ToString("N2")+"|"+obj[1].semi_bailun_inventory_amount.Value.ToString("N2") + "|"+(obj[0].semi_bailun_inventory_amount.Value == 0 ? 0 : (obj[1].semi_bailun_inventory_amount.Value - obj[0].semi_bailun_inventory_amount.Value) / obj[0].semi_bailun_inventory_amount.Value * 100).ToString("N2"));
                list.Add(s[24]+"|"+obj[0].semi_hani_inventory_amount.Value.ToString("N2")+"|"+obj[1].semi_hani_inventory_amount.Value.ToString("N2") + "|"+(obj[0].semi_hani_inventory_amount.Value == 0 ? 0 : (obj[1].semi_hani_inventory_amount.Value - obj[0].semi_hani_inventory_amount.Value) / obj[0].semi_hani_inventory_amount.Value * 100).ToString("N2"));
                list.Add(s[25] + "|" + obj[0].semi_prod_inventory_amount.Value.ToString("N2") + "|" + obj[1].semi_prod_inventory_amount.Value.ToString("N2") + "|" + (obj[0].semi_prod_inventory_amount.Value == 0 ? 0 : (obj[1].semi_prod_inventory_amount.Value - obj[0].semi_prod_inventory_amount.Value) / obj[0].semi_prod_inventory_amount.Value * 100).ToString("N2"));
                list.Add(s[26]+"|"+obj[0].semi_transfer_amount.Value.ToString("N2")+"|"+obj[1].semi_transfer_amount.Value.ToString("N2") + "|"+(obj[0].semi_transfer_amount.Value == 0 ? 0 : (obj[1].semi_transfer_amount.Value - obj[0].semi_transfer_amount.Value) / obj[0].semi_transfer_amount.Value * 100).ToString("N2"));
                list.Add(s[27]+"|"+obj[0].semi_bailun_transfer_amount.Value.ToString("N2")+"|"+obj[1].semi_bailun_transfer_amount.Value.ToString("N2") + "|"+(obj[0].semi_bailun_transfer_amount.Value == 0 ? 0 : (obj[1].semi_bailun_transfer_amount.Value - obj[0].semi_bailun_transfer_amount.Value) / obj[0].semi_bailun_transfer_amount.Value * 100).ToString("N2"));
                list.Add(s[28]+"|"+obj[0].semi_hani_transfer_amount.Value.ToString("N2")+"|"+obj[1].semi_hani_transfer_amount.Value.ToString("N2") + "|"+(obj[0].semi_hani_transfer_amount.Value == 0 ? 0 : (obj[1].semi_hani_transfer_amount.Value - obj[0].semi_hani_transfer_amount.Value) / obj[0].semi_hani_transfer_amount.Value * 100).ToString("N2"));
                list.Add(s[29] + "|" + obj[0].purchase_pro_amount.Value.ToString("N2") + "|" + obj[1].purchase_pro_amount.Value.ToString("N2") + "|" + (obj[0].purchase_pro_amount.Value == 0 ? 0 : (obj[1].purchase_pro_amount.Value - obj[0].purchase_pro_amount.Value) / obj[0].purchase_pro_amount.Value * 100).ToString("N2"));
                list.Add(s[30]+"|"+obj[0].fa_oneyear_noncurrent_assets.Value.ToString("N2")+"|"+obj[1].fa_oneyear_noncurrent_assets.Value.ToString("N2") + "|"+(obj[0].fa_oneyear_noncurrent_assets.Value == 0 ? 0 : (obj[1].fa_oneyear_noncurrent_assets.Value - obj[0].fa_oneyear_noncurrent_assets.Value) / obj[0].fa_oneyear_noncurrent_assets.Value * 100).ToString("N2"));
                list.Add(s[31]+"|"+obj[0].fa_other_assets.Value.ToString("N2")+"|"+obj[1].fa_other_assets.Value.ToString("N2") + "|"+(obj[0].fa_other_assets.Value == 0 ? 0 : (obj[1].fa_other_assets.Value - obj[0].fa_other_assets.Value) / obj[0].fa_other_assets.Value * 100).ToString("N2"));
                list.Add(s[32]+"|"+obj[0].fa_count.Value.ToString("N2")+"|"+obj[1].fa_count.Value.ToString("N2") + "|"+(obj[0].fa_count.Value == 0 ? 0 : (obj[1].fa_count.Value - obj[0].fa_count.Value) / obj[0].fa_count.Value * 100).ToString("N2"));
                list.Add(s[33]+"|"+obj[0].nca_avai_for_sale_fassets.Value.ToString("N2")+"|"+obj[1].nca_avai_for_sale_fassets.Value.ToString("N2") + "|"+(obj[0].nca_avai_for_sale_fassets.Value == 0 ? 0 : (obj[1].nca_avai_for_sale_fassets.Value - obj[0].nca_avai_for_sale_fassets.Value) / obj[0].nca_avai_for_sale_fassets.Value * 100).ToString("N2"));
                list.Add(s[34]+"|"+obj[0].nca_heldon_investment.Value.ToString("N2")+"|"+obj[1].nca_heldon_investment.Value.ToString("N2") + "|"+(obj[0].nca_heldon_investment.Value == 0 ? 0 : (obj[1].nca_heldon_investment.Value - obj[0].nca_heldon_investment.Value) / obj[0].nca_heldon_investment.Value * 100).ToString("N2"));
                list.Add(s[35]+"|"+obj[0].nca_longterm_receivable.Value.ToString("N2")+"|"+obj[1].nca_longterm_receivable.Value.ToString("N2") + "|"+(obj[0].nca_longterm_receivable.Value == 0 ? 0 : (obj[1].nca_longterm_receivable.Value - obj[0].nca_longterm_receivable.Value) / obj[0].nca_longterm_receivable.Value * 100).ToString("N2"));
                list.Add(s[36]+"|"+obj[0].nca_longterm_equity_investment.Value.ToString("N2")+"|"+obj[1].nca_longterm_equity_investment.Value.ToString("N2") + "|"+(obj[0].nca_longterm_equity_investment.Value == 0 ? 0 : (obj[1].nca_longterm_equity_investment.Value - obj[0].nca_longterm_equity_investment.Value) / obj[0].nca_longterm_equity_investment.Value * 100).ToString("N2"));
                list.Add(s[37]+"|"+obj[0].nca_investment_property.Value.ToString("N2")+"|"+obj[1].nca_investment_property.Value.ToString("N2") + "|"+(obj[0].nca_investment_property.Value == 0 ? 0 : (obj[1].nca_investment_property.Value - obj[0].nca_investment_property.Value) / obj[0].nca_investment_property.Value * 100).ToString("N2"));
                list.Add(s[38]+"|"+obj[0].fixed_assets.ToString("N2")+"|"+obj[1].fixed_assets.ToString("N2") + "|"+(obj[0].fixed_assets == 0 ? 0 : (obj[1].fixed_assets - obj[0].fixed_assets) / obj[0].fixed_assets * 100).ToString("N2"));
                list.Add(s[39]+"|"+obj[0].nca_construction_in_process.Value.ToString("N2")+"|"+obj[1].nca_construction_in_process.Value.ToString("N2") + "|"+(obj[0].nca_construction_in_process.Value == 0 ? 0 : (obj[1].nca_construction_in_process.Value - obj[0].nca_construction_in_process.Value) / obj[0].nca_construction_in_process.Value * 100).ToString("N2"));



                list.Add(s[40]+"|"+obj[0].nca_engineering_material.Value.ToString("N2")+"|"+obj[1].nca_engineering_material.Value.ToString("N2") + "|"+(obj[0].nca_engineering_material.Value == 0 ? 0 : (obj[1].nca_engineering_material.Value - obj[0].nca_engineering_material.Value) / obj[0].nca_engineering_material.Value * 100).ToString("N2"));
                list.Add(s[41]+"|"+obj[0].nca_disposal_of_fixed_assets.Value.ToString("N2")+"|"+obj[1].nca_disposal_of_fixed_assets.Value.ToString("N2") + "|"+(obj[0].nca_disposal_of_fixed_assets.Value == 0 ? 0 : (obj[1].nca_disposal_of_fixed_assets.Value - obj[0].nca_disposal_of_fixed_assets.Value) / obj[0].nca_disposal_of_fixed_assets.Value * 100).ToString("N2"));
                list.Add(s[42]+"|"+obj[0].nca_productive_biological_asset.Value.ToString("N2")+"|"+obj[1].nca_productive_biological_asset.Value.ToString("N2") + "|"+(obj[0].nca_productive_biological_asset.Value == 0 ? 0 : (obj[1].nca_productive_biological_asset.Value - obj[0].nca_productive_biological_asset.Value) / obj[0].nca_productive_biological_asset.Value * 100).ToString("N2"));
                list.Add(s[43]+"|"+obj[0].nca_oil_and_gas_assets.Value.ToString("N2")+"|"+obj[1].nca_oil_and_gas_assets.Value.ToString("N2") + "|"+(obj[0].nca_oil_and_gas_assets.Value == 0 ? 0 : (obj[1].nca_oil_and_gas_assets.Value - obj[0].nca_oil_and_gas_assets.Value) / obj[0].nca_oil_and_gas_assets.Value * 100).ToString("N2"));
                list.Add(s[44]+"|"+obj[0].nca_intangible_assets.Value.ToString("N2")+"|"+obj[1].nca_intangible_assets.Value.ToString("N2") + "|"+(obj[0].nca_intangible_assets.Value == 0 ? 0 : (obj[1].nca_intangible_assets.Value - obj[0].nca_intangible_assets.Value) / obj[0].nca_intangible_assets.Value * 100).ToString("N2"));
                list.Add(s[45]+"|"+obj[0].nca_development_expenditure.Value.ToString("N2")+"|"+obj[1].nca_development_expenditure.Value.ToString("N2") + "|"+(obj[0].nca_development_expenditure.Value == 0 ? 0 : (obj[1].nca_development_expenditure.Value - obj[0].nca_development_expenditure.Value) / obj[0].nca_development_expenditure.Value * 100).ToString("N2"));
                list.Add(s[46]+"|"+obj[0].nca_goodwill.Value.ToString("N2")+"|"+obj[1].nca_goodwill.Value.ToString("N2") + "|"+(obj[0].nca_goodwill.Value == 0 ? 0 : (obj[1].nca_goodwill.Value - obj[0].nca_goodwill.Value) / obj[0].nca_goodwill.Value * 100).ToString("N2"));
                list.Add(s[47]+"|"+obj[0].nca_longterm_unamortized_expenses.Value.ToString("N2")+"|"+obj[1].nca_longterm_unamortized_expenses.Value.ToString("N2") + "|"+(obj[0].nca_longterm_unamortized_expenses.Value == 0 ? 0 : (obj[1].nca_longterm_unamortized_expenses.Value - obj[0].nca_longterm_unamortized_expenses.Value) / obj[0].nca_longterm_unamortized_expenses.Value * 100).ToString("N2"));
                list.Add(s[48]+"|"+obj[0].nca_deferred_tax_assets.Value.ToString("N2")+"|"+obj[1].nca_deferred_tax_assets.Value.ToString("N2") + "|"+(obj[0].nca_deferred_tax_assets.Value == 0 ? 0 : (obj[1].nca_deferred_tax_assets.Value - obj[0].nca_deferred_tax_assets.Value) / obj[0].nca_deferred_tax_assets.Value * 100).ToString("N2"));
                list.Add(s[49]+"|"+obj[0].nca_other_assets.Value.ToString("N2")+"|"+obj[1].nca_other_assets.Value.ToString("N2") + "|"+(obj[0].nca_other_assets.Value == 0 ? 0 : (obj[1].nca_other_assets.Value - obj[0].nca_other_assets.Value) / obj[0].nca_other_assets.Value * 100).ToString("N2"));
                list.Add(s[50]+"|"+obj[0].nca_count.Value.ToString("N2")+"|"+obj[1].nca_count.Value.ToString("N2") + "|"+(obj[0].nca_count.Value == 0 ? 0 : (obj[1].nca_count.Value - obj[0].nca_count.Value) / obj[0].nca_count.Value * 100).ToString("N2"));
                list.Add(s[51]+"|"+obj[0].count_assets.Value.ToString("N2")+"|"+obj[1].count_assets.Value.ToString("N2") + "|"+(obj[0].count_assets.Value == 0 ? 0 : (obj[1].count_assets.Value - obj[0].count_assets.Value) / obj[0].count_assets.Value * 100).ToString("N2"));
                list.Add(s[52]+"|"+obj[0].short_term_borrow.ToString("N2")+"|"+obj[1].short_term_borrow.ToString("N2") + "|"+(obj[0].short_term_borrow == 0 ? 0 : (obj[1].short_term_borrow - obj[0].short_term_borrow) / obj[0].short_term_borrow * 100).ToString("N2"));
                list.Add(s[53]+"|"+obj[0].cl_trading_financ_liabilities.Value.ToString("N2")+"|"+obj[1].cl_trading_financ_liabilities.Value.ToString("N2") + "|"+(obj[0].cl_trading_financ_liabilities.Value == 0 ? 0 : (obj[1].cl_trading_financ_liabilities.Value - obj[0].cl_trading_financ_liabilities.Value) / obj[0].cl_trading_financ_liabilities.Value * 100).ToString("N2"));
                list.Add(s[54]+"|"+obj[0].cl_notes_payable.Value.ToString("N2")+"|"+obj[1].cl_notes_payable.Value.ToString("N2") + "|"+(obj[0].cl_notes_payable.Value == 0 ? 0 : (obj[1].cl_notes_payable.Value - obj[0].cl_notes_payable.Value) / obj[0].cl_notes_payable.Value * 100).ToString("N2"));
                list.Add(s[55]+"|"+obj[0].accounts_payable.ToString("N2")+"|"+obj[1].accounts_payable.ToString("N2") + "|"+(obj[0].accounts_payable == 0 ? 0 : (obj[1].accounts_payable - obj[0].accounts_payable) / obj[0].accounts_payable * 100).ToString("N2"));
                list.Add(s[56]+"|"+obj[0].finished_accounts_payable.Value.ToString("N2")+"|"+obj[1].finished_accounts_payable.Value.ToString("N2") + "|"+(obj[0].finished_accounts_payable.Value == 0 ? 0 : (obj[1].finished_accounts_payable.Value - obj[0].finished_accounts_payable.Value) / obj[0].finished_accounts_payable.Value * 100).ToString("N2"));
                list.Add(s[57]+"|"+obj[0].semi_accounts_payable.Value.ToString("N2")+"|"+obj[1].semi_accounts_payable.Value.ToString("N2") + "|"+(obj[0].semi_accounts_payable.Value == 0 ? 0 : (obj[1].semi_accounts_payable.Value - obj[0].semi_accounts_payable.Value) / obj[0].semi_accounts_payable.Value * 100).ToString("N2"));
                list.Add(s[58]+"|"+obj[0].logistics_accounts_payable.Value.ToString("N2")+"|"+obj[1].logistics_accounts_payable.Value.ToString("N2") + "|"+(obj[0].logistics_accounts_payable.Value == 0 ? 0 : (obj[1].logistics_accounts_payable.Value - obj[0].logistics_accounts_payable.Value) / obj[0].logistics_accounts_payable.Value * 100).ToString("N2"));
                list.Add(s[59]+"|"+obj[0].advance_received.ToString("N2")+"|"+obj[1].advance_received.ToString("N2") + "|"+(obj[0].advance_received == 0 ? 0 : (obj[1].advance_received - obj[0].advance_received) / obj[0].advance_received * 100).ToString("N2"));



                list.Add(s[60]+"|"+obj[0].payable_remuneration.ToString("N2")+"|"+obj[1].payable_remuneration.ToString("N2") + "|"+(obj[0].payable_remuneration == 0 ? 0 : (obj[1].payable_remuneration - obj[0].payable_remuneration) / obj[0].payable_remuneration * 100).ToString("N2"));
                list.Add(s[61]+"|"+obj[0].taxes_payable.ToString("N2")+"|"+obj[1].taxes_payable.ToString("N2") + "|"+(obj[0].taxes_payable == 0 ? 0 : (obj[1].taxes_payable - obj[0].taxes_payable) / obj[0].taxes_payable * 100).ToString("N2"));
                list.Add(s[62]+"|"+obj[0].cl_payable_interest.Value.ToString("N2")+"|"+obj[1].cl_payable_interest.Value.ToString("N2") + "|"+(obj[0].cl_payable_interest.Value == 0 ? 0 : (obj[1].cl_payable_interest.Value - obj[0].cl_payable_interest.Value) / obj[0].cl_payable_interest.Value * 100).ToString("N2"));
                list.Add(s[63]+"|"+obj[0].cl_dividends_payable.Value.ToString("N2")+"|"+obj[1].cl_dividends_payable.Value.ToString("N2") + "|"+(obj[0].cl_dividends_payable.Value == 0 ? 0 : (obj[1].cl_dividends_payable.Value - obj[0].cl_dividends_payable.Value) / obj[0].cl_dividends_payable.Value * 100).ToString("N2"));
                list.Add(s[64]+"|"+obj[0].other_accounts_payable.ToString("N2")+"|"+obj[1].other_accounts_payable.ToString("N2") + "|"+(obj[0].other_accounts_payable == 0 ? 0 : (obj[1].other_accounts_payable - obj[0].other_accounts_payable) / obj[0].other_accounts_payable * 100).ToString("N2"));
                list.Add(s[65]+"|"+obj[0].cl_oneyear_noncurrent_liabilities.Value.ToString("N2")+"|"+obj[1].cl_oneyear_noncurrent_liabilities.Value.ToString("N2") + "|"+(obj[0].cl_oneyear_noncurrent_liabilities.Value == 0 ? 0 : (obj[1].cl_oneyear_noncurrent_liabilities.Value - obj[0].cl_oneyear_noncurrent_liabilities.Value) / obj[0].cl_oneyear_noncurrent_liabilities.Value * 100).ToString("N2"));
                list.Add(s[66]+"|"+obj[0].cl_other_liabilities.Value.ToString("N2")+"|"+obj[1].cl_other_liabilities.Value.ToString("N2") + "|"+(obj[0].cl_other_liabilities.Value == 0 ? 0 : (obj[1].cl_other_liabilities.Value - obj[0].cl_other_liabilities.Value) / obj[0].cl_other_liabilities.Value * 100).ToString("N2"));
                list.Add(s[67]+"|"+obj[0].cl_count.Value.ToString("N2")+"|"+obj[1].cl_count.Value.ToString("N2") + "|"+(obj[0].cl_count.Value == 0 ? 0 : (obj[1].cl_count.Value - obj[0].cl_count.Value) / obj[0].cl_count.Value * 100).ToString("N2"));
                list.Add(s[68]+"|"+obj[0].ncl_longterm_loan.Value.ToString("N2")+"|"+obj[1].ncl_longterm_loan.Value.ToString("N2") + "|"+(obj[0].ncl_longterm_loan.Value == 0 ? 0 : (obj[1].ncl_longterm_loan.Value - obj[0].ncl_longterm_loan.Value) / obj[0].ncl_longterm_loan.Value * 100).ToString("N2"));
                list.Add(s[69]+"|"+obj[0].ncl_bonds_payable.Value.ToString("N2")+"|"+obj[1].ncl_bonds_payable.Value.ToString("N2") + "|"+(obj[0].ncl_bonds_payable.Value == 0 ? 0 : (obj[1].ncl_bonds_payable.Value - obj[0].ncl_bonds_payable.Value) / obj[0].ncl_bonds_payable.Value * 100).ToString("N2"));
                list.Add(s[70]+"|"+obj[0].long_term_accounts_payable.ToString("N2")+"|"+obj[1].long_term_accounts_payable.ToString("N2") + "|"+(obj[0].long_term_accounts_payable == 0 ? 0 : (obj[1].long_term_accounts_payable - obj[0].long_term_accounts_payable) / obj[0].long_term_accounts_payable * 100).ToString("N2"));
                list.Add(s[71]+"|"+obj[0].ncl_special_payable.Value.ToString("N2")+"|"+obj[1].ncl_special_payable.Value.ToString("N2") + "|"+(obj[0].ncl_special_payable.Value == 0 ? 0 : (obj[1].ncl_special_payable.Value - obj[0].ncl_special_payable.Value) / obj[0].ncl_special_payable.Value * 100).ToString("N2"));
                list.Add(s[72]+"|"+obj[0].ncl_anticipation_liabilities.Value.ToString("N2")+"|"+obj[1].ncl_anticipation_liabilities.Value.ToString("N2") + "|"+(obj[0].ncl_anticipation_liabilities.Value == 0 ? 0 : (obj[1].ncl_anticipation_liabilities.Value - obj[0].ncl_anticipation_liabilities.Value) / obj[0].ncl_anticipation_liabilities.Value * 100).ToString("N2"));
                list.Add(s[73]+"|"+obj[0].ncl_deferred_income_tax_liabilities.Value.ToString("N2")+"|"+obj[1].ncl_deferred_income_tax_liabilities.Value.ToString("N2") + "|"+(obj[0].ncl_deferred_income_tax_liabilities.Value == 0 ? 0 : (obj[1].ncl_deferred_income_tax_liabilities.Value - obj[0].ncl_deferred_income_tax_liabilities.Value) / obj[0].ncl_deferred_income_tax_liabilities.Value * 100).ToString("N2"));
                list.Add(s[74]+"|"+obj[0].ncl_other_liabilities.Value.ToString("N2")+"|"+obj[1].ncl_other_liabilities.Value.ToString("N2") + "|"+(obj[0].ncl_other_liabilities.Value == 0 ? 0 : (obj[1].ncl_other_liabilities.Value - obj[0].ncl_other_liabilities.Value) / obj[0].ncl_other_liabilities.Value * 100).ToString("N2"));
                list.Add(s[75]+"|"+obj[0].ncl_count.Value.ToString("N2")+"|"+obj[1].ncl_count.Value.ToString("N2") + "|"+(obj[0].ncl_count.Value == 0 ? 0 : (obj[1].ncl_count.Value - obj[0].ncl_count.Value) / obj[0].ncl_count.Value * 100).ToString("N2"));
                list.Add(s[76]+"|"+obj[0].count_liabilities.Value.ToString("N2")+"|"+obj[1].count_liabilities.Value.ToString("N2") + "|"+(obj[0].count_liabilities.Value == 0 ? 0 : (obj[1].count_liabilities.Value - obj[0].count_liabilities.Value) / obj[0].count_liabilities.Value * 100).ToString("N2"));
                list.Add(s[77]+"|"+obj[0].oe_paicl_up_capital.Value.ToString("N2")+"|"+obj[1].oe_paicl_up_capital.Value.ToString("N2") + "|"+(obj[0].oe_paicl_up_capital.Value == 0 ? 0 : (obj[1].oe_paicl_up_capital.Value - obj[0].oe_paicl_up_capital.Value) / obj[0].oe_paicl_up_capital.Value * 100).ToString("N2"));
                list.Add(s[78]+"|"+obj[0].oe_capital_reserve.Value.ToString("N2")+"|"+obj[1].oe_capital_reserve.Value.ToString("N2") + "|"+(obj[0].oe_capital_reserve.Value == 0 ? 0 : (obj[1].oe_capital_reserve.Value - obj[0].oe_capital_reserve.Value) / obj[0].oe_capital_reserve.Value * 100).ToString("N2"));
                list.Add(s[79]+"|"+obj[0].oe_inventory_amount.Value.ToString("N2")+"|"+obj[1].oe_inventory_amount.Value.ToString("N2") + "|"+(obj[0].oe_inventory_amount.Value == 0 ? 0 : (obj[1].oe_inventory_amount.Value - obj[0].oe_inventory_amount.Value) / obj[0].oe_inventory_amount.Value * 100).ToString("N2"));



                list.Add(s[80]+"|"+obj[0].oe_surplus_public_accumulation.Value.ToString("N2")+"|"+obj[1].oe_surplus_public_accumulation.Value.ToString("N2") + "|"+(obj[0].oe_surplus_public_accumulation.Value == 0 ? 0 : (obj[1].oe_surplus_public_accumulation.Value - obj[0].oe_surplus_public_accumulation.Value) / obj[0].oe_surplus_public_accumulation.Value * 100).ToString("N2"));
                list.Add(s[81]+"|"+obj[0].oe_undistributed_profit.Value.ToString("N2")+"|"+obj[1].oe_undistributed_profit.Value.ToString("N2") + "|"+(obj[0].oe_undistributed_profit.Value == 0 ? 0 : (obj[1].oe_undistributed_profit.Value - obj[0].oe_undistributed_profit.Value) / obj[0].oe_undistributed_profit.Value * 100).ToString("N2"));
                list.Add(s[82]+"|"+obj[0].oe_count.Value.ToString("N2")+"|"+obj[1].oe_count.Value.ToString("N2") + "|"+(obj[0].oe_count.Value == 0 ? 0 : (obj[1].oe_count.Value - obj[0].oe_count.Value) / obj[0].oe_count.Value * 100).ToString("N2"));
                list.Add(s[83]+"|"+obj[0].count_liabilities_and_oe.Value.ToString("N2")+"|"+obj[1].count_liabilities_and_oe.Value.ToString("N2") + "|"+(obj[0].count_liabilities_and_oe.Value == 0 ? 0 : (obj[1].count_liabilities_and_oe.Value - obj[0].count_liabilities_and_oe.Value) / obj[0].count_liabilities_and_oe.Value * 100).ToString("N2"));

                for (var i = 0; i < list.Count; i++)
                {

                    var arr = list[i].Split('|');

                    list[i] = arr[0] + "|" + arr[1] +"|"+arr[2]+"|"+arr[3]+"|"+(decimal.Parse(arr[2])-decimal.Parse(arr[1]));

                    if (i >= 0 && i < 33)
                    {
                        list[i] = ("流动资产")+"|"+list[i];
                    }
                    else if (i >= 33 && i < 51)
                    {
                        list[i] = ("非流动资产") + "|" + list[i];
                    }
                    else if (i >= 51 && i < 52)
                    {
                        list[i] = ("资产合计") + "|" + list[i];
                    }
                    else if (i >= 52 && i < 68)
                    {
                        list[i] = ("流动负债") + "|" + list[i];
                    }
                    else if (i >= 68 && i < 76)
                    {
                        list[i] = ("非流动负债") + "|" + list[i];
                    }
                    else if (i >= 76 && i < 77)
                    {
                        list[i] = ("负债合计") + "|" + list[i];
                    }
                    else if (i >= 77 && i < 83)
                    {
                        list[i] = ("所有者权益(或股东权益)") + "|" + list[i];
                    }
                    else if (i >= 83 && i < 84)
                    {
                        list[i] = ("所有者权益(或股东权益)合计") + "|" + list[i];
                    }
                
                    
                }

                var guid = Guid.NewGuid().ToString();
                var filename = "资产负债表环比明细 "+start.ToString("yyyy-MM-dd") + " " + end.ToString("yyyy-MM-dd");
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(list, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");


            }
            catch (Exception ex)
            {
                
            }

            return View();
        }

        /// <summary>
        /// 资产负债表-子项趋势图
        /// </summary>
        /// <param name="colname">子项名称</param>
        /// <param name="head">日期</param>
        /// <param name="vals">值</param>
        /// <returns></returns>
        public ActionResult Index2TrendChart(string colname,string head,string vals)
        {
            ViewBag.colname = colname;
            ViewBag.head = head;
            ViewBag.vals = vals;

            return View();
        }

        public ActionResult BalanceSheetSubDetail(string type, DateTime day)
        {
            ViewBag.type = type;
            ViewBag.day = day.ToString("yyyy-MM-dd");

            return View();
        }

        /// <summary>
        /// 资产负债表手工导入明细数据
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="type"></param>
        /// <param name="day"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListBalanceSheetSubDetailJson(BtTableParameter parameter,string type, DateTime day)
        {
            var user = HttpContextHelper.Current?.User;

            var total = 0;
            var _service = new Services.BalanceSheetServices();
            var obj = _service.List(type, day,parameter,ref total);

            var objCount = _service.GetCount(type, day);

            var list = obj.Select(a => new {
                a.fromsource,
                a.detailname,
                a.amount,
                day = a.day.ToString("yyyy-MM-dd"),
                a.note1,
                a.note2,
                a.note3,
                a.note4,
                a.note5
            });


            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    fromsource = "总计",
                    amount = objCount,
                },
                uid = user != null ? user.GetUid() : 0,
                username = user != null ? user.GetUserName() : ""
            });
        }

        /// <summary>
        /// 导入资产负债表手工数据
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult UploadBalanceSheetSubDetail(string t,string typename,int uid,string username)
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();
                var list = new List<dc_balance_sheet_subdetail>();
                var service = new Services.BalanceSheetServices();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    try
                    {
                        var day = row["日期"].ToString();
                        var source = row["来源"].ToString();

                        if (string.IsNullOrWhiteSpace(day) || string.IsNullOrWhiteSpace(source))
                        {
                            continue;
                        }

                        var detailname = row["类型/名称"].ToString();
                        var amount = row["金额"].ToString();

                        if (string.IsNullOrWhiteSpace(detailname))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "类型/名称不能为空！",
                            });
                        }

                        if (string.IsNullOrWhiteSpace(amount))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "金额不能为空！",
                            });
                        }

                        decimal _amount = 0;
                        decimal.TryParse(amount, out _amount);

                        if (_amount == 0)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "金额不能为0！",
                            });
                        }

                        var note1 = row["备注1"].ToString();
                        var note2 = row["备注2"].ToString();
                        var note3 = row["备注3"].ToString();
                        var note4 = row["备注4"].ToString();
                        var note5 = row["备注5"].ToString();

                        list.Add(new dc_balance_sheet_subdetail {
                            amount = _amount,
                            fromsource = source,
                            detailname = detailname,
                            day = DateTime.Parse(day),
                            note1 = note1,
                            note2 = note2,
                            note3 = note3,
                            note4 = note4,
                            note5 = note5,
                            createtime = DateTime.Now,
                            createuserid = uid,
                            createusername = username,
                            type = t,
                            type_note = "",
                        });   
                    }
                    catch (Exception ex)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "导入失败，异常信息：" + ex.Message
                        });
                    }
                }

                if (list.Count == 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "表格没有数据。",
                    });

                }

                var result = service.AddRang(list);

                if (result > 0)
                {
                    var paramname = "";
                    switch (t)
                    {
                        case "other_accounts_receivable":  //其他应收账款
                            paramname = "otherAccountsReceivableImport";
                            break;
                        case "other_accounts_payable":  //其他应付
                            paramname = "otherAccountsPayableImport";
                            break;
                        case "fixed_assets":  //固定资产
                            paramname = "fixedAssetsImport";  
                            break;
                        case "nca_deferred_tax_assets":  //递延所得税
                            paramname = "ncaDeferredTaxAssetsImport";
                            break;
                        case "accounts_receivable_import":  //应收账款导入
                            paramname = "accountsReceivableImport";
                            break;
                    }

                    if (!string.IsNullOrEmpty(paramname))
                    {
                        var _service = new Services.BalanceSheetServices();
                        var amount = _service.GetCount(t, list.FirstOrDefault().day);

                        new Services.FinanceReportServices().UpdateLogisticsEndAmount(list.FirstOrDefault().day, amount, paramname);
                    }

                    
                }

                return Json(new
                {
                    success = result>0,
                    msg = ""
                });
            }
            else
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件"
                });
            }
        }

        /// <summary>
        /// 其他应收账款明细汇总
        /// </summary>
        /// <param name="paycompanyid"></param>
        /// <param name="date"></param>
        /// <returns></returns>
        public ActionResult OtherReceivableCount(int? paycompanyid, DateTime date)
        {
            var objCount = new Services.FinanceReportServices().ListBorrowAmountCount(date, paycompanyid??0);
            var hander = new Services.BalanceSheetServices().GetCount("other_accounts_receivable", date);

            ViewBag.borrow = objCount.amount;
            ViewBag.handerfee = hander;

            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;

            return View();
        }

        #endregion

        #region 平台余额

        public ActionResult ListAccoutBalanceCount()
        {
            ViewBag.listplatform = new Services.FinanceReportServices().ListAccountBalancePlatform();

            return View();
        }

        /// <summary>
        /// 平台账号余额管理列表数据
        /// </summary>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【平台余额】->【查询】页面", 0)]
        public string ListAccoutBalanceCountJson(BtTableParameter request, DateTime day, string platformname)
        {
            var user = HttpContextHelper.Current?.User;

            var services = new Services.FinanceReportServices();
            var total = 0;
            var list = services.ListCount(day, platformname, request.pageIndex, 1000, request.sort, request.order, ref total);

            var countM = services.ListCounts(day, platformname);

            countM.platformname = "总计：";
            countM.amount = Math.Round(countM.amount, 2, MidpointRounding.AwayFromZero);
            countM.amount_rmb = Math.Round(countM.amount_rmb, 2, MidpointRounding.AwayFromZero);
            countM.amount_sales = Math.Round(countM.amount_sales, 2, MidpointRounding.AwayFromZero);
            countM.before_balance = Math.Round(countM.before_balance, 2, MidpointRounding.AwayFromZero);
            countM.freeze_amount = Math.Round(countM.freeze_amount, 2, MidpointRounding.AwayFromZero);
            countM.freeze_amount_rmb = Math.Round(countM.freeze_amount_rmb, 2, MidpointRounding.AwayFromZero);
            countM.userable_amount = Math.Round(countM.userable_amount, 2, MidpointRounding.AwayFromZero);
            countM.userable_amount_rmb = Math.Round(countM.userable_amount_rmb, 2, MidpointRounding.AwayFromZero);
            countM.withdraw_amount = Math.Round(countM.withdraw_amount, 2, MidpointRounding.AwayFromZero);


            //对展示结果排序
            var listTemp = new List<dc_platform_balance>();

            listTemp.AddRange(list.Where(a => a.platformcode.ToLower() == "paypal").OrderByDescending(p=>p.amount_rmb));
            listTemp.AddRange(list.Where(a => a.platformcode.ToLower() == "速卖通").OrderByDescending(p => p.amount_rmb));
            listTemp.AddRange(list.Where(a => a.platformcode.ToLower() == "payoneer").OrderByDescending(p => p.amount_rmb));
            listTemp.AddRange(list.Where(a => a.platformcode.ToLower() == "beepay").OrderByDescending(p => p.amount_rmb));
            listTemp.AddRange(list.Where(a => a.platformcode.ToLower() == "pingpong").OrderByDescending(p => p.amount_rmb));

            listTemp.AddRange(list.Where(a => !(listTemp.Select(b => b.platformcode).Contains(a.platformcode))));

            //pagination.records = total;
            //pagination.total = total / pagination.rows + (total % pagination.rows > 0 ? 1 : 0);
            var i = 1;
            var obj = listTemp.Select(p => new {
                r = (i++),
                day = p.day.ToString("yyyy-MM-dd"),
                p.account,
                p.currency,
                p.amount,
                p.userable_amount,
                p.freeze_amount,
                p.exchangerate,
                p.amount_rmb,
                p.userable_amount_rmb,
                p.freeze_amount_rmb,
                p.platformcode,
                p.platformname,
                puttime = p.day.ToString("yyyy-MM-dd")
            });

            

            
            return JsonConvert.SerializeObject(new {
                total = request.limit,
                rows = obj,
                count_row =countM,
                uid = user!=null?user.GetUid():0,
                username = user!=null?user.GetUserName():""
            });
        }

        /// <summary>
        /// 上传平台账号余额明细
        /// </summary>
        /// <returns></returns>
        public JsonResult UpdateBalanceCount(int uid,string username)
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();
                var list = new List<dc_platform_balance>();
                var service = new Services.FinanceReportServices();
                var listRate = new List<Tuple<string, decimal>>();
                var commonServices = new Services.CommonServices();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    try
                    {
                        var platformcode = row["平台名称"].ToString();
                        var account = row["帐号"].ToString();

                        if (string.IsNullOrEmpty(platformcode))
                        {
                            continue;
                        }

                        //var account = row["平台账号"].ToString();
                        var currency = row["原币种"].ToString();
                        var day = DateTime.Parse(row["日期"].ToString());

                        if (string.IsNullOrEmpty(platformcode))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "平台编码不能为空！",
                            });
                        }

                        if (string.IsNullOrEmpty(currency))
                        {
                            return Json(new {
                                success = false,
                                msg = "币种不能为空！"
                            });
                        }

                        if (string.IsNullOrWhiteSpace(account))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "帐号不能为空！"
                            });
                        }

                        var objplatform = service.GetPlatformByName(platformcode);
                        if (objplatform == null)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "系统找不到该销售平台【" + platformcode + "】，请检测平台名称是否正确或联系管理员。",
                            });
                        }

                        var rate = listRate.Where(a => a.Item1 == currency).FirstOrDefault();
                        if (rate == null)
                        {
                            var objRate = Services.CommonServices.GetExchangeRate(currency, "CNY");
                            rate = new Tuple<string, decimal>(currency, objRate);

                            listRate.Add(rate);
                        }

                        var m = new Services.FinanceReportServices().GetPlatformBalance(platformcode, currency, day,account);


                        //var amount = decimal.Parse(row["当日余额"].ToString().Trim());
                        var userable = decimal.Parse(row["可用余额"].ToString().Trim());
                        var freezeamount = decimal.Parse(row["冻结余额"].ToString().Trim());
                        var amount = userable + freezeamount;

                        //var saleday = DateTime.Parse(row["初始额统计日期"].ToString());
                        //var puttime = DateTime.Parse(row["放款时间"].ToString());
                        //var dailysale = decimal.Parse(row["平台每天总销售额"].ToString().Trim());
                        var notes = row["备注"].ToString();

                        //if (puttime < DateTime.Parse("1999-01-01"))
                        //{
                        //    return Json(new
                        //    {
                        //        success = false,
                        //        msg = "请填写正确的放款时间！",
                        //    });
                        //}

                        if (m != null && m.amount_sales > 0)
                        {
                            return Json(new {
                                success = false,
                                msg = "平台【"+platformcode+"】，币种【"+m.currency+"】在"+day.ToShortDateString()+"已经导入了数据，请删除该数据后重新导入。"
                            });
                        }

                        list.Add(new dc_platform_balance
                        {
                            id= (m!=null?m.id:0),
                            account = account,
                            currency = currency,
                            amount = amount,
                            exchangerate = rate.Item2,
                            freeze_amount = freezeamount,
                            userable_amount = userable,
                            day = day,
                            delstatus = 0,
                            platformcode = objplatform.english_name,
                            platformname = objplatform.china_name,
                            paycompanyid = 2, //默认设置香港百伦

                            amount_rmb = amount * rate.Item2,
                            freeze_amount_rmb = freezeamount * rate.Item2,
                            userable_amount_rmb = userable * rate.Item2,
                            puttime = DateTime.Parse("1990-01-01"),
                            notes = notes,
                            saleday = DateTime.Parse("1990-01-01"),
                            fromsource = "",
                            amount_sales = 0,
                            withdraw_amount = (m!=null?m.withdraw_amount:0),
                            before_balance = (m!=null?m.before_balance:0),
                            createtime = DateTime.Now,
                            createuserid = uid,
                            createusername = username,
                            end_balance = amount * rate.Item2,
                        });

                        
                    }
                    catch (Exception ex)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "导入失败，异常信息：" + ex.Message
                        });
                    }
                }

                if (list.Count == 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "表格没有数据。",
                    });

                }

                var result = service.AddPlatformBalances(list);
                return Json(new
                {
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }
            else
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件"
                });
            }
        }

        public string UpdateBalanceTest()
        {
            var result = new Services.FinanceReportServices().ListPlatformBalance(DateTime.Parse("2019-02-20"));

            return result;
        }

        /// <summary>
        /// 平台账号余额明细页面
        /// </summary>
        /// <returns></returns>
        public ActionResult ListAccountBalance()
        {
            ViewBag.listplatform = new Services.FinanceReportServices().ListAccountBalancePlatform();
            return View();
        }

        /// <summary>
        /// 平台账号余额明细数据
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="day"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public string ListAccountBalanceJson(BtTableParameter request, DateTime day, string platformname,string currency)
        {
            var services = new Services.FinanceReportServices();
            var total = 0;
            var list = services.List(day, platformname,currency, request.pageIndex, request.limit, request.sort, request.order, ref total);

            //pagination.records = total;
            //pagination.total = total / pagination.rows + (total % pagination.rows > 0 ? 1 : 0);

            var obj = list.Select(p => new {
                p.id,
                day = p.day.ToString("yyyy-MM-dd"),
                p.account,
                p.amount,
                p.amount_rmb,
                p.currency,
                p.exchangerate,
                p.freeze_amount,
                p.freeze_amount_rmb,
                p.userable_amount,
                p.userable_amount_rmb,
                p.platformcode,
                p.platformname,
                puttime = p.puttime.ToString("yyyy-MM-dd"),
                p.notes,
                p.amount_sales,
                p.before_balance,
                p.withdraw_amount
            });

            return JsonConvert.SerializeObject(new { total = total, rows = obj.ToList() });

        }

        /// <summary>
        /// 获取平台余额汇总
        /// </summary>
        /// <param name="day"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public JsonResult ListAccountBalanceSum(DateTime day, string code)
        {
            var m = new Services.FinanceReportServices().ListSum(day, code);

            return Json(m);
        }

        /// <summary>
        /// 删除账号余额记录
        /// </summary>
        /// <param name="id">账号余额id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelAccountBalance(int id)
        {
            var service = new Services.FinanceReportServices();
            var result = service.DelPlatformBalance(id);

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

        /// <summary>
        /// 更新平台余额的提现金额
        /// </summary>
        /// <param name="id"></param>
        /// <param name="balance"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SavePlatformBalance(int id, decimal balance)
        {
            var service = new Services.FinanceReportServices();
            var result = service.UpdatePlatformBalance(id, balance);

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

        #endregion

        #region 每日销售额

        /// <summary>
        /// 每日销售额统计
        /// </summary>
        public ActionResult DailySalesCount()
        {
            return View();
        }

        /// <summary>
        /// 每日销售额统计
        /// </summary>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【每日销售额】->【查询】页面", 0)]
        public string DailySalesCountJson(BtTableParameter request, DateTime day, string platformcode)
        {
            var services = new Services.FinanceReportServices();
            var total = 0;
            var list = services.ListDailyPlatformAmountCount(day, platformcode, request.pageIndex, request.limit, request.sort, request.order, ref total);

            var obj = list.Select(p => new {
                day = p.day.ToString("yyyy-MM-dd"),
                p.account,
                p.currency,
                p.platformcode,
                p.platformname,
                p.put_amount,
                p.put_amount_rmb,
                put_amount_time = p.put_amount_time.ToString("yyyy-MM-dd"),
                p.freeze_amount,
            });
            
            return JsonConvert.SerializeObject(new { total = obj.Count(), rows = obj });
        }

        /// <summary>
        /// 每日销售额明细
        /// </summary>
        /// <returns></returns>
        public ActionResult DailySales()
        {
            return View();
        }

        /// <summary>
        /// 每日销售额明细
        /// </summary>
        /// <param name="pagination"></param>
        /// <param name="day"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public string DailySalesJson(BtTableParameter request, DateTime day, string code)
        {
            var services = new Services.FinanceReportServices();
            var total = 0;
            var list = services.ListDailyPlatformAmount(day, code, request.pageIndex, request.limit, request.sort, request.order, ref total);

            var obj = list.Select(p => new {
                day = p.day.ToString("yyyy-MM-dd"),
                put_amount_time = p.put_amount_time.ToString("yyyy-MM-dd"),
                p.account,
                p.currency,
                p.platformcode,
                p.platformname,
                p.freeze_amount,
                p.freeze_amount_rmb,
                p.putcount,
                p.put_amount,
                p.put_amount_rmb,
                p.id,
            });

            return JsonConvert.SerializeObject(new { total = obj.Count(), rows = obj });
        }

        /// <summary>
        /// 上传每日销售额
        /// </summary>
        /// <returns></returns>
        public JsonResult UploadDailySales()
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();
                var list = new List<dc_daily_platformamout>();
                var service = new Services.FinanceReportServices();
                var listRate = new List<Tuple<string, decimal>>();
                var commonServices = new Services.CommonServices();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    try
                    {
                        var platformcode = row["平台名称"].ToString();
                        var account = row["平台账号"].ToString();
                        var currency = row["币种"].ToString();
                        var puttime = DateTime.Parse(row["放款时间"].ToString());
                        var put_amount = decimal.Parse(row["放款金额"].ToString());
                        var freeze_amount = decimal.Parse(row["冻结金额"].ToString());
                        var count = int.Parse(row["月放款次数"].ToString());
                        var day = DateTime.Parse(row["统计日期"].ToString());


                        if (string.IsNullOrEmpty(platformcode))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "平台编码不能为空！",
                            });
                        }

                        if (puttime < DateTime.Parse("1999-01-01"))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "请填写正确的放款时间！",
                            });
                        }

                        var objplatform = service.GetPlatformByName(platformcode);
                        if (objplatform == null)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "系统找不到该销售平台【" + platformcode + "】，请检测平台名称是否正确或联系管理员。",
                            });
                        }

                        var rate = listRate.Where(a => a.Item1 == currency).FirstOrDefault();
                        if (rate == null)
                        {
                            var objRate = Services.CommonServices.GetExchangeRate(currency, "CNY");
                            rate = new Tuple<string, decimal>(currency, objRate);

                            listRate.Add(rate);
                        }

                        list.Add(new dc_daily_platformamout
                        {
                            account = account,
                            currency = currency,
                            day = day,
                            delstatus = 0,
                            platformcode = objplatform.english_name,
                            platformname = objplatform.china_name,
                            put_amount_time = puttime,
                            put_amount = put_amount,
                            put_amount_rmb = put_amount * rate.Item2,
                            freeze_amount = freeze_amount,
                            freeze_amount_rmb = freeze_amount * rate.Item2,
                            putcount = count,
                        });

                    }
                    catch (Exception ex)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "导入失败，异常信息：" + ex.Message
                        });
                    }
                }

                if (list.Count == 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "表格没有数据。",
                    });

                }

                var result = service.AddDailySale(list);
                return Json(new
                {
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }
            else
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件"
                });
            }
        }

        /// <summary>
        /// 删除每日销售额
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DelDailySales(int id)
        {
            var service = new Services.FinanceReportServices();
            var result = service.DeleteDailySale(id);

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

        #endregion
        
        #region Common

        /// <summary>
        /// 获取平台列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListPlatform()
        {
            var service = new Services.FinanceReportServices();
            var list = service.ListPlatforms().Select(p => new {
                code = p.english_name,
                name = p.china_name
            });

            return Json(list);
        }

        /// <summary>
        /// 获取采购公司列表（固定资产）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ListCompanyValue()
        {
            var list = Services.CommonServices.ListCompanyValue();

            return Json(list);
        }


        #endregion

        #region 采购入库、调拨入库、发货、调拨出库

        public ActionResult FinanceExpore()
        {

            return View();
        }


        #endregion

        #region 发生额

        /// <summary>
        /// 每日发生额汇总
        /// </summary>
        /// <returns></returns>
        public ActionResult HappenAmountCount()
        {
            return View();
        }

        /// <summary>
        /// 每日发生额汇总数据
        /// </summary>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="dateWay">统计方式 1按日 2按周  3按月</param>
        /// <returns></returns>
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【每日发生额汇总】->【查询】页面", 0)]
        public JsonResult HappenAmountCountJson(DateTime start, DateTime end,int dateWay)
        {
            var list = new List<mHappenAmount>();
            var obj = new Services.FinanceReportServices().ListHappenAmount(start, end);

            if (obj.Count == 0)
            {
                return Json(new
                {
                    success = true,
                    list = list,
                    msg = ""
                });
            }

            var head = new List<string>() { "" };
            if (dateWay == 2)  //按周
            {
                var first = obj.FirstOrDefault();
                var DayOfWeek = first.day.DayOfWeek;

                var startDay = first.day;
                var endDay = first.day.AddDays((7 - (int)DayOfWeek));

                foreach (var item in obj)
                {
                    var m = list.OrderBy(a => a.type).ToList();

                    if (m.Count <= 0)
                    {
                        //管理成本
                        var m1 = new mHappenAmount
                        {
                            type = 1,
                            typename = "管理成本",
                            start = startDay,
                            end = endDay,
                            list = new List<decimal>(),
                        };

                        m1.list.Add(item.ac_amount_pay);
                        m1.list.Add(item.ac_amount_happen);
                        m1.list.Add(item.ac_amount_sales);

                        //头程物流
                        var m2 = new mHappenAmount
                        {
                            type = 2,
                            typename = "头程物流费",
                            start = startDay,
                            end = endDay,
                            list = new List<decimal>(),
                        };

                        m2.list.Add(item.hl_amount_pay);
                        m2.list.Add(item.hl_amount_happen);
                        m2.list.Add(item.hl_amount_sales);

                        //尾程物流
                        var m3 = new mHappenAmount
                        {
                            type = 3,
                            typename = "尾程物流费",
                            start = startDay,
                            end = endDay,
                            list = new List<decimal>()
                        };

                        m3.list.Add(0);  //item.tl_amount_pay  //头程和尾程物流费取值是一样的，只显示头程的物流付款数据
                        m3.list.Add(item.tl_amount_happen);
                        m3.list.Add(item.tl_amount_sales);

                        //一级供应商采购
                        var m4 = new mHappenAmount
                        {
                            type = 4,
                            typename = "一级供应商采购",
                            start = startDay,
                            end = endDay,
                            list = new List<decimal>()
                        };

                        m4.list.Add(item.tos_amount_pay);
                        m4.list.Add(item.tos_amount_happen);
                        m4.list.Add(item.tos_amount_sales);

                        //二级供应商采购
                        var m5 = new mHappenAmount
                        {
                            type = 5,
                            typename = "二级供应商采购",
                            start = startDay,
                            end = endDay,
                            list = new List<decimal>()
                        };

                        m5.list.Add(item.ss_amount_pay);
                        m5.list.Add(item.ss_amount_happen);
                        m5.list.Add(0);  //item.ss_amount_sales  二级供应商采购销售额

                        list.Add(m1);
                        list.Add(m2);
                        list.Add(m3);
                        list.Add(m4);
                        list.Add(m5);

                        head.Add(startDay.ToString("MMdd") + "-" + (endDay > end ? end : endDay).ToString("MMdd") + "已付款统计");
                        head.Add(startDay.ToString("MMdd") + "-" + (endDay > end ? end : endDay).ToString("MMdd") + "发生额统计");
                        head.Add(startDay.ToString("MMdd") + "-" + (endDay > end ? end : endDay).ToString("MMdd") + "销售部分统计");
                    }
                    else
                    {
                        //if (head.Where(a => a.Contains(item.day.ToString("MMdd"))).Count() > 0)  //累加
                        if(startDay<=item.day && item.day<=endDay)
                        {
                            m[0].list[m[0].list.Count - 3] += (item.ac_amount_pay);
                            m[0].list[m[0].list.Count - 2] += (item.ac_amount_happen);
                            m[0].list[m[0].list.Count - 1] += (item.ac_amount_sales);

                            m[1].list[m[1].list.Count - 3] += (item.hl_amount_pay);
                            m[1].list[m[1].list.Count - 2] += (item.hl_amount_happen);
                            m[1].list[m[1].list.Count - 1] += (item.hl_amount_sales);

                            //m[2].list[m[2].list.Count - 3] += (item.tl_amount_pay);    //尾程物流费付款额
                            m[2].list[m[2].list.Count - 2] += (item.tl_amount_happen);
                            m[2].list[m[2].list.Count - 1] += (item.tl_amount_sales);

                            m[3].list[m[3].list.Count - 3] += (item.tos_amount_pay);
                            m[3].list[m[3].list.Count - 2] += (item.tos_amount_happen);
                            m[3].list[m[3].list.Count - 1] += (item.tos_amount_sales);

                            m[4].list[m[4].list.Count - 3] += (item.ss_amount_pay);
                            m[4].list[m[4].list.Count - 2] += (item.ss_amount_happen);
                            //m[4].list[m[4].list.Count - 1] += (item.ss_amount_sales);    //二级供应商采购销售额
                        }
                        else   //新增
                        {
                            startDay = endDay.AddDays(1);
                            endDay = endDay.AddDays(7);

                            m[0].list.Add(item.ac_amount_pay);
                            m[0].list.Add(item.ac_amount_happen);
                            m[0].list.Add(item.ac_amount_sales);

                            m[1].list.Add(item.hl_amount_pay);
                            m[1].list.Add(item.hl_amount_happen);
                            m[1].list.Add(item.hl_amount_sales);

                            m[2].list.Add(0);  //item.tl_amount_pay  尾程物流费付款额
                            m[2].list.Add(item.tl_amount_happen);
                            m[2].list.Add(item.tl_amount_sales);

                            m[3].list.Add(item.tos_amount_pay);
                            m[3].list.Add(item.tos_amount_happen);
                            m[3].list.Add(item.tos_amount_sales);

                            m[4].list.Add(item.ss_amount_pay);
                            m[4].list.Add(item.ss_amount_happen);
                            m[4].list.Add(0);    //item.ss_amount_sales   二级供应商采购销售额

                            head.Add(startDay.ToString("MMdd") + "-" + (endDay > end ? end : endDay).ToString("MMdd") + "已付款统计");
                            head.Add(startDay.ToString("MMdd") + "-" + (endDay > end ? end : endDay).ToString("MMdd") + "发生额统计");
                            head.Add(startDay.ToString("MMdd") + "-" + (endDay > end ? end : endDay).ToString("MMdd") + "销售部分统计");

                        }
                    }
                }
            }
            else if (dateWay == 3) //按月
            {
                foreach (var item in obj)
                {
                    var m = list.OrderBy(a => a.type).ToList();

                    if (m.Count <= 0)
                    {
                        //管理成本
                        var m1 = new mHappenAmount
                        {
                            type = 1,
                            typename = "管理成本",
                            list = new List<decimal>(),
                        };

                        m1.list.Add(item.ac_amount_pay);
                        m1.list.Add(item.ac_amount_happen);
                        m1.list.Add(item.ac_amount_sales);

                        //头程物流
                        var m2 = new mHappenAmount
                        {
                            type = 2,
                            typename = "头程物流费",
                            list = new List<decimal>(),
                        };

                        m2.list.Add(item.hl_amount_pay);
                        m2.list.Add(item.hl_amount_happen);
                        m2.list.Add(item.hl_amount_sales);

                        //尾程物流
                        var m3 = new mHappenAmount
                        {
                            type = 3,
                            typename = "尾程物流费",
                            list = new List<decimal>()
                        };

                        m3.list.Add(0);  //item.tl_amount_pay  //头程和尾程物流费取值是一样的，只显示头程的物流付款数据
                        m3.list.Add(item.tl_amount_happen);
                        m3.list.Add(item.tl_amount_sales);

                        //一级供应商采购
                        var m4 = new mHappenAmount
                        {
                            type = 4,
                            typename = "一级供应商采购",
                            list = new List<decimal>()
                        };

                        m4.list.Add(item.tos_amount_pay);
                        m4.list.Add(item.tos_amount_happen);
                        m4.list.Add(item.tos_amount_sales);

                        //二级供应商采购
                        var m5 = new mHappenAmount
                        {
                            type = 5,
                            typename = "二级供应商采购",
                            list = new List<decimal>()
                        };

                        m5.list.Add(item.ss_amount_pay);
                        m5.list.Add(item.ss_amount_happen);
                        m5.list.Add(0);  //item.ss_amount_sales  二级供应商采购销售额

                        list.Add(m1);
                        list.Add(m2);
                        list.Add(m3);
                        list.Add(m4);
                        list.Add(m5);

                        head.Add(item.day.ToString("MM") + "已付款统计");
                        head.Add(item.day.ToString("MM") + "发生额统计");
                        head.Add(item.day.ToString("MM") + "销售部分统计");
                    }
                    else
                    {
                        if (head.Where(a => a.Contains(item.day.ToString("MM"))).Count() > 0)  //累加
                        {
                            m[0].list[m[0].list.Count - 3] += (item.ac_amount_pay);
                            m[0].list[m[0].list.Count - 2] += (item.ac_amount_happen);
                            m[0].list[m[0].list.Count - 1] += (item.ac_amount_sales);

                            m[1].list[m[1].list.Count - 3] += (item.hl_amount_pay);
                            m[1].list[m[1].list.Count - 2] += (item.hl_amount_happen);
                            m[1].list[m[1].list.Count - 1] += (item.hl_amount_sales);

                            //m[2].list[m[2].list.Count - 3] += (item.tl_amount_pay);    //尾程物流费付款额
                            m[2].list[m[2].list.Count - 2] += (item.tl_amount_happen);
                            m[2].list[m[2].list.Count - 1] += (item.tl_amount_sales);

                            m[3].list[m[3].list.Count - 3] += (item.tos_amount_pay);
                            m[3].list[m[3].list.Count - 2] += (item.tos_amount_happen);
                            m[3].list[m[3].list.Count - 1] += (item.tos_amount_sales);

                            m[4].list[m[4].list.Count - 3] += (item.ss_amount_pay);
                            m[4].list[m[4].list.Count - 2] += (item.ss_amount_happen);
                            //m[4].list[m[4].list.Count - 1] += (item.ss_amount_sales);    //二级供应商采购销售额
                        }
                        else   //新增
                        {

                            m[0].list.Add(item.ac_amount_pay);
                            m[0].list.Add(item.ac_amount_happen);
                            m[0].list.Add(item.ac_amount_sales);

                            m[1].list.Add(item.hl_amount_pay);
                            m[1].list.Add(item.hl_amount_happen);
                            m[1].list.Add(item.hl_amount_sales);

                            m[2].list.Add(0);  //item.tl_amount_pay  尾程物流费付款额
                            m[2].list.Add(item.tl_amount_happen);
                            m[2].list.Add(item.tl_amount_sales);

                            m[3].list.Add(item.tos_amount_pay);
                            m[3].list.Add(item.tos_amount_happen);
                            m[3].list.Add(item.tos_amount_sales);

                            m[4].list.Add(item.ss_amount_pay);
                            m[4].list.Add(item.ss_amount_happen);
                            m[4].list.Add(0);    //item.ss_amount_sales   二级供应商采购销售额

                            head.Add(item.day.ToString("MM") + "已付款统计");
                            head.Add(item.day.ToString("MM") + "发生额统计");
                            head.Add(item.day.ToString("MM") + "销售部分统计");
                        }
                    }
                }
            }
            else if (dateWay == 1)
            {
                foreach (var item in obj)
                {
                    var m = list.OrderBy(a => a.type).ToList();

                    if (m.Count <= 0)
                    {
                        //管理成本
                        var m1 = new mHappenAmount
                        {
                            type = 1,
                            typename = "管理成本",
                            list = new List<decimal>(),
                        };

                        m1.list.Add(item.ac_amount_pay);
                        m1.list.Add(item.ac_amount_happen);
                        m1.list.Add(item.ac_amount_sales);

                        //头程物流
                        var m2 = new mHappenAmount
                        {
                            type = 2,
                            typename = "头程物流费",
                            list = new List<decimal>(),
                        };

                        m2.list.Add(item.hl_amount_pay);
                        m2.list.Add(item.hl_amount_happen);
                        m2.list.Add(item.hl_amount_sales);

                        //尾程物流
                        var m3 = new mHappenAmount
                        {
                            type = 3,
                            typename = "尾程物流费",
                            list = new List<decimal>()
                        };

                        m3.list.Add(0);  //item.tl_amount_pay  //头程和尾程物流费取值是一样的，只显示头程的物流付款数据
                        m3.list.Add(item.tl_amount_happen);
                        m3.list.Add(item.tl_amount_sales);

                        //一级供应商采购
                        var m4 = new mHappenAmount
                        {
                            type = 4,
                            typename = "一级供应商采购",
                            list = new List<decimal>()
                        };

                        m4.list.Add(item.tos_amount_pay);
                        m4.list.Add(item.tos_amount_happen);
                        m4.list.Add(item.tos_amount_sales);

                        //二级供应商采购
                        var m5 = new mHappenAmount
                        {
                            type = 5,
                            typename = "二级供应商采购",
                            list = new List<decimal>()
                        };

                        m5.list.Add(item.ss_amount_pay);
                        m5.list.Add(item.ss_amount_happen);
                        m5.list.Add(0);  //item.ss_amount_sales  二级供应商采购销售额

                        list.Add(m1);
                        list.Add(m2);
                        list.Add(m3);
                        list.Add(m4);
                        list.Add(m5);

                        head.Add(item.day.ToString("MMdd") + "已付款统计");
                        head.Add(item.day.ToString("MMdd") + "发生额统计");
                        head.Add(item.day.ToString("MMdd") + "销售部分统计");
                    }
                    else
                    {
                        if (head.Where(a => a.Contains(item.day.ToString("MMdd"))).Count() > 0)  //累加
                        {
                            m[0].list[m[0].list.Count - 3] += (item.ac_amount_pay);
                            m[0].list[m[0].list.Count - 2] += (item.ac_amount_happen);
                            m[0].list[m[0].list.Count - 1] += (item.ac_amount_sales);

                            m[1].list[m[1].list.Count - 3] += (item.hl_amount_pay);
                            m[1].list[m[1].list.Count - 2] += (item.hl_amount_happen);
                            m[1].list[m[1].list.Count - 1] += (item.hl_amount_sales);

                            //m[2].list[m[2].list.Count - 3] += (item.tl_amount_pay);    //尾程物流费付款额
                            m[2].list[m[2].list.Count - 2] += (item.tl_amount_happen);
                            m[2].list[m[2].list.Count - 1] += (item.tl_amount_sales);

                            m[3].list[m[3].list.Count - 3] += (item.tos_amount_pay);
                            m[3].list[m[3].list.Count - 2] += (item.tos_amount_happen);
                            m[3].list[m[3].list.Count - 1] += (item.tos_amount_sales);

                            m[4].list[m[4].list.Count - 3] += (item.ss_amount_pay);
                            m[4].list[m[4].list.Count - 2] += (item.ss_amount_happen);
                            //m[4].list[m[4].list.Count - 1] += (item.ss_amount_sales);    //二级供应商采购销售额
                        }
                        else   //新增
                        {

                            m[0].list.Add(item.ac_amount_pay);
                            m[0].list.Add(item.ac_amount_happen);
                            m[0].list.Add(item.ac_amount_sales);

                            m[1].list.Add(item.hl_amount_pay);
                            m[1].list.Add(item.hl_amount_happen);
                            m[1].list.Add(item.hl_amount_sales);

                            m[2].list.Add(0);  //item.tl_amount_pay  尾程物流费付款额
                            m[2].list.Add(item.tl_amount_happen);
                            m[2].list.Add(item.tl_amount_sales);

                            m[3].list.Add(item.tos_amount_pay);
                            m[3].list.Add(item.tos_amount_happen);
                            m[3].list.Add(item.tos_amount_sales);

                            m[4].list.Add(item.ss_amount_pay);
                            m[4].list.Add(item.ss_amount_happen);
                            m[4].list.Add(0);    //item.ss_amount_sales   二级供应商采购销售额

                            head.Add(item.day.ToString("MMdd") + "已付款统计");
                            head.Add(item.day.ToString("MMdd") + "发生额统计");
                            head.Add(item.day.ToString("MMdd") + "销售部分统计");

                        }
                    }
                }

            }

            if (list.Count > 0)
            {
                var m = new mHappenAmount {
                    type = 99,
                    typename = "总计",
                    list = new List<decimal>()
                };

                foreach (var item in list)
                {
                    for (var i = 0; i < item.list.Count; i++)
                    {
                        if (m.list.Count > i)
                        {
                            m.list[i] += (item.list[i]);
                        }
                        else
                        {
                            m.list.Add(item.list[i]);
                        }
                    }
                }

                list.Add(m);
            }

            
            //按日

            return Json(new {
                success = true,
                list = list,
                msg = "",
                head = head
            });
        }


        /// <summary>
        /// 每日发生额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListHappenAmount(DateTime start,DateTime end)
        {

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");

            return View();
        }

        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// 
        /// <param name="type">类型</param>
        /// <returns></returns>
        public string ListHappenAmountJson(DateTime start, DateTime end,string categorytype,int type)
        {
            
            return "";
        }


        #region 发生额明细

        #region 管理成本

        /// <summary>
        /// 管理成本费用汇总
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ListPayAdminCostCount(DateTime start, DateTime end)
        {
            //var url = "http://api.fee.bailuntec.com/purchase/other/cost/api/manageCostList?o=0";
            //var cwurl = "http://cw.bailuntec.com/api/api/GetRepayPlanDetails?";

            //url += "&startDate=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&endDate=" + end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");
            //cwurl += "BeginRepayTime=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&EndRepayTime=" + end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");


            var url = "http://api.fee.bailuntec.com/purchase/other/cost/api/manageCostList?o=0";
            var cwurl = "http://cw.bailuntec.com/api/api/GetRepayPlanDetails?";
            var lgurl = "http://api.fee.bailuntec.com/fee/api/cost/api/logisticsCostList?";

            url += "&startDate=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&endDate=" + end.ToString("yyyy-MM-dd HH:mm:ss");
            cwurl += "BeginRepayTime=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&EndRepayTime=" + end.ToString("yyyy-MM-dd HH:mm:ss");
            lgurl += "startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");

            //利息支出
            var listInterest = new Bailun.DC.Services.FinanceReportServices().ListInterestExpense(cwurl);

            //管理成本
            var list = new Bailun.DC.Services.FinanceReportServices().ListOtherCost(url);
            //物流费支出
            var listlg = new Services.FinanceReportServices().ListLogisticFee(lgurl);

            
            var listFeeType = new List<string> { "推广费", "税费", "平台费用", "服务费", "其他" };

            list = list.Where(a => a.companyName.Contains("广州歌戈儿生活科技有限公司") || a.companyValue == 5 || a.companyValue == 1 || a.companyValue == 3 || a.companyValue == 8 || a.companyValue == 2).ToList();



            //利息支出
            //var listInterest = new Bailun.DC.Services.FinanceReportServices().ListInterestExpense(cwurl);

            //管理成本
            //var list = new Bailun.DC.Services.FinanceReportServices().ListOtherCost(url);

            var CostCount = 0M;
            var InterestCount = 0M;
            var LGCount = 0M;

            if (list.Count > 0)
            {
                CostCount = list.Sum(a => a.amountRmb);

            }

            if (listInterest.Count > 0)
            {
                InterestCount = listInterest.Sum(a => a.RepayInterestRMB);
            }

            if (listlg.Count > 0)
            {
                LGCount = listlg.Sum(a => a.amountRmb);
            }

            ViewBag.CostCount = CostCount.ToString("N2");
            ViewBag.InterestCount = InterestCount.ToString("N2");
            ViewBag.LGCount = LGCount.ToString("N2");

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }
        
        /// <summary>
        /// 管理成本付款明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListPayAdminCost(DateTime start, DateTime end,int type)
        {

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            ViewBag.type = type;

            return View();
        }

        
        /// <summary>
        /// 获取管理成本付款明细--管理成本（不包含利息支出）
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListPayAdminCostJson(DateTime start, DateTime end,int type)
        {
            var url = "http://api.fee.bailuntec.com/purchase/other/cost/api/manageCostList?o=0";
            url += "&startDate=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&endDate=" + end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");

            //管理成本
            var list = new Bailun.DC.Services.FinanceReportServices().ListOtherCost(url);

            if (type == 3)  //按销售统计
            {
                var listFeeType = new List<string> { "推广费", "税费", "平台费用", "服务费", "其他" };

                list = list.Where(a => a.companyValue == 5 || a.companyValue == 2).Where(b => listFeeType.Contains(b.feeSuperType)).ToList();
            }

            var total = 0M;
            if (list.Count > 0)
            {
                total = list.Sum(a => a.amountRmb);
            }

            return JsonConvert.SerializeObject(new { total = list.Count(), rows = list });
        }

        /// <summary>
        /// 导出管理成本明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <param name="type">统计类型 1：付款  2：发生额  3：销售额</param>
        /// <returns></returns>
        public ActionResult ExportPayAdminCost(DateTime start, DateTime end, int type)
        {
            var url = "http://api.fee.bailuntec.com/purchase/other/cost/api/manageCostList?o=0";
            url += "&startDate=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&endDate=" + end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");

            //管理成本
            var obj = new Bailun.DC.Services.FinanceReportServices().ListOtherCost(url);

            if (type == 3)  //按销售统计
            {
                var listFeeType = new List<string> { "推广费", "税费", "平台费用", "服务费", "其他" };

                obj = obj.Where(a => a.companyValue == 5 || a.companyValue == 2).Where(b => listFeeType.Contains(b.feeSuperType)).ToList();
            }

            var colNames = new List<string> { "费用单号", "成本类型", "部门名称", "付款主体", "分类名称", "收款单位", "金额", "付款时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.no + "|" + item.manageCostType + "|" + item.departmentName + "|" + item.companyName + "|" + item.feeSuperType + "|" + 
                    item.receiveUnit+"|"+ item.amountRmb.ToString("N2")+"|"+item.payTime
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd")+"至"+end.ToString("yyyy-MM-dd") + " 管理成本明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }

        /// <summary>
        /// 获取管理成本付款明细--利息支出
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListPayAdminCostInterest(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 获取管理成本付款明细--利息支出
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListPayAdminCostInterestJson(DateTime start, DateTime end)
        {
            var cwurl = "http://cw.bailuntec.com/api/api/GetRepayPlanDetails?";
            cwurl += "BeginRepayTime=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&EndRepayTime=" + end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");

            //利息支出
            var listInterest = new Bailun.DC.Services.FinanceReportServices().ListInterestExpense(cwurl);

            var total = 0M;
            if (listInterest.Count > 0)
            {
                total = listInterest.Sum(a => a.RepayInterestRMB);
            }

            return JsonConvert.SerializeObject(new { total = listInterest.Count(), rows = listInterest });
        }

        public ActionResult ExportPayAdminCostInterest(DateTime start, DateTime end)
        {
            var cwurl = "http://cw.bailuntec.com/api/api/GetRepayPlanDetails?";
            cwurl += "BeginRepayTime=" + start.ToString("yyyy-MM-dd HH:mm:ss") + "&EndRepayTime=" + end.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss");

            //利息支出
            var listInterest = new Bailun.DC.Services.FinanceReportServices().ListInterestExpense(cwurl);

            var colNames = new List<string> { "借入公司名称", "借款帐号", "借款银行", "借款持卡人", "债权方", "归还利息", "归还利息RMB", "还款时间" };

            var list = new List<string>();
            foreach (var item in listInterest)
            {
                list.Add(item.Company + "|" + item.BankCard + "|" + item.BankCardUser + "|" + item.BankName + "|" + item.Creditor + "|" +
                    item.RepayInterest + "|" + item.RepayInterestRMB.ToString("N2") + "|" + item.ActualRepayTime
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 管理成本-利息支出明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 获取管理成本付款明细--物流支出
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListPayLogistic(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 获取管理成本付款明细--物流支出
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListPayLogisticJson(DateTime start, DateTime end)
        {
            var lgurl = "http://api.fee.bailuntec.com/fee/api/cost/api/logisticsCostList?";
            lgurl += "startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");
            //物流费支出
            var listlg = new Services.FinanceReportServices().ListLogisticFee(lgurl);
            

            var total = 0M;
            if (listlg.Count > 0)
            {
                total = listlg.Sum(a => a.amountRmb);
            }

            return JsonConvert.SerializeObject(new { total = listlg.Count(), rows = listlg });
        }

        public ActionResult ExportListPayLogistic(DateTime start, DateTime end)
        {
            var lgurl = "http://api.fee.bailuntec.com/fee/api/cost/api/logisticsCostList?";
            lgurl += "startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");
            //物流费支出
            var listlg = new Services.FinanceReportServices().ListLogisticFee(lgurl);

            /*
             * 
             { field: 'receiveUnit', title: '被出纳公司名', width: '160' },
                { field: 'reason', title: '原因', width: '130' },
                { field: 'payTime', title: '出纳时间', width: '130' },
                { field: 'departmentName', title: '部门', width: '130' },
                { field: 'companyName', title: '付款主体', width: '150' },
                { field: 'feeSuperType', title: '费用主类型', width: '120' },
                { field: 'feeSubType', title: '费用子类型', width: '130' },
                { field: 'amountRmb', title: '人民币金额', width: '110' }
             * 
             */

            var colNames = new List<string> { "被出纳公司名", "原因", "出纳时间", "部门", "付款主体", "费用主类型", "费用子类型", "人民币金额" };

            var list = new List<string>();
            foreach (var item in listlg)
            {
                list.Add(item.receiveUnit + "|" + item.reason + "|" + item.payTime + "|" + item.departmentName + "|" + item.companyName + "|" +
                    item.feeSuperType + "|" + item.feeSubType + "|" + item.amountRmb.ToString("N2")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 管理成本-物流支出明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 获取管理成品出纳单的出纳凭证
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetFeeCashAttachment(string no)
        {
            var url = "http://api.fee.bailuntec.com/purchase/other/cost/list/getCostDetail?costNo=";

            var result = Common.HttpHelper.NetHelper.HttpPost(url + no,"");
            if (result == "")
            {
                return Json(new
                {
                    success = false,
                    msg = "该费用单没有找到出纳凭证文件。",
                });
            }
            else
            {
                var json = Newtonsoft.Json.Linq.JObject.Parse(result);

                return Json(new {
                    success = json["success"].ToBoolean()==true,
                    msg = (json["data"]["cashierDownloadPath"].ToString() != ""?"": "该费用单没有找到出纳凭证文件。"),
                    data = json["data"]["cashierDownloadPath"].ToString()
                });
            }
        }

        #endregion

        #region 头程物流

        /// <summary>
        /// 付款明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListHeadLogistic(DateTime start, DateTime end)
        {

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");

            return View();
        }

        /// <summary>
        /// 付款明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListHeadLogisticJson(BtTableParameter parameter,DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var obj = _services.ListHeadLogisticPay(parameter,start, end,ref total);
            var objCount = _services.ListHeadLogisticPayCount(start, end);

            return JsonConvert.SerializeObject(new { total = total, rows = obj,
                count_row = new
                {
                    paymoney_rmb = objCount.paymoney_rmb.ToString("N2"),
                    cashier_paymoneyrmb = objCount.cashier_paymoneyrmb.ToString("N2"),
                    companymain_name_from = "总计"
                }
            });
        }

        /// <summary>
        /// 导出头程物流付款明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportHeadLogisticPay(DateTime start, DateTime end)
        {
            var obj = new Services.FinanceReportServices().ListHeadLogisticPay(start, end);

            var colNames = new List<string> { "出纳单编码", "申请标题", "费用大类", "公司主体名称", "交易总金额", "出纳金额", "出纳时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.code + "|" + item.detail_name + "|" + item.type_name + "|" + item.companymain_name_from + "|" + item.paymoney_rmb + "|" +
                    item.cashier_paymoneyrmb + "|" + item.cashier_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 头程物流付款明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }




        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListHeadLogisticHappen(DateTime start, DateTime end)
        {

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListHeadLogisticHappenJson(BtTableParameter parameter,DateTime start, DateTime end)
        {
            var _service = new Services.FinanceReportServices();
            var obj = _service.ListHeadLogisticHappen(start, end);

            return JsonConvert.SerializeObject(new { total = obj.Count(), rows = obj });
        }

        /// <summary>
        /// 导出发生额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportHeadLogisticHappen(DateTime start, DateTime end)
        {
            var obj = new Services.FinanceReportServices().ListHeadLogisticHappen(start, end);

            var colNames = new List<string> { "物流单号", "箱号", "调拨单号", "头程费", "操作时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.channel_order_id + "|" + item.box_id + "|" + item.transfer_order_id + "|" + item.cost_first + "|" + item.operation_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 头程物流发生额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
            
        }


        /// <summary>
        /// 销售额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ListHeadLogisticSale(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 销售额明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListHeadLogisticSaleJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _service = new Services.FinanceReportServices();

            var obj = _service.ListHeadLogisticSale(parameter, start, end, ref total);
            var objCount = _service.ListHeadLogisticSaleCount(start, end);

            return JsonConvert.SerializeObject(new { total = total, rows = obj ,
                count_row = new {
                    objCount.cost_first,
                    bailun_sku = "总计"
                }
            });
        }

        /// <summary>
        /// 导出销售额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportHeadLogisticSale(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListHeadLogisticSale(new BtTableParameter { limit = 0 }, start, end,ref total);

            var colNames = new List<string> { "平台类型", "平台单号", "Sku", "头程费", "下单时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.platform_type + "|" + item.origin_order_id + "|" + item.bailun_sku + "|" + item.cost_first + "|" + item.create_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 头程物流销售额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }


        #endregion

        #region 尾程物流

        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListTailLogisticHappen(DateTime start,DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListTailLogisticHappenJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;

            var _service = new Services.FinanceReportServices();

            var obj = _service.ListTailLogisticHappen(parameter, start, end, ref total);
            var objCount = _service.ListTailLogisticHappenCount(start, end);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.cost_tail,
                    bailun_sku = "总计"
                }
            });
        }

        /// <summary>
        /// 导出尾程物流发生额
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportTailLogisticHappen(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListTailLogisticHappen(new BtTableParameter() { limit = 0 }, start, end, ref total);

            var colNames = new List<string> { "平台单号", "配货单号", "物流跟踪号", "Sku", "尾程费", "发货时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.origin_order_id + "|" + item.pick_order_id + "|" + item.tracking_order_id + "|" + item.bailun_sku+"|"+item.cost_tail + "|" + item.shipping_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 尾程物流发生额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }

        /// <summary>
        /// 销售额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListTailLogisticSale(DateTime start, DateTime end)
        {

            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 销售额明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListTailLogisticSaleJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var obj = _services.ListTailLogisticSale(parameter, start, end, ref total);
            var objCount = _services.ListTailLogisticSaleCount(start, end);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.cost_logistics,
                    bailun_sku = "总计"
                }
            });
        }

        /// <summary>
        /// 导出尾程物流销售额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportTailLogisticSale(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListTailLogisticSale(new BtTableParameter { limit = 0 }, start, end,ref total);

            var colNames = new List<string> { "平台类型", "平台单号", "Sku", "尾程费", "付款时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.platform_type + "|" + item.origin_order_id + "|" + item.bailun_sku + "|" + item.cost_tail + "|" + item.paid_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 尾程物流销售额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        #endregion

        #region 一级供应商

        /// <summary>
        /// 付款明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListFirstSupplierPay(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 付款明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListFirstSupplierPayJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var obj = _services.ListFirstSupplierPay(parameter, start, end, ref total);
            var objCount = _services.ListFirstSupplierPayCount(start, end);


            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.paymoney_rmb,
                    objCount.cashier_paymoneyrmb,
                    companymain_name_from = "总计"
                }
            });

        }

        /// <summary>
        /// 导出一级供应商付款额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportFirstSupplierPay(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListFirstSupplierPay(new BtTableParameter { limit = 0}, start, end, ref total);

            var colNames = new List<string> { "出纳单编码", "申请标题", "费用大类", "公司主体名称", "交易总金额", "出纳金额", "出纳时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.code + "|" + item.detail_name + "|" + item.type_name + "|" + item.companymain_name_from +"|"+ item.paymoney_rmb + "|" + item.cashier_paymoneyrmb + "|" + item.cashier_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 一级供应商付款额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }
        
        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListFirstSupplierHappen(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }


        /// <summary>
        /// 发生额明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListFirstSupplierHappenJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var obj = _services.ListFirstSupplierHappen(parameter, start, end, ref total);
            var objCount = _services.ListFirstSupplierHappenCount(start, end);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.amount,
                    bailun_sku = "总计"
                }
            });
        }

        /// <summary>
        /// 导出一级供应商发生额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportFirstSupplierHappen(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListFirstSupplierHappen(new BtTableParameter { limit = 0}, start, end,ref total);

            var colNames = new List<string> { "采购单号", "Sku", "采购数量", "采购价", "采购金额", "下单时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.purchase_id + "|" + item.bailun_sku + "|" + item.quantity_purchase + "|" + item.unit_price + "|" + item.amount + "|" + item.create_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 一级供应商发生额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }




        /// <summary>
        /// 销售额明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListFirstSupplierSale(DateTime start,DateTime end)
        {

            ViewBag.start = start.ToString("yyyy-MM-dd ");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 销售额明细汇总
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListFirstSupplierSaleJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();

            var obj = _services.ListFirstSupplierSale(parameter, start, end, ref total);
            var objCount = _services.ListFirstSupplierSaleCount(start, end);
            
            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.amount_sale_count,
                    bailun_sku = "总计"
                }
            });
        }

        /// <summary>
        /// 导出一级供应商销售额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportFirstSupplierSale(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListFirstSupplierSale(new BtTableParameter { limit=0}, start, end, ref total);

            var colNames = new List<string> { "平台单号", "配货单号", "物流跟踪号", "Sku", "发货数量", "采购价", "发货成本", "发货时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.origin_order_id + "|" + item.pick_order_id + "|" + item.tracking_order_id + "|" + item.bailun_sku + "|" + item.quantity_shipped + "|" + item.bailun_sku_unit_price + "|" + item.amount_sale_count + "|" + item.shipping_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 一级供应商销售额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }


        #endregion

        #region 二级供应商

        /// <summary>
        /// 付款额
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListSecondSupplierPay(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 付款额
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListSecondSupplierPayJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _service = new Services.FinanceReportServices();
            var obj = _service.ListSecondSupplierPay(parameter, start, end, ref total);
            var objCount = _service.ListSecondSupplierPayCount(start, end);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.cashier_paymoneyrmb,
                    companymain_name_from = "总计"
                }
            });
        }

        /// <summary>
        /// 导出二级供应商付款额明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public ActionResult ExportSecondSupplierPay(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListSecondSupplierPay(new BtTableParameter { limit = 0 }, start, end, ref total);
            
            var colNames = new List<string> { "出纳单编码", "申请标题", "费用大类", "公司主体名称", "交易总金额", "出纳金额", "出纳时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.code + "|" + item.detail_name + "|" + item.type_name + "|" + item.companymain_name_from + "|" + item.paymoney_rmb + "|" + item.cashier_paymoneyrmb + "|" + item.cashier_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 二级供应商付款额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        /// <summary>
        /// 发生额
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public ActionResult ListSecondSupplierHappen(DateTime start, DateTime end)
        {
            ViewBag.start = start.ToString("yyyy-MM-dd");
            ViewBag.end = end.ToString("yyyy-MM-dd");
            return View();
        }

        /// <summary>
        /// 发生额
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        public string ListSecondSupplierHappenJson(BtTableParameter parameter, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var obj = _services.ListSecondSupplierHappen(parameter, start, end, ref total);
            var objCount = _services.ListSecondSupplierHappenCount(start, end);

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = obj,
                count_row = new
                {
                    objCount.amount,
                    bailun_sku = "总计"
                }
            });
        }

        public ActionResult ExportSecondSupplierHappen(DateTime start, DateTime end)
        {
            var total = 0;
            var obj = new Services.FinanceReportServices().ListSecondSupplierHappen(new BtTableParameter { limit = 0 }, start, end,ref total);

            var colNames = new List<string> { "半成品采购单号", "Sku", "采购数量", "采购价", "采购金额", "下单时间" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.purchase_id + "|" + item.bailun_sku + "|" + item.quantity_purchase + "|" + item.unit_price + "|" + item.amount  + "|" + item.create_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 二级供应商发生额明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }



        #endregion

        #endregion

        #endregion
        
        #region Ebay收入报告分析

        /// <summary>
        /// Ebay收入报告明细
        /// </summary>
        /// <returns></returns>
        public ActionResult ListEbayIncome()
        {
            return View();
        }

        /// <summary>
        /// Ebay收入报告明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="account">符合条件的记录数</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListEbayIncomeJson(BtTableParameter parameter, DateTime start, DateTime end, string account)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;

            var _services = new Services.FinanceReportServices();
            var obj = _services.ListPaypalIncome(parameter, start, end, account, ref total);
            var objCount = _services.ListPaypalIncomeCount(start, end, account);

            var list = obj.Select(a => new {
                record_time = a.record_time.ToString("yyyy-MM-dd HH:mm:ss"),
                a.account_name,
                a.time_zone,
                a.type,
                a.status,
                a.currency,
                gross = a.gross.ToString("N2"),
                fee = a.fee.ToString("N2"),
                net = a.net.ToString("N2"),


                a.from_email,
                a.to_email,
                a.transaction_id,
                shipping_handling_amount = a.shipping_handling_amount.ToString("N2"),
                insurance_amount = a.insurance_amount.ToString("N2"),
                sales_tax = a.sales_tax.ToString("N2"),


                a.custom_number,
                quantity = a.quantity.ToString("N2"),
                balance = a.balance.ToString("N2"),
                a.country_code,
                a.balance_impact,
                createtime = a.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
            });

            
            return JsonConvert.SerializeObject(new { total = total, rows = list,
                count_row = new {
                    status = "总计",
                    balance = objCount.balance.ToString("N2"),
                    fee = objCount.fee.ToString("N2"),
                    gross = objCount.gross.ToString("N2"),
                    insurance_amount = objCount.insurance_amount.ToString("N2"),
                    net = objCount.net.ToString("N2"),
                    quantity = objCount.quantity.ToString("N0"),
                    sales_tax = objCount.sales_tax.ToString("N2"),
                    shipping_handling_amount = objCount.shipping_handling_amount.ToString("N2")
                },
                companyid 
            });
        }

        /// <summary>
        /// 导入Ebay收入明细
        /// </summary>
        /// <param name="formattype">1：中文账户，2：英文国外账户，3：英文国内账户 </param>
        /// <returns></returns>
        public JsonResult UploadEbayIncome(int companyid,int formattype)
        {
            var result = "";
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            foreach (var item in Request.Form.Files)
            {
                var file = item;

                //var index = file.FileName.IndexOf("==");
                //var accountname = file.FileName.Substring(index + 2, file.FileName.Length - (index + 2));
                //var indexdot = accountname.ToLower().IndexOf(".csv");

                //accountname = accountname.Substring(0, indexdot);

                //if (accountname.Length == 0)
                //{
                //    return Json(new
                //    {
                //        success = false,
                //        msg = "请填写正确的帐号信息"
                //    });
                //}

                try
                {

                    var read = new System.IO.StreamReader(file.OpenReadStream());
                    var list = new List<dc_base_income_ebay_paypal>();
                    var s = read.ReadLine();  //不要第一行

                    if (formattype == 1 && s.Replace("\"","").Substring(0, 2) != "日期")
                    {
                        return Json(new
                        {
                            success = false,
                            msg = file.FileName + "不是中文格式"
                        });
                    }
                    else if (formattype != 1 && s.Substring(0, 2) != "日期")
                    {
                        return Json(new
                        {
                            success = false,
                            msg = file.FileName + "不是英文格式"
                        });
                    }


                    s = read.ReadLine();
                    var row_index = 1;
                    while (!string.IsNullOrEmpty(s))
                    {
                        if (s.Length > 0)
                        {

                            var tempArr = s.Split("\"");
                            if (tempArr.Length > 0)
                            {
                                s = tempArr[0];
                                for (var i = 1; i < tempArr.Length - 1; i++)
                                {
                                    if ((tempArr[i - 1] == "" || tempArr[i - 1].Substring(tempArr[i - 1].Length - 1, 1) == ",") && (tempArr[i + 1] == "" || tempArr[i + 1].Substring(0, 1) == ",") && tempArr[i].Length > 1)
                                    {
                                        tempArr[i] = tempArr[i].Replace(",", "||");
                                    }
                                    s += tempArr[i];
                                }
                                s += tempArr[tempArr.Length - 1];
                            }

                            var arr = s.Split(',');
                            if (arr.Length > 1)             //中文账户
                            {
                                var time = DateTime.Now;

                                if (formattype == 1)
                                {
                                    time = DateTime.Parse(arr[0] + " " + arr[1]);
                                }
                                else if (formattype == 2)   //英文国外账户
                                {
                                    var arrDate = arr[0].Split('/');

                                    if (arrDate.Length == 3)
                                    {
                                        time = DateTime.Parse(arrDate[2] + "-" + arrDate[0] + "-" + arrDate[1] + " " + arr[1]);
                                    }
                                    else
                                    {
                                        return Json(new
                                        {
                                            success = false,
                                            msg = "第" + row_index + "行时间格式转换失败，请重试或联系管理员。",
                                        });
                                    }
                                }
                                else if (formattype == 3)   //英文国内账户
                                {
                                    var arrDate = arr[0].Split('/');

                                    if (arrDate.Length == 3)
                                    {
                                        time = DateTime.Parse(arrDate[2] + "-" + arrDate[1] + "-" + arrDate[0] + " " + arr[1]);
                                    }
                                    else
                                    {
                                        return Json(new
                                        {
                                            success = false,
                                            msg = "第" + row_index + "行时间格式转换失败，请重试或联系管理员。",
                                        });
                                    }
                                }

                                try
                                {
                                    var m = new dc_base_income_ebay_paypal()
                                    {
                                        company_id = companyid,
                                        record_time = time,
                                        //account_name = accountname,

                                        time_zone = arr[2],
                                        name = arr[3],
                                        type = arr[4],
                                        status = arr[5],
                                        currency = arr[6],
                                        gross = decimal.Parse(arr[7].Replace("||", ",")),
                                        fee = decimal.Parse(arr[8].Replace("||", ",")),
                                        net = decimal.Parse(arr[9].Replace("||", ",")),

                                        from_email = arr[10].Replace("||", ","),
                                        to_email = arr[11].Replace("||", ","),
                                        transaction_id = arr[12],
                                        shipping_address = arr[13].Replace("||", ","),
                                        address_status = arr[14],
                                        item_title = arr[15].Replace("||", ","),
                                        item_id = arr[16],

                                        shipping_handling_amount = decimal.Parse(arr[17] == "" ? "0" : arr[17].Replace("||", ",")),
                                        insurance_amount = decimal.Parse(arr[18] == "" ? "0" : arr[18].Replace("||", ",")),
                                        sales_tax = decimal.Parse(arr[19] == "" ? "0" : arr[19].Replace("||", ",")),
                                        option_name1 = arr[20].Replace("||", ","),
                                        option_value1 = arr[21].Replace("||", ","),
                                        option_name2 = arr[22].Replace("||", ","),
                                        option_value2 = arr[23].Replace("||", ","),
                                        reference_txn_id = arr[24],
                                        invoice_number = arr[25],
                                        custom_number = arr[26],

                                        quantity = int.Parse(arr[27] == "" ? "0" : arr[27]),
                                        receipt_id = arr[28],
                                        balance = decimal.Parse(arr[29] == "" ? "0" : arr[29].Replace("||", ",")),

                                        address_line1 = arr[30].Replace("||", ","),
                                        address_line2 = arr[31].Replace("||", ","),
                                        town = arr[32].Replace("||", ","),
                                        province = arr[33].Replace("||", ","),
                                        postal_code = arr[34],
                                        country = arr[35],
                                        contact_phone_number = arr[36],
                                        subject = arr[37].Replace("||", ","),
                                        note = arr[38].Replace("||", ","),
                                        country_code = arr[39],
                                        balance_impact = arr[40],
                                        createtime = DateTime.Now,
                                        createuserid = 0,
                                        createusername = "",
                                    };

                                    list.Add(m);
                                }
                                catch (Exception ex)
                                {
                                    return Json(new
                                    {
                                        success = false,
                                        msg = "第" + row_index + "行出现异常，异常信息：" + ex.Message,
                                    });
                                }
                            }

                        }

                        s = read.ReadLine();
                        row_index++;
                    }

                    var msg = "";
                    if (list.Count > 0)
                    {
                        //匹配当前帐号
                        var first = list.GroupBy(a=>a.to_email).OrderByDescending(a=>a.Count()).FirstOrDefault();
                        if (first != null)
                        {
                            foreach (var temp in list)
                            {
                                temp.account_name = first.Key;
                            }
                        }

                        msg = new Services.FinanceReportServices().SaveEbayPayPalInfo(list);
                    }

                    if (string.IsNullOrEmpty(msg) && list.Count>0)
                    {
                        var objPaypal = list.OrderBy(a => a.record_time).FirstOrDefault();
                        if (objPaypal != null)
                        {
                            var firstDay = DateTime.Parse(objPaypal.record_time.ToString("yyyy-MM") + "-01");

                            var r = new Services.FinanceReportServices().Analyze_PaypalIncoming(list.FirstOrDefault().account_name, firstDay,firstDay.AddMonths(1));

                            if (!string.IsNullOrEmpty(r))
                            {
                                return Json(new
                                {
                                    success = false,
                                    msg = "保存" + file.FileName + "成功，生成分录信息失败，异常信息：" + r,
                                });
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(msg))
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "保存"+file.FileName+"失败，失败信息：" + msg,
                        });
                    }

                }
                catch (Exception ex)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "解析出现异常，异常信息：" + ex.Message,
                    });
                }
            }

            return Json(new
            {
                success = true,
                msg = "",
            });
        }

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

        /// <summary>
        /// paypal收入分录记录
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="month">月份</param>
        /// <param name="account">paypal帐号</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListPaypalIncomeAnalyzeJson(BtTableParameter parameter, string month, string account,string currency)
        {
            var companyid = HttpContextHelper.Current?.User?.GetCompanyId().ToInt32();
            var total = 0;
            var obj = new Services.FinanceReportServices().ListPaypalIncoming(parameter, month, account, currency, ref total);

            var list = obj.Select(a => new {
                a.account_subject,
                amount = a.amount.ToString("N2"),
                a.balance_impact,
                createtime = a.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
                a.currency,

                a.note,
                a.paypal_account,
                a.platform_bank,
                a.receive_account,
                a.recordtime,
            });


            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                companyid
            });
        }


        #region Private

        /// <summary>
        /// 格式化ebay收入 中文字段
        /// </summary>
        /// <param name="account">帐号信息</param>
        /// <param name="row">表格行信息</param>
        /// <returns></returns>
        private dc_base_income_ebay_paypal FormatTableRowForChs(dc_base_company_account account,DataRow row,int companyid)
        {
            var Date = row["日期"].ToString();
            var Time = DateTime.Parse(row["时间"].ToString()).ToString("HH:mm:ss");
            var Gross = row["总额"];
            var Fee = row["费用"];
            var Net = row["净额"];
            var PostageandPackagingAmount = row["运费和手续费金额"];
            var InsuranceAmount = row["保险金额"];
            var VAT = row["营业税"];
            var Quantity = row["数量"];
            var Balance = row["余额"];

            var m = new dc_base_income_ebay_paypal() {
                company_id = companyid,
                record_time = DateTime.Parse(Date + " " + Time),
                //account_id = account.account_id,
                account_name = account.account_name,

                time_zone = row["时区"].ToString(),
                name = row["名称"].ToString(),
                type = row["类型"].ToString(),
                status = row["状态"].ToString(),
                currency = row["币种"].ToString(),
                gross = decimal.Parse(Gross.ToString()),
                fee = decimal.Parse(Fee.ToString()),
                net = decimal.Parse(Net.ToString()),

                from_email = row["发件人邮箱地址"].ToString(),
                to_email = row["收件人邮箱地址"].ToString(),
                transaction_id = row["交易号"].ToString(),
                shipping_address = row["收货地址"].ToString(),
                address_status = row["地址状态"].ToString(),
                item_title = row["物品名称"].ToString(),
                item_id = row["物品号"].ToString(),

                shipping_handling_amount = decimal.Parse(PostageandPackagingAmount.ToString()),
                insurance_amount = decimal.Parse(InsuranceAmount.ToString()),
                sales_tax = decimal.Parse(VAT.ToString()),
                option_name1 = row["选项 1 名称"].ToString(),
                option_value1 = row["选项 1 值"].ToString(),
                option_name2 = row["选项 2 名称"].ToString(),
                option_value2= row["选项 2 值"].ToString(),
                reference_txn_id = row["参考交易号"].ToString(),
                invoice_number = row["账单号"].ToString(),
                custom_number = row["自定义号码"].ToString(),

                quantity = int.Parse(Quantity.ToString()),
                receipt_id = row["收据号"].ToString(),
                balance = decimal.Parse(Balance.ToString()),

                address_line1 = row["地址第1行"].ToString(),
                address_line2 = row["地址第2行/区/临近地区"].ToString(),
                town = row["城镇/城市"].ToString(),
                province = row["省/市/自治区/直辖市/特别行政区"].ToString(),
                postal_code = row["邮政编码"].ToString(),
                country = row["国家/地区"].ToString(),
                contact_phone_number = row["联系电话号码"].ToString(),
                subject = row["主题"].ToString(),
                note = row["备注"].ToString(),
                country_code = row["国家/地区代码"].ToString(),
                balance_impact = row["引起余额变动"].ToString(),
                createtime = DateTime.Now,
                createuserid = 0,
                createusername = "引起余额变动",
            };

            return m;
        }

        private dc_base_income_ebay_paypal FormatTableRowForEnglish(dc_base_company_account account, DataRow row, int companyid)
        {
            var Date = row["Date"].ToString();
            var Time = DateTime.Parse(row["Time"].ToString()).ToString("HH:mm:ss");
            var Gross = row["Gross"];
            var Fee = row["Fee"];
            var Net = row["Net"];
            var ShippingandHandlingAmount = "";
            try
            {
                ShippingandHandlingAmount = row["Postage and Packaging Amount"].ToString(); //运费和手续费金额
            }
            catch (Exception ex)
            {
                ShippingandHandlingAmount = row["Shipping and Handling Amount"].ToString();  //运费和手续费金额
            }

            var InsuranceAmount = row["Insurance Amount"];

            var SalesTax = "";
            try
            {
                SalesTax = row["VAT"].ToString();              //营业税
            }
            catch
            {
                SalesTax = row["Sales Tax"].ToString();   //营业税
            }


            var Quantity = row["Quantity"];
            var Balance = row["Balance"];
            
            var m = new dc_base_income_ebay_paypal() {
                company_id = companyid,
                record_time = DateTime.Parse(Date + " " + Time),
                //account_id = account.account_id,
                account_name = account.account_name,

                time_zone = row["TimeZone"].ToString(),
                name = row["Name"].ToString(),
                type = row["Type"].ToString(),
                status = row["Status"].ToString(),
                currency = row["Currency"].ToString(),
                gross = decimal.Parse(Gross.ToString()),
                fee = decimal.Parse(Fee.ToString()),
                net = decimal.Parse(Net.ToString()),

                from_email = row["From Email Address"].ToString(),
                to_email = row["To Email Address"].ToString(),
                transaction_id = row["Transaction ID"].ToString(),
                shipping_address = row["Shipping Address"].ToString(),
                address_status = row["Address Status"].ToString(),
                item_title = row["Item Title"].ToString(),
                item_id = row["Item ID"].ToString(),
                shipping_handling_amount = decimal.Parse(ShippingandHandlingAmount),
                insurance_amount = decimal.Parse(InsuranceAmount.ToString()),
                sales_tax = decimal.Parse(SalesTax),
                option_name1 = row["Option 1 Name"].ToString(),
                option_value1 = row["Option 1 Value"].ToString(),


                option_name2 = row["Option 2 Name"].ToString(),
                option_value2 = row["Option 2 Value"].ToString(),
                reference_txn_id = row["Reference Txn ID"].ToString(),
                invoice_number = row["Invoice Number"].ToString(),
                custom_number = row["Custom Number"].ToString(),
                quantity = int.Parse(Quantity.ToString()),
                receipt_id = row["Receipt ID"].ToString(),
                balance = decimal.Parse(Balance.ToString()),

                address_line1 = row["Address Line 1"].ToString(),
                address_line2 = row["Address Line 2/District/Neighborhood"].ToString(),
                town = row["Town/City"].ToString(),
                province = row["State/Province/Region/County/Territory/Prefecture/Republic"].ToString(),
                postal_code = row["Zip/Postal Code"].ToString(),
                country = row["Country"].ToString(),

                contact_phone_number = row["Contact Phone Number"].ToString(),
                subject = row["Subject"].ToString(),
                note = row["Note"].ToString(),
                country_code = row["Country Code"].ToString(),
                balance_impact = row["Balance Impact"].ToString(),
                createtime = DateTime.Now,
                createuserid = 0,
                createusername = "",

            };
                
            return m;
        }


        #endregion

        #endregion

        #region 跨境电商现金流

        /// <summary>
        /// 总收支报表
        /// </summary>
        /// <returns></returns>
        public ActionResult TotalIncomePay()
        {
            return View();
        }

        /// <summary>
        /// 总收支报表Json
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult TotalIncomePayJson(DateTime start,DateTime end)
        {
            try
            {
                var _service = new Services.FinanceReportServices();
                var obj = _service.ListDailyPayIncoming(start, end);

                return Json(new {
                    success = true,
                    list = obj.Select(p => new {
                        amount_income = p.amount_income.ToString("N2"),
                        amount_payed = p.amount_payed.ToString("N2"),
                        record_time = p.record_time.ToString("yyyy-MM-dd")
                    }),
                    msg = "",
                    countpayed = (obj.Count>0?obj.Sum(a=>a.amount_payed):0).ToString("N2"),
                    countincoming = (obj.Count>0?obj.Sum(a=>a.amount_income):0).ToString("N2")
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息："+ex.Message,

                });
            }
        }


        public ActionResult TotalIncomePay_PayDetail(DateTime date)
        {
            ViewBag.date = date.ToString("yyyy-MM-dd");



            return View();
        }

        public ActionResult ExportTotalIncomePay_PayDetail(DateTime start,DateTime end, int t)
        {
            //支出包含两部分，一部分是百伦管理费，一部分是产品成本支出
            //管理成本  广州百伦、香港百伦、电子服装厂、阳山仓、深圳仓的管理成本
            var url = "http://api.fee.bailuntec.com/fee/api/cost/api/manageCostList?";
            var cwurl = "http://cw.bailuntec.com/api/api/GetRepayPlanDetails?";
            var lgurl = "http://api.fee.bailuntec.com/fee/api/cost/api/logisticsCostList?";

            url += "&startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");
            cwurl += "BeginRepayTime=" + start.ToString("yyyy-MM-dd") + "&EndRepayTime=" + end.ToString("yyyy-MM-dd");
            lgurl += "startDate=" + start.ToString("yyyy-MM-dd") + "&endDate=" + end.ToString("yyyy-MM-dd");



            //decimal costTotal = 0;
            //costTotal = listInterest.Count > 0 ? listInterest.Sum(a => a.RepayInterestRMB) : 0;

            ////管理成本 只取付款主体为广州百伦供应链科技有限公司、香港百伦科技有限公司、广州电子服装仓、阳山仓、深圳仓、广州哥戈尔生活科技有限公司、广州迪致美容科技有限公司的数据
            //list = list.Where(a => a.companyName.Contains("广州歌戈儿生活科技有限公司") || a.companyValue == 5 || a.companyValue == 1 || a.companyValue == 3 || a.companyValue == 8 || a.companyValue == 2 || a.companyValue == 7).ToList();
            //if (list.Count > 0)
            //{
            //    costTotal += list.Sum(a => a.amountRmb);
            //}

            ////支出 物流费支出
            //if (listlg != null && listlg.Count() > 0)
            //{
            //    costTotal += listlg.Sum(a => a.amountRmb);
            //}


            ////支出 2、成品采购+半成品采购+百伦（广州、香港）支付给哈倪曼和拉古娜的费用+百伦管理费用
            //var sql = $@"select sum(cashier_paymoneyrmb) as amount from dc_base_finance_cashier where cashier_status=1 and cashier_type=1 and cashier_time>='{start.ToString("yyyy-MM-dd HH:mm:ss")}' and cashier_time<'{end.ToString("yyyy-MM-dd HH:mm:ss")}'  and ((sourcecode in ('Buy','SemiFinishedProduct') and companymain_value_from !=14 and companymain_value_from!=48) or (tradeb_bjectname in ('广州哈倪蔓生物科技有限公司','广州拉古娜生物科技有限公司','广州美甲生产仓') and companymain_value_from in (1,2,5,7,8) and sourcecode in ('newCost','IncomeAndExpenditure')))";


            if (t == 1)  //管理成本
            {
                //管理成品
                var list = new Services.FinanceReportServices().ListFinanceManageCost(start, end, "", "", "", null);

                var colNames = new List<string>() { "费用单号", "管理成本单类型", "部门名称", "付款主体名称", "父级分类", "金额", "付款时间" };

                //管理成本 只取付款主体为广州百伦供应链科技有限公司、香港百伦科技有限公司、广州电子服装仓、阳山仓、深圳仓、广州哥戈尔生活科技有限公司、广州迪致美容科技有限公司的数据
                list = list.Where(a => a.company_name.Contains("广州歌戈儿生活科技有限公司") || a.company_value == 5 || a.company_value == 1 || a.company_value == 3 || a.company_value == 8 || a.company_value == 2 || a.company_value == 7).ToList();

                var listval = new List<string>();
                foreach (var item in list)
                {
                    listval.Add(item.no + "|" + item.manage_cost_type + "|" + item.department_name + "|" + item.company_name + "|" + item.fee_super_type + "|" + item.amount_rmb + "|" +
                        (item.pay_time.HasValue ? item.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss") : "")
                        );
                }

                var guid = Guid.NewGuid().ToString();
                var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 现金流量表-管理成本支出";
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(listval, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");

            }
            else if (t == 2)  //利息
            {
                //利息支出
                var listInterest = new Services.FinanceReportServices().ListInterestExpense(cwurl);


                var colNames = new List<string>() { "借款公司", "借款帐号", "借款持卡人", "债权方", "本期归还利息", "实际还款时间" };

                var listval = new List<string>();
                foreach (var item in listInterest)
                {
                    listval.Add(item.Company + "|" + item.BankCard + "|" + item.BankName + "|" + item.Creditor + "|" + item.RepayInterestRMB + "|" + (item.ActualRepayTime.HasValue ? item.ActualRepayTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : "")
                        );
                }

                var guid = Guid.NewGuid().ToString();
                var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 现金流量表-利息成本支出";
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(listval, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");
            }
            else if (t == 3)  //物流
            {
                //物流费支出 
                var listlg = new Services.FinanceReportServices().ListLogisticFee(start, end);//new Services.FinanceReportServices().ListLogisticFee(lgurl);

                var colNames = new List<string>() { "单号", "被出纳公司名", "出纳时间", "类型", "部门", "付款主体", "费用主类型", "金额" };


                var listval = new List<string>();
                foreach (var item in listlg)
                {
                    listval.Add(item.no + "|" + item.receive_unit + "|" + item.pay_time.ToString("yyyy-MM-dd HH:mm:ss") + "|" + item.manage_cost_type + "|" + item.department_name + "|" + item.company_name + "|" + item.fee_super_type + "|" + item.amount_rmb
                        );
                }

                var guid = Guid.NewGuid().ToString();
                var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 现金流量表-物流费支出";
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(listval, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");


            }
            else if (t == 4) //采购成本
            {
                var listpurchase = new Services.FinanceReportServices().ListPurchaseCost(start, end);

                var colNames = new List<string>() { "出纳单编号", "申请标题", "费用大类", "公司主体名称", "金额", "出纳时间" };

                //code,detail_name,type_name,companymain_name_from,cashier_paymoneyrmb,cashier_time

                var listval = new List<string>();
                foreach (var item in listpurchase)
                {
                    listval.Add(item.code + "|" + item.detail_name + "|" + item.type_name + "|" + item.companymain_name_from + "|" + item.cashier_paymoneyrmb + "|" + item.cashier_time.ToString("yyyy-MM-dd HH:mm:ss")
                        );
                }

                var guid = Guid.NewGuid().ToString();
                var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 现金流量表-采购成本支出";
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(listval, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");
            }
            else if (t == 5)
            {
                var listpurchase = new Services.FinanceReportServices().ListPurchaseCost(start, end,0);
                var colNames = new List<string>() { "出纳单编号", "申请标题", "费用大类", "公司主体名称", "金额", "出纳时间" };

                var listval = new List<string>();
                foreach (var item in listpurchase)
                {
                    listval.Add(item.code + "|" + item.detail_name + "|" + item.type_name + "|" + item.companymain_name_from + "|" + item.cashier_paymoneyrmb + "|" + item.cashier_time.ToString("yyyy-MM-dd HH:mm:ss")
                        );
                }

                var guid = Guid.NewGuid().ToString();
                var filename = start.ToString("yyyy-MM-dd") + "至" + end.ToString("yyyy-MM-dd") + " 现金流量表-成品采购退货收款明细";
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(listval, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");
            }


            return View();
        }


        /// <summary>
        /// 现金流动态分析明细
        /// </summary>
        /// <returns></returns>
        public ActionResult ListDailyCompanyMoney()
        {
            return View();
        }

        /// <summary>
        /// 现金流动态分析明细
        /// </summary>
        /// <param name="start">开始日期</param>
        /// <param name="end">结束日期</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【跨境电商现金流报告】->【查询】页面", 0)]
        public JsonResult ListDailyCompanyMoneyJson(DateTime start, DateTime end)
        {
            try
            {
                var _service = new Services.FinanceReportServices();
                var obj = _service.ListDailyCompanyMoney(start, end);

                var m = new dc_daily_companymoneystatus() {
                    amount_arrivaled = 0,
                    amount_incoming = 0,
                    amount_payed = 0,
                    amount_purchase = 0,
                    amount_receivable = 0,
                    amount_sale = 0,
                    amount_stock = 0,
                    amount_withdrawonway = 0,
                };

                if (obj.Count > 0)
                {
                    m.amount_arrivaled = obj.Sum(a => a.amount_arrivaled);
                    m.amount_incoming = obj.Sum(a => a.amount_incoming);
                    m.amount_payed = obj.Sum(a => a.amount_payed);
                    m.amount_purchase = obj.Sum(a => a.amount_purchase);
                    m.amount_receivable = obj.Sum(a => a.amount_receivable);
                    m.amount_sale = obj.Sum(a => a.amount_sale);
                    m.amount_stock = obj.Sum(a => a.amount_stock);
                    m.amount_withdrawonway = obj.Sum(a => a.amount_withdrawonway);
                }

                return Json(new
                {
                    success = true,
                    list = obj.Select(p=>new {
                        amount_arrivaled = p.amount_arrivaled.ToString("N2"),
                        amount_incoming = p.amount_incoming.ToString("N2"),
                        amount_payed = p.amount_payed.ToString("N2"),
                        amount_purchase = p.amount_purchase.ToString("N2"),
                        amount_receivable = p.amount_receivable.ToString("N2"),
                        amount_sale = p.amount_sale.ToString("N2"),
                        amount_stock = p.amount_stock.ToString("N2"),
                        amount_withdrawonway = p.amount_withdrawonway.ToString("N2"),
                        record_time = p.record_time.ToString("yyyy-MM-dd")
                    }),
                    msg = "",
                    count = new {
                        amount_arrivaled = m.amount_arrivaled.ToString("N2"),
                        amount_incoming = m.amount_incoming.ToString("N2"),
                        amount_payed = m.amount_payed.ToString("N2"),
                        amount_purchase = m.amount_purchase.ToString("N2"),
                        amount_receivable = m.amount_receivable.ToString("N2"),
                        amount_sale = m.amount_sale.ToString("N2"),
                        amount_stock = m.amount_stock.ToString("N2"),
                        amount_withdrawonway = m.amount_withdrawonway.ToString("N2"),
                    }
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message,

                });
            }
        }

        #endregion

        #region 进销存报表

        #region 成品仓

        /// <summary>
        /// 仓库进销存报表
        /// </summary>
        /// <returns></returns>
        public ActionResult WHPurchaseSellStock()
        {
            return View();
        }

        /// <summary>
        /// 仓库进销存报表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="start">期初时间</param>
        /// <param name="end">期末时间</param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【成品仓库进销存】->【查询】页面", 0)]
        public string WHPurchaseSellStockJson(BtTableParameter parameter, string warehousetype, string warehouse, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var obj = _services.ListWHPurchaseSellStock(parameter, warehousetype, warehouse, start, end, ref total);
            var objCount = _services.ListWHPurchaseSellStockCount(warehousetype, warehouse, start, end);

            var list = obj.Select(a => new {
                a.warehouse_code,
                a.warehouse_name,
                start_onway_amount = a.start_onway_amount.ToString("N2"),
                start_onway_count = a.start_onway_count.ToString("N0"),
                start_stock_amount=a.start_stock_amount.ToString("N2"),
                start_stock_count = a.start_stock_count.ToString("N0"),

                end_onway_amount = a.end_onway_amount.ToString("N2"),
                end_onway_count = a.end_onway_count.ToString("N0"),
                end_stock_amount = a.end_stock_amount.ToString("N2"),
                end_stock_count = a.end_stock_count.ToString("N0"),
                
                diff_onway_amount = (a.end_onway_amount-a.start_onway_amount).ToString("N2"),
                diff_onway_count = (a.end_onway_count-a.start_onway_count).ToString("N0"),
                diff_stock_amount = (a.end_stock_amount-a.start_stock_amount).ToString("N2"),
                diff_stock_count = (a.end_stock_count - a.start_stock_count).ToString("N0"),

                count = a.count.ToString("N0"),
                amount = a.amount.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new { total = total, rows = list,
                count_row = new {
                    warehouse_name = "总计",
                    start_onway_amount = objCount.start_onway_amount.ToString("N2"),
                    start_onway_count = objCount.start_onway_count.ToString("N0"),
                    start_stock_amount = objCount.start_stock_amount.ToString("N2"),
                    start_stock_count = objCount.start_stock_count.ToString("N0"),

                    end_onway_amount = objCount.end_onway_amount.ToString("N2"),
                    end_onway_count = objCount.end_onway_count.ToString("N0"),
                    end_stock_amount = objCount.end_stock_amount.ToString("N2"),
                    end_stock_count = objCount.end_stock_count.ToString("N0"),

                    diff_onway_amount = (objCount.end_onway_amount-objCount.start_onway_amount).ToString("N2"),
                    diff_onway_count = (objCount.end_onway_count-objCount.start_onway_count).ToString("N0"),
                    diff_stock_amount = (objCount.end_stock_amount-objCount.start_stock_amount).ToString("N2"),
                    diff_stock_count = (objCount.end_stock_count-objCount.start_stock_count).ToString("N0"),

                    count = objCount.count.ToString("N0"),
                    amount = objCount.amount.ToString("N2"),
                }
            });
        }

        /// <summary>
        /// Sku进销存报表
        /// </summary>
        /// <returns></returns>
        public ActionResult SkuPurchaseSellStock(string warehouse,DateTime? start,DateTime? end)
        {
            string warehousetype = "";
            if (!string.IsNullOrEmpty(warehouse))
            {
                var objWH = new Services.WareHouseServices().GetWarehouse(warehouse);
                if (objWH != null)
                {
                    warehousetype = objWH.hq_type;
                }
            }

            ViewBag.warehousetype = warehousetype;
            ViewBag.warehouse = warehouse;
            ViewBag.start = start.HasValue ? start.Value.ToString("yyyy-MM-dd") : DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
            ViewBag.end = end.HasValue ? end.Value.ToString("yyyy-MM-dd") : DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");


            return View();
        }

        /// <summary>
        /// Sku进销存报表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="start">期初日期</param>
        /// <param name="end">期末日期</param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【成品SKU进销存】->【查询】页面", 0)]
        public string SkuPurchaseSellStockJson(BtTableParameter parameter, string sku,string warehousetype, string warehouse, DateTime start, DateTime end)
        {
            var _service = new Services.FinanceReportServices();
            var total = 0;
            var obj = _service.ListSkuPurchaseSellStock(parameter, sku, warehousetype, warehouse, start, end, ref total);
            var objCount = _service.ListWHPurchaseSellStockCount(warehousetype, warehouse, start, end,sku);

            var list = obj.Select(a => new {
                a.bailun_sku,
                a.sku_title_cn,
                a.warehouse_code,
                a.warehouse_name,
                start_onway_amount = a.start_onway_amount.ToString("N2"),
                start_onway_count = a.start_onway_count.ToString("N0"),
                start_stock_amount = a.start_stock_amount.ToString("N2"),
                start_stock_count = a.start_stock_count.ToString("N0"),

                end_onway_amount = a.end_onway_amount.ToString("N2"),
                end_onway_count = a.end_onway_count.ToString("N0"),
                end_stock_amount = a.end_stock_amount.ToString("N2"),
                end_stock_count = a.end_stock_count.ToString("N0"),

                diff_onway_amount = (a.end_onway_amount - a.start_onway_amount).ToString("N2"),
                diff_onway_count = (a.end_onway_count - a.start_onway_count).ToString("N0"),
                diff_stock_amount = (a.end_stock_amount - a.start_stock_amount).ToString("N2"),
                diff_stock_count = (a.end_stock_count - a.start_stock_count).ToString("N0"),

                count = a.count.ToString("N0"),
                amount = a.amount.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "总计",
                    start_onway_amount = objCount.start_onway_amount.ToString("N2"),
                    start_onway_count = objCount.start_onway_count.ToString("N0"),
                    start_stock_amount = objCount.start_stock_amount.ToString("N2"),
                    start_stock_count = objCount.start_stock_count.ToString("N0"),

                    end_onway_amount = objCount.end_onway_amount.ToString("N2"),
                    end_onway_count = objCount.end_onway_count.ToString("N0"),
                    end_stock_amount = objCount.end_stock_amount.ToString("N2"),
                    end_stock_count = objCount.end_stock_count.ToString("N0"),

                    diff_onway_amount = (objCount.end_onway_amount - objCount.start_onway_amount).ToString("N2"),
                    diff_onway_count = (objCount.end_onway_count - objCount.start_onway_count).ToString("N0"),
                    diff_stock_amount = (objCount.end_stock_amount - objCount.start_stock_amount).ToString("N2"),
                    diff_stock_count = (objCount.end_stock_count - objCount.start_stock_count).ToString("N0"),

                    count = objCount.count.ToString("N0"),
                    amount = objCount.amount.ToString("N2"),
                }
            });

        }

        #endregion

        #region 半成品仓

        /// <summary>
        /// 半成品仓库进销存报表
        /// </summary>
        /// <returns></returns>
        public ActionResult SemiWHPurchaseSellStock()
        {
            return View();
        }

        /// <summary>
        /// 半成品仓库进销存报表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="start">期初时间</param>
        /// <param name="end">期末时间</param>
        /// <returns></returns>
       [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【半成品仓库进销存报表】->【查询】页面", 0)]
        public string SemiWHPurchaseSellStockJson(BtTableParameter parameter, string warehousetype, string warehouse, DateTime start, DateTime end)
        {
            var total = 0;
            var _services = new Services.FinanceReportServices();
            var obj = _services.ListSemiWHPurchaseSellStock(parameter, warehousetype, warehouse, start, end, ref total);
            var objCount = _services.ListSemiWHPurchaseSellStockCount(warehousetype, warehouse, start, end);

            var list = obj.Select(a => new {
                a.warehouse_code,
                a.warehouse_name,
                start_onway_amount = a.start_onway_amount.ToString("N2"),
                start_onway_count = a.start_onway_count.ToString("N2"),
                start_stock_amount = a.start_stock_amount.ToString("N2"),
                start_stock_count = a.start_stock_count.ToString("N2"),

                end_onway_amount = a.end_onway_amount.ToString("N2"),
                end_onway_count = a.end_onway_count.ToString("N2"),
                end_stock_amount = a.end_stock_amount.ToString("N2"),
                end_stock_count = a.end_stock_count.ToString("N2"),

                diff_onway_amount = (a.end_onway_amount - a.start_onway_amount).ToString("N2"),
                diff_onway_count = (a.end_onway_count - a.start_onway_count).ToString("N2"),
                diff_stock_amount = (a.end_stock_amount - a.start_stock_amount).ToString("N2"),
                diff_stock_count = (a.end_stock_count - a.start_stock_count).ToString("N2"),

                count = a.count.ToString("N2"),
                amount = a.amount.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "总计",
                    start_onway_amount = objCount.start_onway_amount.ToString("N2"),
                    start_onway_count = objCount.start_onway_count.ToString("N2"),
                    start_stock_amount = objCount.start_stock_amount.ToString("N2"),
                    start_stock_count = objCount.start_stock_count.ToString("N2"),

                    end_onway_amount = objCount.end_onway_amount.ToString("N2"),
                    end_onway_count = objCount.end_onway_count.ToString("N2"),
                    end_stock_amount = objCount.end_stock_amount.ToString("N2"),
                    end_stock_count = objCount.end_stock_count.ToString("N2"),

                    diff_onway_amount = (objCount.end_onway_amount - objCount.start_onway_amount).ToString("N2"),
                    diff_onway_count = (objCount.end_onway_count - objCount.start_onway_count).ToString("N2"),
                    diff_stock_amount = (objCount.end_stock_amount - objCount.start_stock_amount).ToString("N2"),
                    diff_stock_count = (objCount.end_stock_count - objCount.start_stock_count).ToString("N2"),

                    count = objCount.count.ToString("N2"),
                    amount = objCount.amount.ToString("N2"),
                }
            });
        }

        /// <summary>
        /// 半成品 Sku进销存报表
        /// </summary>
        /// <returns></returns>
        public ActionResult SemiSkuPurchaseSellStock(string warehouse, DateTime? start, DateTime? end)
        {
            string warehousetype = "";
            if (!string.IsNullOrEmpty(warehouse))
            {
                var objWH = new Services.WareHouseServices().GetWarehouse(warehouse);
                if (objWH != null)
                {
                    warehousetype = objWH.hq_type;
                }
            }

            ViewBag.warehousetype = warehousetype;
            ViewBag.warehouse = warehouse;
            ViewBag.start = start.HasValue ? start.Value.ToString("yyyy-MM-dd") : DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
            ViewBag.end = end.HasValue ? end.Value.ToString("yyyy-MM-dd") : DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");


            return View();
        }

        /// <summary>
        /// 半成品 Sku进销存报表
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="start">期初日期</param>
        /// <param name="end">期末日期</param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【半成品SKU进销存】->【查询】页面", 0)]
        public string SemiSkuPurchaseSellStockJson(BtTableParameter parameter, string sku, string warehousetype, string warehouse, DateTime start, DateTime end)
        {
            var _service = new Services.FinanceReportServices();
            var total = 0;
            var obj = _service.ListSemiSkuPurchaseSellStock(parameter, sku, warehousetype, warehouse, start, end, ref total);
            var objCount = _service.ListSemiWHPurchaseSellStockCount(warehousetype, warehouse, start, end, sku);

            var list = obj.Select(a => new {
                a.bailun_sku,
                a.sku_title_cn,
                a.warehouse_code,
                a.warehouse_name,
                start_onway_amount = a.start_onway_amount.ToString("N2"),
                start_onway_count = a.start_onway_count.ToString("N2"),
                start_stock_amount = a.start_stock_amount.ToString("N2"),
                start_stock_count = a.start_stock_count.ToString("N2"),

                end_onway_amount = a.end_onway_amount.ToString("N2"),
                end_onway_count = a.end_onway_count.ToString("N2"),
                end_stock_amount = a.end_stock_amount.ToString("N2"),
                end_stock_count = a.end_stock_count.ToString("N2"),

                diff_onway_amount = (a.end_onway_amount - a.start_onway_amount).ToString("N2"),
                diff_onway_count = (a.end_onway_count - a.start_onway_count).ToString("N2"),
                diff_stock_amount = (a.end_stock_amount - a.start_stock_amount).ToString("N2"),
                diff_stock_count = (a.end_stock_count - a.start_stock_count).ToString("N2"),

                count = a.count.ToString("N2"),
                amount = a.amount.ToString("N2"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "总计",
                    start_onway_amount = objCount.start_onway_amount.ToString("N2"),
                    start_onway_count = objCount.start_onway_count.ToString("N2"),
                    start_stock_amount = objCount.start_stock_amount.ToString("N2"),
                    start_stock_count = objCount.start_stock_count.ToString("N2"),

                    end_onway_amount = objCount.end_onway_amount.ToString("N2"),
                    end_onway_count = objCount.end_onway_count.ToString("N2"),
                    end_stock_amount = objCount.end_stock_amount.ToString("N2"),
                    end_stock_count = objCount.end_stock_count.ToString("N2"),

                    diff_onway_amount = (objCount.end_onway_amount - objCount.start_onway_amount).ToString("N2"),
                    diff_onway_count = (objCount.end_onway_count - objCount.start_onway_count).ToString("N2"),
                    diff_stock_amount = (objCount.end_stock_amount - objCount.start_stock_amount).ToString("N2"),
                    diff_stock_count = (objCount.end_stock_count - objCount.start_stock_count).ToString("N2"),

                    count = objCount.count.ToString("N2"),
                    amount = objCount.amount.ToString("N2"),
                }
            });

        }


        #endregion


        #endregion

        #region 平台充值记录

        /// <summary>
        /// 速卖通充值记录
        /// </summary>
        /// <returns></returns>
        public ActionResult AliExpressCharge()
        {
            return View();
        }
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【分平台利润统计】->【AliExpress】->【速卖通充值记录】->【查询】页面", 0)]
        public string AliExpressChargeJson(BtTableParameter parameter, string account, DateTime? start, DateTime? end)
        {
            var total = 0;
            var _service = new Services.FinanceReportServices();

            var obj = _service.ListAliExpressCharge(parameter, account, start, end,ref total);
            var objCount = _service.ListAliExpressChargeCount(account, start, end);

            var list = obj.Select(a => new {
                a.accountname,
                amount = a.amount.ToString("N2"),
                record_time = a.record_time.ToString("yyyy-MM-dd"),
                createtime = a.createtime.ToString("yyyy-MM-dd HH:mm:ss"),
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    accountname = "总计",
                    amount = objCount.amount.ToString("N2")
                }
            });
        }

        /// <summary>
        /// 导入速卖通充值记录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [BrowseLog("Bailun_data", "触发【百伦数据中心】->【分平台利润统计】->【AliExpress】->【速卖通充值记录】->【导入】操作", 1)]
        public JsonResult UploadAliExpressCharge()
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();
                var list = new List<dc_base_finance_aliexpress_recharge>();
                var service = new Services.FinanceReportServices();
                var listRate = new List<Tuple<string, decimal>>();
                var commonServices = new Services.CommonServices();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    try
                    {
                        var account = row["帐号名称"].ToString();

                        if (string.IsNullOrEmpty(account))
                        {
                            continue;
                        }

                        var amount = decimal.Parse(row["充值金额"].ToString());
                        var day = DateTime.Parse(row["记录日期"].ToString());

                        if (string.IsNullOrEmpty(account))
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "帐号名称不能为空！",
                            });
                        }

                        if (amount<=0)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "充值金额必须大于0！"
                            });
                        }
                        

                        var objaccount = Services.CommonServices.GetCompanyAccount(account,1);
                        if (objaccount == null)
                        {
                            return Json(new
                            {
                                success = false,
                                msg = "系统找不到该帐号【" + objaccount + "】，请检测帐号名称是否正确。",
                            });
                        }

                        var m = new dc_base_finance_aliexpress_recharge {
                            accountid = objaccount.account_id,
                            accountname = objaccount.account_name,
                            amount = amount,
                            record_time = day,
                            createtime = DateTime.Now,
                            delstatus = 0
                        };
                        list.Add(m);
                    }
                    catch (Exception ex)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "导入失败，异常信息：" + ex.Message
                        });
                    }
                }

                if (list.Count == 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "表格没有数据。",
                    });

                }

                var result = service.SaveAliExpressCharge(list);
                return Json(new
                {
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }
            else
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件"
                });
            }
        }

        #endregion

        #region 每月销售利润统计报表

        /// <summary>
        /// 月度销售利润统计报表
        /// </summary>
        /// <returns></returns>
        public ActionResult MonthSaleProfit()
        {
            return View();
        }

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

            try
            {
                var obj = _service.ListMonthSaleProfit(month, "");
                var objDescription = _service.ListMonthSaleProfitDescription(month, "");


                var list = obj.Select(a => new
                {
                    amount_sale = a.amount_sale.ToString("N2"),
                    cost_sale = (a.cost_sale).ToString("N2"),
                    a.cost_sale_,
                    pt_count = a.pt_count.ToString("N2"), //(a.pt_platformfee+a.pt_ebay_postingfee+a.pt_paypal_fee+a.pt_platform_logistics_fee+a.pt_platform_ad_subscribe_fee + a.pt_platform_storage_fee+a.pt_refund_amount).ToString("N2"),
                    pt_platformfee = a.pt_platformfee.ToString("N2"),
                    pt_ebay_postingfee = a.pt_ebay_postingfee.ToString("N2"),
                    pt_paypal_fee = a.pt_paypal_fee.ToString("N2"),
                    pt_platform_logistics_fee = (a.pt_platform_logistics_fee).ToString("N2"),
                    a.pt_platform_logistics_fee_,
                    pt_platform_ad_subscribe_fee = (a.pt_platform_ad_subscribe_fee).ToString("N2"),
                    a.pt_platform_ad_subscribe_fee_,
                    pt_platform_storage_fee = a.pt_platform_storage_fee.ToString("N2"),
                    pt_refund_amount = a.pt_refund_amount.ToString("N2"),
                    pt_incoming = a.pt_incoming.ToString("N2"),


                    ls_count = a.ls_count.ToString("N2"),
                    ls_head_cost = (a.ls_head_cost).ToString("N2"),
                    a.ls_head_cost_,
                    ls_tail_cost = (a.ls_tail_cost).ToString("N2"),
                    a.ls_tail_cost_,
                    ls_oversea_storage = a.ls_oversea_storage.ToString("N2"),
                    ls_platform_operation_fee = a.ls_platform_operation_fee.ToString("N2"),


                    sale_fee_count = a.sale_fee_count.ToString("N2"),
                    sale_profit = a.sale_profit.ToString("N2"),
                    sale_profit_rate = (a.sale_profit_rate*100).ToString("N2")+"%",
                    sale_manager_cost = a.sale_manager_cost.ToString("N2"),
                    handlingcharges = a.handlingcharges.ToString("N2"),
                    payfor_platform_related_fee = a.payfor_platform_related_fee.ToString("N2"),
                    direct_manager_cost = a.direct_manager_cost.ToString("N2"),
                    manager_cost_hkbailun = a.manager_cost_hkbailun.ToString("N2"),
                    manager_cost_gzbailun = a.manager_cost_gzbailun.ToString("N2"),
                    manager_cost_meijiadian = a.manager_cost_meijiadian.ToString("N2"),
                    manager_cost_finish_wh = a.manager_cost_finish_wh.ToString("N2"),
                    manager_cost_yangshan = a.manager_cost_yangshan.ToString("N2"),
                    manager_cost_xinhuilan = a.manager_cost_xinhuilan.ToString("N2"),

                    finance_fee = a.finance_fee.ToString("N2"),
                    manager_cost_count = a.manager_cost_count.ToString("N2"),
                    business_profit = a.business_profit.ToString("N2"),
                    business_profit_rate = (a.business_profit_rate*100).ToString("N2")+"%",
                    other_incoming = a.other_incoming.ToString("N2"),


                    nonbusiness_income = a.nonbusiness_income.ToString("N2"),
                    nonbusiness_pay = a.nonbusiness_pay.ToString("N2"),
                    actual_profit = a.actual_profit.ToString("N2"),
                    participation_in_profit = a.participation_in_profit.ToString("N2"),
                    balance_of_profit = a.balance_of_profit.ToString("N2"),
                    
                    a.month
                });

                var head = new List<Tuple<string, string,string,string,string>>(); //字段名，项目名，编辑字段格式，基础数据，调整数据
                head.Add(new Tuple<string, string, string, string, string>("amount_sale", "<td style=\"font-weight:bold;text-align:center;\">销售额</td>", "<span class=\"lbl_amount_sale\">{amount_sale+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{amount_sale_desc}\" />", "{amount_sale}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("cost_sale", "<td style=\"font-weight:bold;text-align:center;\">成本</td>", "<span class=\"lbl_cost_sale\">{cost_sale+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{cost_sale_desc}\" /><a class=\"cost_sale_\" onclick=\"Edit('cost_sale_','成本','{month}','{cost_sale_}')\">编辑</a>", "{cost_sale-cost_sale_}", "{cost_sale_}"));
                head.Add(new Tuple<string, string, string, string, string>("pt_count", "<td style=\"font-weight:bold;text-align:center;\">平台扣费及退款</td>", "<span class=\"lbl_pt_count\">{pt_count+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_count_desc}\" />", "{pt_count}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("pt_platformfee", "<td>平台费</td>", "<span class=\"lbl_pt_platformfee\">{pt_platformfee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_platformfee_desc}\" />", "{pt_platformfee}","0"));
                head.Add(new Tuple<string, string, string, string, string>("pt_ebay_postingfee", "<td>ebay刊登费</td>", "<span class=\"lbl_pt_ebay_postingfee\">{pt_ebay_postingfee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_ebay_postingfee_desc}\" />", "{pt_ebay_postingfee}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("pt_paypal_fee", "<td>paypal费用</td>", "<span class=\"lbl_pt_paypal_fee\">{pt_paypal_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_paypal_fee_desc}\" />", "{pt_paypal_fee}","0"));
                head.Add(new Tuple<string, string, string, string, string>("pt_platform_logistics_fee", "<td>平台的物流费</td>", "<span class=\"lbl_pt_platform_logistics_fee\">{pt_platform_logistics_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_platform_logistics_fee_desc}\" /><a class=\"pt_platform_logistics_fee_\" onclick=\"Edit('pt_platform_logistics_fee_','平台的物流费','{month}','{pt_platform_logistics_fee_}')\" val=\"\">编辑</a>", "{pt_platform_logistics_fee-pt_platform_logistics_fee_}", "{pt_platform_logistics_fee_}"));
                head.Add(new Tuple<string, string, string, string, string>("pt_platform_ad_subscribe_fee", "<td>广告及宣传费-订阅费</td>", "<span class=\"lbl_pt_platform_ad_subscribe_fee\">{pt_platform_ad_subscribe_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_platform_ad_subscribe_fee_desc}\" /><a class=\"pt_platform_ad_subscribe_fee_\" onclick=\"Edit('pt_platform_ad_subscribe_fee_','广告及宣传费-订阅费','{month}','{pt_platform_ad_subscribe_fee_}')\" val=\"\">编辑</a>", "{pt_platform_ad_subscribe_fee-pt_platform_ad_subscribe_fee_}", "{pt_platform_ad_subscribe_fee_}"));
                head.Add(new Tuple<string, string, string, string, string>("pt_platform_storage_fee", "<td>平台的仓储费</td>", "<span class=\"lbl_pt_platform_storage_fee\">{pt_platform_storage_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_platform_storage_fee_desc}\" /><a class=\"pt_platform_storage_fee\" onclick=\"Edit('pt_platform_storage_fee','平台的仓储费','{month}','{pt_platform_storage_fee}')\" val=\"\">编辑</a>", "0", "{pt_platform_storage_fee}"));
                head.Add(new Tuple<string, string, string, string, string>("pt_refund_amount", "<td>退款</td>", "<span class=\"lbl_pt_refund_amount\">{pt_refund_amount+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_refund_amount_desc}\" />", "{pt_refund_amount}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("pt_incoming", "<td style=\"font-weight:bold;\">回款</td>", "<span class=\"lbl_pt_incoming\">{pt_incoming+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{pt_incoming_desc}\" />", "{pt_incoming}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("ls_count", "<td style=\"font-weight:bold;text-align:center;\">物流仓储费用</td>", "<span class=\"lbl_ls_count\">{ls_count+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{ls_count_desc}\" />", "{ls_count}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("ls_head_cost", "<td>头程运输</td>", "<span class=\"lbl_ls_head_cost\">{ls_head_cost+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{ls_head_cost_desc}\" /><a class=\"ls_head_cost_\" onclick=\"Edit('ls_head_cost_','头程运输','{month}','{ls_head_cost_}')\" val=\"\">编辑</a>", "{ls_head_cost-ls_head_cost_}", "{ls_head_cost_}"));
                head.Add(new Tuple<string, string, string, string, string>("ls_tail_cost", "<td>尾程物流</td>", "<span class=\"lbl_ls_tail_cost\">{ls_tail_cost+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{ls_tail_cost_desc}\" /><a class=\"ls_tail_cost_\" onclick=\"Edit('ls_tail_cost_','尾程物流','{month}','{ls_tail_cost_}')\" val =\"\">编辑</a>", "{ls_tail_cost-ls_tail_cost_}", "{ls_tail_cost_}"));
                head.Add(new Tuple<string, string, string, string, string>("ls_oversea_storage", "<td>海外仓的仓储费</td>", "<span class=\"lbl_ls_oversea_storage\">{ls_oversea_storage+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{ls_oversea_storage_desc}\" /><a class=\"ls_oversea_storage\" onclick=\"Edit('ls_oversea_storage','海外仓的仓储费','{month}','{ls_oversea_storage}')\" val=\"\">编辑</a>", "0", "{ls_oversea_storage}"));
                head.Add(new Tuple<string, string, string, string, string>("ls_platform_operation_fee", "<td>平台操作费</td>", "<span class=\"lbl_ls_platform_operation_fee\">{ls_platform_operation_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{ls_platform_operation_fee_desc}\" />", "{ls_platform_operation_fee}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("sale_fee_count", "<td style=\"font-weight:bold;text-align:center;\">销售费用合计</td>", "<span class=\"lbl_sale_fee_count\">{sale_fee_count+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{sale_fee_count_desc}\" />", "{sale_fee_count}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("sale_profit", "<td style=\"font-weight:bold;text-align:center;\">销售利润</td>", "<span class=\"lbl_sale_profit\">{sale_profit+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{sale_profit_desc}\" />", "{sale_profit}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("sale_profit_rate", "<td style=\"font-weight:bold;text-align:center;\">销售毛利率</td>", "<span class=\"lbl_sale_profit_rate\">{sale_profit_rate+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{sale_profit_rate_desc}\" />", "{sale_profit_rate}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("sale_manager_cost", "<td style=\"font-weight:bold;text-align:center;\">销售相关的管理成本</td>", "<span class=\"lbl_sale_manager_cost\">{sale_manager_cost+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{sale_manager_cost_desc}\" />", "{sale_manager_cost}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("handlingcharges", "<td>处理费</td>", "<span class=\"lbl_handlingcharges\">{handlingcharges+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{handlingcharges_desc}\" /><a class=\"handlingcharges\" onclick=\"Edit('handlingcharges','处理费','{month}','{handlingcharges}')\" val=\"\">编辑</a>", "0", "{handlingcharges}"));
                head.Add(new Tuple<string, string, string, string, string>("payfor_platform_related_fee", "<td>直接支付的与销售平台相关费用</td>", "<span class=\"lbl_payfor_platform_related_fee\">{payfor_platform_related_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{payfor_platform_related_fee_desc}\" /><a class=\"payfor_platform_related_fee\" onclick=\"Edit('payfor_platform_related_fee','直接支付的与销售平台相关费用','{month}','{payfor_platform_related_fee}')\" val=\"\">编辑</a>", "0", "{payfor_platform_related_fee}"));
                head.Add(new Tuple<string, string, string, string, string>("direct_manager_cost", "<td style=\"font-weight:bold;text-align:center;\">直接管理成本</td>", "<span class=\"lbl_direct_manager_cost\">{direct_manager_cost+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{direct_manager_cost_desc}\" />", "{direct_manager_cost}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("manager_cost_hkbailun", "<td>管理成本-香港百伦（不含直接支付的与销售平台相关的费用）</td>", "<span class=\"lbl_manager_cost_hkbailun\">{manager_cost_hkbailun+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_hkbailun_desc}\" /><a class=\"manager_cost_hkbailun\" onclick=\"Edit('manager_cost_hkbailun','管理成本-香港百伦（不含直接支付的与销售平台相关的费用）','{month}','{manager_cost_hkbailun}')\" val=\"\">编辑</a>", "0", "{manager_cost_hkbailun}"));
                head.Add(new Tuple<string, string, string, string, string>("manager_cost_gzbailun", "<td>管理成本-广州百伦</td>", "<span class=\"lbl_manager_cost_gzbailun\">{manager_cost_gzbailun+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_gzbailun_desc}\" /><a class=\"manager_cost_gzbailun\" onclick=\"Edit('manager_cost_gzbailun','管理成本-广州百伦','{month}','{manager_cost_gzbailun}')\" val=\"\">编辑</a>", "0", "{manager_cost_gzbailun}"));
                head.Add(new Tuple<string, string, string, string, string>("manager_cost_meijiadian", "<td>管理成本-美甲店</td>", "<span class=\"lbl_manager_cost_meijiadian\">{manager_cost_meijiadian+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_meijiadian_desc}\" /><a class=\"manager_cost_meijiadian\" onclick=\"Edit('manager_cost_meijiadian','管理成本-美甲店','{month}','{manager_cost_meijiadian}')\" val=\"\">编辑</a>", "0", "{manager_cost_meijiadian}"));
                head.Add(new Tuple<string, string, string, string, string>("manager_cost_yangshan", "<td>管理成本-杨杉</td>", "<span class=\"lbl_manager_cost_yangshan\">{manager_cost_yangshan+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_yangshan_desc}\" /><a class=\"manager_cost_yangshan\" onclick=\"Edit('manager_cost_yangshan','管理成本-杨杉','{month}','{manager_cost_yangshan}')\" val=\"\">编辑</a>", "0", "{manager_cost_yangshan}"));
                head.Add(new Tuple<string, string, string, string, string>("manager_cost_xinhuilan", "<td>管理成本-信荟蓝</td>", "<span class=\"lbl_manager_cost_xinhuilan\">{manager_cost_xinhuilan+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_xinhuilan_desc}\" /><a class=\"manager_cost_xinhuilan\" onclick=\"Edit('manager_cost_xinhuilan','管理成本-信荟蓝','{month}','{manager_cost_xinhuilan}')\" val=\"\">编辑</a>", "0", "{manager_cost_xinhuilan}"));


                head.Add(new Tuple<string, string, string, string, string>("manager_cost_finish_wh", "<td>管理成本-成品仓（不含直接支付的与销售平台相关的费用）</td>", "<span class=\"lbl_manager_cost_finish_wh\">{manager_cost_finish_wh+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_finish_wh_desc}\" /><a class=\"manager_cost_finish_wh\" onclick=\"Edit('manager_cost_finish_wh','管理成本-成品仓（不含直接支付的与销售平台相关的费用）','{month}','{manager_cost_finish_wh}')\" val=\"\">编辑</a>", "0", "{manager_cost_finish_wh}"));
                head.Add(new Tuple<string, string, string, string, string>("finance_fee", "<td>财务费用</td>", "<span class=\"lbl_finance_fee\">{finance_fee+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{finance_fee_desc}\" /><a class=\"finance_fee\" onclick=\"Edit('finance_fee','财务费用','{month}','{finance_fee}')\" val=\"\">编辑</a>", "0", "{finance_fee}"));
                head.Add(new Tuple<string, string, string, string, string>("manager_cost_count", "<td style=\"font-weight:bold;text-align:center;\">管理成本合计</td>", "<span class=\"lbl_manager_cost_count\">{manager_cost_count+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{manager_cost_count_desc}\" />", "{manager_cost_count}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("business_profit", "<td style=\"font-weight:bold;text-align:center;\">营业利润</td>", "<span class=\"lbl_business_profit\">{business_profit+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{business_profit_desc}\" />", "{business_profit}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("business_profit_rate", "<td style=\"font-weight:bold;text-align:center;\">营业毛利率</td>", "<span class=\"lbl_business_profit_rate\">{business_profit_rate+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{business_profit_rate_desc}\" />", "{business_profit_rate}", "0"));
                head.Add(new Tuple<string, string, string, string, string>("other_incoming", "<td>加：其他收入</td>", "<span class=\"lbl_other_incoming\">{other_incoming+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{other_incoming_desc}\" /><a class=\"other_incoming\" onclick=\"Edit('other_incoming','加：其他收入','{month}','{other_incoming}')\" val=\"\">编辑</a>", "0", "{other_incoming}"));
                head.Add(new Tuple<string, string, string, string, string>("nonbusiness_income", "<td>加：营业外收入</td>", "<span class=\"lbl_nonbusiness_income\">{nonbusiness_income+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{nonbusiness_income_desc}\" /><a class=\"nonbusiness_income\" onclick=\"Edit('nonbusiness_income','加：营业外收入','{month}','{nonbusiness_income}')\" val=\"\">编辑</a>", "0", "{nonbusiness_income}"));
                head.Add(new Tuple<string, string, string, string, string>("nonbusiness_pay", "<td>减：营业外支出</td>", "<span class=\"lbl_nonbusiness_pay\">{nonbusiness_pay+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{nonbusiness_pay_desc}\" /><a class=\"nonbusiness_pay\" onclick=\"Edit('nonbusiness_pay','减：营业外支出','{month}','{nonbusiness_pay}')\" val=\"\">编辑</a>", "0", "{nonbusiness_pay}"));
                head.Add(new Tuple<string, string, string, string, string>("actual_profit", "<td style=\"font-weight:bold;text-align:center;\">实际利润</td>", "<span class=\"lbl_actual_profit\">{actual_profit+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{actual_profit_desc}\" />", "{actual_profit}","0"));
                head.Add(new Tuple<string, string, string, string, string>("participation_in_profit", "<td>减：分红</td>", "<span class=\"lbl_participation_in_profit\">{participation_in_profit+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{participation_in_profit_desc}\" /><a class=\"participation_in_profit\" onclick=\"Edit('participation_in_profit','减：营业外支出','{month}','{participation_in_profit}')\" val=\"\">编辑</a>", "0", "{participation_in_profit}"));
                head.Add(new Tuple<string, string, string, string, string>("balance_of_profit", "<td style=\"font-weight:bold;text-align:center;\">利润结余</td>", "<span class=\"lbl_balance_of_profit\">{balance_of_profit+}</span><img src=\"/img/icon-quetion.png\" style=\"width:18px;margin-left:3px\" title=\"{balance_of_profit_desc}\" />", "{balance_of_profit}","0"));

                return Json(new {
                    success = true,
                    msg = "",
                    data = list,
                    head = head,
                    listdesc = objDescription
                });
            }
            catch (Exception ex) 
            {
                return Json(new {
                    success = false,
                    msg = "出现异常，异常信息："+ex.Message
                });                
            }
        }

        /// <summary>
        /// 更新月度销售利润报表
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult SaveMonthSaleProfit(mMonthSaleProfit_Input m)
        {
            var user = HttpContextHelper.Current?.User;

            var _service = new Services.FinanceReportServices();

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

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

        /// <summary>
        /// 更新月度销售利润报表的取数描述
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult UpdateMonthSaleProfitDescription(mMonthSaleProfitDesc_Input m)
        {
            var user = HttpContextHelper.Current?.User;
            var obj = new Services.FinanceReportServices().SaveMonthSaleProfitDescription(m, user != null ? user.GetUid() : 0, user != null ? user.GetUserName() : "");

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

        /// <summary>
        /// 月销售利润明细
        /// </summary>
        /// <returns></returns>
        public ActionResult MonthSaleProfitDetails(string month,string col,string colname,int? isnew)
        {

            ViewBag.month = month;
            ViewBag.col = col;
            ViewBag.colname = colname;
            ViewBag.isnew = (isnew ?? 0);

            return View();
        }

        /// <summary>
        /// 月销售利润明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="month">月份</param>
        /// <param name="col">列名</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string ListMonthSaleProfitDetailJson(BtTableParameter parameter, string month, string col,int? isnew)
        {
            var user = HttpContextHelper.Current?.User;
            var total = 0;
            var _service = new Services.FinanceReportServices();

            var obj = _service.ListMonthSaleProfitDetail(parameter, month, col, ref total,(isnew??0));
            var objCount = _service.ListMonthSaleProfitDetailCount(month, col, (isnew ?? 0));

            var list = obj.Select(a => new {
                a.id,
                a.month,
                a.colname,
                a.type,
                amount = a.amount.ToString("N2"),
                a.note_one,
                a.note_two,
                createtime = a.createtime.ToString("yyyy-MM-dd HH:mm:ss")
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    type = "总计",
                    amount = objCount.amount.ToString("N2"),
                },
                userid = user!=null?user.GetUid():0,
                username = user!=null?user.GetUserName():"",
            });

        }

        /// <summary>
        /// 上传月销售利润明细
        /// </summary>
        /// <param name="month"></param>
        /// <param name="col"></param>
        /// <param name="colname"></param>
        /// <param name="uid"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public JsonResult UploadMonthSaleProfitDetail(string month,string col,string colname,int uid,string username, int? isnew)
        {
            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件！"
                });
            }

            var file = Request.Form.Files[0];
            Dictionary<string, DataTable> dic = Base.NpolHelper.ExcelToDataTable(file.OpenReadStream(), file.FileName, true);
            if (dic.Count > 0)
            {
                var tb = dic.FirstOrDefault();
                var list = new List<dc_month_sale_profit_details>();
                var service = new Services.FinanceReportServices();

                for (var i = 0; i < tb.Value.Rows.Count; i++)
                {
                    var row = tb.Value.Rows[i];

                    try
                    {
                        var type = row["类型"].ToString();
                        var amount = row["金额"].ToString();
                        var note_one = row["备注1"].ToString();
                        var note_two = row["备注2"].ToString();

                        if (type != "" && amount != "")
                        {
                            list.Add(new dc_month_sale_profit_details
                            {
                                type = type,
                                amount = decimal.Parse(amount),
                                note_one = note_one,
                                note_two = note_two,

                                month = month,
                                colval = col,
                                colname = colname,
                                isnew = (isnew??0)
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        return Json(new
                        {
                            success = false,
                            msg = "导入失败，第"+(i+1)+"行报错，异常信息：" + ex.Message
                        });
                    }
                }

                if (list.Count == 0)
                {
                    return Json(new
                    {
                        success = false,
                        msg = "表格没有数据。",
                    });

                }

                var result = service.SaveMonthSaleProfitDetail(list, uid,username);
                return Json(new
                {
                    success = string.IsNullOrEmpty(result),
                    msg = result
                });
            }
            else
            {
                return Json(new
                {
                    success = false,
                    msg = "请上传文件"
                });
            }
        }

        /// <summary>
        /// 删除月销售利润明细
        /// </summary>
        /// <param name="id">明细id</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult DelMonthSaleProfitDetail(int id)
        {
            var user = HttpContextHelper.Current?.User;
            
            var result = new Services.FinanceReportServices().DelMonthSaleProfitDetail(id, user != null ? user.GetUid() : 0, user != null ? user.GetUserName() : "");

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

        /// <summary>
        /// 删除月销售利润明细
        /// </summary>
        /// <param name="id">明细id</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult DelMonthSaleProfitDetailBatch(string ids)
        {
            var user = HttpContextHelper.Current?.User;

            var listId = ids.Split(',').Where(a => !string.IsNullOrEmpty(a)).Select(b=>int.Parse(b)).ToList();
            if (listId.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    msg = "请至少选择一个项进行删除"
                });
            }

            var result = new Services.FinanceReportServices().DelMonthSaleProfitDetailBatch(listId, user != null ? user.GetUid() : 0, user != null ? user.GetUserName() : "");

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

        #region 新表

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

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

            try
            {
                var obj = _service.ListMonthSaleProfitNew(month, "");
                var objDescription = _service.ListMonthSaleProfitNewDescription(month, "");
                

                var list = obj.Select(a => new
                {
                    amount_sales = a.amount_sales.ToString("N2"),
                    amount_sales_dianzi = a.amount_sales_dianzi.ToString("N2"),
                    amount_sales_fuzhuang = a.amount_sales_fuzhuang.ToString("N2"),
                    amount_sales_jiaju = a.amount_sales_jiaju.ToString("N2"),
                    amount_sales_jingyou = a.amount_sales_jingyou.ToString("N2"),
                    amount_sales_meirongmj = a.amount_sales_meirongmj.ToString("N2"),
                    amount_sales_other = a.amount_sales_other.ToString("N2"),

                    amount_withdraw = a.amount_withdraw.ToString("N2"),

                    cost = a.cost.ToString("N2"),
                    cost_dianzi = a.cost_dianzi.ToString("N2"),
                    cost_fuzhuang = a.cost_fuzhuang.ToString("N2"),
                    cost_jiaju = a.cost_jiaju.ToString("N2"),
                    cost_jingyou = a.cost_jingyou.ToString("N2"),
                    cost_meirongmj = a.cost_meirongmj.ToString("N2"),
                    cost_other = a.cost_other.ToString("N2"),

                    fee_fba = a.fee_fba.ToString("N2"),
                    fee_ad = a.fee_ad.ToString("N2"),
                    fee_finance = a.fee_finance.ToString("N2"),
                    fee_logistics_direct = a.fee_logistics_direct.ToString("N2"),
                    fee_logistics_first = a.fee_logistics_first.ToString("N2"),
                    fee_logistics_tail = a.fee_logistics_tail.ToString("N2"),
                    fee_logistics_storage = a.fee_logistics_storage.ToString("N2"),
                    fee_paycash_sales= a.fee_paycash_sales.ToString("N2"),
                    fee_platform = a.fee_platform.ToString("N2"),
                    fee_platform_and_refund = a.fee_platform_and_refund.ToString("N2"),
                    fee_refund = a.fee_refund.ToString("N2"),
                    fee_sales_count = a.fee_sales_count.ToString("N2"),
                    fee_storage = a.fee_storage.ToString("N2"),
                    fee_storage_incidentals = a.fee_storage_incidentals.ToString("N2"),

                    incoming_non_operating = a.incoming_non_operating.ToString("N2"),
                    incoming_other = a.incoming_other.ToString("N2"),
                    incoming_refundtax = a.incoming_refundtax.ToString("N2"),
                    incoming_gogirl = a.incoming_gogirl.ToString("N2"),
                    a.isedit,

                    managecost_bl_gz = a.managecost_bl_gz.ToString("N2"),
                    managecost_bl_xg = a.managecost_bl_xg.ToString("N2"),
                    managecost_meijia = a.managecost_meijia.ToString("N2"),
                    managercost_chengpincang = a.managercost_chengpincang.ToString("N2"),
                    managercost_count = a.managercost_count.ToString("N2"),
                    managercost_xinhuilan = a.managercost_xinhuilan.ToString("N2"),
                    managercost_yangshan = a.managercost_yangshan.ToString("N2"),
                    managercost_dizhi = a.managercost_dizhi.ToString("N2"),
                    managercost_meijiashengchan = a.managercost_meijiashengchan.ToString("N2"),

                    pay_non_operating = a.pay_non_operating.ToString("N2"),
                    profit = a.profit.ToString("N2"),
                    profit_balance = a.profit_balance.ToString("N2"),
                    profit_sales = a.profit_sales.ToString("N2"),
                    rate_profit = (a.rate_profit*100).ToString("N2"),
                    rate_profit_actual = (a.rate_profit_actual*100).ToString("N2"),
                    rate_profit_sales = (a.rate_profit_sales*100).ToString("N2"),

                    actual_profit = a.actual_profit.ToString("N2"), 
                    dividend = a.dividend.ToString("N2"),

                    impairment_assets = (a.impairment_assets??0).ToString("N2"),

                    a.month
                });

                var listHead = new List<Tuple<string, string,int>>();
                listHead.Add(new Tuple<string, string,int>("销售额", "amount_sales", 1));
                listHead.Add(new Tuple<string, string, int>("精油产品", "amount_sales_jingyou", 0));
                listHead.Add(new Tuple<string, string, int>("电子产品", "amount_sales_dianzi", 0));
                listHead.Add(new Tuple<string, string, int>("家居产品", "amount_sales_jiaju", 0));
                listHead.Add(new Tuple<string, string, int>("美容美甲产品", "amount_sales_meirongmj", 0));
                listHead.Add(new Tuple<string, string, int>("服装", "amount_sales_fuzhuang", 0));
                listHead.Add(new Tuple<string, string, int>("其他", "amount_sales_other", 0));
                listHead.Add(new Tuple<string, string, int>("退款", "fee_refund", 0));

                listHead.Add(new Tuple<string, string, int>("成本", "cost", 1));
                listHead.Add(new Tuple<string, string, int>("精油产品", "cost_jingyou", 0));
                listHead.Add(new Tuple<string, string, int>("电子产品", "cost_dianzi", 0));
                listHead.Add(new Tuple<string, string, int>("家居产品", "cost_jiaju", 0));
                listHead.Add(new Tuple<string, string, int>("美容美甲产品", "cost_meirongmj", 0));
                listHead.Add(new Tuple<string, string, int>("服装", "cost_fuzhuang", 0));
                listHead.Add(new Tuple<string, string, int>("其他", "cost_other", 0));


                listHead.Add(new Tuple<string, string, int>("平台费用", "fee_platform_and_refund", 1));
                listHead.Add(new Tuple<string, string, int>("平台费", "fee_platform", 0));
                listHead.Add(new Tuple<string, string, int>("FBA费", "fee_fba", 0));
                listHead.Add(new Tuple<string, string, int>("广告及宣传费", "fee_ad", 0));
                //listHead.Add(new Tuple<string, string, int>("平台提现回款", "amount_withdraw", 0));


                listHead.Add(new Tuple<string, string, int>("物流仓储费用", "fee_logistics_storage", 1));
                listHead.Add(new Tuple<string, string, int>("头程运输", "fee_logistics_first", 0));
                listHead.Add(new Tuple<string, string, int>("直邮物流费", "fee_logistics_direct", 0));
                listHead.Add(new Tuple<string, string, int>("尾程物流费", "fee_logistics_tail", 0));
                listHead.Add(new Tuple<string, string, int>("海外仓仓储费", "fee_storage", 0));
                listHead.Add(new Tuple<string, string, int>("海外仓其他杂费", "fee_storage_incidentals", 0)); 
                listHead.Add(new Tuple<string, string, int>("付现销售费用", "fee_paycash_sales", 0));
                 
                listHead.Add(new Tuple<string, string, int>("销售费用合计", "fee_sales_count", 1));
                listHead.Add(new Tuple<string, string, int>("销售利润", "profit_sales", 0));
                listHead.Add(new Tuple<string, string, int>("销售毛利率", "rate_profit_sales", 0));

                listHead.Add(new Tuple<string, string, int>("财务费用", "fee_finance", 0));
                listHead.Add(new Tuple<string, string, int>("管理成本合计", "managercost_count", 1));
                //listHead.Add(new Tuple<string, string, int>("香港百伦科技有限公司", "managecost_bl_xg", 0));
                listHead.Add(new Tuple<string, string, int>("广州百伦供应链科技有限公司", "managecost_bl_gz", 0));
                listHead.Add(new Tuple<string, string, int>("广州歌戈儿生活科技有限公司", "managecost_meijia", 0));
                listHead.Add(new Tuple<string, string, int>("深圳前海扬杉创新科技有限公司", "managercost_yangshan", 0));
                listHead.Add(new Tuple<string, string, int>("广州信荟蓝科技有限公司", "managercost_xinhuilan", 0));
                listHead.Add(new Tuple<string, string, int>("广州电子服装仓&阳山", "managercost_chengpincang", 0));
                listHead.Add(new Tuple<string, string, int>("广州迪致美容科技有限公司", "managercost_dizhi", 0));
                //listHead.Add(new Tuple<string, string, int>("广州美甲生产仓", "managercost_meijiashengchan", 0));

                
                
                listHead.Add(new Tuple<string, string, int>("营业利润", "profit", 1));
                listHead.Add(new Tuple<string, string, int>("营业毛利率", "rate_profit", 0));
                listHead.Add(new Tuple<string, string, int>("加：其他收入", "incoming_other", 0));
                listHead.Add(new Tuple<string, string, int>("其中：出口退税收入", "incoming_refundtax", 0));
                listHead.Add(new Tuple<string, string, int>("其中：歌戈儿收入", "incoming_gogirl", 0));
                listHead.Add(new Tuple<string, string, int>("加：营业外收入", "incoming_non_operating", 0));
                listHead.Add(new Tuple<string, string, int>("减：营业外支出", "pay_non_operating", 0));
                listHead.Add(new Tuple<string, string, int>("减：资产减值损失", "impairment_assets", 0));
                listHead.Add(new Tuple<string, string, int>("实际利润", "actual_profit", 1));
                //listHead.Add(new Tuple<string, string, int>("减：分红", "dividend", 0));
                //listHead.Add(new Tuple<string, string, int>("利润结余", "profit_balance", 0));
                listHead.Add(new Tuple<string, string, int>("净利率", "rate_profit_actual", 1));

                var listCount = new List<dc_month_sales_profit>();
                var listMonth = obj.GroupBy(a => a.month);
                foreach(var item in listMonth)
                {
                    var m = new dc_month_sales_profit();
                    m.amount_sales = item?.Sum(a => a.amount_sales)??0;
                    m.amount_sales_dianzi = item?.Sum(a => a.amount_sales_dianzi) ?? 0;
                    m.amount_sales_fuzhuang = item.Sum(a => a.amount_sales_fuzhuang);
                    m.amount_sales_jiaju = item.Sum(a => a.amount_sales_jiaju);
                    m.amount_sales_jingyou = item.Sum(a => a.amount_sales_jingyou);
                    m.amount_sales_meirongmj = item.Sum(a => a.amount_sales_meirongmj);
                    m.amount_sales_other = item.Sum(a => a.amount_sales_other);
                    m.amount_withdraw = item.Sum(a => a.amount_withdraw);


                    m.cost = item.Sum(a => a.cost);
                    m.cost_dianzi = item.Sum(a => a.cost_dianzi);
                    m.cost_fuzhuang = item.Sum(a => a.cost_fuzhuang);
                    m.cost_jiaju = item.Sum(a => a.cost_jiaju);
                    m.cost_jingyou = item.Sum(a => a.cost_jingyou);
                    m.cost_meirongmj = item.Sum(a => a.cost_meirongmj);
                    m.cost_other = item.Sum(a => a.cost_other);


                    m.dividend = item.Sum(a => a.dividend);
                    m.fee_fba = item.Sum(a => a.fee_fba);
                    m.fee_ad = item.Sum(a => a.fee_ad);
                    m.fee_finance = item.Sum(a => a.fee_finance);
                    m.fee_logistics_direct = item.Sum(a => a.fee_logistics_direct);
                    m.fee_logistics_first = item.Sum(a => a.fee_logistics_first);
                    m.fee_logistics_tail = item.Sum(a => a.fee_logistics_tail);
                    m.fee_logistics_storage = item.Sum(a => a.fee_logistics_storage);
                    m.fee_paycash_sales = item.Sum(a => a.fee_paycash_sales);
                    m.fee_platform = item.Sum(a => a.fee_platform);
                    m.fee_platform_and_refund = item.Sum(a => a.fee_platform_and_refund);
                    m.fee_refund = item.Sum(a => a.fee_refund);
                    m.fee_sales_count = item.Sum(a => a.fee_sales_count);
                    m.fee_storage = item.Sum(a => a.fee_storage);
                    m.fee_storage_incidentals = item.Sum(a => a.fee_storage_incidentals);

                    m.incoming_non_operating = item.Sum(a => a.incoming_non_operating);
                    m.incoming_other = item.Sum(a => a.incoming_other);
                    m.incoming_refundtax = item.Sum(a => a.incoming_refundtax);
                    m.incoming_gogirl = item.Sum(a => a.incoming_gogirl);
                    m.isedit = 2; //合并的
                    m.managecost_bl_gz = item.Sum(a => a.managecost_bl_gz);
                    m.managecost_bl_xg = item.Sum(a => a.managecost_bl_xg);
                    m.managecost_meijia = item.Sum(a => a.managecost_meijia);
                    m.managercost_chengpincang = item.Sum(a => a.managercost_chengpincang);
                    m.managercost_count = item.Sum(a => a.managercost_count);
                    m.managercost_xinhuilan = item.Sum(a => a.managercost_xinhuilan);
                    m.managercost_yangshan = item.Sum(a => a.managercost_yangshan);
                    m.managercost_dizhi = item.Sum(a => a.managercost_dizhi);
                    m.managercost_meijiashengchan = item.Sum(a => a.managercost_meijiashengchan);
                    m.month = item.Key;

                    m.pay_non_operating = item.Sum(a => a.pay_non_operating);

                    m.impairment_assets = item.Sum(a => (a.impairment_assets??0));

                    //销售额=家居用品类+服装类+电子产品类+精油类+美容美甲类+其他-平台退款
                    m.amount_sales = m.amount_sales_dianzi + m.amount_sales_fuzhuang + m.amount_sales_jiaju + m.amount_sales_jingyou + m.amount_sales_meirongmj + m.amount_sales_other-m.fee_refund;

                    //产品成本=家居用品类+服装类+电子产品类+精油类+美容美甲类+其他类型成本
                    m.cost = m.cost_dianzi + m.cost_fuzhuang + m.cost_jiaju + m.cost_jingyou + m.cost_meirongmj + m.cost_other;

                    //平台费用
                    m.fee_platform_and_refund = m.fee_platform + m.fee_fba + m.fee_ad;

                    //物流仓储费用 = 头程运输+直邮物流费+尾程费+海外仓仓储+海外仓其他杂费
                    m.fee_logistics_storage = m.fee_logistics_first + m.fee_logistics_direct+m.fee_logistics_tail + m.fee_storage+m.fee_storage_incidentals;

                    //销售费用合计=平台扣费及退款+物流仓储费用+付现销售费用
                    m.fee_sales_count = m.fee_platform_and_refund + m.fee_logistics_storage + m.fee_paycash_sales;

                    //销售利润=销售额-产品成本-销售费用合计
                    m.profit_sales = m.amount_sales - m.cost - m.fee_sales_count;

                    //销售毛利率=销售利润/销售额
                    m.rate_profit_sales = m.amount_sales > 0 ? m.profit_sales / m.amount_sales : 0;

                    //管理成本=广州百伦+美容美甲店+杨杉+信荟蓝+成品仓
                    m.managercost_count = m.managecost_bl_gz + m.managecost_meijia + m.managercost_chengpincang + m.managercost_xinhuilan + m.managercost_yangshan + m.managercost_dizhi;

                    //营业利润=销售利润-管理成本合计-财务费用
                    m.profit = m.profit_sales - m.managercost_count - m.fee_finance;

                    //营业毛利率=营业利润/销售额
                    m.rate_profit = m.amount_sales > 0 ? m.profit / m.amount_sales : 0;

                    m.incoming_other = m.incoming_refundtax + m.incoming_gogirl;

                    //实际利润=营业利润+其他收入+营业外收入-营业外支出-资产减值
                    m.actual_profit = m.profit + m.incoming_other + m.incoming_non_operating - m.pay_non_operating-(m.impairment_assets??0);

                    //利润结余=实际利润
                    m.profit_balance = m.actual_profit;

                    //净利率 = 利润结余/销售额
                    m.rate_profit_actual = m.amount_sales > 0 ? m.profit_balance / m.amount_sales : 0;

                    listCount.Add(m);
                }

                var objCount = listCount.Select(a => new
                {
                    amount_sales = a.amount_sales.ToString("N2"),
                    amount_sales_dianzi = a.amount_sales_dianzi.ToString("N2"),
                    amount_sales_fuzhuang = a.amount_sales_fuzhuang.ToString("N2"),
                    amount_sales_jiaju = a.amount_sales_jiaju.ToString("N2"),
                    amount_sales_jingyou = a.amount_sales_jingyou.ToString("N2"),
                    amount_sales_meirongmj = a.amount_sales_meirongmj.ToString("N2"),
                    amount_sales_other = a.amount_sales_other.ToString("N2"),

                    amount_withdraw = a.amount_withdraw.ToString("N2"),

                    cost = a.cost.ToString("N2"),
                    cost_dianzi = a.cost_dianzi.ToString("N2"),
                    cost_fuzhuang = a.cost_fuzhuang.ToString("N2"),
                    cost_jiaju = a.cost_jiaju.ToString("N2"),
                    cost_jingyou = a.cost_jingyou.ToString("N2"),
                    cost_meirongmj = a.cost_meirongmj.ToString("N2"),
                    cost_other = a.cost_other.ToString("N2"),

                    fee_fba = a.fee_fba.ToString("N2"),
                    fee_ad = a.fee_ad.ToString("N2"),
                    fee_finance = a.fee_finance.ToString("N2"),
                    fee_logistics_direct = a.fee_logistics_direct.ToString("N2"),
                    fee_logistics_first = a.fee_logistics_first.ToString("N2"),
                    fee_logistics_storage = a.fee_logistics_storage.ToString("N2"),
                    fee_logistics_tail = a.fee_logistics_tail.ToString("N2"),
                    fee_paycash_sales = a.fee_paycash_sales.ToString("N2"),
                    fee_platform = a.fee_platform.ToString("N2"),
                    fee_platform_and_refund = a.fee_platform_and_refund.ToString("N2"),
                    fee_refund = a.fee_refund.ToString("N2"),
                    fee_sales_count = a.fee_sales_count.ToString("N2"),
                    fee_storage = a.fee_storage.ToString("N2"),
                    fee_storage_incidentals = a.fee_storage_incidentals.ToString("N2"),

                    incoming_non_operating = a.incoming_non_operating.ToString("N2"),
                    incoming_other = a.incoming_other.ToString("N2"),
                    incoming_refundtax = a.incoming_refundtax.ToString("N2"),
                    incoming_gogirl = a.incoming_gogirl.ToString("N2"),
                    a.isedit,

                    managecost_bl_gz = a.managecost_bl_gz.ToString("N2"),
                    managecost_bl_xg = a.managecost_bl_xg.ToString("N2"),
                    managecost_meijia = a.managecost_meijia.ToString("N2"),
                    managercost_chengpincang = a.managercost_chengpincang.ToString("N2"),
                    managercost_count = a.managercost_count.ToString("N2"),
                    managercost_xinhuilan = a.managercost_xinhuilan.ToString("N2"),
                    managercost_yangshan = a.managercost_yangshan.ToString("N2"),
                    managercost_dizhi = a.managercost_dizhi.ToString("N2"),
                    managercost_meijiashengchan = a.managercost_meijiashengchan.ToString("N2"),

                    pay_non_operating = a.pay_non_operating.ToString("N2"),
                    profit = a.profit.ToString("N2"),
                    profit_balance = a.profit_balance.ToString("N2"),
                    profit_sales = a.profit_sales.ToString("N2"),
                    rate_profit = (a.rate_profit * 100).ToString("N2"),
                    rate_profit_actual = (a.rate_profit_actual * 100).ToString("N2"),
                    rate_profit_sales = (a.rate_profit_sales * 100).ToString("N2"),

                    actual_profit = a.actual_profit.ToString("N2"),
                    dividend = a.dividend.ToString("N2"),

                    impairment_assets = (a.impairment_assets??0).ToString("N2"),

                    a.month
                });


                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,
                    listdesc = objDescription
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = "出现异常，异常信息：" + ex.Message
                });
            }
        }

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

            var _service = new Services.FinanceReportServices();

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

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

        /// <summary>
        /// 导出月销售利润报表
        /// </summary>
        /// <param name="month">月份</param>
        /// <returns></returns>
        public ActionResult ExportMonthSaleProfitNew(string month)
        {

            var _service = new Services.FinanceReportServices();


            var obj = _service.ListMonthSaleProfitNew(month, "");

            var listCount = new List<dc_month_sales_profit>();
            var listMonth = obj.GroupBy(a => a.month);



            var arrValue = new List<Models.Common.KeyValue>();
            arrValue.Add(new Models.Common.KeyValue() { Key = "销售额", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "精油产品", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "电子产品", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "家居产品", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "美容美甲产品", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "服装", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "其他", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "退款", Value = "" });


            arrValue.Add(new Models.Common.KeyValue() { Key = "成本", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "精油产品 ", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "电子产品 ", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "家居产品 ", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "美容美甲产品 ", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "服装 ", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "其他 ", Value = "" });


            arrValue.Add(new Models.Common.KeyValue() { Key = "平台费用", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "平台费", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "FBA费", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "广告及宣传费", Value = "" });


            arrValue.Add(new Models.Common.KeyValue() { Key = "物流仓储费用", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "头程运输", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "直邮物流费", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "尾程物流费", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "海外仓仓储费", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "海外仓其他杂费", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "付现销售费用", Value = "" });


            arrValue.Add(new Models.Common.KeyValue() { Key = "销售费用合计", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "销售利润", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "销售毛利率", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "财务费用", Value = "" });


            arrValue.Add(new Models.Common.KeyValue() { Key = "管理成本合计", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "广州百伦供应链科技有限公司", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "广州歌戈儿生活科技有限公司", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "深圳前海扬杉创新科技有限公司", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "广州信荟蓝科技有限公司", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "广州电子服装仓&阳山", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "广州迪致美容科技有限公司", Value = "" });


            arrValue.Add(new Models.Common.KeyValue() { Key = "营业利润", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "营业毛利率", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "加：其他收入", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "其中：出口退税收入", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "其中：歌戈儿收入", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "加：营业外收入", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "减：营业外支出", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "实际利润", Value = "" });
            arrValue.Add(new Models.Common.KeyValue() { Key = "净利率", Value = "" });

            var str_head = "项目,";
            foreach (var item in listMonth)
            {
                str_head += item.Key + "基础数据," + item.Key + "调整数据," + item.Key + "合计数据,";

                var objBase = item.Where(a => a.isedit == 0).FirstOrDefault();
                var objEdit = item.Where(a => a.isedit == 1).FirstOrDefault();

                if (objBase == null)
                {
                    continue;
                }
                if (objEdit == null)
                {
                    objEdit = new dc_month_sales_profit();
                }

                var amount_sales = arrValue.Where(a => a.Key == "销售额").FirstOrDefault();
                amount_sales.Value += objBase.amount_sales + "," + objEdit.amount_sales + "," + (objBase.amount_sales + objEdit.amount_sales + ",");
                var amount_sales_jingyou = arrValue.Where(a => a.Key == "精油产品").FirstOrDefault();
                amount_sales_jingyou.Value += objBase.amount_sales_jingyou + "," + objEdit.amount_sales_jingyou + "," + (objBase.amount_sales_jingyou + objEdit.amount_sales_jingyou + ",");
                var amount_sales_dianzi = arrValue.Where(a => a.Key == "电子产品").FirstOrDefault();
                amount_sales_dianzi.Value += objBase.amount_sales_dianzi + "," + objEdit.amount_sales_dianzi + "," + (objBase.amount_sales_dianzi + objEdit.amount_sales_dianzi + ",");
                var amount_sales_jiaju = arrValue.Where(a => a.Key == "家居产品").FirstOrDefault();
                amount_sales_jiaju.Value += objBase.amount_sales_jiaju + "," + objEdit.amount_sales_jiaju + "," + (objBase.amount_sales_jiaju + objEdit.amount_sales_jiaju + ",");
                var amount_sales_meirongmj = arrValue.Where(a => a.Key == "美容美甲产品").FirstOrDefault();
                amount_sales_meirongmj.Value += objBase.amount_sales_meirongmj + "," + objEdit.amount_sales_meirongmj + "," + (objBase.amount_sales_meirongmj + objEdit.amount_sales_meirongmj + ",");
                var amount_sales_fuzhuang = arrValue.Where(a => a.Key == "服装").FirstOrDefault();
                amount_sales_fuzhuang.Value += objBase.amount_sales_fuzhuang + "," + objEdit.amount_sales_fuzhuang + "," + (objBase.amount_sales_fuzhuang + objEdit.amount_sales_fuzhuang + ",");
                var amount_sales_other = arrValue.Where(a => a.Key == "其他").FirstOrDefault();
                amount_sales_other.Value += objBase.amount_sales_other + "," + objEdit.amount_sales_other + "," + (objBase.amount_sales_other + objEdit.amount_sales_other + ",");
                var fee_refund = arrValue.Where(a => a.Key == "退款").FirstOrDefault();
                fee_refund.Value += objBase.fee_refund + "," + objEdit.fee_refund + "," + (objBase.fee_refund + objEdit.fee_refund + ",");


                var cost = arrValue.Where(a => a.Key == "成本").FirstOrDefault();
                cost.Value += objBase.cost + "," + objEdit.cost + "," + (objBase.cost + objEdit.cost + ",");
                var cost_jingyou = arrValue.Where(a => a.Key == "精油产品 ").FirstOrDefault();
                cost_jingyou.Value += objBase.cost_jingyou + "," + objEdit.cost_jingyou + "," + (objBase.cost_jingyou + objEdit.cost_jingyou + ",");
                var cost_dianzi = arrValue.Where(a => a.Key == "电子产品 ").FirstOrDefault();
                cost_dianzi.Value += objBase.cost_dianzi + "," + objEdit.cost_dianzi + "," + (objBase.cost_dianzi + objEdit.cost_dianzi + ",");
                var cost_jiaju = arrValue.Where(a => a.Key == "家居产品 ").FirstOrDefault();
                cost_jiaju.Value += objBase.cost_jiaju + "," + objEdit.cost_jiaju + "," + (objBase.cost_jiaju + objEdit.cost_jiaju + ",");
                var cost_meirongmj = arrValue.Where(a => a.Key == "美容美甲产品 ").FirstOrDefault();
                cost_meirongmj.Value += objBase.cost_meirongmj + "," + objEdit.cost_meirongmj + "," + (objBase.cost_meirongmj + objEdit.cost_meirongmj + ",");
                var cost_fuzhuang = arrValue.Where(a => a.Key == "服装 ").FirstOrDefault();
                cost_fuzhuang.Value += objBase.cost_fuzhuang + "," + objEdit.cost_fuzhuang + "," + (objBase.cost_fuzhuang + objEdit.cost_fuzhuang + ",");
                var cost_other = arrValue.Where(a => a.Key == "其他 ").FirstOrDefault();
                cost_other.Value += objBase.cost_other + "," + objEdit.cost_other + "," + (objBase.cost_other + objEdit.cost_other + ",");



                var fee_platform_and_refund = arrValue.Where(a => a.Key == "平台费用").FirstOrDefault();
                fee_platform_and_refund.Value += objBase.fee_platform_and_refund + "," + objEdit.fee_platform_and_refund + "," + (objBase.fee_platform_and_refund + objEdit.fee_platform_and_refund + ",");
                var fee_platform = arrValue.Where(a => a.Key == "平台费").FirstOrDefault();
                fee_platform.Value += objBase.fee_platform + "," + objEdit.fee_platform + "," + (objBase.fee_platform + objEdit.fee_platform + ",");
                var fee_fba = arrValue.Where(a => a.Key == "FBA费").FirstOrDefault();
                fee_fba.Value += objBase.fee_fba + "," + objEdit.fee_fba + "," + (objBase.fee_fba + objEdit.fee_fba + ",");
                var fee_ad = arrValue.Where(a => a.Key == "广告及宣传费").FirstOrDefault();
                fee_ad.Value += objBase.fee_ad + "," + objEdit.fee_ad + "," + (objBase.fee_ad + objEdit.fee_ad + ",");



                var fee_logistics_storage = arrValue.Where(a => a.Key == "物流仓储费用").FirstOrDefault();
                fee_logistics_storage.Value += objBase.fee_logistics_storage + "," + objEdit.fee_logistics_storage + "," + (objBase.fee_logistics_storage + objEdit.fee_logistics_storage + ",");
                var fee_logistics_first = arrValue.Where(a => a.Key == "头程运输").FirstOrDefault();
                fee_logistics_first.Value += objBase.fee_logistics_first + "," + objEdit.fee_logistics_first + "," + (objBase.fee_logistics_first + objEdit.fee_logistics_first + ",");
                var fee_logistics_direct = arrValue.Where(a => a.Key == "直邮物流费").FirstOrDefault();
                fee_logistics_direct.Value += objBase.fee_logistics_direct + "," + objEdit.fee_logistics_direct + "," + (objBase.fee_logistics_direct + objEdit.fee_logistics_direct + ",");
                var fee_logistics_tail = arrValue.Where(a => a.Key == "尾程物流费").FirstOrDefault();
                fee_logistics_tail.Value += objBase.fee_logistics_tail + "," + objEdit.fee_logistics_tail + "," + (objBase.fee_logistics_tail + objEdit.fee_logistics_tail + ",");
                var fee_storage = arrValue.Where(a => a.Key == "海外仓仓储费").FirstOrDefault();
                fee_storage.Value += objBase.fee_storage + "," + objEdit.fee_storage + "," + (objBase.fee_storage + objEdit.fee_storage + ",");
                var fee_storage_incidentals = arrValue.Where(a => a.Key == "海外仓其他杂费").FirstOrDefault();
                fee_storage_incidentals.Value += objBase.fee_storage_incidentals + "," + objEdit.fee_storage_incidentals + "," + (objBase.fee_storage_incidentals + objEdit.fee_storage_incidentals + ",");
                var fee_paycash_sales = arrValue.Where(a => a.Key == "付现销售费用").FirstOrDefault();
                fee_paycash_sales.Value += objBase.fee_paycash_sales + "," + objEdit.fee_paycash_sales + "," + (objBase.fee_paycash_sales + objEdit.fee_paycash_sales + ",");


                var fee_sales_count = arrValue.Where(a => a.Key == "销售费用合计").FirstOrDefault();
                fee_sales_count.Value += objBase.fee_sales_count + "," + objEdit.fee_sales_count + "," + (objBase.fee_sales_count + objEdit.fee_sales_count + ",");
                var profit_sales = arrValue.Where(a => a.Key == "销售利润").FirstOrDefault();
                profit_sales.Value += objBase.profit_sales + "," + objEdit.profit_sales + "," + (objBase.profit_sales + objEdit.profit_sales + ",");
                var rate_profit_sales = arrValue.Where(a => a.Key == "销售毛利率").FirstOrDefault();
                rate_profit_sales.Value += objBase.rate_profit_sales + "," + objEdit.rate_profit_sales + "," + ((item.Sum(m=>m.profit_sales) / item.Sum(m=>m.amount_sales)) + ",");
                var fee_finance = arrValue.Where(a => a.Key == "财务费用").FirstOrDefault();
                fee_finance.Value += objBase.fee_finance + "," + objEdit.fee_finance + "," + (objBase.fee_finance + objEdit.fee_finance + ",");


                var managercost_count = arrValue.Where(a => a.Key == "管理成本合计").FirstOrDefault();
                managercost_count.Value += objBase.managercost_count + "," + objEdit.managercost_count + "," + (objBase.managercost_count + objEdit.managercost_count + ",");
                var managecost_bl_gz = arrValue.Where(a => a.Key == "广州百伦供应链科技有限公司").FirstOrDefault();
                managecost_bl_gz.Value += objBase.managecost_bl_gz + "," + objEdit.managecost_bl_gz + "," + (objBase.managecost_bl_gz + objEdit.managecost_bl_gz + ",");
                var managecost_meijia = arrValue.Where(a => a.Key == "广州歌戈儿生活科技有限公司").FirstOrDefault();
                managecost_meijia.Value += objBase.managecost_meijia + "," + objEdit.managecost_meijia + "," + (objBase.managecost_meijia + objEdit.managecost_meijia + ",");
                var managercost_yangshan = arrValue.Where(a => a.Key == "深圳前海扬杉创新科技有限公司").FirstOrDefault();
                managercost_yangshan.Value += objBase.managercost_yangshan + "," + objEdit.managercost_yangshan + "," + (objBase.managercost_yangshan + objEdit.managercost_yangshan + ",");
                var managercost_xinhuilan = arrValue.Where(a => a.Key == "广州信荟蓝科技有限公司").FirstOrDefault();
                managercost_xinhuilan.Value += objBase.managercost_xinhuilan + "," + objEdit.managercost_xinhuilan + "," + (objBase.managercost_xinhuilan + objEdit.managercost_xinhuilan + ",");
                var managercost_chengpincang = arrValue.Where(a => a.Key == "广州电子服装仓&阳山").FirstOrDefault();
                managercost_chengpincang.Value += objBase.managercost_chengpincang + "," + objEdit.managercost_chengpincang + "," + (objBase.managercost_chengpincang + objEdit.managercost_chengpincang + ",");
                var managercost_dizhi = arrValue.Where(a => a.Key == "广州迪致美容科技有限公司").FirstOrDefault();
                managercost_dizhi.Value += objBase.managercost_dizhi + "," + objEdit.managercost_dizhi + "," + (objBase.managercost_dizhi + objEdit.managercost_dizhi + ",");


                var profit = arrValue.Where(a => a.Key == "营业利润").FirstOrDefault();
                profit.Value += objBase.profit + "," + objEdit.profit + "," + (objBase.profit + objEdit.profit + ",");
                var rate_profit = arrValue.Where(a => a.Key == "营业毛利率").FirstOrDefault();
                rate_profit.Value += objBase.rate_profit + "," + objEdit.rate_profit + "," + ((item.Sum(m=>m.profit) / item.Sum(m=>m.amount_sales)) + ",");
                var incoming_other = arrValue.Where(a => a.Key == "加：其他收入").FirstOrDefault();
                incoming_other.Value += objBase.incoming_other + "," + objEdit.incoming_other + "," + (objBase.incoming_other + objEdit.incoming_other + ",");
                var incoming_refundtax = arrValue.Where(a => a.Key == "其中：出口退税收入").FirstOrDefault();
                incoming_refundtax.Value += objBase.incoming_refundtax + "," + objEdit.incoming_refundtax + "," + (objBase.incoming_refundtax + objEdit.incoming_refundtax + ",");
                var incoming_gogirl = arrValue.Where(a => a.Key == "其中：歌戈儿收入").FirstOrDefault();
                incoming_gogirl.Value += objBase.incoming_gogirl + "," + objEdit.incoming_gogirl + "," + (objBase.incoming_gogirl + objEdit.incoming_gogirl + ",");
                var incoming_non_operating = arrValue.Where(a => a.Key == "加：营业外收入").FirstOrDefault();
                incoming_non_operating.Value += objBase.incoming_non_operating + "," + objEdit.incoming_non_operating + "," + (objBase.incoming_non_operating + objEdit.incoming_non_operating + ",");
                var pay_non_operating = arrValue.Where(a => a.Key == "减：营业外支出").FirstOrDefault();
                pay_non_operating.Value += objBase.pay_non_operating + "," + objEdit.pay_non_operating + "," + (objBase.pay_non_operating + objEdit.pay_non_operating + ",");
                var actual_profit = arrValue.Where(a => a.Key == "实际利润").FirstOrDefault();
                actual_profit.Value += objBase.actual_profit + "," + objEdit.actual_profit + "," + (objBase.actual_profit + objEdit.actual_profit + ",");
                var rate_profit_actual = arrValue.Where(a => a.Key == "净利率").FirstOrDefault();

                rate_profit_actual.Value += objBase.rate_profit_actual + "," + objEdit.rate_profit_actual + "," + ((item.Sum(a=>a.profit_balance)/item.Sum(a=>a.amount_sales)) + ",");
                
            }

            var colNames = str_head.Split(',').Where(a=>!string.IsNullOrEmpty(a)).ToList();

            var list = new List<string>();
            foreach (var item in arrValue)
            {
                list.Add(item.Key + "|" + item.Value.Replace(",", "|").Substring(0,item.Value.Length-1));
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "月销售利润报表" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");


        }

        /// <summary>
        /// 费用明细
        /// </summary>
        /// <param name="month">月份</param>
        /// <param name="col">字段类型</param>
        /// <returns></returns>
        public ActionResult MonthSaleProfitNew_FeeOrderDetail(string month,string col)
        {

            ViewBag.month = month;
            ViewBag.col = col;

            return View();
        }

        /// <summary>
        /// 费用单明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="month">月份</param>
        /// <param name="col">字段类型</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        public string MonthSaleProfitNew_FeeOrderDetailJson(BtTableParameter parameter,string month,string col)
        {
            var total = 0;

            var start = DateTime.Parse(month + "-1");
            var end = start.AddMonths(1).AddDays(-1);

            var obj = new Services.FinanceReportServices().ListMonthProfitFeeOrderDetail(parameter, start, end, col, ref total);


            var list = obj.Select(a => new {
                amount = (a.amount??0).ToString("###,###.##"),
                amountRmb = (a.amount_rmb??0).ToString("###,###.##"),
                companyName = a.company_name,
                currency = a.dic,
                departmentName = a.department_name,
                a.type_name,
                a.accounting_subject_name,
                //feeSuperType = a.fee_super_type,
                no = a.cost_no,
                manageCostType = a.accounting_subject_name,
                receiveUnit = a.bank_company,
                reason = a.cost_reason,
                payTime = a.pay_time.HasValue ? a.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss") : ""
            }).ToList();


            return JsonConvert.SerializeObject(new
            {
                total = list.Count,
                rows = list,
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportAdministrativeCost", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        /// <summary>
        /// 更新月度销售利润报表的取数描述
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        public JsonResult UpdateMonthSalesProfitDescription(mMonthSalesProfitDesc_Input m)
        {
            var user = HttpContextHelper.Current?.User;
            var obj = new Services.FinanceReportServices().SaveMonthSaleProfitNewDescription(m, user != null ? user.GetUid() : 0, user != null ? user.GetUserName() : "");

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

        /// <summary>
        /// 导出分类管理成品明细
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="paycompanyid"></param>
        /// <param name="headname"></param>
        /// <param name="categoryname"></param>
        /// <param name="type"></param>
        /// <param name="issub"></param>
        /// <returns></returns>
        public ActionResult ExportMonthSaleProfitNewFeeOrderDetail(string month, string col)
        {
            var total = 0;

            var start = DateTime.Parse(month + "-1");
            var end = start.AddMonths(1).AddDays(-1);

            var obj = new Services.FinanceReportServices().ListMonthProfitFeeOrderDetail(new BtTableParameter { offset=1,limit=0}, start, end, col, ref total);

            var colNames = new List<string> {"费用单号","一级部门","付款主体名称","费用类别", "会计科目",
                                            "金额","币种", "人民币金额","收款单位","收款理由","付款时间","备注" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.cost_no + "|" + item.department_name + "|" + item.company_name + "|" + item.type_name + "|" + item.accounting_subject_name + "|" +
                    item.amount + "|" + item.dic + "|" + item.amount_rmb + "|" + item.bank_company + "|" + item.cost_reason + "|" + item.pay_time.Value.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = " 管理成本明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }


        public ActionResult MonthSaleProfitNew_OrderDetail(string month,string financecategory)
        {
            ViewBag.month = month;
            ViewBag.financecategory = financecategory;
            
            return View();
        }

        [BailunAuthentication(LoginMode.Enforce)]
        public string MonthSaleProfitNew_OrderDetailJson(BtTableParameter parameter,string month,string financecategory)
        {
            var total = 0;

            var _service = new Services.FinanceReportServices();

            var obj = _service.ListMonthProfitOrderDetail(parameter, month, financecategory,ref total);

            var list = obj.Select(a=> new dc_month_sales_profit_orderdetail{
                financecategoryname = a.financecategoryname,
                platform_type = a.platform_type,
                bailun_sku = a.bailun_sku,
                origin_order_id = a.origin_order_id,
                bailun_order_id = a.bailun_order_id,

                quantity_shipped = a.quantity_shipped,

                amount_sales = a.amount_sales*a.quantity_shipped*a.seller_order_exchange_rate,
                cost_fba_fee = a.cost_fba_fee * a.quantity_shipped * a.seller_order_exchange_rate,
                cost_first = a.cost_first * a.quantity_shipped,
                cost_handle_platform = a.cost_handle_platform* a.quantity_shipped,
                cost_logistics = a.cost_logistics * a.quantity_shipped,
                cost_paypal_fee = a.cost_paypal_fee * a.quantity_shipped * a.seller_order_exchange_rate,
                cost_platform_fee = a.cost_platform_fee * (a.platform_type.ToLower() == "ebay"?a.seller_other_exchange_rate:a.seller_order_exchange_rate)*a.quantity_shipped,
                cost_product = a.cost_product * a.quantity_shipped,
                total_fee = (a.total_fee - a.shipping) * a.wms_to_cny_exchange_rate * a.quantity_shipped,  //仓储费

                sale_profit = 0,

                shipping_time = a.shipping_time,

            }).ToList();

            foreach(var item in list)
            {
                item.sale_profit = item.amount_sales - item.cost_fba_fee - item.cost_first - item.cost_handle_platform - item.cost_logistics - item.cost_paypal_fee - item.cost_platform_fee - item.cost_product - item.total_fee;
            }


            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                isexport = 1,
            });
        }

        public ActionResult ExportMonthSaleProfitNew_OrderDetail(string month, string financecategory)
        {
            var total = 0;

            var _service = new Services.FinanceReportServices();

            var obj = _service.ListMonthProfitOrderDetail(new BtTableParameter { offset=0,limit=0}, month, financecategory, ref total);

            var list = obj.Select(a => new dc_month_sales_profit_orderdetail
            {
                financecategoryname = a.financecategoryname,
                platform_type = a.platform_type,
                bailun_sku = a.bailun_sku,
                origin_order_id = a.origin_order_id,
                bailun_order_id = a.bailun_order_id,

                quantity_shipped = a.quantity_shipped,

                amount_sales = a.amount_sales * a.quantity_shipped * a.seller_order_exchange_rate,
                cost_fba_fee = a.cost_fba_fee * a.quantity_shipped * a.seller_order_exchange_rate,
                cost_first = a.cost_first * a.quantity_shipped,
                cost_handle_platform = a.cost_handle_platform * a.quantity_shipped,
                cost_logistics = a.cost_logistics * a.quantity_shipped,
                cost_paypal_fee = a.cost_paypal_fee * a.quantity_shipped * a.seller_order_exchange_rate,
                cost_platform_fee = a.cost_platform_fee * (a.platform_type.ToLower() == "ebay" ? a.seller_other_exchange_rate : a.seller_order_exchange_rate) * a.quantity_shipped,
                cost_product = a.cost_product * a.quantity_shipped,
                total_fee = (a.total_fee - a.shipping) * a.wms_to_cny_exchange_rate * a.quantity_shipped,  //仓储费

                sale_profit = 0,

                shipping_time = a.shipping_time,

            }).ToList();

            foreach (var item in list)
            {
                item.sale_profit = item.amount_sales - item.cost_fba_fee - item.cost_first - item.cost_handle_platform - item.cost_logistics - item.cost_paypal_fee - item.cost_platform_fee - item.cost_product - item.total_fee;
            }

            var colNames = new List<string> {"财务分类","平台类型","平台订单号","SKU", "销售额",
                                            "产品成本","平台费", "Paypal费","FBA费","头程费",
                                            "尾程费","仓储费","平台操作费","销售利润","发货数量",
                                            "发货时间" };

            var listval = new List<string>();
            foreach (var item in obj)
            {
                listval.Add(item.financecategoryname + "|" + item.platform_type + "|" + item.origin_order_id + "|" + item.bailun_sku + "|" + item.amount_sales + "|" +
                    item.cost_product + "|" + item.cost_platform_fee + "|" + item.cost_paypal_fee + "|" + item.cost_fba_fee + "|" + item.cost_first + "|" +
                    item.cost_logistics + "|" + item.total_fee + "|" + item.cost_handle_platform + "|" + item.sale_profit + "|" + item.quantity_shipped + "|" +
                    item.shipping_time.ToString("yyyy-MM-dd HH:mm:ss")
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = " 订单明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listval, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");

        }


        /// <summary>
        /// 新月销售利润-广告类型选择页面
        /// </summary>
        /// <param name="month"></param>
        /// <returns></returns>
        public ActionResult MonthSaleProfitNew_ADCount(string month)
        {
            ViewBag.start = DateTime.Parse(month+"-01");
            ViewBag.end = DateTime.Parse(month + "-01").AddMonths(1).AddDays(-1);

            ViewBag.month = month;

            return View();
        }

        #endregion

        #endregion

        #region 平台应收账款

        /// <summary>
        /// 平台应收款列表
        /// </summary>
        /// <returns></returns>
        public ActionResult PlatformReceivable()
        {
            ViewBag.start = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
            ViewBag.end = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

            return View();
        }

        /// <summary>
        /// 平台应收款
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="start">开始时间</param>
        /// <param name="end">结束时间</param>
        /// <param name="platform">平台类型</param>
        /// <returns></returns>
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【平台应收账款】->【搜索】页面", 0)]
        public string PlatformReceivableJson(BtTableParameter parameter, DateTime start, DateTime end, string platform,int type)
        {
            var total = 0;
            var _service = new Services.FinanceReportServices();

            var obj = _service.ListReceivable(parameter, platform, start, end,type, ref total);

            var list = obj.Select(a => new {
                id = start == end ?a.id:0,
                a.platform,
                day = start!=end? (start.ToString("yyyy-MM-dd") +"至"+ end.ToString("yyyy-MM-dd")) : start.ToString("yyyy-MM-dd"), //a.day.ToString("yyyy-MM-dd"),
                amount_end = a.amount_end.ToString("N2"),
                amount_incoming = a.amount_incoming.ToString("N2"),
                amount_other = a.amount_other.ToString("N2"),
                amount_platformfee = a.amount_platformfee.ToString("N2"),
                amount_refund = a.amount_refund.ToString("N2"),
                amount_sale_pay = a.amount_sale_pay.ToString("N2"),
                amount_sale_shipping = a.amount_sale_shipping.ToString("N2"),
                amount_shipping = a.amount_shipping.ToString("N2"),
                amount_start = a.amount_start.ToString("N2"),
                lastupdatetime = a.lastupdatetime.ToString("yyyy-MM-dd HH:mm:ss"),
                note = (a.note??"")
            });

            var objCount = _service.ListReceivableCount(platform, start, end,type);

            var objStartEnd = _service.ListReceivableStartEnd(platform, start, end, type);
            
            return JsonConvert.SerializeObject(new {
                total = total,
                rows = list,
                count_row = new
                {
                    platform="合计",
                    amount_end = objStartEnd.amount_end.ToString("N2"),
                    amount_incoming = objCount.amount_incoming.ToString("N2"),
                    amount_other = objCount.amount_other.ToString("N2"),
                    amount_platformfee = objCount.amount_platformfee.ToString("N2"),
                    amount_refund = objCount.amount_refund.ToString("N2"),
                    amount_sale_pay = objCount.amount_sale_pay.ToString("N2"),
                    amount_sale_shipping = objCount.amount_sale_shipping.ToString("N2"),
                    amount_shipping = objCount.amount_shipping.ToString("N2"),
                    amount_start = objStartEnd.amount_start.ToString("N2"),
                }
            });

        }

        /// <summary>
        /// 更新平台应收款其他金额
        /// </summary>
        /// <param name="id">应收款id</param>
        /// <param name="amount">金额</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdatePlatformReceivable(int id, decimal amount,int type=1)
        {
            var user = HttpContextHelper.Current.User;

            var result = new Services.FinanceReportServices().UpdateReceivable(id, amount,(user!=null? user.GetUid():0),(user!=null? user.GetUserName():""),type);

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

        /// <summary>
        /// 更新平台应收款备注
        /// </summary>
        /// <param name="id">应收款id</param>
        /// <param name="note">备注</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdatePlatformReceivableNote(int id, string note)
        {
            var user = HttpContextHelper.Current.User;

            var result = new Services.FinanceReportServices().UpdateReceivableNote(id, note, (user != null ? user.GetUid() : 0), (user != null ? user.GetUserName() : ""));

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

        #endregion

        #region 进销存不合理报告分析

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

        /// <summary>
        /// 进销存差异汇总
        /// </summary>
        /// <param name="month">月份</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [HttpPost]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【进销存差异汇总】->【搜索】页面", 0)]
        public JsonResult UnReasonableJson(string month)
        {
            if (string.IsNullOrEmpty(month))
            {
                return Json(new
                {
                    success = false,
                    msg = "请选择月份。",
                });
            }

            try
            {
                var _service = new Services.FinanceReportServices();
                var obj1 = _service.ListMonthSalePutin(month, null);
                var obj2 = _service.ListMonthSalePutin(month, 1); //增加部分
                var obj3 = _service.ListMonthSalePutin(month, 2);  //减少部分

                if (obj1.Count > 0)
                {
                    obj1.Add(new dc_mid_month_sale_putin
                    {
                        warehouse_type = "总计",
                        category_simple_name = "",
                        count_outbound = obj1.Sum(a => a.count_outbound),
                        amount_outbound = obj1.Sum(a => a.amount_outbound),
                        count_putin = obj1.Sum(a => a.count_putin),
                        amount_putin = obj1.Sum(a => a.amount_putin),
                        count_diff = obj1.Sum(a => a.count_diff),
                        amount_diff = obj1.Sum(a => a.amount_diff)
                    });
                }

                if (obj2.Count > 0)
                {
                    obj2.Add(new dc_mid_month_sale_putin
                    {
                        warehouse_type = "总计",
                        category_simple_name = "",
                        count_outbound = obj2.Sum(a => a.count_outbound),
                        amount_outbound = obj2.Sum(a => a.amount_outbound),
                        count_putin = obj2.Sum(a => a.count_putin),
                        amount_putin = obj2.Sum(a => a.amount_putin),
                        count_diff = obj2.Sum(a => a.count_diff),
                        amount_diff = obj2.Sum(a => a.amount_diff)
                    });
                }

                if (obj3.Count > 0)
                {
                    obj3.Add(new dc_mid_month_sale_putin
                    {
                        warehouse_type = "总计",
                        category_simple_name = "",
                        count_outbound = obj3.Sum(a => a.count_outbound),
                        amount_outbound = obj3.Sum(a => a.amount_outbound),
                        count_putin = obj3.Sum(a => a.count_putin),
                        amount_putin = obj3.Sum(a => a.amount_putin),
                        count_diff = obj3.Sum(a => a.count_diff),
                        amount_diff = obj3.Sum(a => a.amount_diff)
                    });
                }

                return Json(new
                {
                    success = true,
                    msg = "",
                    list0 = obj1,
                    list1 = obj2,
                    list2 = obj3
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                });
            }
        }

        /// <summary>
        /// 销进比差异明细
        /// </summary>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="month">月份</param>
        /// <param name="type">是否筛选增加了或者减少了，1：增加了，2：减少了</param>
        /// <returns></returns>
        public ActionResult ListUnReasonable(string warehousetype, string month,int? type, string category, int isun=-1)
        {
            ViewBag.warehousetype = warehousetype;
            ViewBag.month = (string.IsNullOrEmpty(month)?DateTime.Now.AddMonths(-1).ToString("yyyy-MM"):month);
            ViewBag.type = type ?? -1;
            ViewBag.isun = isun;
            ViewBag.category = category;

            return View();
        }

        /// <summary>
        /// 销进比差异明细
        /// </summary>
        /// <param name="parameter">分页信息</param>
        /// <param name="month">月份</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="type">是否筛选增加了或者减少了，1：增加了，2：减少了</param>
        /// <param name="isclear">是否清货</param>
        /// <param name="isnew">是否新品</param>
        /// <param name="isaims">是否aims下单</param>
        /// <returns></returns>
        [BailunAuthentication(LoginMode.Enforce)]
        [BrowseLog("Bailun_data", "访问【百伦数据中心】->【财务报表】->【每月进销存合理报表】->【搜索】页面", 0)]
        public string ListUnReasonableJson(BtTableParameter parameter, string month, string warehousetype,string warehouse,int? type,int? isclear,int? isnew,int? isaims,string category, int isreasonable = -1)
        {
            var total = 0;
            var _service = new Services.FinanceReportServices();

            var obj = _service.ListMonthSalePutinDetail(parameter, month, warehousetype, warehouse, type, isclear, isnew, isaims, ref total, category, isreasonable);
            var objCount = _service.ListMonthSalePutinDetailCount(month, warehousetype, warehouse, type, isclear, isnew, isaims, category, isreasonable);

            var list = obj.Select(a=> new {
                a.warehouse_type,
                a.warehouse_code,
                a.warehouse_name,
                a.bailun_sku,

                a.count_outbound,
                a.amount_outbound,
                a.count_putin,
                a.amount_putin,
                a.count_diff,
                a.amount_diff,
                a.category_simple_name,

                is_clear = (a.is_clear??0)==0?"否":"是",
                is_new = (a.is_new??0)==0?"否":"是",
                is_aimsorder = (a.is_aimsorder??0)==0?"否":"是",
                a.count_usable_stock,
                a.avg_sevenday_sales,
                a.avg_fourteenday_sales,
                a.avg_thirtyday_sales,
                a.avg_sales,
                a.avg_weighting_day_sales,
                sale_putin_id = a.is_reasonable==0?"不合理":"合理"
            });

            return JsonConvert.SerializeObject(new
            {
                total = total,
                rows = list,
                count_row = new
                {
                    warehouse_name = "总计",
                    count_outbound = objCount.count_outbound.ToString("N2"),
                    amount_outbound = (objCount.amount_outbound??0).ToString("N2"),
                    count_putin = objCount.count_putin.ToString("N2"),
                    amount_putin = (objCount.amount_putin??0).ToString("N2"),
                    count_diff = objCount.count_diff.ToString("N2"),
                    amount_diff = (objCount.amount_diff??0).ToString("N2"),
                    count_usable_stock = objCount.count_usable_stock.ToString("N2")
                },
                isexport = Services.UserAuthorityServices.checkUserExportAuthority("ExportUnReasonable", HttpContextHelper.Current.User.GetUserName()),
            });
        }

        /// <summary>
        /// 导出进销存明细
        /// </summary>
        /// <param name="month">月</param>
        /// <param name="warehousetype">仓库类型</param>
        /// <param name="warehouse">仓库编码</param>
        /// <param name="type"></param>
        /// <param name="isclear">是否清货</param>
        /// <param name="isnew">是否新品</param>
        /// <param name="isaims">是否aims下单</param>
        /// <param name="isreasonable">是否获取不合理数据，0：是</param>
        /// <returns></returns>
        public ActionResult ExportUnReasonable(string month, string warehousetype, string warehouse, int? type, int? isclear, int? isnew, int? isaims, string category,int isreasonable = -1)
        {
            var total = 0;
            var _service = new Services.FinanceReportServices();

            var obj = _service.ListMonthSalePutinDetail(new BtTableParameter { limit=0,offset=1}, month, warehousetype, warehouse, type, isclear, isnew, isaims, ref total, category, isreasonable);
            
            var list = obj.Select(a => new {
                a.warehouse_type,
                a.warehouse_code,
                a.warehouse_name,
                a.bailun_sku,

                a.count_outbound,
                a.amount_outbound,
                a.count_putin,
                a.amount_putin,
                a.count_diff,
                a.amount_diff,

                is_clear = (a.is_clear ?? 0) == 0 ? "否" : "是",
                is_new = (a.is_new ?? 0) == 0 ? "否" : "是",
                is_aimsorder = (a.is_aimsorder ?? 0) == 0 ? "否" : "是",
                a.count_usable_stock,
                a.avg_sevenday_sales,
                a.avg_fourteenday_sales,
                a.avg_thirtyday_sales,
                a.avg_sales,
                sale_putin_id = a.is_reasonable == 0 ? "不合理" : "合理",
                a.category_simple_name,
                a.avg_weighting_day_sales
            });

            var colNames = new List<string>() { "仓库类型", "仓库名称", "sku","百伦简单分录", "出库数量", "出库金额", "入库数量", "入途金额", "(入库-出库)数量", "(入库-出库)金额" };

            
            colNames.AddRange(new List<string> { "是否清货", "是否新品", "是否Aims下单","可用库存", "7日日均", "14日日均", "30日日均","加权日均", "可消耗天数","是否合理"});
            

            

            var listval = new List<string>();
            foreach (var item in list)
            {
                listval.Add(item.warehouse_type + "|" + item.warehouse_name + "|" + item.bailun_sku +"|"+item.category_simple_name+ "|" + item.count_outbound + "|" + item.amount_outbound + "|" +
                    item.count_putin + "|" + item.amount_putin + "|" + item.count_diff + "|" + item.amount_diff+("|"+item.is_clear+"|"+item.is_new+"|"+item.is_aimsorder+"|"+item.count_usable_stock+"|"+item.avg_sevenday_sales+"|"+item.avg_fourteenday_sales+"|"+item.avg_thirtyday_sales+"|"+item.avg_weighting_day_sales+"|"+item.avg_sales+"|"+item.sale_putin_id)
                    );
            }

            var guid = Guid.NewGuid().ToString();
            var filename = "每月进销存合理报告" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(listval, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        #endregion

        #region oms发货收入

        /// <summary>
        /// oms发货收入
        /// </summary>
        /// <returns></returns>
        public ActionResult ShippingIncoming(int type=1)
        {
            ViewBag.type = type;

            return View();
        }

        /// <summary>
        /// oms发货收入
        /// </summary>
        /// <param name="type">1:自发货，2：FBA</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ShippingIncomingJson(string month,int type)
        {
            try
            {
                var result = new List<dc_month_shipping_incoming>();
                var list = new Services.FinanceReportServices().ListMonthShippingIncoming(month,type==2);

                //组装数据
                list = list.OrderBy(a => a.platform_type).ToList();
                var groupPlatform = list.GroupBy(a => a.platform_type);
                foreach (var item in groupPlatform)
                {
                    var platform = item.Key;

                    var groupWebSite = item.GroupBy(a => a.website);
                    foreach(var website in groupWebSite)
                    {
                        var groupCurrency = website.GroupBy(a => a.currency);
                        foreach (var c in groupCurrency)
                        {
                            foreach (var o in c)
                            {
                                result.Add(new dc_month_shipping_incoming
                                {
                                    platform_type = platform,
                                    currency = c.Key,
                                    financecategoryname = o.financecategoryname,
                                    amount = o.amount,
                                    month = o.month,
                                    website = website.Key
                                });
                            }
                        }

                        result.Add(new dc_month_shipping_incoming
                        {
                            platform_type = "合计",
                            currency = "",
                            website = "",
                            financecategoryname = "",
                            amount = website.Sum(a => a.amount),
                            month = website.FirstOrDefault().month,
                        });
                    }
                }

                result.Add(new dc_month_shipping_incoming
                {
                    platform_type = "总计",
                    currency = "",
                    website = "",
                    financecategoryname = "",
                    amount = list.Sum(a => a.amount),
                    month = list.FirstOrDefault()?.month,
                });


                return Json(new
                {
                    success = true,
                    msg = "",
                    data = result,
                });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                });
            }
            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="month"></param>
        /// <param name="type">1:自发货，2：FBA</param>
        /// <returns></returns>
        public ActionResult ExportShippingIncoming(string month, int type)
        {
            try
            {
                var result = new List<dc_month_shipping_incoming>();
                var obj = new Services.FinanceReportServices().ListMonthShippingIncoming(month, type == 2);

                //组装数据
                obj = obj.OrderBy(a => a.platform_type).ToList();
                var groupPlatform = obj.GroupBy(a => a.platform_type);
                foreach (var item in groupPlatform)
                {
                    var platform = item.Key;

                    var groupWebSite = item.GroupBy(a => a.website);
                    foreach (var website in groupWebSite)
                    {
                        var groupCurrency = website.GroupBy(a => a.currency);
                        foreach (var c in groupCurrency)
                        {
                            foreach (var o in c)
                            {
                                result.Add(new dc_month_shipping_incoming
                                {
                                    platform_type = platform,
                                    currency = c.Key,
                                    financecategoryname = o.financecategoryname,
                                    amount = o.amount,
                                    month = o.month,
                                    website = website.Key
                                });
                            }
                        }

                        result.Add(new dc_month_shipping_incoming
                        {
                            platform_type = "合计",
                            currency = "",
                            financecategoryname = "",
                            amount = website.Sum(a => a.amount),
                            month = website.FirstOrDefault().month,
                        });
                    }
                }

                var colNames = new List<string> {"平台类型","站点","原币种","中文分类", "订单总金额" };

                var list = new List<string>();
                foreach (var item in result)
                {
                    list.Add(item.platform_type+"|"+item.website+"|"+item.currency+"|"+item.financecategoryname+"|"+item.amount);
                }

                var guid = Guid.NewGuid().ToString();
                var filename = month+$" {(type == 1? "OMS":"FBA")}发货收入" + DateTime.Now.ToString("yyyyMMddHHmmss");
                var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
                ToCSV(list, colNames, guid, filepath);

                var ms = new System.IO.MemoryStream();
                using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
                {
                    f.CopyTo(ms);
                }

                ms.Position = 0;
                return File(ms, "text/csv", filename + ".csv");
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    success = false,
                    msg = ex.Message,
                });
            }
        }


        /// <summary>
        /// 导出发货数据会计凭证
        /// </summary>
        /// <param name="month">月份</param>
        /// <param name="type">1:自发货，2：FBA</param>
        /// <returns></returns>
        public ActionResult ExportShippingIncomingCertficate(string month,int type)
        {
            var result = new List<dc_month_shipping_incoming>();
            var obj = new Services.FinanceReportServices().ListMonthShippingIncoming(month, type == 2);

            //组装数据
            obj = obj.OrderBy(a => a.platform_type).ToList();
            var groupPlatform = obj.GroupBy(a => a.platform_type);
            foreach (var item in groupPlatform)
            {
                var platform = item.Key;

                var groupWebSite = item.GroupBy(a => a.website);
                foreach (var website in groupWebSite)
                {
                    var groupCurrency = website.GroupBy(a => a.currency);
                    foreach (var c in groupCurrency)
                    {
                        result.Add(new dc_month_shipping_incoming
                        {
                            platform_type = platform,
                            currency = c.Key,
                            financecategoryname = "",
                            amount = website.Sum(a => a.amount),
                            month = website.FirstOrDefault().month,
                            website = website.Key,
                        });

                        foreach (var o in c)
                        {
                            result.Add(new dc_month_shipping_incoming
                            {
                                platform_type = platform,
                                currency = c.Key,
                                financecategoryname = o.financecategoryname,
                                amount = o.amount,
                                month = o.month,
                                website = website.Key
                            });
                        }

                    }

                }
            }

            var listPlatformSettings = new List<mPlatformAccountingSetting>
            {
                new mPlatformAccountingSetting{ platform_type="Aliexpress",cert_id="700",creator = "张滢萍",subject_no="1122",customer_no="02054",currency="USD",currencyname="美元",website="Global",text="速卖通平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Lazada",cert_id="701",creator = "张滢萍",subject_no="1122",customer_no="06006",currency="PHP",currencyname="菲律宾比索",website="PH",text="lazada平台菲律宾站点发货确认收入（PH)"},
                new mPlatformAccountingSetting{ platform_type="Lazada",cert_id="702",creator = "张滢萍",subject_no="1122",customer_no="06007",currency="MYR",currencyname="马来西亚-林吉特",website="MY",text="lazada平台马来西亚站点发货确认收入（MY）"},
                new mPlatformAccountingSetting{ platform_type="Lazada",cert_id="703",creator = "张滢萍",subject_no="1122",customer_no="06008",currency="THB",currencyname="泰铢",website="TH",text="lazada平台泰国站点发货确认收入（TH）"},
                new mPlatformAccountingSetting{ platform_type="Lazada",cert_id="704",creator = "张滢萍",subject_no="1122",customer_no="06009",currency="SGD",currencyname="新加坡元",website="SG",text="lazada平台新加坡站点发货确认收入（SG）"},
                new mPlatformAccountingSetting{ platform_type="Lazada",cert_id="705",creator = "张滢萍",subject_no="1122",customer_no="06010",currency="IDR",currencyname="印尼卢比",website="ID",text="lazada平台印尼站点发货确认收入（ID）"},
                new mPlatformAccountingSetting{ platform_type="Lazada",cert_id="706",creator = "张滢萍",subject_no="1122",customer_no="06011",currency="VND",currencyname="越南盾",website="VN",text="lazada平台越南站点发货确认收入（VN)"},


                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="707",creator = "张滢萍",subject_no="1122",customer_no="01104",currency="USD",currencyname="美元",website="US",text="亚马逊平台US站点 发货确认收入Seller"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="708",creator = "张滢萍",subject_no="1122",customer_no="01107",currency="GBP",currencyname="英镑",website="UK",text="亚马逊UK站点 发货确认收入seller"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="709",creator = "张滢萍",subject_no="1122",customer_no="01108",currency="EUR",currencyname="欧元",website="DE",text="亚马逊平台DE站点发货确认收入seller（DE)"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="710",creator = "张滢萍",subject_no="1122",customer_no="01109",currency="EUR",currencyname="欧元",website="ES",text="亚马逊ES站点发货确认收入seller（ES）"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="711",creator = "张滢萍",subject_no="1122",customer_no="01110",currency="EUR",currencyname="欧元",website="FR",text="亚马逊FR站点发货确认收入seller（FR)"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="712",creator = "张滢萍",subject_no="1122",customer_no="01111",currency="EUR",currencyname="欧元",website="IT",text="亚马逊IT站点平台 发货确认收入seller（IT)"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="713",creator = "张滢萍",subject_no="1122",customer_no="01112",currency="EUR",currencyname="欧元",website="NL",text="亚马逊NL站点 发货确认收入seller（NL)"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="714",creator = "张滢萍",subject_no="1122",customer_no="01115",currency="SEK",currencyname="瑞典克朗",website="SE",text="亚马逊SE站点发货确认收入SELLER(SE)"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="715",creator = "张滢萍",subject_no="1122",customer_no="01113",currency="JPY",currencyname="日元",website="JP",text="亚马逊JP站点发货确认收入seller"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="716",creator = "张滢萍",subject_no="1122",customer_no="01106",currency="AUD",currencyname="澳元",website="AU",text="亚马逊AU站点发货确认收入seller"},
                new mPlatformAccountingSetting{ platform_type="Amazon",cert_id="717",creator = "张滢萍",subject_no="1122",customer_no="01105",currency="CAD",currencyname="加元",website="CA",text="亚马逊平台CA站点 发货确认收入SELLER（CA）"},


                new mPlatformAccountingSetting{ platform_type="DHgate",cert_id="718",creator = "赵娟",subject_no="1122",customer_no="09006",currency="USD",currencyname="美元",website="Global",text="DHgate发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="JD",cert_id="719",creator = "赵娟",subject_no="1122",customer_no="29001",currency="THB",currencyname="泰铢",website="Global",text="JD平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Joom",cert_id="720",creator = "赵娟",subject_no="1122",customer_no="19033",currency="USD",currencyname="美元",website="Global",text="joom平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="OpenSky",cert_id="722",creator = "赵娟",subject_no="1122",customer_no="20001",currency="USD",currencyname="美元",website="US",text="opensky平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="PriceMinister",cert_id="723",creator = "赵娟",subject_no="1122",customer_no="16009",currency="EUR",currencyname="欧元",website="Global",text="PriceMinister平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Sears",cert_id="724",creator = "赵娟",subject_no="1122",customer_no="22001",currency="USD",currencyname="美元",website="US",text="Sears平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Shopee",cert_id="725",creator = "赵娟",subject_no="1122",customer_no="17032",currency="IDR",currencyname="印尼卢比",website="ID",text="Shopee平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Shopee",cert_id="726",creator = "赵娟",subject_no="1122",customer_no="17032",currency="MYR",currencyname="马来西亚-林吉特",website="MY",text="Shopee平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Shopee",cert_id="727",creator = "赵娟",subject_no="1122",customer_no="17032",currency="PHP",currencyname="菲律宾比索",website="PH",text="Shopee平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Shopee",cert_id="728",creator = "赵娟",subject_no="1122",customer_no="17032",currency="SGD",currencyname="新加坡元",website="SG",text="Shopee平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Shopee",cert_id="729",creator = "赵娟",subject_no="1122",customer_no="17032",currency="THB",currencyname="泰铢",website="TH",text="Shopee平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Shopee",cert_id="730",creator = "赵娟",subject_no="1122",customer_no="17032",currency="VND",currencyname="越南盾",website="Global",text="Shopee平台发货确认收入"},


                new mPlatformAccountingSetting{ platform_type="Shopify",cert_id="731",creator = "赵娟",subject_no="2203",customer_no="28003",currency="USD",currencyname="美元",website="Global",text="Shopify平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Walmart",cert_id="732",creator = "赵娟",subject_no="1122",customer_no="18006",currency="USD",currencyname="美元",website="US",text="Walmart平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="MARKETING",cert_id="733",creator = "赵娟",subject_no="1122",customer_no="14001",currency="CNY",currencyname="人民币",website="Global",text="线下客户发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="MARKETING",cert_id="734",creator = "赵娟",subject_no="1122",customer_no="14001",currency="USD",currencyname="美元",website="Global",text="线下客户发货确认收入"},


                new mPlatformAccountingSetting{ platform_type="Wish",cert_id="735",creator = "赵娟",subject_no="1122",customer_no="5021",currency="CNY",currencyname="人民币",website="Global",text="wish平台发货确认收入"},
                //new mPlatformAccountingSetting{ platform_type="Ebay",cert_id="736",creator = "赵娟",subject_no="1122",customer_no="030j4",currency="GBP",currencyname="英镑",website="UK"},
                new mPlatformAccountingSetting{ platform_type="Ebay",cert_id="737",creator = "赵娟",subject_no="2203",customer_no="030j3",currency="AUD",currencyname="澳元",website="",text="eBay-paypal平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Ebay",cert_id="738",creator = "赵娟",subject_no="2203",customer_no="030j3",currency="EUR",currencyname="欧元",website="",text="eBay-paypal平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Ebay",cert_id="739",creator = "赵娟",subject_no="2203",customer_no="030j3",currency="GBP",currencyname="英镑",website="",text="eBay-paypal平台发货确认收入"},
                new mPlatformAccountingSetting{ platform_type="Ebay",cert_id="740",creator = "赵娟",subject_no="2203",customer_no="030j3",currency="USD",currencyname="美元",website="",text="eBay-paypal平台发货确认收入"},


                new mPlatformAccountingSetting{ platform_type="Etsy",cert_id="741",creator = "张滢萍",subject_no="2203",customer_no="30001",currency="USD",currencyname="美元",website="US",text="Etsy平台发货确认收入"},

            };

            var listFinanceCategory = new List<mFinanceCategorySubjectNo> { 
                new mFinanceCategorySubjectNo{name="精油类",subject_no="60010101"},
                new mFinanceCategorySubjectNo{name="服装类",subject_no="60010106"},
                new mFinanceCategorySubjectNo{name="电子产品类",subject_no="60010102"},
                new mFinanceCategorySubjectNo{name="美容美甲类",subject_no="60010104"},
                new mFinanceCategorySubjectNo{name="家居用品类",subject_no="60010103"},
            };


            var colNames = new List<string> { "凭证ID", "会计年", "会计期间", "制单日期", "凭证类别", 
                "凭证号", "制单人", "所附单据数", "备注1", "备注2", 
                "科目编码", "摘要", "结算方式编码","票据号", "票据日期",
                "币种名称","汇率","单价","借方数量","贷方数量",
                "原币借方","原币贷方","借方金额","贷方金额","部门编码",
                "职员编码","客户编码","供应商编码","项目大类编码","项目编码",
                "业务员"
            };

            var listRate = GetFundCurrencyRate(month);
            if(listRate.Count==0)
            {
                return Json(new { 
                    success=false,
                    msg = "从资金系统获取汇率失败"
                });
            }

            var day = DateTime.Parse(month + "-01");
            var list = new List<string>();
            foreach (var item in result)
            {
                
                var ID = "";
                var Month = day.Month;
                var Year = day.Year;
                var Date = day.AddMonths(1).AddDays(-1).ToString("yyyy.MM.dd");
                var Creator1 = "";
                var SubjectNo = "";
                var CustomerNo = "";
                var currencyName = "";
                decimal rate = 0;
                var text = "";

                var setting = listPlatformSettings.Where(a => a.platform_type == item.platform_type && a.website == item.website && a.currency == item.currency).FirstOrDefault();
                if(setting==null && item.platform_type=="Ebay")
                {
                    setting = listPlatformSettings.Where(a => a.platform_type == item.platform_type && a.currency == item.currency).FirstOrDefault();
                }
                else if (setting == null && item.platform_type == "MARKETING" && item.currency=="USD")
                {
                    setting = listPlatformSettings.Where(a => a.platform_type == item.platform_type && a.currency == item.currency).FirstOrDefault();
                }

                if (setting!=null)
                {
                    ID = setting.cert_id;
                    Creator1 = setting.creator;
                    SubjectNo = setting.subject_no;
                    CustomerNo = setting.customer_no;
                    currencyName = setting.currencyname;

                    text = setting.text;
                }

                var exchangeRate = listRate.Where(a => a.currency == currencyName).FirstOrDefault();
                if(exchangeRate!=null)
                {
                    rate = exchangeRate.exchange_rate??0;
                }


                //判断是否合计
                if (string.IsNullOrEmpty(item.financecategoryname))
                {
                    list.Add($@"{ID}|{Year}|{Month}|{Date}|记|
                            {ID}|{Creator1}||||
                            {SubjectNo}|{text}||||
                            {currencyName}|{rate}||||
                            {item.amount}||{item.amount*rate}|||
                            ||=""{CustomerNo}""|||
                            "
                            );
                }
                else
                {
                    var subjectSetting = listFinanceCategory.Where(a => a.name == item.financecategoryname).FirstOrDefault();
                    if(subjectSetting !=null)
                    {
                        SubjectNo = subjectSetting.subject_no;
                    }

                    list.Add($@"{ID}|{Year}|{Month}|{Date}|记|
                            {ID}|{Creator1}||||
                            {SubjectNo}|{text}||||
                            {currencyName}|{rate}||||
                            |{item.amount}||{item.amount*rate}||
                            ||||=""{CustomerNo}""|
                            "
                            );
                }

                
            }

            var guid = Guid.NewGuid().ToString();
            var filename = month + $" {(type == 1 ? "OMS" : "FBA")}发货收入凭证" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, guid, filepath);

            var ms = new System.IO.MemoryStream();
            using (var f = new System.IO.FileStream(filepath + guid + ".csv", System.IO.FileMode.Open))
            {
                f.CopyTo(ms);
            }

            ms.Position = 0;
            return File(ms, "text/csv", filename + ".csv");
        }

        /// <summary>
        /// 获取资金系统的每月汇率
        /// </summary>
        /// <param name="month"></param>
        /// <returns></returns>
        private List<mFundExchangRate> GetFundCurrencyRate(string month)
        {
            var result = Common.HttpHelper.NetHelper.Request("http://fund.bailuntec.com/api/GetExchangeRate?month=" + month);

            var json = JsonConvert.DeserializeObject<FundExchangRate_Response>(result);
            if(json.msg=="成功")
            {
                return json.data;
            }
            else
            {
                return new List<mFundExchangRate>();
            }

        }

        #endregion

    }

    class mHappenAmount {
        /// <summary>
        /// 1 管理成本  2 头程物流费   3 尾程物流费  4 一级供应商采购   5 二级供应商采购
        /// </summary>
        public int type { get; set; }

        public string typename { get; set; }

        public DateTime start { get; set; }

        public DateTime end { get; set; }

        public string day { get; set; }

        public List<decimal> list {get;set;}
    }
    
}