using FluentScheduler;
using MongoDB.Driver;
using Siger.Middlelayer.AccRepository;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Dapper.FlowMetek;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Entities;
using System;
using System.Linq;
namespace Siger.ApiFlowMetek.Tasks
{
    public class MetekERPJob : IJob
    {
        private ApiAccDbContext _context;
        private ApiConfigDbContext _cfgContext;
        private ErpRepository _erpRepository;
        public MetekERPJob()
        {
            _context = new ApiAccDbContext();
            _cfgContext = new ApiConfigDbContext();
            _erpRepository = new ErpRepository();
        }

        public void Execute()
        {
            try
            {
                Logger.WriteLineInfo("metekErpJob start...");
                var projectId = _erpRepository.GetConfigPid();

                if (projectId == 0)
                    return;

                var cfg = _cfgContext.siger_project_sync_config.Where(f => f.projectId == projectId && f.module == (int)Module.Acc);

                //订单类型
                SycnWotype(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.CMSMQ));
                //订单
                SycnWo(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.MOCTA));
                //订单更新
               SycModifyWo(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.MOCTA));
                //订单二维码
                SycnWoSn(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.PSMMC));
                //订单二维码更新
                SycnModifyWoSn(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.PSMMC));
                //批次物料
                SycnBatch(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.MOCTE));

                SycnMaterialType(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.INVMA));
                SycnMaterial(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.INVMB));
                SycnSection(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.CMSME));
                SycnUseGroup(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.CMSMJ));
                SycnUser(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.CMSMV));
                //BOM 结构
                // SycnBom(projectId, cfg.FirstOrDefault(f => f.table == MeteERPTable.BOMMD));
            }
            catch (Exception ex)
            {
                Logger.WriteLineInfo(ex.ToString());
            }
        }

        /// <summary>
        /// 工单类型
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnWotype(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpWoType(createdate);
                foreach (var d in data)
                {
                    if (!string.IsNullOrEmpty(d.CreateDate))
                    {
                        createdate = d.CreateDate;
                    }
                    
                    var woType = _context.siger_project_order_type.FirstOrDefault(f => f.projectId == projectId && f.code == d.Code.Trim());
                    if (woType == null)
                    {
                        _context.siger_project_order_type.Add(new Middlelayer.AccRepository.Entities.siger_project_order_type
                        {

                            code = d.Code.Trim(),
                            name = d.Name.Trim(),
                            projectId = projectId,
                            createDate = DateTime.Now,
                            status = 1
                        });
                    }
                   
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.CMSMQ);
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.ToString());
            }
        }

        /// <summary>
        /// 同步工单
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnWo(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpWoInfo(createdate.Trim(), modifydate.Trim());
                //Parallel.ForEach(data, new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount }, d =>
                //{
                //});
                foreach (var d in data)
                {
                    if (!string.IsNullOrEmpty(d.CreateDate))
                        createdate = d.CreateDate;
                    var productId = 0;

                    var productObj = _context.siger_project_product.FirstOrDefault(f => f.projectid == projectId && f.code == d.ProductCode);
                    if (productObj == null)
                    {
                        var productEntity = new siger_project_product
                        {
                            code = d.ProductCode,
                            name = d.ProductName,
                            drawingcode = d.Spc,
                            creatorid = 0,
                            createtime = UnixTimeHelper.GetNow(),
                            projectid = projectId,
                            image = "",
                            remark = "",
                            status = 1
                        };
                        _context.siger_project_product.Add(productEntity);
                        _context.SaveChanges();
                        productId = productEntity.id;
                    }
                    else
                    {
                        productId = productObj.id;
                        productObj.name = d.ProductName;
                        _context.siger_project_product.Update(productObj);
                        _context.SaveChanges();
                    }

                    var woType = _context.siger_project_order_type.FirstOrDefault(f => f.projectId == projectId && f.code == d.WoType);
                    if (woType == null)
                        continue;
                    var planObj = _context.siger_project_product_plan.FirstOrDefault(f => f.projectId == projectId && f.code == d.Wo && f.workordertype == woType.id);
                    if (planObj != null)
                        continue;
                    var qty = d.ExpectQty.ToDouble();
                    _context.siger_project_product_plan.Add(new Middlelayer.AccRepository.Entities.siger_project_product_plan
                    {
                        code = d.Wo,
                        projectId = projectId,
                        product_id = productId,
                        product_code = d.ProductCode,
                        product_name = d.ProductName,
                        draw_number = d.Spc,
                        quantity = Convert.ToInt32(qty),
                        status = 1,
                        workordertype = woType.id,
                        source = 3,
                        create_time = UnixTimeHelper.GetNow(),
                    });
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.MOCTA);
                Logger.WriteLineInfo($"Sync siger_project_product & siger_project_product_plan  Complated startdate '{createdate.Trim()}'");
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }
        /// <summary>
        /// 同步工单 更新
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycModifyWo(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpWoInfo(createdate.Trim(), modifydate.Trim(),true);

                foreach (var d in data)
                {
                    if (!string.IsNullOrEmpty(d.ModifyDate))
                        modifydate = d.ModifyDate;
                    var productId = 0;

                    var productObj = _context.siger_project_product.FirstOrDefault(f => f.projectid == projectId && f.code == d.ProductCode);
                    if (productObj == null)
                    {
                        var productEntity = new siger_project_product
                        {
                            code = d.ProductCode,
                            name = d.ProductName,
                            drawingcode = d.Spc,
                            creatorid = 0,
                            createtime = UnixTimeHelper.GetNow(),
                            projectid = projectId,
                            image = "",
                            remark = "",
                            status = 1
                        };
                        _context.siger_project_product.Add(productEntity);
                        _context.SaveChanges();
                        productId = productEntity.id;
                    }
                    else
                    {
                        productId = productObj.id;
                    }

                    var woType = _context.siger_project_order_type.FirstOrDefault(f => f.projectId == projectId && f.code == d.WoType);
                    if (woType == null)
                        continue;
                    var planObj = _context.siger_project_product_plan.FirstOrDefault(f => f.projectId == projectId && f.code == d.Wo && f.workordertype == woType.id);
                    if (planObj == null)
                        continue;
                    var qty = d.ExpectQty.ToDouble();
                    planObj.code = d.Wo;
                    planObj.quantity = Convert.ToInt32(qty);
                    planObj.product_id = productId;
                    planObj.product_code = d.ProductCode;
                    planObj.product_name = d.ProductName;
                    _context.siger_project_product_plan.Update(planObj);
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.MOCTA,true);
                Logger.WriteLineInfo($"Sync siger_project_product & siger_project_product_plan  Complated modifydate '{modifydate.Trim()}'");
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }
        /// <summary>
        /// 同步工单对应二维码
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnWoSn(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpWoSns(createdate, modifydate);
                foreach (var d in data)
                {
                    if (!string.IsNullOrEmpty(d.CreateDate))
                    {
                        createdate = d.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(d.ModifyDate))
                    {
                        modifydate = d.ModifyDate;
                    }
                    var woType = _context.siger_project_order_type.FirstOrDefault(f => f.projectId == projectId && f.code == d.WoType);
                    if (woType == null)
                        continue;
                    var plan = _context.siger_project_product_plan.FirstOrDefault(f => f.projectId == projectId && f.code == d.Wo && f.workordertype == woType.id);
                    if (plan == null)
                        continue;
                    var product = _context.siger_project_product.FirstOrDefault(f => f.projectid == projectId && f.code == plan.product_code);
                    if (product == null)
                        continue;
                    var snObj = _context.siger_tr_sn_list.FirstOrDefault(f => f.projectId == projectId && f.WoType == d.WoType && f.WO == d.Wo && f.SN == d.Sn);
                    if (snObj == null)
                    {
                        _context.siger_tr_sn_list.Add(new Middlelayer.AccRepository.Entities.SigerTrSnList
                        {
                            WO = d.Wo,
                            WoType = d.WoType,
                            ProductId = product.id,
                            ProductCode = product.code,
                            ResultStatus = "",
                            Line = 0,
                            MaterialId = 0,
                            PN = "",
                            printCount = 0,

                            SN = d.Sn,
                            status = 1,
                            InputDateTime = DateTime.Now,
                            projectId = projectId,
                            TransDateTime = DateTime.Now
                        });
                    }
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.PSMMC);
            }
            catch (Exception e)
            {
                e.ToString();
            }
        }
        void SycnModifyWoSn(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpWoSns(createdate, modifydate,true);
                foreach (var d in data)
                {
                    if (!string.IsNullOrEmpty(d.ModifyDate))
                    {
                        modifydate = d.ModifyDate;
                    }
                    var woType = _context.siger_project_order_type.FirstOrDefault(f => f.projectId == projectId && f.code == d.WoType);
                    if (woType == null)
                        continue;
                    var plan = _context.siger_project_product_plan.FirstOrDefault(f => f.projectId == projectId && f.code == d.Wo && f.workordertype == woType.id);
                    if (plan == null)
                        continue;
                    var product = _context.siger_project_product.FirstOrDefault(f => f.projectid == projectId && f.code == plan.product_code);
                    if (product == null)
                        continue;
                    var snObj = _context.siger_tr_sn_list.FirstOrDefault(f => f.projectId == projectId && f.WoType == d.WoType && f.WO == d.Wo && f.SN == d.Sn);
                    if (snObj == null)
                        continue;

                    snObj.WO = d.Wo;
                    snObj.WoType = d.WoType;
                    snObj.ProductId = product.id;
                    snObj.ProductCode = product.code;
                    snObj.SN = d.Sn;
                    _context.siger_tr_sn_list.Update(snObj);
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.PSMMC,true);
            }
            catch (Exception e)
            {
                e.ToString();
            }
        }
        void SycnBatch(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetBatchrRecord(createdate, modifydate);
                foreach (var d in data)
                {
                    if (!string.IsNullOrEmpty(d.CreateDate))
                    {
                        createdate = d.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(d.ModifyDate))
                    {
                        modifydate = d.ModifyDate;
                    }
                    var woType = _context.siger_project_order_type.FirstOrDefault(f => f.projectId == projectId && f.code == d.WoType);
                    if (woType == null)
                        continue;
                    var plan = _context.siger_project_product_plan.FirstOrDefault(f => f.projectId == projectId && f.code == d.Wo && f.workordertype == woType.id);
                    var assisObj = _context.siger_tr_assist_materials.FirstOrDefault(f => f.projectId == projectId && f.workordertype == d.WoType && f.wo == d.Wo && f.batch == d.Batch && f.pn == d.Pn);
                    if (assisObj == null)
                    {
                        var qty = d.Qty.ToDouble();
                        _context.siger_tr_assist_materials.Add(new Middlelayer.AccRepository.Entities.siger_tr_assist_materials
                        {
                            wo = d.Wo,
                            workordertype = d.WoType,
                            specification = d.Type,
                            batch = d.Batch,
                            status = 1,
                            transdatetime = DateTime.Now,
                            lastupdatetime = DateTime.Now,
                            projectId = projectId,
                            printCount = 0,
                            number = Convert.ToInt32(qty),
                            serial = "",
                            productcode = plan != null ? plan.product_code : "",
                            pn = d.Pn,
                            name = d.Pname,

                        });
                    }
                }

                _context.SaveChanges();
                var batch = _context.siger_tr_assist_materials.Where(q => q.batch.Contains("*")).ToList();
                foreach (var item in batch)
                {
                    _context.siger_tr_assist_materials.Remove(item);
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.MOCTE);
               // Logger.WriteLineInfo($"Sync To 'siger_tr_assist_materials' Complated startdate '{createdate.Trim()}' modifydate '{modifydate.Trim()}'");
            }
            catch (Exception e)
            {
                Logger.WriteLineError(e.ToString());
            }
        }

        /// <summary>
        /// 物料类别
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnMaterialType(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var typeData = _erpRepository.GetMetekMaterialType(createdate, modifydate);
                foreach (var item in typeData)
                {
                    if (!string.IsNullOrEmpty(item.CreateDate))
                    {
                        createdate = item.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(item.ModifyDate))
                    {
                        modifydate = item.ModifyDate;
                    }
                    var typel = _context.siger_tr_material_type.FirstOrDefault(f => f.projectId == projectId && f.status == (int)RowState.Valid && f.tcode == item.tcode && f.parentid != 0);
                    if (typel==null)
                    {
                        var entity = new siger_tr_material_type
                        {
                            projectId = projectId,
                            tcode = item.tcode,
                            name = item.name,
                            parentid = item.parentid,
                            transdatetime = DateTime.Now
                        };
                        _context.siger_tr_material_type.Add(entity);
                    }
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.INVMA);
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        /// <summary>
        /// 物料信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnMaterial(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMeteMaterial(createdate, modifydate);
                foreach (var item in data)
                {
                    if (!string.IsNullOrEmpty(item.CreateDate))
                    {
                        createdate = item.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(item.ModifyDate))
                    {
                        modifydate = item.ModifyDate;
                    }
                    var typel = _context.siger_tr_materials.FirstOrDefault(f => f.projectId == projectId && f.status == (int)RowState.Valid && f.pn == item.pn);
                    if (typel==null)
                    {
                        var entity = new siger_tr_materials
                        {
                            name = item.name,
                            pn = item.pn,
                            typeid = item.typeid,
                            spec = item.spec,
                            supplier = "",
                            manage_mode = "",
                            unit = "",
                            conv_unit = "",
                            conv_proportion = "",
                            price = 0,
                            min_stock = 0,
                            max_stock = 0,
                            is_disable = 0,
                            is_first = 0,
                            priority = "",
                            exp = 0,
                            desc = "",
                            image = "",
                            transdatetime = DateTime.Now,
                            projectId = projectId,
                            category = 0,
                            product_id = 0
                        };
                        _context.siger_tr_materials.Add(entity);
                    }
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.INVMB);
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        /// <summary>
        /// 部门信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnSection(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpSection(createdate, modifydate);
                foreach (var item in data)
                {
                    if (!string.IsNullOrEmpty(item.CreateDate))
                    {
                        createdate = item.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(item.ModifyDate))
                    {
                        modifydate = item.ModifyDate;
                    }
                    var typel = _context.siger_project_section.FirstOrDefault(f => f.id==item.role_id);
                    if (typel==null)
                    {
                        var entity = new siger_project_section
                        {
                            id=item.role_id,
                            title = item.title,
                            role_id = item.role_id,
                            projectid = projectId,
                            description = "",
                            create_mid = 0,
                            create_time = 0,
                            type = 0
                        };
                        _context.siger_project_section.Add(entity);
                    }
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.CMSME);
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        /// <summary>
        /// 岗位信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnUseGroup(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMetekErpUseGroup(createdate, modifydate);
                foreach (var item in data)
                {
                    if (!string.IsNullOrEmpty(item.CreateDate))
                    {
                        createdate = item.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(item.ModifyDate))
                    {
                        modifydate = item.ModifyDate;
                    }
                    var typel = _context.siger_project_usergroup.FirstOrDefault(f => f.projectid==projectId && f.status==(int)RowState.Valid &&f.role_id==item.role_id);
                    if (typel==null)
                    {
                        var entity = new siger_project_usergroup
                        {
                          
                            role_id=item.role_id,
                            title = item.title,
                            projectid = projectId,
                            description = "",
                            create_mid = 0,
                            time = 0,
                            create_ip = ""

                        };
                        _context.siger_project_usergroup.Add(entity);
                    }
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.CMSMJ);
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        /// <summary>
        /// 人员信息
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="config"></param>
        void SycnUser(int projectId, siger_project_sync_config config)
        {
            try
            {
                string createdate = string.Empty;
                string modifydate = string.Empty;
                if (config != null)
                {
                    createdate = config.createDate;
                    modifydate = config.modifyDate;
                }
                var data = _erpRepository.GetMeteUser(createdate, modifydate);
                var password = MD5Helper.Get32MD5("123456");
                foreach (var item in data)
                {
                    if (!string.IsNullOrEmpty(item.CreateDate))
                    {
                        createdate = item.CreateDate;
                    }
                    if (!string.IsNullOrEmpty(item.ModifyDate))
                    {
                        modifydate = item.ModifyDate;
                    }
                    var typel = _context.siger_project_user.FirstOrDefault(f => f.status == (int)RowState.Valid && f.projectid == projectId && f.work_code == item.work_code && f.sectionid > 0);
                    if (typel==null)
                    {
                        var user = new siger_user
                        {
                            type= (int)UserType.User,
                            password= password,
                            nickname = item.name,
                            sex = item.sex,
                            mobile = item.mobile
                        };
                        _context.siger_user.Add(user);
                        _context.SaveChanges();
                        var entity = new siger_project_user
                        {
                            work_code = item.work_code,
                            name = item.name,
                            mid = user.id,
                            sex = item.sex,
                            sectionid = item.sectionid,
                            projectid = projectId,
                            usergroupid = "",
                            is_shift = 0,
                            rank = "",
                            mobile = item.mobile,
                            fixed_line = "",
                            work_email = "",
                            create_time = 0,
                            weixin_account = "",
                            staff_status = 0
                        };
                        _context.siger_project_user.Add(entity);
                    }
                }
                _context.SaveChanges();
                SaveCfg(projectId, config, createdate,modifydate, MeteERPTable.CMSMV);
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }


        void SaveCfg(int projectId, siger_project_sync_config config,string createdate,string modifydate,string table,bool modify=false)
        {
            if (config != null)
            {
                if (modify)
                {
                    config.modifyDate = modifydate.Trim();
                    config.lastupdate = DateTime.Now;
                }
                else
                {
                    config.createDate = createdate.Trim();
                    config.lastupdate = DateTime.Now;
                }
                _cfgContext.siger_project_sync_config.Update(config);
            }
            else
            {
                _cfgContext.siger_project_sync_config.Add(new siger_project_sync_config
                {
                    projectId = projectId,
                    module = (int)Module.Acc,
                    createDate = createdate.Trim(),
                    lastupdate = DateTime.Now,
                    status = 1,
                    table = table
                });
            }
            _cfgContext.SaveChanges();
        }
    }
}
