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.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;
        }

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

        public ActionResult Index2()
        {

            return View();
        }

        /// <summary>
        /// 获取资产负债表数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult IndexJson(int type, DateTime day, int paycompanyvalue)
        {
            var date = day;

            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.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 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;
            }

            return Json(new
            {
                success = list.Count > 0,
                msg = list.Count == 0 ? "暂无数据" : "",
                data = list
            });
        }

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

            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.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 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 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>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AdministrativeCostJson(int t, DateTime start,DateTime end,int? paycompanyid)
        {
            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);

            var list = new Services.FinanceReportServices().ListOtherCost(url);
            var listValue = new List<Tuple<string, List<decimal>>>();
            var listCol = new List<string>();
            var listColVal = new List<int>();

            if (list.Count > 0)
            {
                if (t == 2)  //按付款主体
                {
                    listCol = list.GroupBy(a => a.companyName).Select(p => p.Key).OrderBy(a=>a).ToList();
                    
                }
                else  //按部门
                {
                    listCol = list.GroupBy(a => a.departmentName).Select(p => p.Key).ToList();
                }

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

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

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

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

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

                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;
                        }
                    }
                }

                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.amountRmb)+ listInterest.Sum(a=>a.RepayInterestRMB), 2)
            });
        }

        [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().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.companyName == listCol[i])
                            {
                                var obj = listValue.Where(a => a.Item1 == item.feeSubType).FirstOrDefault();

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

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

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

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

            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)
        {
            ViewBag.start = start;
            ViewBag.end = end;
            ViewBag.paycompanyid = paycompanyid??-1;
            ViewBag.headname = headname;
            ViewBag.categoryname = categoryname;
            ViewBag.type = type;
            ViewBag.isSub = issub;

            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)
        {
            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
                {
                    var val = -1;
                    var objPayCompany = new Services.FinanceReportServices().GetPayCompanyByName(headname);

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

                    url += "&companyValue="+ val;
                }
                
            }

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

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

            if (obj.Count > 0)
            {
                var m = new Models.Api.mOtherFee {
                    no = "",
                    companyName = "",
                    amount = obj.Sum(a => a.amount),
                    amountRmb = obj.Sum(a => a.amountRmb),
                    currency = "",
                    departmentName = "",
                    feeSubType = "",
                    feeSuperType = "合计",
                };

                obj.Add(m);
            }

            var list = obj.Select(a => new {
                amount = a.amount.ToString("###,###.##"),
                amountRmb = a.amountRmb.ToString("###,###.##"),
                a.companyName,
                a.currency,
                a.departmentName,
                a.feeSubType,
                a.feeSuperType,
                a.no,
                a.manageCostType,
                a.receiveUnit,
                a.reason,
                payTime = a.payTime.HasValue?a.payTime.Value.ToString("yyyy-MM-dd HH:mm:ss"):""
            }).ToList();
            

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

        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();
        }

        /// <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)
            {
                cwurl += "&CompanyVal=" + paycompanyid.Value;
            }

            if (type == 1 && headname == "财务部" || type==2)
            {
                //利息支出
                listInterest = new Services.FinanceReportServices().ListInterestExpense(cwurl);
            }
            
            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 });
        }

        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)
            {
                cwurl += "&CompanyVal=" + paycompanyid.Value;
            }

            if (type == 1 && headname == "财务部" || type == 2)
            {
                //利息支出
                listInterest = new 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+"|"+(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)
        {
            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;
                }

            }

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

            var colNames = new List<string> {"部门名称","付款主体名称","父级分类", "子分类", "金额",
                                             "币种", "人民币金额" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.departmentName + "|" + item.companyName + "|" + item.feeSuperType + "|" + item.feeSubType + "|" + item.amount + "|" +
                    item.currency + "|" + item.amountRmb
                    );
            }

            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)
        {
            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 colNames = new List<string> {"部门名称","付款主体名称","父级分类", "子分类", "金额",
                                             "币种", "人民币金额" };

            var list = new List<string>();
            foreach (var item in obj)
            {
                list.Add(item.departmentName+"|"+item.companyName+"|"+item.feeSuperType+"|"+item.feeSubType+"|"+item.amount+"|"+
                    item.currency+"|"+item.amountRmb
                    );
            }

            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.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 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 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");
        }

        #endregion

        #region 平台余额

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

        /// <summary>
        /// 平台账号余额管理列表数据
        /// </summary>
        /// <returns></returns>
        public string ListAccoutBalanceCountJson(BtTableParameter request, DateTime day, string platformcode)
        {

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

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

            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);


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

            var obj = list.Select(p => new {
                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.puttime.ToString("yyyy-MM-dd")
            });
            
            return JsonConvert.SerializeObject(new { total = obj.Count(), rows = obj,count_row=countM });
        }

        /// <summary>
        /// 上传平台账号余额明细
        /// </summary>
        /// <returns></returns>
        public JsonResult UpdateBalanceCount()
        {
            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();

                        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 = "币种不能为空！"
                            });
                        }

                        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);

                        //区分销售和财务
                        if ((row["平台每日到账额"].ToString() == "")) //销售
                        {
                            var amount = decimal.Parse(row["总余额"].ToString().Trim());
                            var userable = decimal.Parse(row["可用余额"].ToString().Trim());
                            var freezeamount = decimal.Parse(row["冻结余额"].ToString().Trim());
                            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 = "",
                                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 = puttime,
                                notes = notes,
                                saleday = saleday,
                                fromsource = "",
                                amount_sales = dailysale,
                                withdraw_amount = (m!=null?m.withdraw_amount:0),
                                before_balance = (m!=null?m.before_balance:0),
                            });

                        }
                        else
                        {
                            var withdrawamount = decimal.Parse(row["平台每日到账额"].ToString());

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

                            list.Add(new dc_platform_balance {
                                id = (m!=null?m.id:0),
                                account = "",
                                currency = currency,
                                amount = (m!=null?m.amount:0),
                                amount_rmb = (m!=null?m.amount_rmb:0),
                                amount_sales = (m!=null?m.amount_sales:0),
                                before_balance = (m!=null?m.before_balance:0),
                                day = day,
                                delstatus = 0,
                                exchangerate = rate.Item2,
                                freeze_amount =(m!=null?m.freeze_amount:0),
                                freeze_amount_rmb=(m!=null?m.freeze_amount_rmb:0),
                                fromsource = (m!=null?m.fromsource:""),
                                notes = (m!=null?m.notes:""),
                                paycompanyid = (m!=null?m.paycompanyid:0),
                                platformcode = objplatform.english_name,
                                platformname = objplatform.china_name,
                                puttime = (m!=null?m.puttime: DateTime.Parse("1999-01-01")),
                                saleday  = (m!=null?m.saleday: DateTime.Parse("1999-01-01")),
                                userable_amount = (m!=null?m.userable_amount:0),
                                userable_amount_rmb = (m!=null?m.userable_amount_rmb:0),
                                withdraw_amount = withdrawamount,
                            });
                        }
                        
                        //if (string.IsNullOrEmpty(account))
                        //{
                        //    return Json(new
                        //    {
                        //        success = false,
                        //        msg = "平台帐号不能为空！",
                        //    });
                        //}
                        
                    }
                    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()
        {
            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 code)
        {
            var services = new Services.FinanceReportServices();
            var total = 0;
            var list = services.List(day, code, 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,
                p.fromsource,
            });

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

        }

        /// <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>
        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]
        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 listInterest = new Bailun.DC.Services.FinanceReportServices().ListInterestExpense(cwurl);

            //管理成本
            var list = new Bailun.DC.Services.FinanceReportServices().ListOtherCost(url);

            var CostCount = 0M;
            var InterestCount = 0M;

            if (list.Count > 0)
            {
                CostCount = list.Sum(a => a.amountRmb);

            }

            if (listInterest.Count > 0)
            {
                InterestCount = listInterest.Sum(a => a.RepayInterestRMB);
            }

            ViewBag.CostCount = CostCount.ToString("N2");
            ViewBag.InterestCount = InterestCount.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");
        }

        #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,

                });
            }
        }

        /// <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]
        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 进销存报表

        /// <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>
        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>
        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 AliExpressCharge()
        {
            return View();
        }

        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]
        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]
        public JsonResult ListMonthSaleProfit(string month)
        {
            try
            {
                var obj = new Services.FinanceReportServices().ListMonthSaleProfit(month, "");

                var list = obj.Select(a => new
                {
                    amount_sale = a.amount_sale.ToString("N2"),
                    cost_sale = (a.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+a.pt_platform_logistics_fee_).ToString("N2"),
                    a.pt_platform_logistics_fee_,
                    pt_platform_ad_subscribe_fee = (a.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+a.ls_head_cost_).ToString("N2"),
                    a.ls_head_cost_,
                    ls_tail_cost = (a.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_finish_wh = a.manager_cost_finish_wh.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.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>>();
                head.Add(new Tuple<string, string, string>("amount_sale", "<td style=\"font-weight:bold;text-align:center;\">销售额</td>", "<span class=\"lbl_amount_sale\">{amount_sale}</span>"));
                head.Add(new Tuple<string, string, string>("cost_sale", "<td style=\"font-weight:bold;text-align:center;\">成本</td>", "<span class=\"lbl_cost_sale\">{cost_sale}</span><a class=\"cost_sale_\" onclick=\"Edit('cost_sale_','成本','{month}','{cost_sale_}')\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("pt_count", "<td style=\"font-weight:bold;text-align:center;\">平台扣费及退款</td>", "<span class=\"lbl_pt_count\">{pt_count}</span>"));
                head.Add(new Tuple<string, string, string>("pt_platformfee", "<td>平台费</td>", "<span class=\"lbl_pt_platformfee\">{pt_platformfee}</span>"));
                head.Add(new Tuple<string, string, string>("pt_ebay_postingfee", "<td>ebay刊登费</td>", "<span class=\"lbl_pt_ebay_postingfee\">{pt_ebay_postingfee}</span>"));
                head.Add(new Tuple<string, string, string>("pt_paypal_fee", "<td>paypal费用</td>", "<span class=\"lbl_pt_paypal_fee\">{pt_paypal_fee}</span>"));
                head.Add(new Tuple<string, string, string>("pt_platform_logistics_fee", "<td>平台的物流费</td>", "<span class=\"lbl_pt_platform_logistics_fee\">{pt_platform_logistics_fee}</span><a class=\"pt_platform_logistics_fee_\" onclick=\"Edit('pt_platform_logistics_fee_','平台的物流费','{month}','{pt_platform_logistics_fee_}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("pt_platform_ad_subscribe_fee", "<td>广告及宣传费-订阅费</td>", "<span class=\"lbl_pt_platform_ad_subscribe_fee\">{pt_platform_ad_subscribe_fee}</span><a class=\"pt_platform_ad_subscribe_fee_\" onclick=\"Edit('pt_platform_ad_subscribe_fee_','广告及宣传费-订阅费','{month}','{pt_platform_ad_subscribe_fee_}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("pt_platform_storage_fee", "<td>平台的仓储费</td>", "<span class=\"lbl_pt_platform_storage_fee\">{pt_platform_storage_fee}</span><a class=\"pt_platform_storage_fee\" onclick=\"Edit('pt_platform_storage_fee','平台的仓储费','{month}','{pt_platform_storage_fee}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("pt_refund_amount", "<td>退款</td>", "<span class=\"lbl_pt_refund_amount\">{pt_refund_amount}</span>"));
                head.Add(new Tuple<string, string, string>("pt_incoming", "<td style=\"font-weight:bold;\">回款</td>", "<span class=\"lbl_pt_incoming\">{pt_incoming}</span>"));
                head.Add(new Tuple<string, string, string>("ls_count", "<td style=\"font-weight:bold;text-align:center;\">物流仓储费用</td>", "<span class=\"lbl_ls_count\">{ls_count}</span>"));
                head.Add(new Tuple<string, string, string>("ls_head_cost", "<td>头程运输</td>", "<span class=\"lbl_ls_head_cost\">{ls_head_cost}</span><a class=\"ls_head_cost_\" onclick=\"Edit('ls_head_cost_','头程运输','{month}','{ls_head_cost_}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("ls_tail_cost", "<td>尾程物流</td>", "<span class=\"lbl_ls_tail_cost\">{ls_tail_cost}</span><a class=\"ls_tail_cost_\" onclick=\"Edit('ls_tail_cost_','尾程物流','{month}','{ls_tail_cost_}')\" val =\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("ls_oversea_storage", "<td>海外仓的仓储费</td>", "<span class=\"lbl_ls_oversea_storage\">{ls_oversea_storage}</span><a class=\"ls_oversea_storage\" onclick=\"Edit('ls_oversea_storage','海外仓的仓储费','{month}','{ls_oversea_storage}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("ls_platform_operation_fee", "<td>平台操作费</td>", "<span class=\"lbl_ls_platform_operation_fee\">{ls_platform_operation_fee}</span>"));
                head.Add(new Tuple<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>"));
                head.Add(new Tuple<string, string, string>("sale_profit", "<td style=\"font-weight:bold;text-align:center;\">销售利润</td>", "<span class=\"lbl_sale_profit\">{sale_profit}</span>"));
                head.Add(new Tuple<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>"));
                head.Add(new Tuple<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>"));
                head.Add(new Tuple<string, string, string>("handlingcharges", "<td>处理费</td>", "<span class=\"lbl_handlingcharges\">{handlingcharges}</span><a class=\"handlingcharges\" onclick=\"Edit('handlingcharges','处理费','{month}','{handlingcharges}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("payfor_platform_related_fee", "<td>直接支付的与销售平台相关费用</td>", "<span class=\"lbl_payfor_platform_related_fee\">{payfor_platform_related_fee}</span><a class=\"payfor_platform_related_fee\" onclick=\"Edit('payfor_platform_related_fee','直接支付的与销售平台相关费用','{month}','{payfor_platform_related_fee}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<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>"));
                head.Add(new Tuple<string, string, string>("manager_cost_hkbailun", "<td>管理成本-香港百伦（不含直接支付的与销售平台相关的费用）</td>", "<span class=\"lbl_manager_cost_hkbailun\">{manager_cost_hkbailun}</span><a class=\"manager_cost_hkbailun\" onclick=\"Edit('manager_cost_hkbailun','管理成本-香港百伦（不含直接支付的与销售平台相关的费用）','{month}','{manager_cost_hkbailun}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("manager_cost_gzbailun", "<td>管理成本-广州百伦</td>", "<span class=\"lbl_manager_cost_gzbailun\">{manager_cost_gzbailun}</span><a class=\"manager_cost_gzbailun\" onclick=\"Edit('manager_cost_gzbailun','管理成本-广州百伦','{month}','{manager_cost_gzbailun}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("manager_cost_finish_wh", "<td>管理成本-成品仓（不含直接支付的与销售平台相关的费用）</td>", "<span class=\"lbl_manager_cost_finish_wh\">{manager_cost_finish_wh}</span><a class=\"manager_cost_finish_wh\" onclick=\"Edit('manager_cost_finish_wh','管理成本-成品仓（不含直接支付的与销售平台相关的费用）','{month}','{manager_cost_finish_wh}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("finance_fee", "<td>财务费用</td>", "<span class=\"lbl_finance_fee\">{finance_fee}</span><a class=\"finance_fee\" onclick=\"Edit('finance_fee','财务费用','{month}','{finance_fee}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<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>"));
                head.Add(new Tuple<string, string, string>("business_profit", "<td style=\"font-weight:bold;text-align:center;\">营业利润</td>", "<span class=\"lbl_business_profit\">{business_profit}</span>"));
                head.Add(new Tuple<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>"));
                head.Add(new Tuple<string, string, string>("other_incoming", "<td>加：其他收入</td>", "<span class=\"lbl_other_incoming\">{other_incoming}</span><a class=\"other_incoming\" onclick=\"Edit('other_incoming','加：其他收入','{month}','{other_incoming}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("nonbusiness_income", "<td>加：营业外收入</td>", "<span class=\"lbl_nonbusiness_income\">{nonbusiness_income}</span><a class=\"nonbusiness_income\" onclick=\"Edit('nonbusiness_income','加：营业外收入','{month}','{nonbusiness_income}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("nonbusiness_pay", "<td>减：营业外支出</td>", "<span class=\"lbl_nonbusiness_pay\">{nonbusiness_pay}</span><a class=\"nonbusiness_pay\" onclick=\"Edit('nonbusiness_pay','减：营业外支出','{month}','{nonbusiness_pay}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<string, string, string>("actual_profit", "<td style=\"font-weight:bold;text-align:center;\">实际利润</td>", "<span class=\"lbl_actual_profit\">{actual_profit}</span>"));
                head.Add(new Tuple<string, string, string>("participation_in_profit", "<td>减：分红</td>", "<span class=\"lbl_participation_in_profit\">{participation_in_profit}</span><a class=\"participation_in_profit\" onclick=\"Edit('participation_in_profit','减：营业外支出','{month}','{participation_in_profit}')\" val=\"\">编辑</a>"));
                head.Add(new Tuple<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>"));

                return Json(new {
                    success = true,
                    msg = "",
                    data = list,
                    head = head
                });
            }
            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
            });
        }


        #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;}
    }
    
}