using Aspose.Words;
using NPOI.HPSF;
using NPOI.POIFS.Crypt.Dsig;
using OASystem.API.OAMethodLib;
using OASystem.Domain.Dtos.Resource;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Domain.ViewModels.QiYeWeChat;
using OASystem.Infrastructure.Repositories.Groups;
using Org.BouncyCastle.Utilities;
using Quartz.Util;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http.Headers;
using static QRCoder.PayloadGenerator.SwissQrCode;

namespace OASystem.API.Controllers
{
    /// <summary>
    /// 资料相关
    /// </summary>
    //[Authorize]
    [Route("api/[controller]/[action]")]
    public class ResourceController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly SqlSugarClient _sqlSugar;
        private readonly IConfiguration _config;
        private readonly CarDataRepository _carDataRep;
        private readonly LocalGuideDataRepository _localGuideDataRep;
        private readonly ThreeCodeRepository _ThreeCodeRep;
        private readonly HotelDataRepository _hotelDataRep;
        private readonly ResItemInfoRepository _resItemInfoRep;
        private readonly SetDataRepository _setDataRepository;
        private readonly CountryFeeRepository _countryFeeRep;
        private readonly SetDataTypeRepository _setDataTypeRep;
        private readonly AirTicketAgentRepository _airTicketAgentRep;
        private readonly InvitationOfficialActivityDataRepository _InvitationOfficialActivityDataRep;
        private readonly OfficialActivitiesRepository _officialActivitiesRep;
        private readonly AskDataRepository _askDataRep;
        private readonly TicketBlackCodeRepository _ticketBlackCodeRep;
        private readonly TourClientListRepository _tourClientListRep;
        private readonly DelegationInfoRepository _delegationInfoRep;

        public ResourceController(IMapper mapper, IConfiguration config, SqlSugarClient sqlSugar, CarDataRepository carDataRep, LocalGuideDataRepository localGuideDataRep,
            ThreeCodeRepository threeCodeRep, HotelDataRepository hotelDataRep, ResItemInfoRepository resItemInfoRep, SetDataRepository setDataRepository,
            CountryFeeRepository countryFeeRep, SetDataTypeRepository setDataTypeRep, AirTicketAgentRepository airTicketAgentRep,
            InvitationOfficialActivityDataRepository invitationOfficialActivityDataRep, OfficialActivitiesRepository officialActivitiesRep, AskDataRepository askDataRep,
            TicketBlackCodeRepository ticketBlackCodeRep, TourClientListRepository tourClientListRep, DelegationInfoRepository delegationInfoRep)
        {
            _mapper = mapper;
            _config = config;
            _sqlSugar = sqlSugar;
            _carDataRep = carDataRep;
            _localGuideDataRep = localGuideDataRep;
            _ThreeCodeRep = threeCodeRep;
            _hotelDataRep = hotelDataRep;
            _resItemInfoRep = resItemInfoRep;
            _setDataRepository = setDataRepository;
            _countryFeeRep = countryFeeRep;
            _setDataTypeRep = setDataTypeRep;
            _airTicketAgentRep = airTicketAgentRep;
            _InvitationOfficialActivityDataRep = invitationOfficialActivityDataRep;
            _officialActivitiesRep = officialActivitiesRep;
            _askDataRep = askDataRep;
            _ticketBlackCodeRep = ticketBlackCodeRep;
            _tourClientListRep = tourClientListRep;
            _delegationInfoRep = delegationInfoRep;
        }


        #region 车公司资料板块

        /// <summary>
        /// 车公司信息查询
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryCarData(QueryCarDataDto dto)
        {
            try
            {
                Result LocalGuide = await _carDataRep.QueryCarData(dto);
                if (LocalGuide.Code == 0)
                {
                    return Ok(JsonView(true, "查询成功", LocalGuide.Data));
                }
                else
                {
                    return Ok(JsonView(false, LocalGuide.Msg));
                }
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }


        }

        /// <summary>
        /// 车公司资料下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryCarSelect()
        {
            try
            {
                var CarData = _carDataRep.QueryDto<Res_CarData, CarDataSelectView>().ToList();
                if (CarData.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }
                CarData.Add(new CarDataSelectView { Id = 0, UnitArea = "全部" });
                CarData = CarData.Where((x, i) => CarData.FindIndex(z => z.UnitArea == x.UnitArea) == i).ToList();
                CarData = CarData.OrderBy(x => x.Id).ToList();
                List<CarDataSelectView> data = new List<CarDataSelectView>();
                foreach (CarDataSelectView car in CarData)
                {
                    if (!string.IsNullOrWhiteSpace(car.UnitArea))
                    {
                        data.Add(car);
                    }
                }
                return Ok(JsonView(true, "查询成功", data));
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 根据Id查询车公司详细数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QuerCarDataDetailById(QueryCarDataDetailDto dto)
        {
            string sql = string.Format(@" Select * From Res_CarData With(Nolock) Where Id = {0} ", dto.Id);
            CarDataDetailDataView info = _resItemInfoRep._sqlSugar.SqlQueryable<CarDataDetailDataView>(sql).First();
            if (info == null)
            {
                return Ok(JsonView(false, "未找到相关数据！"));
            }

            return Ok(JsonView(true, "查询成功", info));
        }


        /// <summary>
        /// 车公司信息添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> AddCarData(AddCarDataDto dto)
        {
            try
            {
                if (dto.UnitArea == "")
                {
                    return Ok(JsonView(false, "请检查单位区域是否填写！"));
                }
                if (dto.UnitName == "")
                {
                    return Ok(JsonView(false, "请检查单位名称是否填写！"));
                }
                if (dto.Contact == "")
                {
                    return Ok(JsonView(false, "请检查单位联系人是否填写！"));
                }
                if (dto.ContactTel == "")
                {
                    return Ok(JsonView(false, "请检查联系方式是否填写正确！"));
                }

                var carDada = _carDataRep.QueryDto<Res_CarData, CarDataView>(a => a.UnitArea == dto.UnitArea && a.UnitName == dto.UnitName && a.Contact == dto.Contact && a.ContactTel == dto.ContactTel).ToList();
                if (carDada.Count != 0)
                {
                    return Ok(JsonView(false, "该信息已存在，请勿重复添加！"));
                }
                Res_CarData _CarData = _mapper.Map<Res_CarData>(dto);
                int id = await _carDataRep.AddAsyncReturnId(_CarData);
                if (id == 0)
                {
                    return Ok(JsonView(false, "添加失败！"));
                }
                return Ok(JsonView(true, "添加成功", new { Id = id }));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 车公司信息修改
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> UpCarData(UpCarDataDto dto)
        {
            try
            {
                if (dto.UnitArea == "")
                {
                    return Ok(JsonView(false, "请检查单位区域是否填写！"));
                }
                if (dto.UnitName == "")
                {
                    return Ok(JsonView(false, "请检查单位名称是否填写！"));
                }
                if (dto.Contact == "")
                {
                    return Ok(JsonView(false, "请检查单位联系人是否填写！"));
                }
                if (dto.ContactTel == "")
                {
                    return Ok(JsonView(false, "请检查联系方式是否填写正确！"));
                }
                bool res = await _carDataRep.UpdateAsync(a => a.Id == dto.Id, a => new Res_CarData
                {
                    UnitArea = dto.UnitArea,
                    UnitName = dto.UnitName,
                    Address = dto.Address,
                    Contact = dto.Contact,
                    ContactTel = dto.ContactTel,
                    ContactEmail = dto.ContactEmail,
                    ContactFax = dto.ContactFax,
                    CarDes = dto.CarDes,
                    CarPicPaths = dto.CarPicPaths,
                    OtherInfo = dto.OtherInfo,
                    Score = dto.Score,
                    QualificationScore = dto.QualificationScore,
                    CarAgeScore = dto.CarAgeScore,
                    CleanImgScore = dto.CleanImgScore,
                    SmellScore = dto.SmellScore,
                    WaterPaperScore = dto.WaterPaperScore,
                    HardwareScore = dto.HardwareScore,
                    TimeScore = dto.TimeScore,
                    SafetyScore = dto.SafetyScore,
                    DrivingAgeScore = dto.DrivingAgeScore,
                    Remark = dto.Remark,
                });
                if (!res) { return Ok(JsonView(false, "修改失败！")); }
                return Ok(JsonView(true, "修改成功"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 车公司信息删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelCarData(DelCarDataDto dto)
        {
            try
            {
                bool res = await _carDataRep.SoftDeleteByIdAsync<Res_CarData>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res) { return Ok(JsonView(false, "删除失败！")); }
                return Ok(JsonView(true, "删除成功"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        #endregion

        #region 导游地接资料板块
        /// <summary>
        /// 导游地接资料查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryLocalGuide(QueryLocalGuide dto)
        {
            try
            {
                Result LocalGuide = await _localGuideDataRep.QueryLocalGuide(dto);
                if (LocalGuide.Code == 0)
                {
                    return Ok(JsonView(true, "查询成功", LocalGuide.Data));
                }
                else
                {
                    return Ok(JsonView(false, LocalGuide.Msg));
                }

            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }


        }

        /// <summary>
        /// 导游地接资料下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryLocalGuideSelect()
        {
            try
            {
                var LocalGuide = _carDataRep.QueryDto<Res_LocalGuideData, QueryLocalGuideSelectView>().ToList();
                if (LocalGuide.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }
                LocalGuide.Add(new QueryLocalGuideSelectView { Id = 0, UnitArea = "全部" });
                LocalGuide = LocalGuide.Where((x, i) => LocalGuide.FindIndex(z => z.UnitArea == x.UnitArea && z.UnitArea != "") == i).ToList();
                LocalGuide = LocalGuide.OrderBy(x => x.Id).ToList();
                List<QueryLocalGuideSelectView> data = new List<QueryLocalGuideSelectView>();
                foreach (QueryLocalGuideSelectView Local in LocalGuide)
                {
                    if (!string.IsNullOrWhiteSpace(Local.UnitArea))
                    {
                        data.Add(Local);
                    }
                }
                return Ok(JsonView(true, "查询成功", data));
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 根据Id查询地接详细数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryLocalGuideDetailById(QueryLocalGuideDetailDto dto)
        {
            string sql = string.Format(@" Select * From Res_LocalGuideData With(Nolock) Where Id = {0} ", dto.Id);
            LocalGuideDetailDataView info = _resItemInfoRep._sqlSugar.SqlQueryable<LocalGuideDetailDataView>(sql).First();
            if(info == null)
            {
                return Ok(JsonView(false, "未找到相关数据！"));
            }

            return Ok(JsonView(true, "查询成功", info));
        }

        /// <summary>
        /// 导游地接信息操作（Status:1.新增,2.修改）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OperationLocalGuide(LocalGuideOperationDto dto)
        {
            try
            {
                if (dto.UnitArea == "")
                {
                    return Ok(JsonView(false, "请检查单位区域是否填写！"));
                }
                if (dto.UnitName == "")
                {
                    return Ok(JsonView(false, "请检查单位名称是否填写！"));
                }
                if (dto.Contact == "")
                {
                    return Ok(JsonView(false, "请检查单位联系人是否填写！"));
                }
                if (dto.ContactTel == "")
                {
                    return Ok(JsonView(false, "请检查联系方式是否填写正确！"));
                }

                Result result = await _localGuideDataRep.LocalGuideOperation(dto);
                if (result.Code != 0)
                {
                    return Ok(JsonView(false, result.Msg));
                }
                return Ok(JsonView(true, result.Msg));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 导游地接信息操作（删除）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelLocalGuide(LocalGuideDelDto dto)
        {
            try
            {
                var res = await _localGuideDataRep.SoftDeleteByIdAsync<Res_LocalGuideData>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        #endregion

        #region 机场三字码信息
        /// <summary>
        /// 机场三字码查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryThreeCode(QueryThreeCodeDto dto)
        {
            try
            {
                Result LocalGuide = await _ThreeCodeRep.QueryThreeCode(dto);
                if (LocalGuide.Code == 0)
                {
                    return Ok(JsonView(true, "查询成功", LocalGuide.Data));
                }
                else
                {
                    return Ok(JsonView(false, LocalGuide.Msg));
                }
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }


        }
        /// <summary>
        /// 机场三字码数据城市下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryThreeCodeSelect()
        {
            try
            {
                var ThreeCode = _carDataRep.QueryDto<Res_ThreeCode, ThreeCodeSelectView>().ToList();
                if (ThreeCode.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }
                ThreeCode.Add(new ThreeCodeSelectView { Id = 0, City = "全部" });
                ThreeCode = ThreeCode.Where((x, i) => ThreeCode.FindIndex(z => z.City == x.City && z.City != "") == i).ToList();
                ThreeCode = ThreeCode.OrderBy(x => x.Id).ToList();
                List<ThreeCodeSelectView> data = new List<ThreeCodeSelectView>();
                foreach (ThreeCodeSelectView _ThreeCode in ThreeCode)
                {
                    if (!string.IsNullOrWhiteSpace(_ThreeCode.City))
                    {
                        data.Add(_ThreeCode);
                    }
                }
                return Ok(JsonView(true, "查询成功", data));
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 机场三字码资料操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OperationThreeCode(ThreeCodeOperationDto dto)
        {
            try
            {
                if (dto.Three == "")
                {
                    return Ok(JsonView(false, "请检查三字码是否填写！"));
                }
                if (dto.Country == "")
                {
                    return Ok(JsonView(false, "请检查国家是否填写！"));
                }
                if (dto.City == "")
                {
                    return Ok(JsonView(false, "请检查城市是否填写正确！"));
                }
                if (dto.AirPort == "")
                {
                    return Ok(JsonView(false, "请检查机场是否填写正确！"));
                }

                Result result = await _ThreeCodeRep.ThreeCodeOperation(dto);
                if (result.Code != 0)
                {
                    return Ok(JsonView(false, result.Msg));
                }
                return Ok(JsonView(true, result.Msg));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 机场三字码资料操作（删除）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelThreeCode(ThreeCodeDelDto dto)
        {
            try
            {
                var res = await _ThreeCodeRep.SoftDeleteByIdAsync<Res_ThreeCode>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        #endregion

        #region 代理出票合作方资料
        /// <summary>
        /// 代理出票合作方资料
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryAirTicketAgent(DtoBase dto)
        {

            try
            {
                List<Res_AirTicketAgent> res_AirTicketAgents = _airTicketAgentRep.Query<Res_AirTicketAgent>(a => a.IsDel == 0).ToList();
                if (res_AirTicketAgents.Count != 0)
                {
                    res_AirTicketAgents = res_AirTicketAgents.OrderByDescending(a => a.CreateTime).ToList();
                    if (dto.PageSize == 0 && dto.PageIndex == 0)
                    {
                        return Ok(JsonView(true, "查询成功！", res_AirTicketAgents));
                    }
                    else
                    {
                        int count = res_AirTicketAgents.Count;
                        float totalPage = (float)count / dto.PageSize;//总页数
                        if (totalPage == 0) totalPage = 1;
                        else totalPage = (int)Math.Ceiling((double)totalPage);

                        List<Res_AirTicketAgent> _AirTicketAgent = new List<Res_AirTicketAgent>();
                        for (int i = 0; i < dto.PageSize; i++)
                        {
                            var RowIndex = i + (dto.PageIndex - 1) * dto.PageSize;
                            if (RowIndex < res_AirTicketAgents.Count)
                            {
                                _AirTicketAgent.Add(res_AirTicketAgents[RowIndex]);
                            }
                            else
                            {
                                break;
                            }
                        }
                        return Ok(JsonView(true, "查询成功！", new { pageCount = count, totalPage = (int)totalPage, pageIndex = dto.PageIndex, pageSize = dto.PageSize, pageSource = _AirTicketAgent }));

                    }
                }
                else
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }

            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 代理出票合作方资料操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OpAirTicketAgent(OpAirTicketAgentDto dto)
        {
            try
            {

                if (dto.Account == "")
                {
                    return Ok(JsonView(false, "请检查代理商账户是否填写！"));
                }
                if (dto.Bank == "")
                {
                    return Ok(JsonView(false, "请检查代理商银行是否填写！"));
                }
                if (dto.Name == "")
                {
                    return Ok(JsonView(false, "请检查代理商名称是否填写正确！"));
                }
                Result result = await _airTicketAgentRep.OpAirTicketAgent(dto);
                if (result.Code != 0)
                {
                    return Ok(JsonView(false, result.Msg));
                }
                return Ok(JsonView(true, result.Msg));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 代理出票合作方资料操作（删除）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelAirTicketAgent(DelBaseDto dto)
        {
            try
            {
                var res = await _airTicketAgentRep.SoftDeleteByIdAsync<Res_AirTicketAgent>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        #endregion

        #region 酒店资料数据
        /// <summary>
        /// 酒店信息查询 Page
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryHotelData(QueryHotelDataDto dto)
        {
            string sqlWhere = string.Empty;
            if (!string.IsNullOrWhiteSpace(dto.Name))
            {
                sqlWhere += string.Format(@" And hd.Name like '%{0}%'", dto.Name);
            }
            if (!string.IsNullOrWhiteSpace(dto.City) && dto.City != "全部")
            {
                sqlWhere += string.Format(@" And hd.City like '%{0}%'", dto.City);
            }
            if (!string.IsNullOrWhiteSpace(dto.Contact))
            {
                sqlWhere += string.Format(@" And hd.Contact like '%{0}%'", dto.Contact);
            }
            if (!string.IsNullOrWhiteSpace(dto.ContactPhone))
            {
                sqlWhere += string.Format(@" And hd.ContactPhone like '%{0}%'", dto.ContactPhone);
            }
            sqlWhere += string.Format(@" And hd.IsDel={0}", 0);
            if (!string.IsNullOrEmpty(sqlWhere.Trim()))
            {
                Regex r = new Regex("And");
                sqlWhere = r.Replace(sqlWhere, "Where", 1);
            }

            string sql = string.Format(@"SELECT
                                           *
                                         FROM
                                           (
                                             SELECT
                                               ROW_NUMBER() OVER (
                                                 ORDER BY
                                                   hd.CreateTime DESC
                                               ) AS Row_Number,
                                               hd.Id,
                                               hd.City,
                                               hd.[Name],
                                               hd.Tel,
                                               hd.Fax,
                                               hd.Contact,
                                               hd.ContactPhone,
                                               u.CnName AS CreateUserName,
                                               hd.CreateTime
                                             FROM
                                               Res_HotelData hd
                                             WITH
                                               (NoLock)
                                               LEFT JOIN Sys_Users u
                                             WITH
                                               (NoLock) ON hd.CreateUserId = u.Id {0} 
                                           ) Temp
                                         ", sqlWhere);

            if (dto.PortType == 1)
            {
                List<HotelDataItemView> HotelDataData = await _sqlSugar.SqlQueryable<HotelDataItemView>(sql).ToListAsync();
                if (HotelDataData.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据"));
                }
                return Ok(JsonView(true, "操作成功", HotelDataData));
            }
            else if (dto.PortType == 2 || dto.PortType == 3)
            {
                RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
                var data = await _sqlSugar.SqlQueryable<HotelDataItemView>(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total); //ToPageAsync

                return Ok(JsonView(true, "操作成功", data, total));
            }
            else return Ok(JsonView(false, "请传入PortType参数！1:Web，2:Android,3:IOS"));


        }

        /// <summary>
        /// 酒店资料
        /// 详情
        /// add time：2024-05-14 11:57:10
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryHotelDataInfo(QueryHotelDataInfoDto dto)
        {
            var _view = await _hotelDataRep._Info(dto.PortType,dto.Id);
            if (_view.Code == 0 )
            {
                return Ok(JsonView(true, _view.Msg,_view.Data));
            }

            return Ok(JsonView(false, _view.Msg));
        }

        /// <summary>
        /// 酒店资料下拉框数据
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryHotelDataSelect()
        {
            try
            {
                var HotelData = _carDataRep.QueryDto<Res_HotelData, QueryHotelDataSelect>().ToList();
                if (HotelData.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }
                HotelData.Add(new QueryHotelDataSelect { Id = 0, City = "全部" });
                HotelData = HotelData.Where((x, i) => HotelData.FindIndex(z => z.City == x.City && z.City != "") == i).ToList();
                HotelData = HotelData.OrderBy(x => x.Id).ToList();
                List<QueryHotelDataSelect> data = new List<QueryHotelDataSelect>();
                foreach (QueryHotelDataSelect Hotel in HotelData)
                {
                    if (!string.IsNullOrWhiteSpace(Hotel.City))
                    {
                        data.Add(Hotel);
                    }
                }
                return Ok(JsonView(true, "查询成功", data));
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 酒店资料操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OperationHotelData(OperationHotelDto dto)
        {
            if (string.IsNullOrEmpty(dto.City)) return Ok(JsonView(false, "请检查酒店所在城市是否填写！"));
            if (string.IsNullOrEmpty(dto.Name)) return Ok(JsonView(false, "请检查酒店名称是否填写！"));
            if (string.IsNullOrEmpty(dto.Address)) return Ok(JsonView(false, "请检查酒店地址是否填写正确！")); 
            if (string.IsNullOrEmpty(dto.Tel)) return Ok(JsonView(false, "请检查酒店联系方式是否填写正确！")); 

            Result result = await _hotelDataRep.OperationHotelData(dto);
            if (result.Code != 0) return Ok(JsonView(false, result.Msg));
            return Ok(JsonView(true, result.Msg));

        }

        /// <summary>
        /// 酒店资料操作（删除）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelHotelData(DelHotelDataDto dto)
        {
            try
            {
                var res = await _hotelDataRep.SoftDeleteByIdAsync<Res_HotelData>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        #endregion

        #region 签证费用资料
        /// <summary>
        /// 签证费用资料查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryCountryFeeCost(DtoBase dto)
        {

            if (dto.PortType == 1)
            {
                var CountryFee = _countryFeeRep.QueryDto<Res_CountryFeeCost, CountryFeeCostView>().ToList();
                if (CountryFee.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }
                CountryFee = CountryFee.OrderByDescending(s => s.CreateTime).ToList();
                return Ok(JsonView(true, "查询成功", CountryFee));
            }
            else if (dto.PortType == 2)
            {
                var CountryFee = _countryFeeRep.QueryDto<Res_CountryFeeCost, CountryFeeCostView>().ToList();
                if (CountryFee.Count == 0)
                {
                    return Ok(JsonView(false, "暂无数据！"));
                }
                CountryFee = CountryFee.OrderByDescending(s => s.CreateTime).ToList();
                return Ok(JsonView(true, "查询成功", CountryFee));
            }
            else
            {
                return Ok(JsonView(false, "请传入PortType参数！1:Web，2:Android,3:IOS"));
            }
        }

        /// <summary>
        /// 签证费用资料操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OperationCountryFeeCost(OperationCountryFeeCostDto dto)
        {
            if (string.IsNullOrWhiteSpace(dto.VisaContinent))
            {
                return Ok(JsonView(false, "请检查州名是否填写！"));
            }
            if (string.IsNullOrWhiteSpace(dto.VisaCountry))
            {
                return Ok(JsonView(false, "请检查国家名是否填写！"));
            }
            if (string.IsNullOrWhiteSpace(dto.VisaTime))
            {
                return Ok(JsonView(false, "请检一般签证时间是否填写正确！"));
            }
            if (string.IsNullOrWhiteSpace(dto.UrgentTime))
            {
                return Ok(JsonView(false, "请检加急时间是否填写正确！"));
            }

            Result result = await _countryFeeRep.OperationCountryFeeCost(dto);
            if (result.Code == 0)
            {
                return Ok(JsonView(true, result.Msg));
            }
            return Ok(JsonView(false, result.Msg));

        }

        /// <summary>
        /// 签证费用资料操作（删除）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelCountryFeeCost(DelCountryFeeCostDto dto)
        {
            var res = await _countryFeeRep.SoftDeleteByIdAsync<Res_CountryFeeCost>(dto.Id.ToString(), dto.DeleteUserId);
            if (!res)
            {
                return Ok(JsonView(false, "删除失败"));
            }
            return Ok(JsonView(true, "删除成功！"));

        }
        #endregion

        #region 物料信息、供应商维护
        #region 供应商
        /// <summary>
        /// 物料供应商查询
        /// </summary>
        /// <param name="paras">Json序列化</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostSearchItemVendor(JsonDtoBase _jsonDto)
        {
            if (string.IsNullOrEmpty(_jsonDto.Paras))
            {
                return Ok(JsonView(false, "参数为空"));
            }

            Search_ResItemVendorDto _ItemVendorDto = System.Text.Json.JsonSerializer.Deserialize<Search_ResItemVendorDto>(_jsonDto.Paras);
            if (_ItemVendorDto != null)
            {
                if (_ItemVendorDto.SearchType == 2) //获取列表
                {
                    Res_ItemVendorListView rstList = _resItemInfoRep.GetVendorList(_ItemVendorDto);
                    return Ok(rstList);
                }
                else
                {
                    Res_ItemVendorView rstInfo = _resItemInfoRep.getVendorInfo(_ItemVendorDto);
                    return Ok(rstInfo);
                }
            }
            else
            {
                return Ok(JsonView(false, "参数反序列化失败"));
            }

            return Ok(JsonView(false));
        }

        /// <summary>
        /// 创建/编辑/删除供应商信息
        /// </summary>
        /// <param name="_dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostEditItemVendor(Edit_ResItemVendorDto _dto)
        {
            bool rst = false;

            if (_dto.EditType >= 0)
            {

                if (string.IsNullOrEmpty(_dto.VendorFullName))
                {
                    return Ok(JsonView(false, "全称未填写"));
                }

                if (string.IsNullOrEmpty(_dto.VendorLinker))
                {
                    return Ok(JsonView(false, "联系人未填写"));
                }

                if (string.IsNullOrEmpty(_dto.VendorMobile))
                {
                    return Ok(JsonView(false, "联系人手机号未填写"));
                }

                if (string.IsNullOrEmpty(_dto.BusRange))
                {
                    return Ok(JsonView(false, "经营范围未选择"));
                }

                if (_dto.EditType == 0)
                {
                    var checkEmpty = _resItemInfoRep.Query<Res_ItemVendor>(s => s.FullName == _dto.VendorFullName).First();
                    if (checkEmpty != null)
                    {
                        return Ok(JsonView(false, "已存在同名供应商"));
                    }

                    rst = await _resItemInfoRep.addVendorInfo(_dto);
                }
                else if (_dto.EditType == 1)
                {
                    if (_dto.VendorId > 0)
                    {
                        Res_ItemVendor _entity = _mapper.Map<Res_ItemVendor>(_dto);

                        rst = await _resItemInfoRep.updVendorInfo(_entity);
                    }
                    else
                    {
                        return Ok(JsonView(false, "供应商不存在"));
                    }
                }
            }
            else
            {
                if (_dto.VendorId < 1 || _dto.SysUserId < 1)
                {
                    return Ok(JsonView(false, "用户Id或供应商Id不存在"));
                }
                Res_ItemVendor _entity = _mapper.Map<Res_ItemVendor>(_dto);

                rst = await _resItemInfoRep.delVendorInfo(_entity);

            }

            return Ok(JsonView(rst));
        }

        #endregion
        #region 物料信息
        /// <summary>
        /// 物料信息查询
        /// </summary>
        /// <param name="paras">Json序列化</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostSearchItemInfo(string paras)
        {
            if (string.IsNullOrEmpty(paras))
            {
                return Ok(JsonView(false, "参数为空"));
            }

            Search_ItemInfoDto _ItemInfoDto = System.Text.Json.JsonSerializer.Deserialize<Search_ItemInfoDto>(paras);
            if (_ItemInfoDto != null)
            {
                if (_ItemInfoDto.SearchType == 2) //获取列表
                {
                    Res_ItemInfoListView rstList = _resItemInfoRep.GetItemList(_ItemInfoDto);
                    return Ok(rstList);
                }
                else
                {
                    Res_ItemInfoView rstInfo = _resItemInfoRep.getItemInfo(_ItemInfoDto);
                    return Ok(rstInfo);
                }
            }
            else
            {
                return Ok(JsonView(false, "参数反序列化失败"));
            }

            return Ok(JsonView(false));
        }

        /// <summary>
        /// 创建/编辑/删除物料信息
        /// </summary>
        /// 
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostEditItemInfo(Edit_ResItemInfoDto _dto)
        {
            bool rst = false;

            if (_dto.EditType >= 0)
            {
                if (_dto.VendorId < 1)
                {
                    return Ok(JsonView(false, "未选择供应商"));
                }
                if (string.IsNullOrEmpty(_dto.ItemName))
                {
                    return Ok(JsonView(false, "物料名称为空"));
                }
                if (_dto.ItemTypeId < 1)
                {
                    return Ok(JsonView(false, "未选择物料类型"));
                }
                if (_dto.SysUserId < 1)
                {
                    return Ok(JsonView(false, "当前操作用户Id为空"));
                }
                if (_dto.CurrRate <= 0)
                {
                    return Ok(JsonView(false, "物料录入价格不能小于等于0"));
                }

                if (_dto.EditType == 0)
                {
                    //判断物料名称、类型、供应商全部重复
                    var checkEmpty = _resItemInfoRep.Query<Res_ItemDetailInfo>(s => s.ItemName == _dto.ItemName && s.ItemTypeId == _dto.ItemTypeId && s.VendorId == _dto.VendorId).First();
                    if (checkEmpty != null)
                    {
                        return Ok(JsonView(false, "已存在重复物料信息"));
                    }
                    Res_ItemDetailInfo _entity = _mapper.Map<Res_ItemDetailInfo>(_dto);
                    DateTime dtNow = DateTime.Now;
                    _entity.CreateUserId = _dto.SysUserId;
                    _entity.IsDel = 0;
                    _entity.MaxRate = _dto.CurrRate;
                    _entity.MaxDt = dtNow;
                    _entity.CurrRate = _dto.CurrRate;
                    _entity.CurrDt = dtNow;
                    _entity.MinRate = _dto.CurrRate;
                    _entity.MinDt = dtNow;

                    rst = await _resItemInfoRep.AddAsync<Res_ItemDetailInfo>(_entity) > 0;
                }
                else if (_dto.EditType == 1)
                {
                    if (_dto.ItemId > 0)
                    {
                        Res_ItemDetailInfo _entity = _mapper.Map<Res_ItemDetailInfo>(_dto);
                        _entity.Id = _dto.ItemId;

                        rst = await _resItemInfoRep.updItemInfo(_entity);
                    }
                    else
                    {
                        return Ok(JsonView(false, "供应商不存在"));
                    }
                }
            }
            else
            {
                if (_dto.ItemId < 1 || _dto.SysUserId < 1)
                {
                    return Ok(JsonView(false, "用户Id或物料信息Id不存在"));
                }
                Res_ItemDetailInfo _entity = _mapper.Map<Res_ItemDetailInfo>(_dto);

                rst = await _resItemInfoRep.delItemInfo(_entity);
            }

            return Ok(JsonView(rst));
        }
        #endregion
        #region 物料类型获取

        #endregion
        #endregion

        #region 备忘录
        /// <summary>
        /// 备忘录查询
        /// </summary>
        /// <param name="paras">Json序列化</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostSearchMemo(JsonDtoBase _jsonDto)
        {
            if (string.IsNullOrEmpty(_jsonDto.Paras))
            {
                return Ok(JsonView(false, "参数为空"));
            }

            Search_ResMemoDto _memoDto = JsonConvert.DeserializeObject<Search_ResMemoDto>(_jsonDto.Paras);
            if (_memoDto != null)
            {
                if (_memoDto.SearchType == 2)
                {
                    //获取列表
                    string sqlWhere = string.Format(" Where IsDel=0 ");

                    #region SqlWhere

                    if (!string.IsNullOrEmpty(_memoDto.Abstracts))
                    {
                        sqlWhere += string.Format(@" And m.Abstracts Like '%{0}%' ", _memoDto.Abstracts);
                    }
                    if (!string.IsNullOrEmpty(_memoDto.Title))
                    {
                        sqlWhere += string.Format(@" And m.Title Like '%{0}%' ", _memoDto.Title);
                    }
                    if (_memoDto.ReadLevel > 0)
                    {
                        sqlWhere += string.Format(@" And m.ReadLevel = {0} ", _memoDto.ReadLevel);
                    }
                    #endregion

                    int currPIndex = (((_memoDto.PageIndex > 0) ? (_memoDto.PageIndex - 1) : 0) * _memoDto.PageSize) + 1;
                    int currPSize = (((_memoDto.PageIndex > 0) ? (_memoDto.PageIndex - 1) : 0) + 1) * _memoDto.PageSize;
                    string sql = string.Format(@" Select * From(Select ROW_NUMBER() Over(order By m.Id desc) as RowNumber,
m.Id as MemoId,d.DepName as DepartmentName,m.ReadLevel,m.Title,m.Abstracts,
m.LastedEditDt,m.LastedEditorId
From Res_Memo as m With(Nolock) Inner Join Sys_Users as u With(Nolock) On m.CreateUserId=u.Id
Inner Join Sys_Department as d With(Nolock) On u.DepId=d.Id {2}
) as tb Where tb.RowNumber Between {0} And {1} ", currPIndex, currPSize, sqlWhere);
                    Res_MemoListView rst = new Res_MemoListView();
                    rst.CurrPageIndex = currPIndex;
                    rst.CurrPageSize = currPSize;
                    List<Res_MemoView> dataSource = _carDataRep._sqlSugar.SqlQueryable<Res_MemoView>(sql).ToList();
                    Dictionary<int, string> userDic = new Dictionary<int, string>();

                    foreach (var item in dataSource)
                    {
                        if (userDic.ContainsKey(item.LastedEditorId))
                        {
                            item.LastedEditor = userDic[item.LastedEditorId];
                        }
                        else
                        {
                            Sys_Users _sysUser = _carDataRep.Query<Sys_Users>(s => s.Id == item.LastedEditorId).First();
                            userDic[item.LastedEditorId] = _sysUser.CnName;
                            item.LastedEditor = _sysUser.CnName;
                        }
                    }
                    rst.DataList = new List<Res_MemoView>(dataSource);

                    if (rst.DataList.Count > 0)
                    {
                        string sqlCount = string.Format(@" Select Id From Res_Memo as m With(Nolock) {0} ", sqlWhere);
                        int dataCount = _carDataRep._sqlSugar.SqlQueryable<Res_MemoInfo>(sqlCount).Count();
                        rst.DataCount = dataCount;
                    }
                    return Ok(JsonView(rst));
                }
                else
                {
                    //获取对象
                    string sqlSingle = string.Format(@" Select 
m.Id as MemoId,d.DepName as DepartmentName,m.ReadLevel,m.Title,m.Abstracts,
m.LastedEditDt,m.LastedEditor,m.MDFilePath
From Res_Memo as m With(Nolock) Inner Join Sys_Users as u With(Nolock) On m.CreateUserId=u.Id
Inner Join Sys_Department as d With(Nolock) On u.DepId=d.Id Where m.Id={0} ", _memoDto.MemoId);
                    Res_MemoView _result = _carDataRep._sqlSugar.SqlQueryable<Res_MemoView>(sqlSingle).First();
                    if (_result != null)
                    {
                        Sys_Users _sysUser = _carDataRep.Query<Sys_Users>(s => s.Id == _result.LastedEditorId).First();
                        _result.LastedEditor = _sysUser.CnName;
                        _result.MarkDownContent = new IOOperatorHelper().Read(_result.MDFilePath);
                        return Ok(JsonView(_result));
                    }
                }
            }
            else
            {
                return Ok(JsonView(false, "参数反序列化失败"));
            }




            return Ok(JsonView(false));
        }


        /// <summary>
        /// 创建/编辑/删除备忘录信息
        /// </summary>
        /// <param name="_dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostEditMemo(Edit_ResMemoDto _dto)
        {
            bool rst = false;
            if (_dto.SysUserId < 1)
            {
                return Ok(JsonView(false, "操作人失效"));
            }
            Sys_Users _sysUser = _resItemInfoRep.Query<Sys_Users>(s => s.Id == _dto.SysUserId).First();
            if (_sysUser == null)
            {
                return Ok(JsonView(false, "操作人失效02"));
            }

            if (_dto.EditType >= 0)
            {
                if (_dto.ReadLevel < 1)
                {
                    return Ok(JsonView(false, "未知的阅读等级"));
                }
                if (string.IsNullOrEmpty(_dto.Title.Trim()))
                {
                    return Ok(JsonView(false, "标题不能为空"));
                }
                if (string.IsNullOrEmpty(_dto.Content.Trim()))
                {
                    return Ok(JsonView(false, "正文内容不能为空"));
                }
                //新增备忘录
                DateTime dtNow = DateTime.Now;
                string dir = AppSettingsHelper.Get("MemoCurrPath");
                string fileName = dtNow.ToString("yyyyMMddHHmmss") + _dto.Title + ".md";
                string content = JsonConvert.SerializeObject(_dto.Content);
                if (_dto.EditType == 0)//新增
                {
                    string savePath = new IOOperatorHelper().Write_CoverFile(content, dir, fileName);

                    if (savePath.Length > 0)
                    {
                        Res_MemoInfo _insert = new Res_MemoInfo();
                        _insert.Abstracts = _dto.Abstracts;
                        _insert.Title = _dto.Title;
                        _insert.DepartmentId = _sysUser.DepId;
                        _insert.CreateUserId = _sysUser.Id;
                        _insert.LastedEditDt = dtNow;
                        _insert.LastedEditor = _sysUser.Id;
                        _insert.MDFilePath = savePath;
                        _insert.ReadLevel = _dto.ReadLevel;
                        _insert.Title = _dto.Title;
                        int result = await _resItemInfoRep.AddAsync(_insert);
                        return Ok(JsonView(result > 0));
                    }
                    else
                    {
                        return Ok(JsonView(false, "路径保存失败"));
                    }
                }
                else//修改
                {
                    if (_dto.MemoId < 1)
                    {
                        return Ok(JsonView(false, "MemoId不存在"));
                    }

                    Res_MemoInfo _source = _resItemInfoRep.Query<Res_MemoInfo>(s => s.Id == _dto.MemoId).First();
                    if (_source == null)
                    {
                        return Ok(JsonView(false, "MemoInfo不存在"));
                    }
                    //修改
                    string sourcePath = _source.MDFilePath;
                    string recycDir = AppSettingsHelper.Get("MemoRecycleBinPath");
                    new IOOperatorHelper().MoveFile(sourcePath, recycDir);
                    string savePath = new IOOperatorHelper().Write_CoverFile(content, dir, fileName);

                    if (savePath.Length > 0)
                    {
                        var result = await _resItemInfoRep._sqlSugar.Updateable<Res_MemoInfo>()
                                                                    .SetColumns(it => it.LastedEditDt == DateTime.Now)
                                                                    .SetColumns(it => it.LastedEditor == _sysUser.Id)
                                                                    .SetColumns(it => it.Abstracts == _dto.Abstracts)
                                                                    .SetColumns(it => it.MDFilePath == savePath)
                                                                    .SetColumns(it => it.ReadLevel == _dto.ReadLevel)
                                                                    .SetColumns(it => it.Title == _dto.Title)
                                                                    .Where(s => s.Id == _source.Id)
                                                                    .ExecuteCommandAsync();
                        return Ok(JsonView(result > 0));
                    }
                }
            }
            else
            {
                //删除
                if (_dto.MemoId < 1)
                {
                    return Ok(JsonView(false, "MemoId不存在"));
                }

                Res_MemoInfo _source = _resItemInfoRep.Query<Res_MemoInfo>(s => s.Id == _dto.MemoId).First();
                if (_source == null)
                {
                    return Ok(JsonView(false, "MemoInfo不存在"));
                }
                //修改
                string sourcePath = _source.MDFilePath;
                string recycDir = AppSettingsHelper.Get("MemoRecycleBinPath");
                new IOOperatorHelper().MoveFile(sourcePath, recycDir);

                var result = await _resItemInfoRep._sqlSugar.Updateable<Res_MemoInfo>()
                                                            .SetColumns(it => it.IsDel == 1)
                                                            .SetColumns(it => it.DeleteUserId == _sysUser.Id)
                                                            .SetColumns(it => it.DeleteTime == DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                                                            .Where(s => s.Id == _source.Id)
                                                            .ExecuteCommandAsync();
                return Ok(JsonView(result > 0));

            }

            return Ok(JsonView(rst));
        }

        #endregion

        #region 商邀资料


        /// <summary>
        /// 商邀资料 基础数据源
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryIOAInitData(QueryIOAInitDataDto dto)
        {
            try
            {
                #region 参数验证

                if (dto.PortType < 1) return Ok(JsonView(false, "请传入有效的PortType参数！"));

                #endregion

                List<Grp_DelegationInfo> _DelegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0).OrderByDescending(it => it.JietuanTime).ToList();
                List<Res_InvitationOfficialActivityData> _ioaDatas = _sqlSugar.Queryable<Res_InvitationOfficialActivityData>().Where(it => it.IsDel == 0).ToList();
                List<Sys_Users> _Users = _sqlSugar.Queryable<Sys_Users>().Where(it => it.IsDel == 0).ToList();

                var _countryData = _ioaDatas.Select(it => it.Country).Distinct().ToList(); _countryData.Remove("");
                var _inviterData = _ioaDatas.Select(it => it.UnitName).Distinct().ToList(); _inviterData.Remove("");
                var _contactData = _ioaDatas.Select(it => it.Contact).Distinct().ToList(); _contactData.Remove("");
                var _domainData = _ioaDatas.Select(it => it.Field).Distinct().ToList(); _domainData.Remove("");
                var _groupNameData = _DelegationInfos.Select(it => new { it.Id, it.TeamName }).ToList();
                var _userNameData = _Users.Select(it => new { it.Id, it.CnName }).ToList();

                var _data = new {
                    CountryData = _countryData,
                    InviterData = _inviterData,
                    DomainData = _domainData,
                    ContactData = _contactData,
                    GroupNameData = _groupNameData,
                    UserNameData = _userNameData,
                };

                return Ok(JsonView(true, $"查询成功!", _data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }

        /// <summary>
        /// 商邀资料查询
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryInvitationOfficialActivityData(QueryInvitationOfficialActivityDataDto dto)
        {
            try
            {
                #region 参数验证

                if (dto.PageIndex < 1) return Ok(JsonView(false, "请传入有效的PageIndex参数！"));

                if (dto.PageSize < 1) return Ok(JsonView(false, "请传入有效的PageSize参数！"));

                #endregion

                string sqlWhere = string.Empty;
                if (!string.IsNullOrWhiteSpace(dto.Country)) { sqlWhere += string.Format(@" And i.Country like '%{0}%'", dto.Country); }
                if (!string.IsNullOrWhiteSpace(dto.UnitName)) { sqlWhere += string.Format(@" And i.UnitName like '%{0}%'", dto.UnitName); }
                if (!string.IsNullOrWhiteSpace(dto.Contact)) { sqlWhere += string.Format(@" And i.Contact like '%{0}%'", dto.Contact); }
                if (!string.IsNullOrWhiteSpace(dto.Delegation)) { sqlWhere += string.Format(@" And i.Delegation like '%{0}%'", dto.Delegation); }
                if (!string.IsNullOrWhiteSpace(dto.Field)) { sqlWhere += string.Format(@" And i.Field like '%{0}%'", dto.Field); }

                if (dto.CreateUserId != 0 && !string.IsNullOrWhiteSpace(dto.CreateUserId.ToString())) { sqlWhere += string.Format(@" And i.CreateUserId={0}", dto.CreateUserId); }
                if (!string.IsNullOrWhiteSpace(dto.StartCreateTime) && !string.IsNullOrWhiteSpace(dto.EndCreateTime))
                {
                    sqlWhere += string.Format(@" And i.CreateTime between '{0}' and '{1}'", dto.StartCreateTime, dto.EndCreateTime);
                }
                sqlWhere += string.Format(@"And i.Isdel={0}", 0);

                if (!string.IsNullOrEmpty(sqlWhere.Trim()))
                {
                    Regex r = new Regex("And");
                    sqlWhere = r.Replace(sqlWhere, "Where", 1);
                }
                string sql = string.Format(@"Select ROW_NUMBER() Over(Order By i.CreateTime Desc) As Row_Number,
                                             i.*,u.CnName As CreateUserName 
                                             From Res_InvitationOfficialActivityData i 
                                             Left Join Sys_Users u On i.CreateUserId = u.Id {0}", sqlWhere);

                int totalCount = 0;

                List<InvitationOfficialActivityDataView> _ivitiesViews = _sqlSugar.SqlQueryable<InvitationOfficialActivityDataView>(sql).ToPageList(dto.PageIndex, dto.PageSize, ref totalCount);

                List<Grp_DelegationInfo> _DelegationInfos = _sqlSugar.Queryable<Grp_DelegationInfo>().ToList();

                foreach (var item in _ivitiesViews)
                {
                    string delegationNameList = "";
                    if (!string.IsNullOrEmpty(item.Delegation))
                    {
                        string[] DelegationName = item.Delegation.Split(',');
                        for (int i = 0; i < DelegationName.Length; i++)
                        {
                            string grpId = DelegationName[i];
                            if (!string.IsNullOrEmpty(grpId))
                            {
                                if (grpId.IsNumeric())
                                {
                                    delegationNameList += _DelegationInfos.Find(it => it.Id == int.Parse(grpId))?.TeamName ?? "Unknown" + ",";
                                }
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(delegationNameList))
                        {
                            item.DelegationStr = delegationNameList.Substring(0, delegationNameList.Length - 1);
                        }
                    }
                }

                return Ok(JsonView(true, $"查询成功!", _ivitiesViews, totalCount));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        /// <summary>
        /// 根据商邀资料Id查询信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryInvitationOfficialActivityById(QueryInvitationOfficialActivityByIdDto dto)
        {
            try
            {
                Result groupData = await _InvitationOfficialActivityDataRep.QueryInvitationOfficialActivityById(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 商邀资料操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OpInvitationOfficialActivity(OpInvitationOfficialActivityDto dto)
        {
            try
            {
                Result groupData = await _InvitationOfficialActivityDataRep.OpInvitationOfficialActivity(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 删除商邀资料信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelInvitationOfficialActivity(DelBaseDto dto)
        {
            try
            {
                var res = await _InvitationOfficialActivityDataRep.SoftDeleteByIdAsync<Res_InvitationOfficialActivityData>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        #endregion

        #region 公务出访
        /// <summary>
        ///  获取团组所有信息,绑定下拉框
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetGroupAllList(OfficialActivitiesByDiIdDto dto)
        {
            //string groupSql = string.Format("Select * From Grp_DelegationInfo With(NoLock) Where IsDel = 0 Order By CreateTime Desc");
            //List<Grp_DelegationInfo> _DelegationInfos = _sqlSugar.SqlQueryable< Grp_DelegationInfo >(groupSql).ToList();

            var _groupData = await _delegationInfoRep.PostShareGroupInfos(1);
            dynamic groupInfos = null;
            if (_groupData.Code == 0) groupInfos = _groupData.Data;

            List<Sys_SetData> data = _sqlSugar.Queryable<Sys_SetData>().Where(a => a.IsDel == 0 && a.STid == 38).ToList();
            List<Grp_DeleFile> _DeleFile = _sqlSugar.Queryable<Grp_DeleFile>().Where(a => a.Diid == dto.DiId && a.IsDel == 0 && a.Category == 970).ToList();
            return Ok(JsonView(true, "查询成功！", new { Delegation = groupInfos, SetData = data, DeleFile = _DeleFile }));
        }
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryOfficialActivitiesByDiId(OfficialActivitiesByDiIdDto dto)
        {
            Result groupData = await _officialActivitiesRep.QueryOfficialActivitiesByDiId(dto);
            if (groupData.Code != 0)
            {
                return Ok(JsonView(false, groupData.Msg));
            }
            return Ok(JsonView(true, groupData.Msg, groupData.Data));
            
        }
        /// <summary>
        /// 根据公务出访数据Id查询数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryOfficialActivitiesById(OfficialActivitiesDiIdDto dto)
        {
            try
            {
                Result groupData = await _officialActivitiesRep.QueryOfficialActivitiesById(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 公务出访操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OpOfficialActivities(OpOfficialActivitiesDto dto)
        {
            try
            {
                Result groupData = await _officialActivitiesRep.OpOfficialActivities(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> UploadOfficialActivities(IFormFile file)
        {
            try
            {
                int Type = int.Parse(Request.Headers["Type"]);//1公务方简介，2公务活动图片，3发票
                int DiId = int.Parse(Request.Headers["DiId"]);
                int CreateUserId = int.Parse(Request.Headers["CreateUserId"]);
                if (file != null)
                {
                    var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
                    //文件名称
                    string projectFileName = file.FileName;
                    //上传的文件的路径
                    string filePath = "";
                    if (!Directory.Exists(fileDir))
                    {
                        Directory.CreateDirectory(fileDir);
                    }

                    //上传的文件的路径
                    filePath = fileDir + $@"\商邀相关文件\{projectFileName}";
                    using (FileStream fs = System.IO.File.Create(filePath))
                    {
                        file.CopyTo(fs);
                        fs.Flush();
                    }
                    Grp_DeleFile d = new Grp_DeleFile();
                    d.Diid = DiId;
                    d.Category = 970;
                    if (Type == 1) d.Kind = 1;
                    else if (Type == 2) d.Kind = 2;
                    else if (Type == 3) d.Kind = 3;
                    d.FileName = projectFileName;
                    d.FilePath = "";
                    d.CreateUserId = CreateUserId;
                    int id = await _sqlSugar.Insertable(d).ExecuteReturnIdentityAsync();

                    return Ok(JsonView(true, "上传成功！", projectFileName));
                }
                else
                {
                    return Ok(JsonView(false, "上传失败！"));
                }
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelloadOfficialActivities(DelBaseDto dto)
        {
            try
            {
                var fileDir = AppSettingsHelper.Get("GrpFileBasePath");
                Grp_DeleFile _DeleFile = await _sqlSugar.Queryable<Grp_DeleFile>().FirstAsync(a => a.Id == dto.Id);
                if (_DeleFile != null)
                {
                    string fileName = _DeleFile.FileName;
                    string filePath = fileDir + "/团组增减款项相关文件/" + fileName;
                    // 删除该文件
                    System.IO.File.Delete(filePath);
                    int id = await _sqlSugar.Updateable<Grp_DeleFile>().Where(a => a.Id == dto.Id).SetColumns(a => new Grp_DeleFile { IsDel = 1, DeleteUserId = dto.DeleteUserId, DeleteTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }).ExecuteCommandAsync();
                    return Ok(JsonView(true, "取消文件成功！"));
                }
                else
                {
                    return Ok(JsonView(false, "取消文件失败！"));
                }
                
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 删除公务出访信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelOfficialActivities(DelBaseDto dto)
        {
            try
            {
                var res = await _officialActivitiesRep.SoftDeleteByIdAsync<Res_OfficialActivities>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }



        /// <summary>
        /// 公务出访
        /// 请示范例提示 
        /// Add Time：2024-05-13 13:56:44
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostOfficialActivitiesReqReqSampleTips(PostOfficialActivitiesReqReqSampleTipsDto dto)
        {
            var res = await _officialActivitiesRep.PostReqReqSampleTips(dto.country, dto.area,dto.client);
            if (res.Code == 0)
            {
                return Ok(JsonView(true, "操作成功!", res.Data));
            }
            return Ok(JsonView(false, res.Msg));
        }

        /// <summary>
        /// 公务出访 (省外办，市外办) File Downlaod
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OfficialActivitiesFileDownload(OfficialActivitiesFileDownload dto)
        {
            #region 参数验证

            if (dto.FileType < 1 || dto.FileType > 2) return Ok(JsonView(false, "请传入有效的FileType参数. 1 省外办出访请示 2 市外办出访请示"));
            if (dto.DiId < 1) return Ok(JsonView(false, "请传入有效的DiId参数."));

            #endregion
            //团组基础信息
            var groupInfo = _sqlSugar.Queryable<Grp_DelegationInfo>().Where(it => it.IsDel == 0 && it.Id == dto.DiId).First();
            if (groupInfo == null) return Ok(JsonView(false, "该团组基本信息不存在"));
            groupInfo.VisitCountry = groupInfo.VisitCountry.Replace("|", "、");

            //团组公务信息
            var obDatas = _sqlSugar.Queryable<Res_OfficialActivities>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId).OrderBy(it => it.Date).ToList();
            //if (obDatas.Count < 1) return Ok(JsonView(false, "请先录入公务信息!"));

            //团组客户名单
            var guestResult = _tourClientListRep._ItemByDiId(1, dto.DiId);
            List<TourClientListByDiIdView> guestInfos = new List<TourClientListByDiIdView>();
            if (guestResult.Result.Code == 0) guestInfos = guestResult.Result.Data as List<TourClientListByDiIdView>;

            string visitCountrys = ""; //××国家（或地区）×天，××国家（或地区）×天
            string countryStayStr = ""; // xx、xx、xx
            //出入境费用 住宿类型
            var dayCostDatas = _sqlSugar.Queryable<Grp_DayAndCost>().Where(it => it.IsDel == 0 && it.DiId == dto.DiId && it.Type == 1).ToList();
            if (dayCostDatas.Count > 0)
            {
                List<int> nationalIds = dayCostDatas.Select(it => it.NationalTravelFeeId).ToList();
                var nationalDatas = _sqlSugar.Queryable<Grp_NationalTravelFee>().Where(it => nationalIds.Contains(it.Id)).ToList();
                var nationalDataGroupByCountry = nationalDatas.GroupBy(it => it.Country);
                foreach (var item in nationalDataGroupByCountry)
                {
                    visitCountrys += $"{item.Key}、";
                    int stayDays = nationalIds.Where(it => it == item.ToList()[0].Id).Count();
                    countryStayStr += $"{item.Key}{stayDays}天，";
                }

                if (visitCountrys.Length > 0) visitCountrys = visitCountrys.Substring(0, visitCountrys.Length - 1);
                if (countryStayStr.Length > 0) countryStayStr = countryStayStr.Substring(0, countryStayStr.Length - 1);

            }
            else
            {
                visitCountrys = groupInfo.VisitCountry;
                countryStayStr = GeneralMethod.GetCountryStandingTime(groupInfo.Id); //计算国家出访天数
            }

            //出访人数
            int visitPeopleNum = groupInfo.VisitPNumber;
            int visitDaysNum = groupInfo.VisitDays;

            //出访单位
            string obInfoStr = "";
            foreach (var ob in obDatas) obInfoStr += @$"{ob.Client.Trim()}{ob.Job.Trim()}{ob.Contact.Trim()}、";
            if (obInfoStr.Length > 0) obInfoStr = obInfoStr.Substring(0, obInfoStr.Length - 1);
            obInfoStr = obInfoStr ?? "[公务出访未录入]";

            //出访路线
            string lineStr = GeneralMethod.GetGroupCityLine(groupInfo.Id, "—");

            if (dto.FileType == 1)
            {
                //载入模板
                string tempPath = AppSettingsHelper.Get("WordBasePath") + "Template/省外办出访请示 - 模板.docx";
                var doc = new Document(tempPath);
                DocumentBuilder builder = new DocumentBuilder(doc);

                //键值对存放数据
                Dictionary<string, string> dic = new Dictionary<string, string>();

                //××（组团单位）:接团客户信息团组
                dic.Add("GroupClient", $"{groupInfo.ClientUnit}\r\n");

                //关于××（职务、姓名）等×人赴××（国家或地区）进行×××（出访目的）的请示
                string guestName = "";
                string guestJob = "";
                string guestInfoStr = "";
                var guestFirstInfo = guestInfos.FirstOrDefault();
                if (guestFirstInfo != null)
                {
                    guestName = guestFirstInfo.LastName.Trim() + guestFirstInfo.FirstName.Trim();
                    guestJob = guestFirstInfo.Job.Trim();
                    guestInfoStr = $@"{guestJob}、{guestName}";
                }
                guestInfoStr = guestInfoStr ?? "[接团客户名单未录入]";
                string askTitle = $@"关于{guestInfoStr }等{visitPeopleNum}人赴{visitCountrys}进行{groupInfo.VisitPurpose}的请示";
                dic.Add("AskTitle", askTitle);

                //应×××（邀请方名称+邀请人职务和姓名）的邀请，我单位拟派×××（职务、姓名）等×人（人数）于×××年×××月×××日赴×××（国家或地区）进行×××（出访目的）。现请示如下。
                string visitDateStr = @$"{groupInfo.VisitDate.Year}年{groupInfo.VisitDate.Month}月{groupInfo.VisitDate.Day}日";
               
                string askSubTitle = $@"应{obInfoStr}的邀请，我单位拟派{guestInfoStr}等{visitPeopleNum}人于{visitDateStr}赴{visitCountrys}进行{groupInfo.VisitPurpose}。现请示如下。";
                dic.Add("AskSubTitle", askSubTitle);

                //出访目的
                dic.Add("VisitPurpose", groupInfo.VisitPurpose);

                //出访任务
                //（一）××（国家或地区）
                //1.拜访×××（机构名称）×××（姓名、职务）洽谈（或调研、推动等）×××（项目或机构名称等）。（例：拜会×××经济与发展司司长×××，商讨“×××活动”相关筹备工作。）
                //2.拜访×××（机构名称）×××（姓名、职务）洽谈（或调研、推动等）×××（项目或机构名称等）。（例：拜会×××经济与发展司司长×××，商讨“×××活动”相关筹备工作。）

                string obBackgroundStr = "";//出访背景
                string taskStr = ""; ; //出访任务
                var countrys = obDatas.GroupBy(it => it.Country);
                int countryIndex = 1;
                foreach (var item in countrys)
                {
                    string taskTitle = $"（{GetToUpperNumber(countryIndex)}）{item.Key}\r\n";

                    string taskContent = "";
                    string obBackgroundContent = "";
                    int obIndex = 1;
                    foreach (var obInfo in item.ToList())
                    {
                        string reqSmaple = "";
                        string settingStr = "";
                        if (!string.IsNullOrEmpty(obInfo.ReqSample)) reqSmaple = obInfo.ReqSample;
                        else reqSmaple = "[公务出访请示范例未录入]";

                        if (!string.IsNullOrEmpty(obInfo.Setting)) settingStr = obInfo.Setting;
                        else settingStr = "[公务方背景未录入]";

                        taskContent += $"{obIndex}. {reqSmaple}\r\n";
                        obBackgroundContent += $"{obIndex}. {obInfo.Client}：{settingStr}\r\n";
                        obIndex++;
                    }

                    taskStr += $"{taskTitle}{taskContent}";
                    obBackgroundStr += $"{taskTitle}{obBackgroundContent}";
                    countryIndex++;
                }

                //出访背景
                if (obBackgroundStr.Length < 1) obBackgroundStr = "[公务出访背景未录入]";
                dic.Add("OBSetting", obBackgroundStr);

                //出访任务
                if (taskStr.Length < 1) taskStr = "[公务出访任务未录入]";
                dic.Add("TaskContent", taskStr);

                //出访时间
                //代表团拟于××年×月×日—×月×日出访，在外停留×天。其中，××国家（或地区）×天，××国家（或地区）×天。
                string visitTimeQuantumStr = $"代表团拟于{groupInfo.VisitStartDate.Year}年{groupInfo.VisitStartDate.Month}月{groupInfo.VisitStartDate.Day}日—{groupInfo.VisitEndDate.Month}月{groupInfo.VisitEndDate.Day}日出访，在外停留{visitDaysNum}天。其中，{countryStayStr}。";
                //出访时间
                dic.Add("TimeQuantum", visitTimeQuantumStr);

                //出访路线
                //成都—××(出境城市名称)—××（转机不出机场）—××（公务所在城市）……—××（入境城市名称）—成都。（例：成都—法兰克福<转机不出机场>—巴黎—巴塞罗那—阿姆斯特丹<转机不出机场>-成都）
                
                dic.Add("Line", lineStr);

                //scheduling //行程安排
                string schedulingStr = $"[OP行程单暂未生成]";

                #region op行程 根据黑屏代码录入

                var opTripView = GeneralMethod.GetBriefStroke(groupInfo.Id);
                if (opTripView.Code != 0) schedulingStr = $"[{opTripView.Msg}]";

                schedulingStr = "";

                List<Grp_TravelList> travelList = new List<Grp_TravelList>();
                travelList = opTripView.Data as List<Grp_TravelList>;

                foreach (var item in travelList)
                {
                    schedulingStr += $"{item.Date}（{item.WeekDay}）\r\n{item.Trip}\r\n";
                }

                #endregion

                dic.Add("Scheduling", schedulingStr);

                #region 填充word模板书签内容
                foreach (var key in dic.Keys)
                {
                    builder.MoveToBookmark(key);
                    builder.Write(dic[key]);
                }
                #endregion

                //获取word里所有表格
                NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
                //获取所填表格的序数
                Aspose.Words.Tables.Table tableOne = allTables[0] as Aspose.Words.Tables.Table;

                var rowStart = tableOne.Rows[0]; //获取第1行

                //循环赋值
                for (int i = 0; i < guestInfos.Count; i++)
                {
                    var guestInfo = guestInfos[i];
                    builder.MoveToCell(0, i + 1, 0, 0);
                    builder.Write(guestInfo.LastName + guestInfo.FirstName);

                    builder.MoveToCell(0, i + 1, 1, 0);
                    int sex = guestInfo.Sex;
                    string sexStr = string.Empty;
                    if (sex == 0) sexStr = "男";
                    else if (sex == 1) sexStr = "女";
                    else sexStr = "-";
                    builder.Write(sexStr);

                    builder.MoveToCell(0, i + 1, 2, 0);
                    builder.Write(guestInfo.CompanyFullName + guestInfo.Job);


                    builder.MoveToCell(0, i + 1, 3, 0);
                    string birthDay = "";
                    string birthDayStr = string.Empty;
                    if (guestInfo.BirthDay != null)
                    {
                        birthDayStr = guestInfo.BirthDay.ToString("yyyy.MM");
                    }
                    builder.Write(birthDayStr);
                }

                //删除多余行
                while (tableOne.Rows.Count > guestInfos.Count + 1)
                {
                    tableOne.Rows.RemoveAt(guestInfos.Count + 1);
                }

                var fileDir = AppSettingsHelper.Get("WordBasePath");
                string fileName = $"{groupInfo.TeamName}省外办出访请示{DateTime.Now.ToString("yyyyMMddHHmmss")}.docx";
                string filePath = fileDir + $@"OfficialActivities/{fileName}";
                doc.Save(filePath);

                string Url = $@"{AppSettingsHelper.Get("WordBaseUrl")}Office/Word/OfficialActivities/{fileName}";
                return Ok(JsonView(true, "操作成功！", Url));
            }
            else if (dto.FileType == 2)
            {
                //载入模板
                string tempPath = AppSettingsHelper.Get("WordBasePath") + "Template/市外办出访请示 - 模板.docx";
                var doc = new Document(tempPath);
                DocumentBuilder builder = new DocumentBuilder(doc);

                //键值对存放数据
                Dictionary<string, string> dic = new Dictionary<string, string>();

                //××（组团单位）:接团客户信息团组
                dic.Add("GroupClient", $"{groupInfo.ClientUnit}");
                
                dic.Add("GroupClient1", $"{groupInfo.ClientUnit}");
                //关于××（职务、姓名）等×人赴××（国家或地区）进行×××（出访目的）的请示
                string guestName = "";
                string guestJob = "";
                string guestInfoStr = "";
                var guestFirstInfo = guestInfos.FirstOrDefault();
                if (guestFirstInfo != null)
                {
                    guestName = guestFirstInfo.LastName.Trim() + guestFirstInfo.FirstName.Trim();
                    guestJob = guestFirstInfo.Job;
                    guestInfoStr = $@"{guestJob}、{guestName.Trim()}";
                }
                string reqTitle = $@"关于{guestInfoStr}等{visitPeopleNum}人赴{visitCountrys}进行{groupInfo.VisitPurpose}的请示";
                dic.Add("ReqTitle", reqTitle);

                //应×××（邀请方名称+邀请人职务和姓名）的邀请，我单位拟派×××（职务、姓名）等×人（人数）于×××年×××月×××日赴×××（国家或地区）进行×××（出访目的）。
                string visitDateStr = @$"{groupInfo.VisitDate.Year}年{groupInfo.VisitDate.Month}月{groupInfo.VisitDate.Day}日";


                string reqSubTitle = $@"应{obInfoStr}的邀请，我单位拟派{guestInfoStr}等{visitPeopleNum}人于{visitDateStr}赴{visitCountrys}进行{groupInfo.VisitPurpose}。";
                dic.Add("ReqSubTitle", reqSubTitle);

                /*
                 * 出访任务
                 * （一）××（国家或地区）
                 * 1．拜访×××（机构名称）×××（姓名、职务）洽谈（或调研、推动等）×××（项目或机构名称等）。（例：拜会×××经济与发展司司长×××，商讨“×××活动”相关筹备工作。）背景：拟拜访机构的优势、拟洽谈项目的前期进展情况等。（例：背景：由×××总领馆联合×××市政府共同举办的“×××活动”将于今年6月在×××举行。）
                 * 2．拜访×××（机构名称）×××（姓名、职务）洽谈（或调研等）×××（项目或机构名称等）。（例：拜会友城×××市市长×××，巩固和发展两市传统友谊，商谈两市未来互动交流合作项目。）背景：拟拜访机构的优势、拟洽谈项目的前期进展情况等。（例：背景：×××年×月，×××市与×××市正式缔结友好城市关系。在此框架下，两市开展了一系列友好互访和商务交流。并于×××年×月共同举办了“×××活动”。）
                 * 
                 */

                string taskStr = string.Empty ;
                List<string> countrys = obDatas.Select(it => it.Country).ToList();
                int countryIndex = 1;
                foreach (var item in countrys)
                {

                    string taskTitle = $"（{GetToUpperNumber(countryIndex)}）{item ?? "[公务出访国家未填写]"}\r\n";

                    string taskContent = "";
                    if (!string.IsNullOrEmpty(item))
                    {
                        var countryObDatas = obDatas.Where(it => it.Country.Contains(item)).OrderBy(it => it.Date).ToList();
                        int obIndex = 1;
                        if (countryObDatas.Count == 0) taskContent = "[公务出访未录入]\r\n";
                        else
                        {
                            foreach (var obInfo in countryObDatas)
                            {
                                taskContent += $"{obIndex}.{obInfo.ReqSample ?? "[公务出访请示范例未填写]"}\r\n背景：{obInfo.Setting ?? "[公务出访背景未填写]"}\r\n";
                                obIndex++;
                            }
                        }
                    }
                    taskStr += $"{taskTitle}{taskContent}";

                    countryIndex++;
                }

                if (string.IsNullOrEmpty(taskStr)) taskStr = "××××××";

                //出访任务
                dic.Add("TaskContent", taskStr);

                //出访目的
                dic.Add("VisitPurpose", groupInfo.VisitPurpose);

                //出访信息
                //代表团拟于××年×月×日—×月×日出访，在外停留×天。其中，××国家（或地区）×天，××国家（或地区）×天。出访路线：成都—××(出境城市名称)—××（转机不出机场）—××（公务所在城市）……—××（入境城市名称）—成都。（例：成都—法兰克福<转机不出机场>—巴黎—巴塞罗那—阿姆斯特丹<转机不出机场>-成都）出访费用：由××承担（注明由外方或上级机关承担，还是由派员单位在年度安排的预算经费中列支）。

                string tripInfoStr = "";
                tripInfoStr = $"代表团拟于{groupInfo.VisitStartDate.Year}年{groupInfo.VisitStartDate.Month}月{groupInfo.VisitStartDate.Day}日—{groupInfo.VisitEndDate.Month}月{groupInfo.VisitEndDate.Day}日出访，在外停留{visitDaysNum}天。其中，{countryStayStr}。出访路线：{lineStr}。出访费用：由××承担（注明由外方或上级机关承担，还是由派员单位在年度安排的预算经费中列支）";


                dic.Add("TripInfo", tripInfoStr);


                #region 填充word模板书签内容
                foreach (var key in dic.Keys)
                {
                    builder.MoveToBookmark(key);
                    builder.Write(dic[key]);
                }
                #endregion

                //获取word里所有表格
                NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
                //获取所填表格的序数
                Aspose.Words.Tables.Table tableOne = allTables[0] as Aspose.Words.Tables.Table;

                var rowStart = tableOne.Rows[0]; //获取第1行

                //循环赋值
                for (int i = 0; i < guestInfos.Count; i++)
                {
                    var guestInfo = guestInfos[i];
                    builder.MoveToCell(0, i + 1, 0, 0);
                    builder.Write(guestInfo.LastName + guestInfo.FirstName);

                    builder.MoveToCell(0, i + 1, 1, 0);
                    int sex = guestInfo.Sex;
                    string sexStr = string.Empty;
                    if (sex == 0) sexStr = "男";
                    else if (sex == 1) sexStr = "女";
                    else sexStr = "未设置";
                    builder.Write(sexStr);

                    builder.MoveToCell(0, i + 1, 2, 0);
                    builder.Write(guestInfo.CompanyFullName + guestInfo.Job);


                    builder.MoveToCell(0, i + 1, 3, 0);
                    DateTime birthDay = guestInfo.BirthDay;
                    string birthDayStr = string.Empty;
                    if (birthDay != null)
                    {
                        birthDayStr = birthDay.ToString("yyyy.MM");
                    }
                    builder.Write(birthDayStr);
                }

                //删除多余行
                while (tableOne.Rows.Count > guestInfos.Count + 1)
                {
                    tableOne.Rows.RemoveAt(guestInfos.Count + 1);
                }

                var fileDir = AppSettingsHelper.Get("WordBasePath");
                string fileName = $"{groupInfo.TeamName}市外办出访请示{DateTime.Now.ToString("yyyyMMddHHmmss")}.docx";
                string filePath = fileDir + $@"OfficialActivities/{fileName}";
                doc.Save(filePath);

                string Url = $@"{AppSettingsHelper.Get("WordBaseUrl")}Office/Word/OfficialActivities/{fileName}";
                return Ok(JsonView(true, "操作成功！", Url));
            }


            return Ok(JsonView(true, "操作失败！"));
        }

        private string GetToUpperNumber(int num)
        {
            string numStr = "";

            if (num == 1) numStr = "一";
            else if (num == 2) numStr = "二";
            else if (num == 3) numStr = "三";
            else if (num == 4) numStr = "四";
            else if (num == 5) numStr = "五";
            else if (num == 6) numStr = "六";
            else if (num == 7) numStr = "七";
            else if (num == 8) numStr = "八";
            else if (num == 9) numStr = "九";
            else if (num == 10) numStr = "十";

            return numStr;
        }

        #endregion

        #region 请示数据库
        /// <summary>
        /// 查询请示数据库初始化
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryAskData(QueryAskDataDto dto)
        {
            try
            {
                Result groupData = await _askDataRep.QueryAskData(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 根据Id查询请示数据库单挑数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryAskDataById(QueryAskDataByIdDto dto)
        {
            try
            {
                Res_AskData _AskData = await _sqlSugar.Queryable<Res_AskData>().FirstAsync(a => a.IsDel == 0 && a.Id == dto.id);
                if (_AskData==null)
                {
                    return Ok(JsonView(true, "暂无数据！", _AskData));
                }
                return Ok(JsonView(true, "查询成功！", _AskData));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 请示数据库操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OpAskData(OpAskDataDto dto)
        {
            try
            {
                Result groupData = await _askDataRep.OpAskData(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 删除请示资料信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelAskData(DelBaseDto dto)
        {
            try
            {
                var res = await _askDataRep.SoftDeleteByIdAsync<Res_AskData>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        #endregion

        #region 机票黑屏代码
        /// <summary>
        /// 根据团组Id查询黑屏代码列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryTicketBlackCodeByDiId(QueryTicketBlackCodeByDiIdDto dto)
        {
            try
            {
                Result groupData = await _ticketBlackCodeRep.QueryTicketBlackCodeByDiId(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 根据黑屏代码数据Id查询信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> QueryTicketBlackCodeById(QueryTicketBlackCodeByIdDto dto)
        {
            try
            {
                Result groupData = await _ticketBlackCodeRep.QueryTicketBlackCodeById(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        /// <summary>
        /// 黑屏代码操作（Status:1.新增,2.修改）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> OpTicketBlackCode(OpTicketBlackCodeDto dto)
        {
            try
            {
                Result groupData = await _ticketBlackCodeRep.OpTicketBlackCode(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }
                return Ok(JsonView(true, groupData.Msg, groupData.Data));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 删除黑屏代码
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> DelTicketBlackCode(DelBaseDto dto)
        {
            try
            {
                var res = await _ticketBlackCodeRep.SoftDeleteByIdAsync<Air_TicketBlackCode>(dto.Id.ToString(), dto.DeleteUserId);
                if (!res)
                {
                    return Ok(JsonView(false, "删除失败"));
                }
                return Ok(JsonView(true, "删除成功！"));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }
        #endregion
    }


}

