using System;
using System.Collections.Generic;
using System.Linq;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.Repository.Repositories
{
    internal class siger_wms_bussinese_contactsRepository : ApiConfigRepositoryBase<siger_wms_bussinese_contacts>, Isiger_wms_bussinese_contactsRepository
    {
        private readonly ApiConfigDbContext dbContext;
        public siger_wms_bussinese_contactsRepository(ApiConfigDbContext context) : base(context)
        {
            dbContext = context;
        }

        private List<int> GetAreaIDs(int pid = 0)
        {
            var ids = new List<int>() { pid };
            var son = new List<int>();
            while (true)
            {
                var id = dbContext.siger_wms_area.Where(f => ids.Contains(f.pid)).Select(f => f.id).ToList();
                if (id.Count() == 0)
                {
                    son.AddRange(ids);
                    break;
                }
                else
                {
                    ids.Clear();
                    ids.AddRange(id.AsEnumerable());
                }
            }
            return son;
        }

        public IEnumerable<ResponseGetBusinessList> GetBusinessList(int materialID, int projectid,string name, WMSEnum type, int typenameid, out int count, int page = 1, int pageSize = 10)
        {
            count = 0;

            var data = GetList(f => f.supply_type == (int)type && f.projectid == projectid && f.status != 0);
            if (typenameid != 0)
            {
                var id = GetAreaIDs(typenameid);
                data = data.Where(f => id.Contains(f.cityid));
            }
            if (!string.IsNullOrEmpty(name))
            {
                data = data.Where(f => f.name.Contains(name));
            }
            //过滤指定物料的供应商
            if(materialID!=0)
            {
                //获取此物料的所有供应商
                var supplierIDs=dbContext.siger_tr_material_supplier.Where(f => f.status == (int)RowState.Valid && f.projectId == projectid && f.material_id == materialID).Select(f=>f.supplier_id).ToList();
                data = data.Where(f => supplierIDs.Contains(f.id));
            }
            count = data.Count();
            data = data.Skip((page - 1) * pageSize).Take(pageSize);
            var result = from info in data.ToList()
                         join area in dbContext.siger_wms_area on info.cityid equals area.id
                         select new ResponseGetBusinessList
                         {
                             id = info.id,
                             typeName = area.name ?? "",
                             name = info.name,
                             serial_number = info.serial_number,
                             enterprise_name = info.enterprise_name,
                             address = info.address,
                             linkman = info.linkman,
                             phone = info.phone,
                             mobile = info.mobile,
                             fax = info.fax,
                             email = info.email,
                             homepage = info.homepage,//网址
                             state = info.status,
                             description = info.description,
                             typeID=info.cityid,
                             duns = info.duns
                         };
            return result;
        }
        public IEnumerable<ResponseGetBusinessList> GetExportData(int pid,string name, WMSEnum type, int typenameid)
        {
            IEnumerable<siger_wms_bussinese_contacts> data;
            if (typenameid != 0)
            {
                var id = GetAreaIDs(typenameid);
                data = GetList( f => f.supply_type == (int)type && id.Contains(f.cityid) &&f.projectid==pid);
            }
            else
            {
                if (string.IsNullOrEmpty(name))
                {
                    data = GetList( f => f.supply_type == (int)type && f.projectid == pid);
                }
                else
                {
                    data = GetList( f => f.supply_type == (int)type && f.name.Contains(name) && f.projectid == pid);
                }
            }
            var result = from info in data.ToList()
                         join area in dbContext.siger_wms_area on info.cityid equals area.id
                         select new ResponseGetBusinessList
                         {
                             id = info.id,
                             typeName = area.name ?? "",
                             name = info.name,
                             serial_number = info.serial_number,
                             enterprise_name = info.enterprise_name,
                             address = info.address,
                             linkman = info.linkman,
                             phone = info.phone,
                             mobile = info.mobile,
                             fax = info.fax,
                             email = info.email,
                             homepage = info.homepage,//网址
                             state = info.status,
                             description = info.description,
                             duns = info.duns
                         };
            return result;
        }

        public IEnumerable<IdTitle> GetPnSupplierIds(int projectId, int materialId)
        {
            var query = from q in dbContext.siger_tr_material_supplier
                join p in dbContext.siger_wms_bussinese_contacts on q.supplier_id equals p.id
                where q.status == (int)RowState.Valid && q.projectId == projectId && q.material_id == materialId
                select new IdTitle
                {
                    id = q.supplier_id,
                    title = p.name
                };
            return query.ToList();
        }

        public IEnumerable<ResponseIdText> GetSupplierList(int projectId)
        {
            var query = from q in dbContext.siger_wms_bussinese_contacts
                where q.status == (int)RowState.Valid && q.projectid == projectId && q.supply_type == (int)WMSEnum.Business
                select new ResponseIdText
                {
                    id = q.id.ToString(),
                    Text = q.name
                };
            return query.ToList();
        }

        public IEnumerable<ResponseIdText> GetSupplierData(int projectId)
        {
            var query = from q in dbContext.siger_wms_bussinese_contacts
                where q.status == (int)RowState.Valid && q.projectid == projectId && q.supply_type == (int)WMSEnum.Business
                select new ResponseIdText
                {
                    id = q.serial_number,
                    Text = q.name
                };
            return query.ToList();
        }

        public CommonImportResult ImportBusiness(IEnumerable<wmsbusinessinfo> data, WMSEnum type, int projectid, int userId)
        {
            var errors = new List<string>();
            var entities = new List<siger_wms_bussinese_contacts>();
            var rowIndex = 1;
            foreach (var temp in data)
            {
                rowIndex++;

                var record = dbContext.siger_wms_bussinese_contacts.FirstOrDefault(f => f.name == temp.name && f.supply_type == (int)type
                && f.status == (int)RowState.Valid && f.projectid == projectid);
                if(record != null)
                {
                    errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.NameHasExist)}");
                }

                var cityid = new siger_wms_area();
                cityid = null;
                var cityids = dbContext.siger_wms_area.Where(f => f.name == temp.city).ToList();
                if (!cityids.Any())
                {
                    errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.CityError)}");
                }
                else
                {
                    foreach (var cityEntity in cityids)
                    {
                        if (dbContext.siger_wms_area.FirstOrDefault(f => f.pid == cityEntity.id) == null)
                        {
                            cityid = cityEntity;
                            break;
                        }
                    }
                    //选择的不是最后一级
                    if (cityid == null)
                    {
                        errors.Add($"{rowIndex},{Convert.ToString((int)RequestEnum.CityError)}");
                    }
                }
                
                if (errors.Any())
                {
                    return new CommonImportResult(0, string.Join(";", errors));
                }

                var entityProjectUser = new siger_wms_bussinese_contacts
                {
                    serial_number = temp.serial_number,
                    cityid = cityid.id,
                    name = temp.name,
                    enterprise_name = temp.enterprise_name,
                    address = temp.address,
                    linkman = temp.linkman,
                    phone = temp.phone,
                    mobile = temp.mobile,
                    fax = temp.fax,
                    email = temp.email,
                    homepage = temp.homepage,
                    description = temp.description,
                    supply_type = (int)type,
                    projectid = projectid,
                    create_time = DateTime.Now,
                    creator = userId,
                    update_time = DateTime.Now,
                    updator = userId,
                    status = (int)RowState.Valid,
                    duns = temp.duns
                };
                entities.Add(entityProjectUser);
            }

            try
            {
                dbContext.siger_wms_bussinese_contacts.AddRange(entities);
                dbContext.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }
    }
}

