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 ZR.Service.Business.IBusinessService.Inspect;
using ZR.Model.Dto.Inspect;
using ZR.Model.Models.Inspect;
using ZR.Service.Business.Inspect;
using UAParser;
using System.Net.Security;

namespace ZR.Admin.WebApi.Controllers.Inspect
{
    /// <summary>
    /// 质检管理/质检记录表Controller
    /// 
    /// @tableName qa_inspect_record
    /// @author admin
    /// @date 2023-05-05
    /// </summary>
    [Verify]
    [Route("business/QaInspectRecord")]
    public class QaInspectRecordController : BaseController
    {
        #region 依赖注入项
        /// <summary>
        /// 接口
        /// </summary>
        private readonly ISapDeliverRecordService _SapDeliverRecordService;
        private readonly IQaInspectRecordService _QaInspectRecordService;
        /// <summary>
        /// 构造函数
        /// </summary>
        public QaInspectRecordController(
            ISapDeliverRecordService SapDeliverRecordService,
            IQaInspectRecordService QaInspectRecordService)
        {
            _QaInspectRecordService = QaInspectRecordService;
            _SapDeliverRecordService = SapDeliverRecordService;
        }
        #endregion

        /// <summary>
        /// 查询质检管理/质检记录表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpGet("list")]
        [ActionPermissionFilter(Permission = "business:qainspectrecord:list")]
        public IActionResult QueryQaInspectRecord([FromQuery] QaInspectRecordQueryDto parm)
        {
            bool isPDA = false;
            ClientInfo clientInfo = HttpContext.GetClientInfo();
            if (clientInfo.OS.ToString().Contains("Android 10"))
            {
                isPDA = true;
            }
            var response = _QaInspectRecordService.GetList(parm, isPDA);
            return SUCCESS(response);
        }


        /// <summary>
        /// 查询质检管理/质检记录表详情
        /// </summary>
        /// <param name="InspectId"></param>
        /// <returns></returns>
        [HttpGet("{InspectId}")]
        [ActionPermissionFilter(Permission = "business:qainspectrecord:query")]
        public IActionResult GetQaInspectRecord(int InspectId)
        {
            var response = _QaInspectRecordService.GetFirst(x => x.InspectId == InspectId);

            return SUCCESS(response);
        }

        /// <summary>
        /// 添加质检管理/质检记录表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionPermissionFilter(Permission = "business:qainspectrecord:add")]
        [Log(Title = "质检管理/质检记录表", BusinessType = BusinessType.INSERT)]
        public IActionResult AddQaInspectRecord([FromBody] QaInspectRecordDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求参数错误");
            }
            var modal = parm.Adapt<QaInspectRecord>().ToCreate(HttpContext);

            var response = _QaInspectRecordService.AddQaInspectRecord(modal);

            return ToResponse(response);
        }

        /// <summary>
        /// 更新质检管理/质检记录表
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        [ActionPermissionFilter(Permission = "business:qainspectrecord:edit")]
        [Log(Title = "质检管理/质检记录表", BusinessType = BusinessType.UPDATE)]
        public IActionResult UpdateQaInspectRecord([FromBody] QaInspectRecordDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }
            var modal = parm.Adapt<QaInspectRecord>().ToUpdate(HttpContext);

            var response = _QaInspectRecordService.UpdateQaInspectRecord(modal);

            return ToResponse(response);
        }

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

            var response = _QaInspectRecordService.Delete(idsArr);

            return ToResponse(response);
        }



        #region 2023 0524 孙亚龙 新增
        /// <summary>
        /// 查询质检完成,未入库完成的交验单号
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        [HttpPost("QueryCheckedSapDeliverData")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:QueryCheckedSapDeliverData")]
        public IActionResult QueryCheckedSapDeliverData([FromBody] QaInspectRecordQueryNoPageDto parm)
        {
            var response = _QaInspectRecordService.GetCheckedDeliverData(parm);
            return SUCCESS(response);
        }
        /// <summary>
        /// 根据交验单号 查询已质检完成的交验单明细数据
        /// </summary>
        /// <param name="deliverNo">交验单号</param>
        /// <returns></returns>
        [HttpPost("QueryCheckedSapDeliverDtlData")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:QueryCheckedSapDeliverDtlData")]
        public IActionResult QueryCheckedSapDeliverDtlData(string deliverNo)
        {
            var response = _QaInspectRecordService.GetCheckedSapDeliverRecordList(deliverNo);
            return SUCCESS(response);
        }

        [HttpPost("QueryInspectRecordData")]
        public IActionResult QueryInspectRecordData(string deliverNo,string materialSpecCode)
        {
            var response = _QaInspectRecordService.GetCheckedSapDeliverRecordList(deliverNo,materialSpecCode);
            return SUCCESS(response);
        }

        /// <summary>
        /// 添加质检记录，并更新对应的交验单明细
        /// </summary>
        /// <param name="parm">已质检的交验单明细 Dto实体类</param>
        /// <returns></returns>
        /// <exception cref="CustomException"></exception>
        [HttpPost("addSapDeliverDtlInspectResult")]
        [ActionPermissionFilter(Permission = "business:sapdeliverrecord:addSapDeliverDtlInspectResult")]
        public IActionResult AddSapDeliverDtlInspectResult([FromBody] SapDeliverRecordExtDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }


            List<SapDeliverRecord> sapDeliverList = _SapDeliverRecordService.Queryable()
                .Where(x => x.DeliverNo == parm.DeliverNo && x.MaterialSpec == parm.MaterialSpec && x.CheckQty < x.Qty)
                .OrderBy(x => x.Id)
                .OrderBy(x => x.Qty)
                .ToList();
            if (sapDeliverList == null || sapDeliverList.Count <= 0)
            {
                throw new CustomException($"交验单：{parm.DeliverNo} 未查询到物料号：{parm.MaterialSpec} 的明细数据！");
            }

            int sumCheckOkQty = parm.CheckOkQty;
            int allotNum = 0;
            List<SapDeliverRecord> allotList = new();
            List<QaInspectRecord> QaInspectList = new();
            while (true)
            {
                SapDeliverRecord? sapDeliverMd = sapDeliverList.FirstOrDefault(x => x.CheckQty < x.Qty);
                if(sapDeliverMd == null || allotNum >= sumCheckOkQty)
                {
                    break;
                }

                int tmpNeedNum = sapDeliverMd.Qty - (int)sapDeliverMd.CheckQty;

                if ((allotNum + tmpNeedNum) > sumCheckOkQty)
                {
                    int realNeedNum = sumCheckOkQty - allotNum;
                    allotNum += realNeedNum;
                    sapDeliverMd.CheckQty += realNeedNum;
                    sapDeliverMd.CheckResult = "PartOk";
                    sapDeliverMd.UpdateBy = HttpContext.GetName();
                    sapDeliverMd.UpdateTime = DateTime.Now;
                    allotList.Add(sapDeliverMd);
                    QaInspectRecord qaInspectRecord = sapDeliverMd.Adapt<QaInspectRecord>();
                    qaInspectRecord.InspectNo = parm.DeliverNo;
                    qaInspectRecord.InspectedBy = HttpContext.GetName();
                    qaInspectRecord.InspectTime = DateTime.Now;
                    qaInspectRecord.CreateBy = HttpContext.GetName();
                    qaInspectRecord.CreateTime = DateTime.Now;
                    qaInspectRecord.UpdateBy = HttpContext.GetName();
                    qaInspectRecord.UpdateTime = DateTime.Now;
                    qaInspectRecord.Result = "OK";
                    qaInspectRecord.CheckQty = (int)sapDeliverMd.CheckQty;
                    qaInspectRecord.BnSnCode = parm.BnSnCode;
                    QaInspectList.Add(qaInspectRecord);
                    break;
                }
                else
                {
                    allotNum += tmpNeedNum;
                    sapDeliverMd.CheckQty += tmpNeedNum;
                    sapDeliverMd.CheckResult = "OK";
                    sapDeliverMd.UpdateBy = HttpContext.GetName();
                    sapDeliverMd.UpdateTime = DateTime.Now;
                    allotList.Add(sapDeliverMd);
                    QaInspectRecord qaInspectRecord = sapDeliverMd.Adapt<QaInspectRecord>();
                    qaInspectRecord.InspectNo = parm.DeliverNo;
                    qaInspectRecord.InspectedBy = HttpContext.GetName();
                    qaInspectRecord.InspectTime = DateTime.Now;
                    qaInspectRecord.CreateBy = HttpContext.GetName();
                    qaInspectRecord.CreateTime = DateTime.Now;
                    qaInspectRecord.UpdateBy = HttpContext.GetName();
                    qaInspectRecord.UpdateTime = DateTime.Now;
                    qaInspectRecord.Result = "OK";
                    qaInspectRecord.CheckQty = (int)sapDeliverMd.CheckQty;
                    qaInspectRecord.BnSnCode = parm.BnSnCode;
                    QaInspectList.Add(qaInspectRecord);
                }
            }
            int response = 0;
            int response1 = 0;
            for (int i = 0; i < allotList.Count; i++)
            {
                response += _SapDeliverRecordService.UpdateSapDeliverRecord(allotList[i]);
                response1 = _QaInspectRecordService.AddQaInspectRecord(QaInspectList[i]);
            }

            //SapDeliverRecord sapDeliverRecordMd = parm.Adapt<SapDeliverRecord>().ToUpdate(HttpContext);
            //QaInspectRecord qaInspectRecordMd = parm.Adapt<QaInspectRecord>();
            //sapDeliverRecordMd.CheckQty += parm.CheckOkQty;
            //if (sapDeliverRecordMd.CheckQty >= sapDeliverRecordMd.Qty)
            //{
            //    sapDeliverRecordMd.CheckResult = "OK";
            //}
            //qaInspectRecordMd.InspectNo = parm.DeliverNo;
            //qaInspectRecordMd.InspectedBy = HttpContext.GetName();
            //qaInspectRecordMd.InspectTime = DateTime.Now;
            //qaInspectRecordMd.CreateBy = HttpContext.GetName();
            //qaInspectRecordMd.CreateTime = DateTime.Now;
            //qaInspectRecordMd.UpdateBy = HttpContext.GetName();
            //qaInspectRecordMd.UpdateTime = DateTime.Now;
            //qaInspectRecordMd.Result = "OK";
            //qaInspectRecordMd.CheckQty = parm.CheckOkQty;

            //int response = _SapDeliverRecordService.UpdateSapDeliverRecord(sapDeliverRecordMd);
            //int response1 = _QaInspectRecordService.AddQaInspectRecord(qaInspectRecordMd);

            return ToResponse(response + response1);
        }
        #endregion

    }
}