using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NPOI.SS.Formula.Functions;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class SigerProjectProductRepository : ApiConfigRepositoryBase<siger_project_product>, ISigerProjectProductRepository
    {
        private readonly ApiConfigDbContext _context;
        public SigerProjectProductRepository(ApiConfigDbContext context) : base(context)
        {
            _context = context;
        }

        public CommonImportResult ImportProducts(IEnumerable<ProductList> products, int projectid, int userid)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var productLists = products.ToList();
            foreach (var product in productLists)
            {
                rowIndex++;
                var entity = _context.siger_project_product.FirstOrDefault(q => q.drawingcode == product.DrawingCode && q.projectid == projectid
                                                         && q.status == (int)RowState.Valid);
                if (entity != null)
                {
                    //errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.DrawingCodeHasExist)}");
                }
            }

            if (errors.Any())
            {
                return new CommonImportResult(0, string.Join(";", errors));
            }

            var now = UnixTimeHelper.GetNow();
            foreach (var product in productLists)
            {
                var drawPro = _context.siger_project_product.FirstOrDefault(q => q.drawingcode == product.DrawingCode && q.projectid == projectid
                                                                                                                     && q.status == (int)RowState.Valid);
                if (drawPro != null)
                {
                    drawPro.code = product.Code;
                    drawPro.createtime = now;
                    drawPro.creatorid = userid;
                    drawPro.name = product.Name;
                    drawPro.remark = product.Remark;
                    _context.siger_project_product.Update(drawPro);
                }
                else
                {
                    var entity = new siger_project_product
                    {
                        drawingcode = product.DrawingCode,
                        projectid = projectid,
                        code = product.Code,
                        createtime = now,
                        creatorid = userid,
                        name = product.Name,
                        remark = product.Remark,
                        status = (int)RowState.Valid
                    };
                    _context.siger_project_product.Add(entity);

                    if (_context.SaveChanges()>0)
                    {
                        SaveProductStrature(entity.id, projectid, userid);
                    }else
                    {
                        return new CommonImportResult(0, "0");
                    }
                    //结构
                   
                }
            }
            return new CommonImportResult(1, "1");
            //try
            //{
            //    _context.SaveChanges();
            //    return new CommonImportResult(1, "1");
            //}
            //catch
            //{
            //    throw;
            //}
        }
        void SaveProductStrature(int productId,int pid,int uid)
        {
            _context.siger_project_product_structure.Add(new siger_project_product_structure
            {
                parent_id = 0,
                itemid = productId,
                itemtype = Common.ModuleEnum.ComboxItem.Product,
                user = uid,
                status = (int)RowState.Valid,
                datetime = DateTime.Now,
                projectid = pid,
            });
            _context.SaveChanges();
        }
        public List<siger_project_product> GetData(int pid, string name, int count)
        {
            var data = _context.siger_project_product.Where(q => q.projectid == pid && q.status == (int)RowState.Valid);
            Expression<Func<siger_project_product, bool>> funcCode = q => true;
            Expression<Func<siger_project_product, bool>> funcName = q => true;
            if (!string.IsNullOrWhiteSpace(name))
            {
                funcName = f => f.name.Contains(name);
                funcCode = f => f.code.Contains(name);
            }
            var predicate = funcCode.Or(funcName);
            var resp = data.Where(predicate).Take(count).ToList();
            return resp;
        }
        /// <summary>
        /// 对接基础数据专用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public siger_project_product InsertSigerProjectProductModel(siger_project_product model)
        {
            Insert(model);
            _context.SaveChanges();
            return model;
        }
    }
}
