﻿using Abp.Domain.Repositories;
using Abp.UI;
using Castle.Core.Logging;
using Microsoft.EntityFrameworkCore;
using NewWechat.Vehicles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NewWechat.CRM
{
    public class CrmCustomerPolicy : NewWechatServiceBase, ICrmCustomerPolicy
    {
        private readonly IRepository<Model, Guid> _modelRepository;

        public CrmCustomerPolicy(IRepository<Model, Guid> modelRepository)
        {
            _modelRepository = modelRepository;
        }

        public async Task CheckModel(CrmCustomer crmCustomer)
        {
            if (crmCustomer == null)
            {
                throw new ArgumentNullException("crmCustomer");
            }
            foreach (var item in crmCustomer.Vehicles.ToList())
            {
                var model = await _modelRepository.GetAll().Include(c => c.Category).Include(m => m.Make).Where(w => w.Code == item.ModelCode).FirstOrDefaultAsync();
                if (model == null)
                {
                    crmCustomer.Vehicles.Remove(item);
                    Logger.Warn($"ModelCode:{item.ModelCode} doesn't exist!");
                }
                if (model.Category?.Code != item.CategoryCode)
                {
                    crmCustomer.Vehicles.Remove(item);
                    Logger.Warn($"CategoryCode:{item.CategoryCode} doesn't match!");
                }
                if (model.Make?.Code != item.MakeCode)
                {
                    crmCustomer.Vehicles.Remove(item);
                    Logger.Warn($"MakeCode:{item.MakeCode} doesn't match!");
                }
            }
        }
    }
}
