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 MiniExcelLibs;
using ZR.Service.Business;
using ZR.Service.Business.IBusinessService.OutStore;
using ZR.Model.Dto.OutStore;
using ZR.Model.Models.OutStore;

namespace ZR.Admin.WebApi.Controllers.OutStore
{
    /// <summary>
    /// 接口管理/SAP关键件清单记录表Controller
    /// 
    /// @tableName sap_bom_record
    /// @author admin
    /// @date 2023-05-05
    /// </summary>
    [Verify]
    [Route("business/SapBomRecord")]
    public class SapBomRecordController : BaseController
    {
        /// <summary>
        /// 接口管理/SAP关键件清单记录表接口
        /// </summary>
        private readonly ISapBomRecordService _SapBomRecordService;

        public SapBomRecordController(ISapBomRecordService SapBomRecordService)
        {
            _SapBomRecordService = SapBomRecordService;
        }

        /// <summary>
        /// 查询接口管理/SAP关键件清单记录表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "business:sapbomrecord:list")]
        public IActionResult QuerySapBomRecord([FromQuery] SapBomRecordQueryDto parm)
        {
            var response = _SapBomRecordService.GetList(parm);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询接口管理/SAP关键件清单记录表详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        [ActionPermissionFilter(Permission = "business:sapbomrecord:query")]
        public IActionResult GetSapBomRecord(int Id)
        {
            var response = _SapBomRecordService.GetFirst(x => x.Id == Id);

            return SUCCESS(response);
        }

        /// <summary>
        /// 添加接口管理/SAP关键件清单记录表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "business:sapbomrecord:add")]
        [Log(Title = "接口管理/SAP关键件清单记录表", BusinessType = BusinessType.INSERT)]
        public IActionResult AddSapBomRecord([FromBody] SapBomRecordDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求参数错误");
            }
            var modal = parm.Adapt<SapBomRecord>().ToCreate(HttpContext);

            var response = _SapBomRecordService.AddSapBomRecord(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 更新接口管理/SAP关键件清单记录表
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "business:sapbomrecord:edit")]
        [Log(Title = "接口管理/SAP关键件清单记录表", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateSapBomRecord([FromBody] SapBomRecordDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }
            var modal = parm.Adapt<SapBomRecord>().ToUpdate(HttpContext);

            var response = _SapBomRecordService.UpdateSapBomRecord(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除接口管理/SAP关键件清单记录表
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{ids}")]
        [ActionPermissionFilter(Permission = "business:sapbomrecord:delete")]
        [Log(Title = "接口管理/SAP关键件清单记录表", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteSapBomRecord(string ids)
        {
            int[] idsArr = Tools.SpitIntArrary(ids);
            if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }

            var response = _SapBomRecordService.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:sapbomrecord:import")]
        public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
        {
            List<dynamic>? list = new();
            //读取上传文件内容。
            using (var stream = formFile.OpenReadStream())
            {
                list = stream.Query().ToList();
            }
            string bomNo = list[2].H;
            if (string.IsNullOrEmpty(bomNo))
            {
                return SUCCESS("未找到生产令号，导入文件格式错误");
            }
            string equipmentName = list[2].D;
            string makeBy = list[3].D;
            DateTime makeTime = list[3].H;
            List<SapBomRecord> sapBomRecords = new();
            for (int i = 5; i < list.Count; i++)
            {
                if (string.IsNullOrEmpty($"{list[i].B}"))
                {
                    break;//序号一列出现空，即表单内容结束
                }
                SapBomRecord sapBomRecord = new()
                {
                    BomNo = bomNo,
                    EquipmentName = equipmentName,
                    MakeBy = makeBy,
                    MakeTime = makeTime,
                    Category = list[i].C,
                    MaterialCode = list[i].D,
                    MaterialName = list[i].E,
                    MaterialSpec = list[i].F,
                    KeyFlag = i % 2 > 0,//非空 模拟数据
                    Qty = Convert.ToInt32(list[i].H),
                    Result = 99,//非空 模拟数据

                    CreateBy = HttpContext.GetName(),
                    CreateTime = DateTime.Now,
                    Remark = "导入数据"
                };
                sapBomRecords.Add(sapBomRecord);
            }
            string msg = _SapBomRecordService.ImportDatas(sapBomRecords);

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


        #region 2023 0524 孙亚龙 新增
        /// <summary>
        /// 查询未出库完成的关键件Bom清单号 数据
        /// </summary>
        /// <param name="parm">关键件Bom清单查询Dto实体类 -- 无分页参数</param>
        /// <returns></returns>
        [HttpPost("QueryBomList")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:QueryBomList")]
        public IActionResult QueryBomList([FromBody] SapBomRecordQueryNoPageDto parm)
        {
            var response = _SapBomRecordService.GetBomList(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 根据Bom单号获取关键件Bom清单明细数据
        /// </summary>
        /// <param name="outTaskNo">Bom单号</param>
        /// <returns></returns>
        [HttpPost("QuerySapBomRecordList")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:QuerySapBomRecordList")]
        public IActionResult QuerySapBomRecordList(string bomNo)
        {
            var response = _SapBomRecordService.GetBomRecordList(bomNo);
            return SUCCESS(response);
        }
        #endregion
    }
}