using Hotline.Application.Systems;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Settings;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Settings;
using Hotline.Tools;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers
{
    public class SystemMobilAreaController : BaseController
    {
        private readonly IMapper _mapper;
        private readonly ISessionContext _sessionContext;
        private readonly IRepository<SystemMobilArea> _systemMobilAreaRepository;
        private readonly ISystemMobilAreaApplication _systemMobilAreaApplication;

        public SystemMobilAreaController(
            IMapper mapper,
            ISessionContext sessionContext,
            IRepository<SystemMobilArea> systemMobilAreaRepository,
           ISystemMobilAreaApplication systemMobilAreaApplication)
        {
            _mapper = mapper;
            _sessionContext = sessionContext;
            _systemMobilAreaRepository = systemMobilAreaRepository;
            _systemMobilAreaApplication = systemMobilAreaApplication;
        }

        /// <summary>
        /// 基础信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("get-base-data")]
        public async Task<List<Kv>> GetBaseData()
        {
            var data = new List<Kv>
            {
                new Kv() { Key = "1", Value = "中国电信" },
                new Kv() { Key = "2", Value = "中国移动" },
                new Kv() { Key = "3", Value = "中国联通" }
            };
            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("add-system-mobil-area")]
        public async Task AddSystemMobilArea([FromBody] AddSystemMobilAreaDto dto)
        {
            if (string.IsNullOrEmpty(dto.TelCode))
                throw UserFriendlyException.SameMessage("座机编号不能为空！");
            if (string.IsNullOrEmpty(dto.MobileCode))
                throw UserFriendlyException.SameMessage("手机编号不能为空！");
            if (string.IsNullOrEmpty(dto.MobileAreaName))
                throw UserFriendlyException.SameMessage("归属地不能为空！");
            if (string.IsNullOrEmpty(dto.OFlag))
                throw UserFriendlyException.SameMessage("运营商不能为空！");
            if (string.IsNullOrEmpty(dto.OperatorName))
                throw UserFriendlyException.SameMessage("卡类型不能为空！");

            var data = await _systemMobilAreaRepository.AnyAsync(p => p.TelCode == dto.TelCode && p.MobileCode == dto.MobileCode && p.OFlag == p.OFlag, HttpContext.RequestAborted);
            if (data)
                throw UserFriendlyException.SameMessage("存在相同数据！");

            SystemMobilArea systemMobilArea = new SystemMobilArea
            {
                TelCode = dto.TelCode,
                MobileCode = dto.MobileCode,
                MobileAreaName = dto.MobileAreaName,
                OFlag = dto.OFlag,
                OperatorName = dto.OperatorName,
                StaId = "0"
            };
            await _systemMobilAreaRepository.AddAsync(systemMobilArea, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("get-system-mobil-area-detail/{id}")]
        public async Task<SystemMobilArea> GetSystemMobilAreaDetail(string id)
        {
            var data = await _systemMobilAreaRepository.GetAsync(p => p.Id == id, HttpContext.RequestAborted);
            if (data == null)
                return new SystemMobilArea();
            return data;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("update-system-mobil-area")]
        public async Task UpdateSystemMobilAreaDetail([FromBody] UpdateSystemMobilAreaDto dto)
        {
            if (string.IsNullOrEmpty(dto.TelCode))
                throw UserFriendlyException.SameMessage("座机编号不能为空！");
            if (string.IsNullOrEmpty(dto.MobileCode))
                throw UserFriendlyException.SameMessage("手机编号不能为空！");
            if (string.IsNullOrEmpty(dto.MobileAreaName))
                throw UserFriendlyException.SameMessage("归属地不能为空！");
            if (string.IsNullOrEmpty(dto.OFlag))
                throw UserFriendlyException.SameMessage("运营商不能为空！");
            if (string.IsNullOrEmpty(dto.OperatorName))
                throw UserFriendlyException.SameMessage("卡类型不能为空！");
            var isCheack = await _systemMobilAreaRepository.AnyAsync(p => p.Id != dto.Id && p.TelCode == dto.TelCode
            && p.MobileCode == dto.MobileCode && p.OFlag == p.OFlag, HttpContext.RequestAborted);
            if (isCheack)
                throw UserFriendlyException.SameMessage("存在相同数据！");

            var data = await _systemMobilAreaRepository.GetAsync(p => p.Id == dto.Id, HttpContext.RequestAborted);
            if (data == null)
                throw UserFriendlyException.SameMessage("修改失败！");

            data.TelCode = dto.TelCode;
            data.MobileCode = dto.MobileCode;
            data.OFlag = dto.OFlag;
            data.OperatorName = dto.OperatorName;
            data.MobileAreaName = dto.MobileAreaName;
            await _systemMobilAreaRepository.UpdateAsync(data, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("delete-system-mobil-area-detail/{id}")]
        public async Task DeleteSystemMobilAreaDetail(string id)
        {
            await _systemMobilAreaRepository.RemoveAsync(id, cancellationToken: HttpContext.RequestAborted);
        }

        /// <summary>
        /// 根据号码查询归属地等信息
        /// </summary>
        /// <param name="phonenum"></param>
        /// <returns></returns>
        [HttpGet("get-phone-card-area/{phonenum}")]
        public async Task<SystemMobilAreaDto> GetPhoneCardArea(string phonenum)
        {
            var data = await _systemMobilAreaApplication.GetPhoneCardArea(phonenum, cancellationToken: HttpContext.RequestAborted);
            if (data != null)
            {
                if (data.OFlag == "1")
                    data.OFlag = "中国电信";
                else if (data.OFlag == "2")
                    data.OFlag = "中国移动";
                else if (data.OFlag == "3")
                    data.OFlag = "中国联通";
            }
            return data;
        }

        /// <summary>
        /// 号码归属地列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get-system-mobil-area-list")]
        public async Task<PagedDto<SystemMobilAreaListDto>> GetSystemMobilAreaList([FromQuery] SystemMobilAreaRequestDto dto)
        {
            var (total, items) = await _systemMobilAreaApplication.GetList(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<SystemMobilAreaListDto>(total, _mapper.Map<IReadOnlyList<SystemMobilAreaListDto>>(items));
        }

        /// <summary>
        /// 号码归属地列表导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("get-system-mobil-area-list-export")]
        public async Task<FileStreamResult> GetSystemMobilAreaListExport([FromBody] ExportExcelDto<SystemMobilAreaRequestDto> dto)
        {
            var query = _systemMobilAreaApplication.GetList(dto.QueryDto);
            List<SystemMobilArea> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }
            var dataDtos = _mapper.Map<ICollection<SystemMobilAreaListDto>>(data);
            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<SystemMobilAreaListDto>(dto.ColumnInfos);

            var dtos = dataDtos
                .Select(stu => _mapper.Map(stu, typeof(SystemMobilAreaListDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "号码归属地列表");
        }
    }
}
