using Furion.DependencyInjection;
using Furion.DistributedIDGenerator;
using Nirvana.Common;
using Nirvana.Common.ApiBase;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using YBDevice.Entity;

namespace YBDevice.NApi.Application.PrintInfo
{
    /// <summary>
    /// 打印编号处理
    /// </summary>
    public class PrintService : IPrintService, ITransient
    {
        private readonly ISqlSugarRepository<YB_PrintCode> repository;
        private readonly SqlSugarClient dbClient;
        public PrintService(ISqlSugarRepository<YB_PrintCode> sqlSugarRepository)
        {
            repository = sqlSugarRepository;
            dbClient = repository.Context;
        }
        /// <summary>
        /// 生成打印编号并记录
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<ResultInfo> GetCodeAsync(PrintCodeC2SDto data)
        {
            if(data.codes == null || data.codes.Count == 0)
            {
                return new ResultInfo(ResultState.FAIL, "请先扫描设备编号");
            }
            //生成编号
            var printcode = new YB_PrintCode
            {
                Id = IDGen.NextID(),
                CreateTime = DateTime.Now
            };
            await dbClient.Insertable(printcode).ExecuteCommandAsync();

            //保存设备序列号
            List<YB_PrintCodeEqu> list = new List<YB_PrintCodeEqu>();
            foreach (var item in data.codes)
            {
                list.Add(new YB_PrintCodeEqu
                {
                    FacEcode = item.ToStr(),
                    PrintId = printcode.Id
                });
            }
            await dbClient.Insertable(list).ExecuteCommandAsync();
            return new ResultInfo(ResultState.SUCCESS, "success", printcode.Id);
        }
        /// <summary>
        /// 根据ID获取设备列表
        /// </summary>
        /// <param name="id">打印记录ID</param>
        /// <returns></returns>
        public async Task<ResultInfo> GetDevCodeListByIdAsync(Guid id)
        {
            if(!await dbClient.Queryable<YB_PrintCode>().AnyAsync(x => x.Id == id))
            {
                return new ResultInfo(ResultState.FAIL, "记录未找到");
            }
            var list = await dbClient.Queryable<YB_PrintCodeEqu>().Where(x => x.PrintId == id).Select(x => x.FacEcode).ToListAsync();
            return new ResultInfo(ResultState.SUCCESS, "success", list);
        }
    }
}
