using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
using GxPress.Common.Tools;

namespace GxPress.Service.Implement
{
    public partial class FlowService
    {
        public async Task<string> DownloadAsync(int flowId)
        {
            var flow = await _flowRepository.GetAsync(flowId);
            var process = await _processRepository.GetAsync(flow.ProcessId);
            var rootPath = StringUtils.GetWebRootPath(_environment.WebRootPath);
            var path = System.IO.Path.Combine(rootPath, StringUtils.RemoveDomain(process.TemplatePath));
            if (!File.Exists(path))
            {
                return $"/template.docx";
            }
            var saveDirectory = DateTime.Now.ToString("yyyyMMdd");
            var absolutePath = System.IO.Path.Combine(rootPath, "cache", saveDirectory, $"{process.Name}.docx");
            var relativePath = $"/cache/{saveDirectory}/{process.Name}.docx";

            var fieldList = await _processFieldRepository.GetListAsync(flow.ProcessId);
            var valueList = await _flowFieldValueRepository.GetListAsync(flowId);
            var nameValueList = new List<KeyValuePair<string, string>>();

            if (fieldList != null)
            {
                foreach (var processField in fieldList)
                {
                    var value = valueList?.FirstOrDefault(v => v.FieldId == processField.Id);
                    if (value != null)
                    {
                        nameValueList.Add(new KeyValuePair<string, string>(processField.Label, GetFieldValue(value)));
                    }
                }
            }

            using (var doc = WordprocessingDocument.Open(path, true))
            {
                var body = doc.MainDocumentPart.Document.Body;
                var paras = body.Elements<Paragraph>();

                foreach (var para in paras)
                {
                    foreach (var run in para.Elements<Run>())
                    {
                        foreach (var text in run.Elements<Text>())
                        {
                            foreach (var pair in nameValueList)
                            {
                                text.Text = text.Text.Replace($"[{pair.Key}]", pair.Value);
                            }
                        }
                    }
                }

                doc.SaveAs(absolutePath);
            }

            return relativePath;
        }

    }
}