//--------------------------------------------------------------------
//     此代码由T4模板自动生成  byzhouhang 20210918
//	   生成时间 2022-03-31 13:18:56 
//     对此文件的更改可能会导致不正确的行为，并且如果重新生成代码，这些更改将会丢失。
//--------------------------------------------------------------------

using IRaCIS.Core.Domain.Models;
using Microsoft.AspNetCore.Mvc;
using IRaCIS.Core.Application.Interfaces;
using IRaCIS.Core.Application.ViewModel;
using IRaCIS.Core.Application.Helper;

namespace IRaCIS.Core.Application.Service
{
    /// <summary>
    /// 系统模板文档配置表   
    /// </summary>	
    [ApiExplorerSettings(GroupName = "Common")]
    public class CommonDocumentService : BaseService, ICommonDocumentService
    {

        private readonly IRepository<CommonDocument> _commonDocumentRepository;

        public CommonDocumentService(IRepository<CommonDocument> commonDocumentRepository)
        {
            _commonDocumentRepository = commonDocumentRepository;
        }


        [HttpPost]
        public async Task<PageOutput<CommonDocumentView>> GetCommonDocumentList(CommonDocumentQuery queryCommonDocument)
        {

            var commonDocumentQueryable = _commonDocumentRepository.AsQueryable(true)
                .WhereIf(queryCommonDocument.FileTypeEnum != null, t => t.FileTypeEnum == queryCommonDocument.FileTypeEnum)

                .WhereIf(queryCommonDocument.CriterionTypeEnum != null, t => t.CriterionTypeEnum == queryCommonDocument.CriterionTypeEnum)
                .WhereIf(queryCommonDocument.BusinessScenarioEnum != null, t => t.BusinessScenarioEnum == queryCommonDocument.BusinessScenarioEnum)
                .WhereIf(string.IsNullOrEmpty(queryCommonDocument.Code), t => t.Code.Contains(queryCommonDocument.Code))
                .WhereIf(string.IsNullOrEmpty(queryCommonDocument.Name), t => t.Name.Contains(queryCommonDocument.Name))
                .ProjectTo<CommonDocumentView>(_mapper.ConfigurationProvider, new { token = _userInfo.UserToken, userId = _userInfo.Id });

            return await commonDocumentQueryable.ToPagedListAsync(queryCommonDocument.PageIndex, queryCommonDocument.PageSize, String.IsNullOrEmpty(queryCommonDocument.SortField) ? nameof(CommonDocument.Code) : queryCommonDocument.SortField, queryCommonDocument.Asc); ;
        }


        public async Task<IResponseOutput> AddOrUpdateCommonDocument(CommonDocumentAddOrEdit addOrEditCommonDocument)
        {
            var verifyExp1 = new EntityVerifyExp<CommonDocument>()
            {
                VerifyExp = t => t.Code == addOrEditCommonDocument.Code,
                VerifyMsg = "文档的Code不能够重复。"
            };

            //var verifyExp3 = new EntityVerifyExp<CommonDocument>()
            //{
            //    VerifyExp = t => t.Code == addOrEditCommonDocument.Code && t.CriterionTypeEnum==addOrEditCommonDocument.CriterionTypeEnum,
            //    VerifyMsg = "标准邮件文档的Code不能够重复。",
            //    IsVerify= addOrEditCommonDocument.CriterionTypeEnum != null
            //};

            var verifyExp2 = new EntityVerifyExp<CommonDocument>()
            {
                VerifyExp = t => t.CriterionTypeEnum == addOrEditCommonDocument.CriterionTypeEnum && t.BusinessScenarioEnum==addOrEditCommonDocument.BusinessScenarioEnum && 
                t.IsDeleted==addOrEditCommonDocument.IsDeleted,
                VerifyMsg = "一个场景一个标准只允许有一个模板文档",
                IsVerify=addOrEditCommonDocument.CriterionTypeEnum !=null && addOrEditCommonDocument.IsDeleted==false
            };


            if (addOrEditCommonDocument.CriterionTypeEnum != null && addOrEditCommonDocument.CriterionTypeEnum != null)
            {
                var testValue = new Dictionary<string, object>()
                {
                    ["SponsorName"] = "Test",
                };

                var templatePhyicalPath = FileStoreHelper.GetPhysicalFilePath(_hostEnvironment, addOrEditCommonDocument.Path);


                if (File.Exists(templatePhyicalPath))
                {

                    try
                    {
                        MemoryStream memoryStream = new MemoryStream();

                        MiniSoftware.MiniWord.SaveAsByTemplate(memoryStream, templatePhyicalPath, testValue);

                        memoryStream.Seek(0, SeekOrigin.Begin);


                    }
                    catch (Exception )
                    {

                        return ResponseOutput.NotOk("读取模板内容失败, 请将文件另存为docx格式尝试!");
                    }


                }
            }

            var entity = await _commonDocumentRepository.InsertOrUpdateAsync(addOrEditCommonDocument, true, verifyExp1, verifyExp2);

            return ResponseOutput.Ok(entity.Id.ToString());

        }

    }
}
