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

namespace ZR.Admin.WebApi.Controllers.OutStore
{
    /// <summary>
    /// 出库管理/装配记录表Controller
    /// 
    /// @tableName out_assemble_record
    /// @author admin
    /// @date 2023-04-14
    /// </summary>
    [Verify]
    [Route("business/OutAssembleRecord")]
    public class OutAssembleRecordController : BaseController
    {
        /// <summary>
        /// 接口
        /// </summary>
        private readonly IOutAssembleRecordService _OutAssembleRecordService;
        private readonly IStkBalanceDtlService _StkBalanceDtlService;
        private readonly ISapBomRecordService _SapBomRecordService;

        public OutAssembleRecordController(IOutAssembleRecordService OutAssembleRecordService,
                                            IStkBalanceDtlService StkBalanceDtlService,
                                            ISapBomRecordService SapBomRecordService)
        {
            _OutAssembleRecordService = OutAssembleRecordService;
            _StkBalanceDtlService = StkBalanceDtlService;
            _SapBomRecordService = SapBomRecordService;
        }

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


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

            return SUCCESS(response);
        }

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

            var response = _OutAssembleRecordService.AddOutAssembleRecord(modal);

            return ToResponse(response);
        }

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

            var response = _OutAssembleRecordService.UpdateOutAssembleRecord(modal);

            return ToResponse(response);
        }

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

            var response = _OutAssembleRecordService.Delete(idsArr);

            return ToResponse(response);
        }


        #region 2023 0524 孙亚龙 新增
        [HttpPost("AddOutAssembleRecordForFile")]
        [ActionPermissionFilter(Permission = "AddOutAssembleRecordForFile")]
        public IActionResult AddOutAssembleRecordForFile([FromForm] SapBomRecordAssembleExtDto assembleDataDto)
        {
            IFormFile? formFile;
            ClientInfo clientInfo = HttpContext.GetClientInfo();
            if (clientInfo.OS.ToString().Contains("Android 10"))
            {
                var file11 = HttpContext.Request.Form.Files[0];
                formFile = file11;
            }
            else
            {
                formFile = assembleDataDto.File;
            }
            if (formFile == null)
            {
                throw new CustomException(ResultCode.PARAM_ERROR, "上传的实物图片不能为空！！");
            }
            SapBomRecord sapBomRecordMd = assembleDataDto.Adapt<SapBomRecord>().ToUpdate();
            sapBomRecordMd.AssembleQty += assembleDataDto.AssembleNum;
            if (sapBomRecordMd.AssembleQty >= sapBomRecordMd.Qty)
            {
                sapBomRecordMd.Result = 99;
            }
            OutAssembleRecord assembleRecordMd = assembleDataDto.Adapt<OutAssembleRecord>();
            using var stream = formFile.OpenReadStream();
            BinaryReader br = new(stream);
            byte[] byData = br.ReadBytes((int)stream.Length);
            assembleRecordMd.Picture = byData;
            assembleRecordMd.BnSnCode = assembleDataDto.BnSnCode;
            assembleRecordMd.AssembleQty = assembleDataDto.AssembleNum;
            assembleRecordMd.CreateBy = HttpContext.GetName();
            assembleRecordMd.CreateTime = DateTime.Now;
            assembleRecordMd.CreateBy = HttpContext.GetName();
            assembleRecordMd.CreateTime = DateTime.Now;
            assembleRecordMd.UpdateBy = HttpContext.GetName();
            assembleRecordMd.UpdateTime = DateTime.Now;
            assembleRecordMd.Result = 99;

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

            int allotNum = 0;
            Dictionary<int, int> allocDic = new();
            foreach (var item in list)
            {
                if ((item.BalanceQty + allotNum) <= assembleDataDto.Qty)
                {
                    allotNum += item.BalanceQty;
                    allocDic.Add(item.BalanceId, item.BalanceQty);
                }
                else
                {
                    allotNum += item.BalanceQty;
                    allocDic.Add(item.BalanceId, allotNum - assembleDataDto.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 = 99;
                    md.UpdateBy = HttpContext.GetName();
                    md.UpdateTime = DateTime.Now;
                    response3 += _StkBalanceDtlService.Update(md);
                }
                else
                {
                    md.Status = 88;
                    md.BalanceQty = item.Value;
                    md.UpdateBy = HttpContext.GetName();
                    md.UpdateTime = DateTime.Now;
                    response3 += _StkBalanceDtlService.Update(md);
                }
            }
            int response1 = _SapBomRecordService.Update(sapBomRecordMd);
            int response2 = _OutAssembleRecordService.Insert(assembleRecordMd);
            return ToResponse(response1 + response2 + response3);
        }
        #endregion

    }
    public class SapBomRecordAssembleExtDto : SapBomRecordDto
    {
        /// <summary>
        /// 本次装配数量
        /// </summary>
        public int AssembleNum { get; set; }
        public string BnSnCode { get; set; }
        public IFormFile? File { get; set; }

    }
}