using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
using XYY.Service.Standard.Finance;
using XYY.Core.Standard.AliYun;
using XYY.Model.Standard.Finance;
using XYY.Core.Standard.Mvc;
using XYY.Common.Standard;
using System.IO;
using XYY.Model.Standard;
using XYY.Service.Standard.Finance.Model;
using XYY.Authentication.Standard;
using Microsoft.AspNetCore.Authorization;

namespace XYY.Api.Finance.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class FinanceController : ApiControllerBase
    {
        ILadingBillService _ladingBillService;
        IAliYunPostFileSerivce _aliYunPostFileSerivce;
        ICustomerLadingBillCostService _customerLadingBillCostApp;


        public FinanceController(ILadingBillService ladingBillService
            , IAliYunPostFileSerivce aliYunPostFileSerivce,
           ICustomerLadingBillCostService customerLadingBillCostApp
          )
        {
            _ladingBillService = ladingBillService;
            _aliYunPostFileSerivce = aliYunPostFileSerivce;
            _customerLadingBillCostApp = customerLadingBillCostApp;
        }

        public async Task<IActionResult> GetQtys()
        {
            var billQtys = await _ladingBillService.GetGroupCounts();
            if (!billQtys.Any(x => x.Key == 0))
                billQtys.Add(0, 0);
            if (!billQtys.Any(x => x.Key == 1))
                billQtys.Add(1, 0);
            if (!billQtys.Any(x => x.Key == 2))
                billQtys.Add(2, 0);

            return Ok(billQtys.Select(x => new { Key = x.Key, Value = x.Value }).ToList());
        }

        [HttpPost]
        public async Task<IActionResult> GetFee(CustomerLadingBillSearchParam search)
        {
            if (search?.LaddingBills?.Any() != true)
                throw new Exception("参数不能为空");

            var content = await _customerLadingBillCostApp.DownloadLadingBillCost(search);
            return File($"提单_{DateTime.Now.ToString("yyyyMMddHHhhss")}.xlsx", content);
        }



        [HttpGet]
        public async Task<IActionResult> GetLadingDetails(string billNumber)
        {
            var content = await _customerLadingBillCostApp.DownloadLadingBillDetailCost(billNumber);
            return File($"提单{billNumber}明细.xlsx", content);
        }

        [HttpGet]
        public async Task<IActionResult> DownloadFile(int id, int type)
        {
            byte[] data = await _ladingBillService.OutBill(id, type);
            return File(DateTime.Now.ToString_yyyyMMddHHmm() + ".xls", data);
        }

        [HttpPost]
        public async Task<IActionResult> GetData(QueryModel queryModel)
        {
            if (queryModel.QueryParamer.Any(x => x.Filed == "BillType" && x.Value == "1"))
            {
                //所属划分
                //查找用户拥有的权限
                var u = User.GetUserContent();
                if (u.Roles.Any(x => x == "头程-朗天" || x == "头程-运控"))
                {
                    var list = u.Roles.Where(x => x == "头程-朗天" || x == "头程-运控").ToList();
                    queryModel.QueryParamer.Add(new QueryParamer
                    {
                        Filed = "DataBindRole",
                        Value = String.Join(",", list.ToArray()),
                        Method = "In"
                    });
                }
                else
                {
                    throw new Exception("无数据权限。请联系管理员添加");
                }
            }

            var data = await _ladingBillService.GetData(queryModel);
            return Ok(data);
        }

        public async Task<IActionResult> GetBillInfo(string billNumber)
        {
            var view = await _ladingBillService.GetInfo(billNumber);
            return Ok(view);
        }

        public async Task<IActionResult> PostStart(Finance_Logistics_LadingBill ladingBill)
        {
            await _ladingBillService.StartFrist(ladingBill.BillNumber, ladingBill.FristFileUrl, ladingBill.FristFee);
            return Ok();
        }

        public async Task<IActionResult> PostStart2(FinanceLadingBillDto dto)
        {
            if (dto.BillType == BillType.客户)
            {
                var u = User.GetUserContent();
                if (u.Roles.Any(x => x == "头程-朗天" || x == "头程-运控"))
                {
                    if (u.Roles.Where(x => x == "头程-朗天" || x == "头程-运控").Count() > 1)
                    {
                        throw new Exception("操作人不应有多个所属，请联系管理员处理");
                    }
                    else
                    {
                        dto.DataBindRole = u.Roles.Where(x => x == "头程-朗天" || x == "头程-运控").First();
                    }
                }
                else
                {
                    throw new Exception("无数据权限。请联系管理员添加");
                }
            }
            await _ladingBillService.StartFrist(dto);
            return Ok();
        }

        [HttpGet]
        public async Task<IActionResult> GetIncidentals(int billId, int type)
        {
            var data = await _ladingBillService.GetIncidentals(billId, type);
            return Ok(data);
        }

        public async Task<IActionResult> PostEditBill(FinanceLadingBillDto ladingBill)
        {
            await _ladingBillService.Update(ladingBill);
            return Ok();
        }

        public async Task<IActionResult> PostPass(string billNumber)
        {
            await _ladingBillService.Review(billNumber, true);
            return Ok();
        }

        public async Task<IActionResult> PostReject(string billId)
        {
            await _ladingBillService.Review(billId, false);
            return Ok();
        }

        public class InputLadingBillDto
        {
            public string url
            {
                get; set;
            }

            public FinanceIncidentalTypeEnum feeType
            {
                get; set;
            }
        }

        readonly string tempPath = AppContext.BaseDirectory + "\\temp";
        [HttpPost]
        public async Task<IActionResult> PostInputFile(InputLadingBillDto dto)
        {
            //string filePath = tempPath + "\\" + Guid.NewGuid() + ".xlsx";
            System.Net.WebClient webClient = new System.Net.WebClient();
            byte[] data = webClient.DownloadData(dto.url);
            //System.IO.File.Delete(filePath);
            await _ladingBillService.ConvertLoadingBatchInputDto(data, dto.feeType);
            return Ok();
        }
        [HttpPost]
        public IActionResult UpdateLoadFile()
        {
            var filelist = Request.Form.Files;

            if (filelist != null && filelist.Count > 0)
            {
                var file = filelist[0];
                string url = _aliYunPostFileSerivce.PostHttpFile(file.OpenReadStream(), file.FileName);
                return Ok(new { url = url });
            }
            else
            {
                return Error("请上传一个文件");
            }
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetEFFinanceBillGroup(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetEFFinanceBillGroup(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId));
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetEFFinanceBillGroupAsCustomer(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetEFFinanceBillGroupAsCustomer(serach.StartDate, serach.EndDate));
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetEFFinanceBillGroupAsChannel(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetEFFinanceBillGroupAsChannel(serach.StartDate, serach.EndDate));
        }


        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetEFFinanceBillDetails(BillSerach serach)
        {
            var list = await _ladingBillService.GetEFFinanceBillDetails(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId);
            return CSVFile("帐单明细.xls", list);
        }




        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetFinanceBillGroup(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetFinanceBillGroup(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId));
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetFinanceBillGroupAsCustomer(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetFinanceBillGroupAsCustomer(serach.StartDate, serach.EndDate));
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetFinanceBillGroupAsChannel(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetFinanceBillGroupAsChannel(serach.StartDate, serach.EndDate));
        }


        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetFinanceBillDetails(BillSerach serach)
        {
            var list = await _ladingBillService.GetFinanceBillDetails(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId);
            return CSVFile("帐单明细.xls", list);
        }

        private SearchFinanceReportParam CreateFinanceReportParam(QueryModel queryModel)
        {
            SearchFinanceReportParam param = new SearchFinanceReportParam();
            if (queryModel?.QueryParamer?.Any() == true)
            {
                foreach (var p in queryModel.QueryParamer)
                {
                    if (p.Filed == "CustomerId" && int.TryParse(p.Value, out int customerId))
                    {
                        param.CustomerId = customerId;
                    }
                    else if (p.Filed == "CreateOrderChannelId" && int.TryParse(p.Value, out int CreateOrderChannelId))
                    {
                        param.CreateOrderChannelId = CreateOrderChannelId;
                    }
                    else if (p.Filed == "BranchCompanyId" && int.TryParse(p.Value, out int BranchCompanyId))
                    {
                        param.BranchCompanyId = BranchCompanyId;
                    }
                    else if (p.Filed == "称重时间" && p.Method == "Gr" && DateTime.TryParse(p.Value, out DateTime receiveTimeStart))
                    {
                        param.ReceiveTimeStart = receiveTimeStart;
                    }
                    else if (p.Filed == "称重时间" && p.Method == "Le" && DateTime.TryParse(p.Value, out DateTime receiveTimeEnd))
                    {
                        param.ReceiveTimeEnd = receiveTimeEnd;
                    }
                    else if (p.Filed == "跟踪号" && !string.IsNullOrWhiteSpace(p.Value))
                    {
                        var arr = p.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
                        param.TrackingNumbers = arr.ToList();
                    }
                    else if (p.Filed == "订单号" && !string.IsNullOrWhiteSpace(p.Value))
                    {
                        var arr = p.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
                        param.TransferNumbers = arr.ToList();
                    }
                    else if (p.Filed == "提单号" && !string.IsNullOrWhiteSpace(p.Value))
                    {
                        var arr = p.Value.Split(',', StringSplitOptions.RemoveEmptyEntries);
                        param.LadingBillNumbers = arr.ToList();
                    }
                }
            }
            return param;
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> DownFinanceBranchProfitReport(QueryModel queryModel)
        {
            var param = CreateFinanceReportParam(queryModel);
            var list = await _ladingBillService.DownFinanceBranchProfitReport(param);
            return CSVFile("财务报表.xls", list);
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> DownFinanceReport(QueryModel queryModel)
        {
            var param = CreateFinanceReportParam(queryModel);
            var list = await _ladingBillService.DownFinanceReport(param);
            return CSVFile("财务报表.xls", list);
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetFinanceReportDetails(QueryModel queryModel)
        {
            var list = await _ladingBillService.QueryFinanceReport(queryModel);
            return Ok(list);
        }

        [AllowAnonymous]
        public async Task<IActionResult> GetIncidentalGroupData(QueryModel queryModel)
        {
            var list = await _ladingBillService.GetIncidentalGroupData(queryModel);
            return Ok(list);
        }

        [AllowAnonymous]
        public async Task<IActionResult> GetIncidentalGroup()
        {
            var list = (await _ladingBillService.GetIncidentalGroup()).Select(x => new { Key = x.Key, Value = x.Value });
            return Ok(list);
        }

        public async Task<IActionResult> GetFinanceBillDetailWeightDifferenceGroup(BillSerach serach)
        {
            var list = await _ladingBillService.GetFinanceBillDetailWeightDifferenceGroup(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId);
            return Ok(list);
        }

        public async Task<IActionResult> OutFinanceBillDetailWeightDifferenceDetails(BillSerach serach)
        {
            byte[] financeBillDetailWeightDifferenceDetails = await _ladingBillService.OutFinanceBillDetailWeightDifferenceDetails(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId);
            return CSVFile("差异明细.xlsx", financeBillDetailWeightDifferenceDetails);
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetBill(BillSerach serach)
        {
            return Ok(await _ladingBillService.GetView_FinanceBills(serach.ChannelId, serach.CustomerId, serach.StartDate, serach.EndDate, serach.SettlementCompany));
        }

        [HttpGet]
        [HttpPost]
        public async Task<IActionResult> GetBillDetail(BillSerach serach)
        {
            var list = await _ladingBillService.GetBillsDetails(serach.ChannelId, serach.CustomerId, serach.StartDate, serach.EndDate, serach.SettlementCompany);
            return CSVFile("帐单明细.csv", list);
        }

        public async Task<IActionResult> postPayment(PostPayment postPayment)
        {
            await _ladingBillService.PostPayment(postPayment.Id, postPayment.PostPaymentFee, postPayment.Type, postPayment.Remark);
            return Ok();
        }

        public async Task<IActionResult> GetLadingBillLogs(int billId, FinanceIncidentalTypeEnum type)
        {
            var list = await _ladingBillService.GetLadingBillLogs(billId, type);
            return Ok(list);
        }

        public async Task<IActionResult> DeleteBill(FinanceLadingBillDto financeLadingBillDto)
        {
            await _ladingBillService.DeleteBill(financeLadingBillDto.Id);
            return Ok();
        }

        public async Task<IActionResult> GetCompletionRate(BillSerach serach)
        {
            var data = await _ladingBillService.GetCompletionRate(serach.StartDate, serach.EndDate, serach.ChannelId, serach.CustomerId);
            return Ok(data);
        }
        [HttpPost]
        public async Task<IActionResult> ExportCustomerMonitoring(QueryModel queryModel)
        {
            var list = await _ladingBillService.OutFinanceBillCustomerMonitoring(queryModel);
            return File("客户监控表.xlsx", list);
        }
        public class PostPayment
        {
            public decimal PostPaymentFee
            {
                get; set;
            }

            public int Id
            {
                get; set;
            }

            public FinanceIncidentalTypeEnum Type
            {
                get; set;
            }

            public string Remark
            {
                get; set;
            }
        }


        public class BillSerach
        {
            public int ChannelId
            {
                get; set;
            }

            public int CustomerId
            {
                get; set;
            }

            public DateTime StartDate
            {
                get; set;
            }

            public DateTime EndDate
            {
                get; set;
            }

            public SettlementCompany? SettlementCompany
            {
                get; set;
            }
            public int SalesmanUserId { get; set; }
            public int BranchCompanyId { get; set; }
        }


        public class FinanceReportSearchParam
        {
            public int? ChannelId
            {
                get; set;
            }

            public int? CustomerId
            {
                get; set;
            }

            public DateTime ReceiveTimeStart
            {
                get; set;
            }

            public DateTime ReceiveTimeEnd
            {
                get; set;
            }

            public int? BranchCompanyId { get; set; }
        }
    }
}
