using Microsoft.AspNetCore.Mvc;
using NPOI.SS.Formula.Functions;
using OASystem.API.OAMethodLib;
using OASystem.API.OAMethodLib.ALiYun;
using OASystem.API.OAMethodLib.ExcelOutput;
using OASystem.Domain.Common;
using OASystem.Domain.Dtos.Baidu;
using OASystem.Domain.Dtos.Business;
using OASystem.Domain.Dtos.CRM;
using OASystem.Domain.Dtos.FileDto;
using OASystem.Domain.Dtos.Financial;
using OASystem.Domain.Dtos.Groups;
using OASystem.Domain.Entities.Business;
using OASystem.Domain.Entities.Customer;
using OASystem.Domain.Entities.Financial;
using OASystem.Domain.Entities.Groups;
using OASystem.Domain.Entities.Resource;
using OASystem.Domain.ViewModels.Business;
using OASystem.Domain.ViewModels.CRM;
using OASystem.Domain.ViewModels.Financial;
using OASystem.Domain.ViewModels.Groups;
using OASystem.Infrastructure.Repositories.Business;
using OASystem.Infrastructure.Repositories.CRM;
using OASystem.Infrastructure.Repositories.Groups;
using OASystem.Infrastructure.Repositories.System;
using Org.BouncyCastle.Asn1.Mozilla;
using StackExchange.Redis;

namespace OASystem.API.Controllers
{
    /// <summary>
    /// 通用业务操作
    /// </summary>
    [Route("api/[controller]/[action]")]
    public class BusinessController : ControllerBase
    {
        private readonly IMapper _mapper;
        private readonly CommonBusRepository _busRep;
        private readonly SetDataRepository _setDataRep;
        private readonly DelegationInfoRepository _groupRep;
        private readonly TeamRateRepository _teamRateRep;
        private readonly TableOperationRecordRepository _TableOperationRecordRep;

        public BusinessController( IMapper mapper, CommonBusRepository busRep, SetDataRepository setDataRep, DelegationInfoRepository groupRep, TeamRateRepository teamRateRep,
            TableOperationRecordRepository tableOperationRecordRep)
        {
            _mapper = mapper;
            _busRep = busRep;
            _setDataRep = setDataRep;
            _groupRep = groupRep;
            _teamRateRep = teamRateRep;
            _TableOperationRecordRep = tableOperationRecordRep;
        }

        #region 团组信息 
        /// <summary>
        ///  团组信息 
        ///  团组简略详情 
        /// </summary>
        /// <param name="dto">团组info请求dto</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostShareGroupInfo(ShareGroupInfoDto dto)
        {
            try
            {
                var groupData = await _groupRep.PostShareGroupInfo(dto);
                if (groupData.Code != 0)
                {
                    return Ok(JsonView(false, groupData.Msg));
                }

                return Ok(JsonView(groupData.Data));
            }
            catch (Exception ex)
            {

                return Ok(JsonView(false, ex.Message));
            }
            
        }

        /// <summary>
        /// 团组信息 团组名称 List
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> GetGroupNameList(GroupNameDto dto)
        {
            var groupData = await _groupRep.GetGroupNameList(dto);
            if (groupData.Code != 0)
            {
                return Ok(JsonView(false, groupData.Msg));
            }

            return Ok(JsonView(groupData.Data, groupData.Data.Count));
        }

        /// <summary>
        /// 获取团组指向分类
        /// </summary>
        /// <param name="_dto">参数Json字符串</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostGroupDirectionalClassificationInit()
        {
            Result result = new Result();
            result = await _setDataRep.GetSetDataBySTId(_setDataRep, 16); //团组指向分类
            if (result.Code != 0)
            {
                return Ok(JsonView(false, "获取失败!"));
            }

            List<SetDataInfoView> _view1 = JsonConvert.DeserializeObject<List<SetDataInfoView>>(JsonConvert.SerializeObject(result.Data));

            SetDataInfoView xc_view = new SetDataInfoView();//77	行程 //移除行程
            xc_view = _view1.Where(it => it.Id == 77).FirstOrDefault();
            if (xc_view != null) {  _view1.Remove(xc_view); };

            List<SetDataInfoView> _view = new List<SetDataInfoView>();
            //_view.Insert(0, new SetDataInfoView { Id = -1, Name = "所有模块" });

            SetDataInfoView qz_view = new SetDataInfoView();//80	签证
            qz_view = _view1.Where(it => it.Id == 80).FirstOrDefault();
            if (qz_view != null) { _view.Insert(0, qz_view); _view1.Remove(qz_view); };

            SetDataInfoView jpyd_view = new SetDataInfoView();//85	机票预订
            jpyd_view = _view1.Where(it => it.Id == 85).FirstOrDefault();
            if (jpyd_view != null) { _view.Insert(1, jpyd_view); _view1.Remove(jpyd_view); };

            SetDataInfoView jdyd_view = new SetDataInfoView();//76	酒店预订
            jdyd_view = _view1.Where(it => it.Id == 76).FirstOrDefault();
            if (jdyd_view != null) { _view.Insert(2, jdyd_view); _view1.Remove(jdyd_view); };

            SetDataInfoView jdzc_view = new SetDataInfoView();//751	酒店早餐
            jdzc_view = _view1.Where(it => it.Id == 751).FirstOrDefault();
            if (jdzc_view != null) { 
                _view1.Remove(jdzc_view); 
                //_view.Insert(3, jdzc_view); _view1.Remove(jdzc_view);
            };

            SetDataInfoView cdy_view = new SetDataInfoView();//79	车/导游地接
            cdy_view = _view1.Where(it => it.Id == 79).FirstOrDefault();
            if (cdy_view != null) { _view.Insert(3, cdy_view); _view1.Remove(cdy_view); };

            SetDataInfoView yqgw_view = new SetDataInfoView();//81	邀请/公务活动
            yqgw_view = _view1.Where(it => it.Id == 81).FirstOrDefault();
            if (yqgw_view != null) { _view.Insert(4, yqgw_view); _view1.Remove(yqgw_view); };

            SetDataInfoView bx_view = new SetDataInfoView();//82	团组客户保险
            bx_view = _view1.Where(it => it.Id == 82).FirstOrDefault();
            if (bx_view != null) { _view.Insert(5, bx_view); _view1.Remove(bx_view); };

            SetDataInfoView qtkx_view = new SetDataInfoView();//98	其他款项
            qtkx_view = _view1.Where(it => it.Id == 98).FirstOrDefault();
            if (qtkx_view != null) { _view.Insert(6, qtkx_view); _view1.Remove(qtkx_view); };

            SetDataInfoView skth_view = new SetDataInfoView();//285	收款退还与其他款项
            skth_view = _view1.Where(it => it.Id == 285).FirstOrDefault();
            if (skth_view != null) { _view.Insert(7, skth_view); _view1.Remove(skth_view); };

            if (_view1.Count > 0)
            {
                _view.AddRange(_view1);
            }

            return Ok(JsonView(_view));
        }


        /// <summary>
        /// 查询团组简略详情列表
        /// Page 根据Ctable And User 返回可操作的团
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostGroupListByCTableAndUserId(GroupListByCTableAndUserIdDto dto)
        {
            if (dto.CTable < 1) Ok(JsonView(false, @"请输入正确的员工给Id!"));

            if (dto.CTable < 1) 
                return Ok(JsonView(false, @"请输入正确的CTable Id ！76 酒店预订  77 行程  79 车/导游地接<br/>80 签证    81 邀请/公务活动  82 团组客户保险<br\>85 机票预订   98 其他款项 751 酒店早餐"));

            if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3)
            {
                string sql = string.Format(@"Select row_number() over(order by di.CreateTime Desc) as Row_Number, 
									         di.Id,di.TeamName,di.TourCode,di.ClientName,di.VisitCountry,di.VisitStartDate,
									         di.VisitEndDate,di.VisitDays,di.VisitPNumber,di.CreateTime
									         From Grp_GroupsTaskAssignment gta
									         Inner Join Grp_DelegationInfo di On gta.DIId = di.Id
									         Where gta.IsDel = 0 And di.IsDel = 0 And gta.IsEnable = 1
									         And gta.CTId = {0} And gta.UId = {1}", dto.CTable, dto.UserId);

                RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
                var data = await _groupRep._sqlSugar.SqlQueryable<GroupListByCTableAndUserIdView>(sql).ToPageListAsync(dto.PageIndex, dto.PageSize, total); //ToPageAsync
                foreach (var item in data)
                {
                    item.VisitStartDate = item.VisitStartDate == "" ? "" : Convert.ToDateTime(item.VisitStartDate).ToString("yyyy-MM-dd");
                    item.VisitEndDate = item.VisitEndDate == "" ? "" : Convert.ToDateTime(item.VisitEndDate).ToString("yyyy-MM-dd");
                }

                return Ok(JsonView(true, "操作成功!", data, total));
            }
            else
            {
                return Ok(JsonView(false, @"请输入正确的PortType 1 Web 2 Android 3 IOS "));
            }
        }

        #endregion

        #region 币种 List
        /// <summary>
        /// 币种 List
        /// </summary>
        /// <returns></returns>
        [HttpGet,HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostCurrencyList()
        {
            try
            {
                Result setData = await _setDataRep.GetSetDataBySTId(_setDataRep, 66); //币种类型
                if (setData.Code == 0)
                {
                    return Ok(JsonView(true, "查询成功", setData.Data));
                }
                else
                {
                    return Ok(JsonView(false, setData.Msg));
                }
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }
        }

        /// <summary>
        /// 团组汇率 币种 Item (来源：团组汇率)
        /// 根据 团组Id And 业务类型(CTable)Id
        /// api处理CTable = 285,默认返回CNY
        /// </summary>
        /// <param name="dto"> 请求参数Dto </param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostGroupTeamRateByDiIdAndCTableId(GeneralTeamRateInfoDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Ok(JsonView(false, "请输入参数!"));
                }

                if (dto.DiId == 0)
                {
                    return Ok(JsonView(false, "请输入正确的团组Id!"));
                }
                if (dto.CTable == 0)
                {
                    return Ok(JsonView(false, "请输入正确的业务类型(CTable)Id!"));
                }


                if (dto.PortType == 1 || dto.PortType == 2 || dto.PortType == 3 )
                {
                    var _vew = await GeneralMethod.PostGroupTeamRateByDiIdAndCTableId(dto.PortType,dto.DiId,dto.CTable);

                    return Ok(JsonView(true, "操作成功!", _vew));

                }
                else
                {
                    return Ok(JsonView(false, "请输入正确的端口号! 1 Web 2 Android 3 Ios;"));
                }



            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }


        /// <summary>
        /// 根据团组Id币种Id及类型Id查询团组汇率
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet, HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostCurrencyByDiid(int DiId,int CId,int CurrencyId)
        {
            try
            {
                Result setData = await _setDataRep.PostCurrencyByDiid( DiId, CId, CurrencyId); //币种类型
                if (setData.Code == 0)
                {
                    return Ok(JsonView(true, "查询成功", setData.Data));
                }
                else
                {
                    return Ok(JsonView(false, setData.Msg));
                }
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
                throw;
            }

        }
        #endregion

        #region 查询页面关联Ctable


        /// <summary>
        /// 页面关联Ctable
        /// 根据PageId 返回 CTable Id
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostPageLinkCTable(PageLinkCTableDto dto)
        {
            try
            {
                if (dto == null)
                {
                    return Ok(JsonView(false, "请求参数不能为空！"));
                }

                if (dto.PageId == 0)
                {
                    return Ok(JsonView(false, "页面Id不能为0！"));
                }

                List<CTableCorrelationPageDatas> data =  AppSettingsHelper.Get<CTableCorrelationPageDatas>("CTableCorrelationPageDatas");
                CTableCorrelationPageDatas correlationPageDatas = new CTableCorrelationPageDatas();

                foreach (var item in data)
                {
                    if (item.PageIdDatas != null)
                    {
                        var pageId = item.PageIdDatas.Where(it => it == dto.PageId).FirstOrDefault();
                        if (pageId != 0)
                        {
                            correlationPageDatas = item;
                            break;
                        }
                    }
                }

                if (correlationPageDatas.CTableId == 0)
                {
                    return Ok(JsonView(false, "您查询的页面Id，未配置AppSettings,请前往配置！"));
                }

                return Ok(JsonView(true, "操作成功",new { CTable = correlationPageDatas.CTableId }));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, ex.Message));
            }
        }
        #endregion

        #region 会务物料单

        /// <summary>
        /// 获取会务活动列表
        /// </summary>
        /// <param name="paras"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostConferenceList()
        {
            List<Grp_DelegationInfo> listSource = _busRep.Query<Grp_DelegationInfo>(s => s.TeamDid == 691 && s.IsDel == 0).ToList();
            List<GroupNameView> viewList = new List<GroupNameView>();
            foreach (var group in listSource)
            {
                GroupNameView _view = new GroupNameView();
                _view.Id = group.Id;
                _view.GroupName = group.TeamName;
            }

            return Ok(JsonView(viewList));
        }

        /// <summary>
        /// 获取会务的采购物品计划清单
        /// </summary>
        /// <param name="ConfId">会务活动Id</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostConfItemList(int ConfId)
        {
            Bus_ConfItemListView view = new Bus_ConfItemListView();

            Bus_ConfItemListInfo _confListInfo = await _busRep.Query<Bus_ConfItemListInfo>(s => s.Diid == ConfId).FirstAsync();
            if (_confListInfo != null)
            {
                view.TotalCost = _confListInfo.TotalCost;

                string sqlItem = string.Format(@" Select c.Id,c.ItemId,d.ItemName,c.[Count],c.CurrCost,c.OpRemark
From Bus_ConfItem as c With(Nolock) 
Inner Join Res_ItemDetail as d with(Nolock) On c.ItemId=d.Id
Where c.ConfListId = {0}", ConfId);
                List<Bus_ConfItemView> confItemList = await _busRep._sqlSugar.SqlQueryable<Bus_ConfItemView>(sqlItem).ToListAsync();
                view.ItemList = new List<Bus_ConfItemView>(confItemList);
            }
            else
            {
                view.ItemList = new List<Bus_ConfItemView>();
                view.TotalCost = 0;
            }

            return Ok(JsonView(view));
        }

        /// <summary>
        /// 获取会务可采购的物料集合
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostOptionalItemList()
        {
            List<OptionalBusRangeView> result = await _busRep.GetViewList_OptionalItem();

            return Ok(JsonView(result));
        }

        /// <summary>
        /// 编辑物料采购清单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostEditOptionalItemList(JsonDtoBase jsonDto)
        {
            if (string.IsNullOrEmpty(jsonDto.Paras))
            {
                return Ok(JsonView(false, "参数为空"));
            }
            Edit_OptionalItemListDto _dto = JsonConvert.DeserializeObject<Edit_OptionalItemListDto>(jsonDto.Paras);
            //Edit_OptionalItemListDto _dto = System.Text.Json.JsonSerializer.Deserialize<Edit_OptionalItemListDto>(jsonDto.Paras);

            if (_dto.DiId < 1)
            {
                return Ok(JsonView(false, "团组Id为空"));
            }

            if (_dto.ConfItemListId < 1)
            {
                //新增
                int rstInsert = await _busRep.Insert_ConfItemList(_dto);
                return Ok(JsonView(rstInsert == 0));
            }
            else
            {
                //修改
                int rstUpdate = await _busRep.Edit_ConfItemList(_dto);
                return Ok(JsonView(rstUpdate == 0));
            }

            return Ok(JsonView(false));
        }

        /// <summary>
        /// 获取会务采购物料清单Excel
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> Excel_ConfItemList(JsonDtoBase jsonDto)
        {
            if (string.IsNullOrEmpty(jsonDto.Paras))
            {
                return Ok(JsonView(false, "参数为空"));
            }

            dynamic confList = JsonConvert.DeserializeObject<dynamic>(jsonDto.Paras);
            int confListId = confList.ConfListId;
            Bus_ConfItemListInfo _entityConfList = await _busRep.Query<Bus_ConfItemListInfo>(s => s.Id == confListId).FirstAsync();
            if (_entityConfList != null)
            {
                string result = new Excel_BusConfItemList().Excel(_entityConfList);


            }
            else
            {
                return Ok(JsonView(false, "请先保存数据"));
            }

            return Ok(JsonView(false));
        }

        #endregion

        #region 阿里云短信测试

        /// <summary>
        /// 编辑物料采购清单
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> AliMessageTest(string mobile)
        {

            string add2dayZH = DateTime.Now.AddDays(2).ToString("yyyy年MM月dd日");
            string templateParam = JsonConvert.SerializeObject(new { teams = "测试团组", date = add2dayZH });
            AliMessagePost.PostMessage(mobile, "泛美国际团组", "SMS_461575447", templateParam);
            return Ok(JsonView(true));
        }

        #endregion


        #region 文件删除
        /// <summary>
        ///  文件操作 
        ///  删除指定文件 
        /// </summary>
        /// <param name="dto">Dto</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostFileDel(FileDelDto dto)
        {
            try
            {
                string pathUrl = dto.PathUrl;
                if (string.IsNullOrEmpty(pathUrl))
                    return Ok(JsonView(false, "路径为空或者不是有效路径!"));

                if (System.IO.File.Exists(pathUrl))
                {
                    System.IO.File.Delete(pathUrl);
                    return Ok(JsonView(false, "操作成功!"));
                }
                else
                {
                    return Ok(JsonView(false, "该文件不存在!"));
                }
            }
            catch (Exception ex)
            {

                return Ok(JsonView(false, ex.Message));
            }
        }

        #endregion

        #region 表操作记录

        /// <summary>
        /// 表操作记录
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostTableOperationRecordAdd(TableOperationRecordAddDto _dto )
        {
            try
            {
                Crm_TableOperationRecord _TableOperationRecord = new Crm_TableOperationRecord() 
                {
                    TableName = _dto.TableName,
                    PortType = _dto.PortType,
                    OperationItem = _dto.OperationItem,
                    DataId = _dto.DataId,
                    CreateUserId = _dto.UserId,
                    CreateTime = DateTime.Now,
                    Remark = "",
                    IsDel = 0
                };

                bool _view = await _TableOperationRecordRep._Add(_TableOperationRecord); 
                if (_view)
                {
                    return Ok(JsonView(true,"操作成功!"));
                }
                else
                {
                    return Ok(JsonView(false,"操作失败!"));
                }
            }
            catch (Exception)
            {
                return Ok(JsonView(false, "程序错误！"));
            }
        }



        /// <summary>
        /// 表操作记录
        /// 分页
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(JsonView), StatusCodes.Status200OK)]
        public async Task<IActionResult> PostTableOperationRecordPageList(TableOperationRecordPageDto _dto)
        {
            try
            {
                string whereSql = "";

                if (!string.IsNullOrEmpty(_dto.TableName))
                {
                    whereSql = string.Format(" And tor.TableName = '{0}'", _dto.TableName);
                }

                string sql = string.Format(@"Select row_number() over(order by tor.CreateTime Desc) As Row_Number,
                                             tor.TableName,tor.PortType,tor.OperationItem,tor.DataId,u.CnName As OperationUserName,
                                             tor.CreateTime,tor.Remark
                                             From Crm_TableOperationRecord tor
                                             Left Join Sys_Users u On tor.CreateUserId = u.Id
                                             Where tor.Isdel = 0 {0}", whereSql);

                RefAsync<int> total = 0;//REF和OUT不支持异步,想要真的异步这是最优解
                var _view = await _TableOperationRecordRep._sqlSugar.SqlQueryable<TableOperationRecordPageView>(sql).ToPageListAsync(_dto.PageIndex, _dto.PageSize, total);//ToPageAsync

                return Ok(JsonView(true, "查询成功!", _view, total));
            }
            catch (Exception ex)
            {
                return Ok(JsonView(false, "程序错误！Msg:" + ex.Message));
            }
        }
       

        #endregion


        /// <summary>
        /// 汉字转拼音
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ChineseToEnFn(ChineseToEn dto)
        {
            var jw = JsonView(false, "请输入中文!");
            if (dto.originalText.Count == 0)
            {
                return Ok(jw);
            }

            List<string> values = new List<string>();
            foreach (var item in dto.originalText)
            {
                var val = item.GetTotalPingYin();
                if (dto.isUp)
                {
                    val = val.Select(x => x.ToUpper()).ToList();
                }
                values.Add(val.Count > 0 ? val[0]: "暂无该拼音!");
            }

            jw = JsonView(true, "转换成功！", values);

            return Ok(jw);
        }
    }
}
