using Microsoft.Extensions.Logging;
using SlnMesnac.Model.domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SlnMesnac.Repository.service.Impl
{
    public class LogoConfigImpl : ILogoConfigService
    {
        private readonly ILogger<LogoConfigImpl> _logger;

        private readonly Repository<LogoConfig> _rep;

        public LogoConfigImpl(ILogger<LogoConfigImpl> logger, Repository<LogoConfig> rep)
        {
            _logger = logger;
            _rep = rep;
        }


        /// <summary>
        /// 从MES查询所有型号
        /// </summary>
        /// <returns></returns>
        public List<ProductModel> GetMesAllRecord()
        {
            List<ProductModel> list = null;
			try
			{
				// 查询MES所有型号
				list = _rep.Context.SqlQueryable<ProductModel>(@"SELECT
	*
FROM
	(
	SELECT
		a.MATERIAL_CODE,
		a.MATERIAL_NAME
	FROM
		(
		SELECT
			T.MATERIAL_CODE,
			( SELECT MAX( B.MATERIAL_NAME ) FROM IMOS_TA_MATERIAL B WHERE B.MATERIAL_CODE = T.MATERIAL_CODE ) AS MATERIAL_NAME
		FROM
			IMOS_TA_MATERIAL t
		WHERE
			T.DETIAL_TYPE_NAME = '成品'
			AND T.FACTORY_CODE = '2006'
		) a
	WHERE
		( a.MATERIAL_CODE LIKE '%%' OR a.MATERIAL_NAME LIKE '%%' )
	ORDER BY
		a.MATERIAL_CODE,
		a.MATERIAL_NAME
	) T;").ToList();
			}
			catch (Exception ex)
			{
				_logger.LogError($"从MES查询数据库所有型号失败:{ex.Message}");
			}
            return list;
        }


        /// <summary>
        /// 根据成品条码从MES查询型号
        /// </summary>
        /// <returns></returns>
        public ProductModel GetMaterialTypeByBarCode(string barCode)
        {
            List<ProductModel> list = null;
            try
            {
                // 成品码SQL查询型号
                string ProductSql = $"SELECT a.BAR_CODE, b.ORDER_NO, b.MATERIAL_CODE,b.MATERIAL_NAME,b.ORDER_QTY  FROM IMOS_TM_PRINT_INFO a LEFT JOIN IMOS_PR_ORDER b ON a.ORDER_NUMBER = lpad( b.ORDER_NO, '12', '0' )  WHERE a.BAR_CODE = '{barCode}'";
                // MES码SQL查询型号
                string MesSql = $"SELECT  a.BAR_CODE,  b.ORDER_NO, b.MATERIAL_CODE, b.MATERIAL_NAME, b.ORDER_QTY  FROM IMOS_PR_BARCODE_RECORD a LEFT JOIN IMOS_PR_ORDER b ON a.ORDER_NO = b.ORDER_NO  WHERE a.BAR_CODE = '{barCode}'";
                if(barCode.Length == 20)
                {
                    // 成品码
                     list = _rep.Context.SqlQueryable<ProductModel>(ProductSql).ToList();
                }
                else
                {
                    // 箱体码
                    list = _rep.Context.SqlQueryable<ProductModel>(MesSql).ToList();
                }
               if(list==null || list.Count() == 0)
                {
                    return null;
                }
           
            }
            catch (Exception ex)
            {
                _logger.LogError($"从MES查询数据库所有型号失败:{ex.Message}");
                return null;
            }
            return list.First();
        }


        /// <summary>
        /// 模糊查询，从本地查询某个型号
        /// </summary>
        /// <returns></returns>
        public async  Task<List<LogoConfig>> GetLikeByCode(string code)
		{
            List<LogoConfig> list = null;
            list = await _rep.GetListAsync(x=>x.MaterialType.Contains(code) || x.MaterialName.Contains(code));
            return list;
        }

        /// <summary>
        /// 从本地查询所有型号用来展示
        /// </summary>
        /// <returns></returns>
        public async Task<List<LogoConfig>> GetLocalAllRecordAsync()
		{
            List<LogoConfig> list = null;
			list =await _rep.GetListAsync();
			return list;

        }

        /// <summary>
        ///指定型号查询
        /// </summary>
        /// <returns></returns>
        public LogoConfig GetByMaterialType(string materialType)
        {
            LogoConfig logoConfig = null;
            logoConfig = _rep.GetFirst(x => x.MaterialType == materialType);
            return logoConfig;
        }

        /// <summary>
        ///指定型号修改是否校验
        /// </summary>
        /// <returns></returns>
        public bool updateByMaterialType(LogoConfig record)
        {
           bool result = _rep.Update(record);
            return result;
        }




        /// <summary>
        /// 批量插入型号
        /// </summary>
        /// <returns></returns>
        public async Task<bool> InsertListAsync(List<LogoConfig> list)
		{
		    bool result =	await _rep.InsertRangeAsync(list);
			return result;
		}
    }
}
