using Infrastructure;
using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Model;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters;
using ZR.Common;
using Microsoft.AspNetCore.Authorization;
using MiniExcelLibs;
using ZR.Model.System;
using ZR.Service.Business;
using ZR.Service.Business.IBusinessService.BaseSet;
using ZR.Model.Dto.BaseSet;
using ZR.Model.Models.BaseSet;

namespace ZR.Admin.WebApi.Controllers.BaseSet
{
    /// <summary>
    /// 基础资料/库位信息表Controller
    /// 
    /// @tableName bas_bin
    /// @author admin
    /// @date 2023-04-11
    /// </summary>
    [Verify]
    [Route("business/BasBin")]
    public class BasBinController : BaseController
    {
        /// <summary>
        /// 基础资料/库位信息表接口
        /// </summary>
        private readonly IBasBinService _BasBinService;
        /// <summary>
        /// 库位信息控制器
        /// </summary>
        /// <param name="BasBinService"></param>
        public BasBinController(IBasBinService BasBinService)
        {
            _BasBinService = BasBinService;
        }

        /// <summary>
        /// 查询基础资料/库位信息表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "business:basbin:list")]
        public IActionResult QueryBasBin([FromQuery] BasBinQueryDto parm)
        {
            var response = _BasBinService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询基础资料/库位信息表详情
        /// </summary>
        /// <param name="BinId"></param>
        /// <returns></returns>
        [HttpGet("{BinId}")]
        [ActionPermissionFilter(Permission = "business:basbin:query")]
        public IActionResult GetBasBin(long BinId)
        {
            var response = _BasBinService.GetFirst(x => x.BinId == BinId);

            return SUCCESS(response);
        }

        /// <summary>
        /// 添加基础资料/库位信息表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "business:basbin:add")]
        [Log(Title = "基础资料/库位信息表", BusinessType = BusinessType.INSERT)]
        public IActionResult AddBasBin([FromBody] BasBinDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求参数错误");
            }
            var modal = parm.Adapt<BasBin>().ToCreate(HttpContext);

            var response = _BasBinService.AddBasBin(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 更新基础资料/库位信息表
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "business:basbin:edit")]
        [Log(Title = "基础资料/库位信息表", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateBasBin([FromBody] BasBinDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }
            var modal = parm.Adapt<BasBin>().ToUpdate(HttpContext);

            var response = _BasBinService.UpdateBasBin(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除基础资料/库位信息表
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        [ActionPermissionFilter(Permission = "business:basbin:delete")]
        [Log(Title = "基础资料/库位信息表", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteBasBin(string ids)
        {
            int[] idsArr = Tools.SpitIntArrary(ids);
            if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败 Id 不能为空")); }

            var response = _BasBinService.Delete(idsArr);

            return ToResponse(response);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="formFile">使用IFromFile必须使用name属性否则获取不到文件</param>
        /// <returns></returns>
        [HttpPost("importData")]
        [Log(Title = "库位导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false, IsSaveResponseData = false)]
        [ActionPermissionFilter(Permission = "business:basbin:import")]
        public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
        {
            List<BasBin> bins = new();
            using (var stream = formFile.OpenReadStream())
            {
                bins = stream.Query<BasBin>().ToList();
            }

            string msg = _BasBinService.ImportDatas(bins);

            //TODO 业务逻辑,自行插入数据到db
            return SUCCESS(bins);
        }

        /// <summary>
        /// 用户导入模板下载
        /// </summary>
        /// <returns></returns>
        [HttpGet("importTemplate")]
        [Log(Title = "库位模板", BusinessType = BusinessType.EXPORT, IsSaveRequestData = false, IsSaveResponseData = false)]
        [AllowAnonymous]
        public IActionResult ImportTemplateExcel()
        {
            List<BasBinImportTemplate> bin = new();
            MemoryStream stream = new();

            var fileInfo = DownloadImportTemplate(bin, stream, "库位列表");
            //2023年4月25日 下载的文件有问题，弃用  赵
            //return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"{sFileName}");
            return ExportExcel(fileInfo.Item1, fileInfo.Item2);
        }

        /// <summary>
        /// 库位导出
        /// </summary>
        /// <returns></returns>
        [HttpGet("export")]
        [ActionPermissionFilter(Permission = "business:basbin:export")]
        [Log(Title = "库位导出", BusinessType = BusinessType.EXPORT, IsSaveResponseData = false)]
        public IActionResult Export()
        {
            var list = _BasBinService.GetAll();

            string sFileName = ExportExcel(list, "Basregion", "库位");
            return SUCCESS(new { path = "/export/" + sFileName, fileName = sFileName });
        }
    }
}