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

namespace ZR.Admin.WebApi.Controllers.OutStore
{
    /// <summary>
    /// 出库管理/出库记录表Controller
    /// 
    /// @tableName out_outstore_record
    /// @author admin
    /// @date 2023-04-18
    /// </summary>
    [Verify]
    [Route("business/OutOutstoreRecord")]
    public class OutOutstoreRecordController : BaseController
    {
        /// <summary>
        /// 接口
        /// </summary>
        private readonly IOutOutstoreRecordService _OutOutstoreRecordService;
        private readonly IStkBalanceDtlService _StkBalanceDtlService;
        private readonly ISapOutTaskRecordService _SapOutTaskRecordService;

        public OutOutstoreRecordController(IOutOutstoreRecordService OutOutstoreRecordService,
            IStkBalanceDtlService StkBalanceDtlService,
            ISapOutTaskRecordService SapOutTaskRecordService)
        {
            _OutOutstoreRecordService = OutOutstoreRecordService;
            _StkBalanceDtlService = StkBalanceDtlService;
            _SapOutTaskRecordService = SapOutTaskRecordService;
        }

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


        /// <summary>
        /// 查询出库管理/出库记录表详情
        /// </summary>
        /// <param name="OutStoreId"></param>
        /// <returns></returns>
        [HttpGet("{OutStoreId}")]
        [ActionPermissionFilter(Permission = "business:outoutstorerecord:query")]
        public IActionResult GetOutOutstoreRecord(int OutStoreId)
        {
            var response = _OutOutstoreRecordService.GetFirst(x => x.OutStoreId == OutStoreId);

            return SUCCESS(response);
        }

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

            var response = _OutOutstoreRecordService.AddOutOutstoreRecord(modal);

            return ToResponse(response);
        }

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

            var response = _OutOutstoreRecordService.UpdateOutOutstoreRecord(modal);

            return ToResponse(response);
        }

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

            var response = _OutOutstoreRecordService.Delete(idsArr);

            return ToResponse(response);
        }


        #region 2023 0524 孙亚龙 新增
        [HttpPost("AddOutstoreRecord")]
        public IActionResult AddOutstoreRecord([FromBody] SapOutTaskRecordExtDto parm)
        {
            if (parm == null)
            {
                throw new CustomException("请求实体不能为空");
            }
            SapOutTaskRecord sapOutTaskRecordMd = parm.Adapt<SapOutTaskRecord>().ToUpdate(HttpContext);
            sapOutTaskRecordMd.OutQty += parm.OutNum;
            if (sapOutTaskRecordMd.OutQty >= sapOutTaskRecordMd.Qty)
            {
                sapOutTaskRecordMd.Result = 99;
            }

            OutOutstoreRecord outOutstoreMd = parm.Adapt<OutOutstoreRecord>();
            outOutstoreMd.OutSotreNo = parm.BomNo;
            outOutstoreMd.BnSnCode = parm.BnSnCode;
            outOutstoreMd.OutStoreQty = parm.OutNum;
            outOutstoreMd.Result = 99;
            outOutstoreMd.CreateBy = HttpContext.GetName();
            outOutstoreMd.CreateTime = DateTime.Now;
            outOutstoreMd.CreateBy = HttpContext.GetName();
            outOutstoreMd.CreateTime = DateTime.Now;
            outOutstoreMd.UpdateBy = HttpContext.GetName();
            outOutstoreMd.UpdateTime = DateTime.Now;

            List<StkBalanceDtl> list = _StkBalanceDtlService.GetBalanceDtlList(new GetOutOperateBalanceQueryDto
            {
                BomNo = parm.BomNo,
                MaterialCode = parm.MaterialCode,
                BnSnCode = parm.BnSnCode,
                Qty = parm.Qty,
            }).Adapt<List<StkBalanceDtl>>();

            int allotNum = 0;
            Dictionary<int, int> allocDic = new();
            foreach (var item in list)
            {
                if ((item.BalanceQty + allotNum) <= parm.Qty)
                {
                    allotNum += item.BalanceQty;
                    allocDic.Add(item.BalanceId, item.BalanceQty);
                }
                else
                {
                    allotNum += item.BalanceQty;
                    allocDic.Add(item.BalanceId, allotNum - parm.Qty);
                    break;
                }
            }

            int response3 = 0;
            foreach (var item in allocDic)
            {
                StkBalanceDtl md = list.FirstOrDefault(x => x.BalanceId == item.Key);
                if (md.BalanceQty == item.Value)
                {
                    md.Status = 88;
                    md.UpdateBy = HttpContext.GetName();
                    md.UpdateTime = DateTime.Now;
                    response3 += _StkBalanceDtlService.Update(md);
                }
                else
                {
                    md.Status = 55;
                    md.BalanceQty = item.Value;
                    md.UpdateBy = HttpContext.GetName();
                    md.UpdateTime = DateTime.Now;
                    response3 += _StkBalanceDtlService.Update(md);
                }
                if (outOutstoreMd.MaterialCode == md.MaterialCode)
                {
                    outOutstoreMd.KeyFlag = md.KeyFlag;
                }
            }
            int response1 = _SapOutTaskRecordService.UpdateSapOutTaskRecord(sapOutTaskRecordMd);
            int response2 = _OutOutstoreRecordService.Insert(outOutstoreMd);
            return ToResponse(response1 + response2 + response3);
        }
        #endregion

    }
}