using Hotline.Api.Filter;
using Hotline.Application.ExportWord;
using Hotline.Caching.Interfaces;
using Hotline.Configurations;
using Hotline.Orders;
using Hotline.Quality;
using Hotline.Settings;
using Hotline.Share.Dtos.OrderExportWord;
using Hotline.Share.Dtos.QualityExportWord;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using MongoDB.Driver.Linq;
using Novacode.NETCorePort;
using XF.Domain.Repository;
using XF.Utility.EnumExtensions;

namespace Hotline.Api.Controllers
{
    public class ExportWordController : BaseController
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IWordHelperService _wordHelperService;
        private readonly IMapper _mapper;
        private readonly IRepository<OrderVisit> _orderVisitRepository;
        private readonly IRepository<OrderVisitDetail> _orderVisitedDetailRepository;
        private readonly ILogger<ExportWordController> _logger;
        private readonly IOptionsSnapshot<AppConfiguration> _appOptions;
        private readonly ISystemSettingCacheManager _systemSettingCacheManager;
		private readonly IQualityRepository _qualityRepository;

		public ExportWordController(IOrderRepository orderRepository,
            IWordHelperService wordHelperService,
            IMapper mapper,
           IRepository<OrderVisit> orderVisitRepository,
           IRepository<OrderVisitDetail> orderVisitedDetailRepository,
           ILogger<ExportWordController> logger,
            IOptionsSnapshot<AppConfiguration> appOptions,
            ISystemSettingCacheManager systemSettingCacheManager,
			IQualityRepository qualityRepository)
        {
            _orderRepository = orderRepository;
            _wordHelperService = wordHelperService;
            _mapper = mapper;
            _orderVisitRepository = orderVisitRepository;
            _orderVisitedDetailRepository = orderVisitedDetailRepository;
            _logger = logger;
            _appOptions = appOptions;
            _systemSettingCacheManager = systemSettingCacheManager;
			_qualityRepository = qualityRepository;

		}

        /// <summary>
        /// 工单交办单导出         
        /// </summary>
        /// <returns></returns>
        [HttpPost("order_submission_form")]
		[LogFilterAlpha("导出日志")]
		public async Task<IActionResult> OrderSubmissionForm([FromBody] List<string> Ids)
        {
            var streams = new Dictionary<string, Stream>();
            var path = $"{Directory.GetCurrentDirectory()}/Template/AssignmentForm.doc";
            int num = 1;
            var isTheAssignmentFormConfidential = bool.Parse(_systemSettingCacheManager.GetSetting(SettingConstants.IsTheAssignmentFormConfidential).SettingValue[0]);
            foreach (var item in Ids)
            {
                var order = await _orderRepository.GetAsync(item, HttpContext.RequestAborted);
                if (order == null)
                    continue;

                //处理保密数据
                if (isTheAssignmentFormConfidential && order.IsSecret)
                {
                    var maskString = "***";
                    order.Contact = maskString;
                    order.FromName = maskString;
                    order.FromGender = EGender.Unknown;
                    order.FromPhone = maskString;
                    order.FullAddress = maskString;
                    order.Address = maskString;
                    order.City = maskString;
                    order.Street = maskString;
                    order.ContactMask = maskString;
                }

                var exportTest = _mapper.Map<OrderSubmissionForm>(order);

                if (_appOptions.Value.IsZiGong)
                    exportTest.CityName = "自贡市";
                else if (_appOptions.Value.IsYiBin)
                    exportTest.CityName = "宜宾市";
                else if (_appOptions.Value.IsLuZhou)
                    exportTest.CityName = "泸州市";

                //查询回访信息
                var visitData = await _orderVisitRepository.GetAsync(p => p.OrderId == order.Id && p.VisitState == EVisitState.Visited, HttpContext.RequestAborted);
                if (visitData != null)
                {
                    //回访明细
                    var visitDetail = await _orderVisitedDetailRepository.Queryable().Where(p => p.VisitId == visitData.Id && p.VisitTarget == Share.Enums.Order.EVisitTarget.Org).ToListAsync();
                    string visit = "";
                    foreach (var itemVisit in visitDetail)
                    {
                        visit += "回访部门：" + itemVisit.VisitOrgName;
                        visit += " \n办件结果：" + itemVisit.OrgProcessingResults?.Value + "    办事态度：" + itemVisit.OrgHandledAttitude?.Value + "\n";

                        if (itemVisit.VisitOrgCode == order.ActualHandleOrgCode)
                            exportTest.VisitContent = "回访内容：" + itemVisit.VisitContent;
                    }
                    exportTest.VisitOrg = visit;
                }
                if (Ids.Count > 1)
                {
                    streams.Add(order.No + "_" + num + path.Substring(path.LastIndexOf(".")), _wordHelperService.WordStream(path, exportTest));
                    num = num + 1;
                }
                else
                {
                    var btyes = _wordHelperService.WordByte(path, exportTest);
                    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
                    return File(btyes, "application/vnd.ms-word", order.No + path.Substring(path.LastIndexOf(".")));
                }
            }

            //调用压缩方法 进行压缩 (接收byte[] 数据)
            byte[] fileBytes = _wordHelperService.ConvertZipStream(streams);
            HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
            var name = DateTime.Now.ToString("yyyyMMddHHmmss");
            return File(fileBytes, "application/octet-stream", $"{name}.zip");
        }


        /// <summary>
        /// 质检单导出
        /// </summary>
        /// <param name="Ids"></param>
        /// <returns></returns>
		[HttpPost("quality_certificate")]
		[LogFilterAlpha("导出日志")]
		public async Task<IActionResult> QualityCertificate([FromBody] List<string> Ids) {

			var streams = new Dictionary<string, Stream>();
			var path = $"{Directory.GetCurrentDirectory()}/Template/QualityCertificate.doc";
			int num = 1;
			foreach (var item in Ids)
			{
                var quality = await _qualityRepository.GetAsync(item, HttpContext.RequestAborted);
				if (quality == null)
					continue;
				var order = await _orderRepository.GetAsync(quality.OrderId, HttpContext.RequestAborted);
				if (order == null)
					continue;

				var exportTest = _mapper.Map<QualityCertificate>(order);

				if (_appOptions.Value.IsZiGong)
					exportTest.CityName = "自贡市";
				else if (_appOptions.Value.IsYiBin)
					exportTest.CityName = "宜宾市";
				else if (_appOptions.Value.IsLuZhou)
					exportTest.CityName = "泸州市";

                //质检信息
                exportTest.Grade = quality.Grade.ToString();
                exportTest.QualityContent = quality.Content;
				exportTest.UserName = quality.UserName;
				exportTest.QualityTime = quality.QualityTime.HasValue? quality.QualityTime.Value.ToString("yyyy-MM-dd HH:mm:ss") :string.Empty;
				exportTest.CenterToOrgTime = order.CenterToOrgTime.HasValue ? order.CenterToOrgTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty;
                exportTest.CreationTime = order.CreationTime.ToString("yyyy-MM-dd HH:mm:ss");
                exportTest.ExpiredTime = order.ExpiredTime.HasValue ? order.ExpiredTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty;
				exportTest.FromGender = order.FromGender.GetDescription();

				//查询回访信息
				var visitData = await _orderVisitRepository.GetAsync(p => p.OrderId == order.Id && p.VisitState == EVisitState.Visited, HttpContext.RequestAborted);
				if (visitData != null)
				{
					//回访明细
					var visitDetail = await _orderVisitedDetailRepository.Queryable().Where(p => p.VisitId == visitData.Id && p.VisitTarget == Share.Enums.Order.EVisitTarget.Org).ToListAsync();
					string visit = "";
					foreach (var itemVisit in visitDetail)
					{
						visit += "回访部门：" + itemVisit.VisitOrgName;
						visit += " \n办件结果：" + itemVisit.OrgProcessingResults?.Value + "    办事态度：" + itemVisit.OrgHandledAttitude?.Value + "\n";

						if (itemVisit.VisitOrgCode == order.ActualHandleOrgCode)
							exportTest.VisitContent = "回访内容：" + itemVisit.VisitContent;
					}
					exportTest.VisitOrg = visit;
				}
				if (Ids.Count > 1)
				{
					streams.Add(order.No + "_" + num + path.Substring(path.LastIndexOf(".")), _wordHelperService.WordStream(path, exportTest));
					num = num + 1;
				}
				else
				{
					var btyes = _wordHelperService.WordByte(path, exportTest);
					HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
					return File(btyes, "application/vnd.ms-word", order.No + path.Substring(path.LastIndexOf(".")));
				}
			}

			//调用压缩方法 进行压缩 (接收byte[] 数据)
			byte[] fileBytes = _wordHelperService.ConvertZipStream(streams);
			HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
			var name = DateTime.Now.ToString("yyyyMMddHHmmss");
			return File(fileBytes, "application/octet-stream", $"{name}.zip");
		}

	}
}
