using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Bailun.DC.Models;
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();
        }

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


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

        /// <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.AddMonths(-1);
            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";

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

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

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

            if (list.Count > 0)
            {
                if (t == 2)  //按付款主体
                {
                    listCol = list.GroupBy(a => a.companyName).Select(p => p.Key).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>();

                foreach (var item in listValue)
                {
                    for (var i = 0; i < item.Item2.Count; i++)
                    {
                        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 = list.Sum(a=>a.amountRmb)
            });
        }

        [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
                {
                    url += "&companyValue="+headname;
                }
                
            }

            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 {
                    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,
            }).ToList();
            

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

        /// <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 filename = categoryname+"+"+headname+" 管理成本明细" + DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\";
            ToCSV(list, colNames, filename, filepath);

            return File("~/Files/Report/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + filename + ".csv", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 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 filename = "管理成本明细"+DateTime.Now.ToString("yyyyMMddHHmmss");
            var filepath = _hostingEnvironment.WebRootPath + "\\Files\\Report\\"+DateTime.Now.ToString("yyyy-MM-dd")+"\\";
            ToCSV(list, colNames, filename, filepath);

            return File("~/Files/Report/"+ DateTime.Now.ToString("yyyy-MM-dd") + "/" + filename + ".csv", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", 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 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 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});
        }

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

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

        /// <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)
        {
            ViewBag.date = date;
            ViewBag.paycompanyid = paycompanyid;
            return View();
        }

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

            //var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePay(request,date, paycompanyid, 1,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 });
        }

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

        /// <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)
        {

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

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

            var paycompany = _services.GetPayCompany(paycompanyid);
            var obj = _services.ListPrePay(request,date, paycompanyid, 0,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});
        }

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


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

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

        #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+"】在"+day+"已经导入了数据，请删除该数据后重新导入。"
                                });
                            }

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

        #endregion

    }
}