using Infrastructure;
using Infrastructure.Attribute;
using Infrastructure.Enums;
using Infrastructure.Model;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using ZR.Model.Dto;
using ZR.Model.Models;
using ZR.Service.Business.IBusinessService;
using ZR.Admin.WebApi.Extensions;
using ZR.Admin.WebApi.Filters;
using ZR.Common;
using ZR.Service.Business.IBusinessService.OutStore;
using ZR.Model.Dto.OutStore;
using System.Data;
using ZR.Model.Dto.Inspect;
using ZR.Model.Models.Inspect;

namespace ZR.Admin.WebApi.Controllers.OutStore
{
    /// <summary>
    /// Controller
    /// 
    /// @tableName sap_out_task_record
    /// @author admin
    /// @date 2023-05-10
    /// </summary>
    [Verify]
    [Route("SapInterface")]
    public class SapOutTaskRecordController : BaseController
    {
        /// <summary>
        /// 接口
        /// </summary>
        private readonly ISapOutTaskRecordService _SapOutTaskRecordService;

        public SapOutTaskRecordController(ISapOutTaskRecordService SapOutTaskRecordService)
        {
            _SapOutTaskRecordService = SapOutTaskRecordService;
        }

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("QuerySapOutTaskRecord")]
        [ActionPermissionFilter(Permission = "business:sapouttaskrecord:list")]
        public IActionResult QuerySapOutTaskRecord([FromQuery] SapOutTaskRecordQueryDto parm)
        {
            var response = _SapOutTaskRecordService.GetList(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询未出库完成的出库任务单号数据
        /// </summary>
        /// <param name="parm">出库任务单查询Dto实体类 -- 无分页参数</param>
        /// <returns></returns>
        [HttpPost("QuerySapOutTaskList")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:QuerySapOutTaskList")]
        public IActionResult QuerySapOutTaskList([FromBody] SapOutTaskQueryNoPageDto parm)
        {
            var response = _SapOutTaskRecordService.GetSapOutTaskList(parm);
            return SUCCESS(response);
        }

        /// <summary>
        /// 根据出库任务单号获取出库任务单明细数据
        /// </summary>
        /// <param name="outTaskNo">出库任务单号</param>
        /// <returns></returns>
        [HttpPost("QuerySapOutTaskRecordList")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:QuerySapOutTaskRecordList")]
        public IActionResult QuerySapOutTaskRecordList(string outTaskNo)
        {
            var response = _SapOutTaskRecordService.GetSapOutTaskRecordList(outTaskNo);
            return SUCCESS(response);
        }

        /// <summary>
        /// 查询详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("GetSapOutTaskRecord")]
        [ActionPermissionFilter(Permission = "business:sapouttaskrecord:query")]
        public IActionResult GetSapOutTaskRecord(int Id)
        {
            var response = _SapOutTaskRecordService.GetFirst(x => x.Id == Id);

            return SUCCESS(response);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <returns></returns>
        [HttpPost("AddSapOutTaskRecord")]
        [ActionPermissionFilter(Permission = "business:sapouttaskrecord:add")]
        [Log(Title = "", BusinessType = BusinessType.INSERT)]
        public IActionResult AddSapOutTaskRecord([FromBody] SapOutTaskRecordDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求参数错误");
            }
            var modal = parm.Adapt<SapOutTaskRecord>().ToCreate(HttpContext);

            var response = _SapOutTaskRecordService.AddSapOutTaskRecord(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <returns></returns>
        [HttpPut("UpdateSapOutTaskRecord")]
        [ActionPermissionFilter(Permission = "business:sapouttaskrecord:edit")]
        [Log(Title = "", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateSapOutTaskRecord([FromBody] SapOutTaskRecordDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }
            var modal = parm.Adapt<SapOutTaskRecord>().ToUpdate(HttpContext);

            var response = _SapOutTaskRecordService.UpdateSapOutTaskRecord(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("DeleteSapOutTaskRecord/{ids}")]
        [ActionPermissionFilter(Permission = "business:sapouttaskrecord:delete")]
        [Log(Title = "", BusinessType = BusinessType.DELETE)]
        public IActionResult DeleteSapOutTaskRecord(string ids)
        {
            int[] idsArr = Tools.SpitIntArrary(ids);
            if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); }

            var response = _SapOutTaskRecordService.Delete(idsArr);

            return ToResponse(response);
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="formFile">使用IFromFile必须使用name属性否则获取不到文件</param>
        /// <param name="category"></param>
        /// <returns></returns>
        [HttpPost("OutTaskImportData")]
        [Log(Title = "出库任务单导入", BusinessType = BusinessType.IMPORT, IsSaveRequestData = false, IsSaveResponseData = false)]
        [ActionPermissionFilter(Permission = "business:sapouttaskrecord:import")]
        public IActionResult ImportData([FromForm(Name = "file")] IFormFile formFile)
        {
            DataSet dataSet = ExcelReader.ReadExcel(formFile);

            if (dataSet == null)
            {
                return SUCCESS("导入失败。<br/><br/>导入错误。文件不是xls文件也不是xlsx文件。");
            }
            //简单验证表格式
            if (!dataSet.Tables[0].Rows[0][1].ToString().Contains("领料单号"))
            {
                return SUCCESS($"导入失败。<br/>请确认文件无误。");
            }
            //通过领料单号，验证是否已存在出库任务单
            string checkOutTaskNo = dataSet.Tables[0].Rows[1][1].ToString().Trim();
            if (string.IsNullOrEmpty(checkOutTaskNo))
            {
                return SUCCESS($"导入失败。<br/>B列出库任务单号有误。");
            }
            var response = _SapOutTaskRecordService.GetList(
                new SapOutTaskRecordQueryDto { OutTaskNo = checkOutTaskNo });
            if (response.Result.Count > 0)
            {
                return SUCCESS($"导入失败。<br/><br/>导入出库任务单【{checkOutTaskNo}】已存在。");
            }

            List<SapOutTaskRecord> sapOutTaskRecords = new();
            //实例化交验单表对象
            for (int i = 1; i < dataSet.Tables[0].Rows.Count; i++)
            //去除第一行标题行
            {
                //row中空单元格会转化为空字符串而不是null
                SapOutTaskRecord sapOutTaskRecord = new();
                if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][1].ToString().Trim()))
                {
                    return SUCCESS($"导入失败。<br/><br/>{i + 1}行B列，领料单号有误。");
                }
                else
                    sapOutTaskRecord.OutTaskNo = dataSet.Tables[0].Rows[i][1].ToString().Trim();//*
                if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][9]!.ToString().Trim()))
                {
                    return SUCCESS($"导入失败。<br/><br/>{i + 1}行J列，WBS元素有误。");
                }
                else
                    sapOutTaskRecord.BomNo = dataSet.Tables[0].Rows[i][9].ToString().Trim();//*

                sapOutTaskRecord.Category = "";//暂时没用，给个空字符串

                if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][7].ToString().Trim()))
                {
                    return SUCCESS($"导入失败。<br/><br/>{i + 1}行H列，物料编码有误。");
                }
                else
                    sapOutTaskRecord.MaterialCode = dataSet.Tables[0].Rows[i][7].ToString().Trim();//*

                if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][20].ToString().Trim()))
                {
                    return SUCCESS($"导入失败。<br/><br/>{i + 1}行U列，物料名称有误。");
                }
                else
                    sapOutTaskRecord.MaterialName = dataSet.Tables[0].Rows[i][20].ToString().Trim();//*
                if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][19].ToString().Trim()))
                {
                    return SUCCESS($"导入失败。<br/><br/>{i + 1}行T列，规格型号/图号有误。");
                }
                else
                    sapOutTaskRecord.MaterialSpec = dataSet.Tables[0].Rows[i][19].ToString().Trim();//*

                sapOutTaskRecord.Unit= dataSet.Tables[0].Rows[i][11].ToString().Trim();

                if (string.IsNullOrEmpty(dataSet.Tables[0].Rows[i][12].ToString().Trim()))
                {
                    return SUCCESS($"导入失败。<br/><br/>{i + 1}行M列，物料数量有误。");
                }
                else
                    sapOutTaskRecord.Qty = Convert.ToInt32(dataSet.Tables[0].Rows[i][12]);//*

                sapOutTaskRecord.OutQty = 0;

                sapOutTaskRecord.CreateBy = HttpContext.GetName();
                sapOutTaskRecord.CreateTime = DateTime.Now;
                sapOutTaskRecord.Remark = "导入数据";
                sapOutTaskRecords.Add(sapOutTaskRecord);

            }

            string msg = _SapOutTaskRecordService.ImportDatas(sapOutTaskRecords);

            //TODO 业务逻辑,自行插入数据到db
            return SUCCESS("交验单导入成功！");
        }


    }
}