using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.DncRepository.Entities;
using Siger.Middlelayer.DncRepository.Repositories.Interface;
using Siger.Middlelayer.DncRepository.Response;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Response;

namespace Siger.Middlelayer.DncRepository.Repositories
{
    internal class SigerProjectDncProgramRepository : DncRepositoryBase<siger_project_dnc_program>, ISigerProjectDncProgramRepository
    {
        private readonly ApiDncDbContext _context;
        public SigerProjectDncProgramRepository(ApiDncDbContext context) : base(context)
        {
            _context = context;
        }

        public void CheckProgramPost(int projectId, int userId, int programid, string check_remark, int num, string programcode)
        {
            //审核通过，以前已审核相同程序号的删除
            if (num == 1)
            {
                var oldData = _context.siger_project_dnc_program.Where(f => f.program_code == programcode &&
                                                                      f.checkstatus == (int)CheckState.Checked &&
                                                                      f.id != programid && f.projectid == projectId);
                //观察是否修改成功
                foreach (var item in oldData)
                {
                    item.status = (int)RowState.Invalid;
                }
                _context.siger_project_dnc_program.UpdateRange(oldData);
            }
            var res = _context.siger_project_dnc_program.Find(programid);
           
            res.checkmid = userId;
            res.checktime = UnixTimeHelper.GetNow();
            res.check_remark = check_remark;
            res.checkinfo = (num == (int)CheckInfo.OK) ? ((int)CheckInfo.OK) : ((int)CheckInfo.NOK);//1通过，2不通过
            res.checkstatus = (num == (int)CheckState.Waiting) ? ((int)CheckState.Checked) : ((int)CheckState.Reject);//1待审核，2已审核，3被拒绝
            _context.siger_project_dnc_program.Update(res);
            _context.SaveChanges();
        }

        public void EditProgram(int programid, string file_url, string file_name, int file_size, int productid, int checkmid, string createremark, string programcode)
        {
            var data = _context.siger_project_dnc_program.Find(programid);

            data.file_url = file_url;
            data.file_name = file_name;
            data.file_size = file_size.ToString();
            data.productid = productid;
            data.checkmid = checkmid;
            data.create_remark = createremark;
            data.createtime = UnixTimeHelper.GetNow();
            data.checkstatus = (int)CheckState.Waiting; //状态改为待审核状态
            data.program_code = programcode;
            _context.siger_project_dnc_program.Update(data);
            _context.SaveChanges();
        }

        public ResponseProgramInfo GetProgramInfo(int projectId, int programid)
        {
            var data = (from program in _context.siger_project_dnc_program
                        join product in _context.siger_project_product on program.productid equals product.id into tmp
                        from productInfo in tmp.DefaultIfEmpty()
                        join uc in _context.siger_project_user on program.createmid equals uc.mid into tmp1
                        from ucInfo in tmp1.DefaultIfEmpty()
                        join us in _context.siger_project_user on program.checkmid equals us.mid into re
                        from result in re.DefaultIfEmpty()
                        join s in _context.siger_project_product_route on program.productid equals s.productId into temp
                        from tp in temp.DefaultIfEmpty()
                        where program.projectid == projectId && program.id == programid &&
                              program.status == (int)RowState.Valid
                        select new ResponseProgramInfo
                        {
                            id = program.id,
                            program_code = program.program_code,
                            productid = program.productid,
                            createmid = program.createmid,
                            createtime = program.createtime,
                            create_remark = program.create_remark,
                            checkmid = program.checkmid,
                            checktime = program.checktime,
                            check_remark = program.check_remark,
                            checkinfo = program.checkinfo,
                            checkstatus = program.checkstatus,
                            file_url = program.file_url,
                            file_name = program.file_name,
                            projectid = program.projectid,
                            file_size = program.file_size,
                            productname = productInfo != null ? productInfo.name : "",
                            productcode = productInfo != null ? productInfo.drawingcode : "",
                            createname = ucInfo != null ? ucInfo.name : "",
                            checkname = result != null ? result.name : "",
                            drawno = program.drawno,
                            workproccess = program.work_proccess,
                            processname = tp != null ? tp.name : "",
                            processid = tp != null ? tp.id : 0
                        }).ToList();//.FirstOrDefault();
            if (data != null && data.Count > 0)
            {
                return data.First();
            }
            else
            {
                return null;
            }
            //return data;
        }

        public ResponseProgramInfo GetProgramInfos(int projectId, int programid)
        {
            var data = (from program in _context.siger_project_dnc_program
                        join product in _context.siger_project_product on program.productid equals product.id
                        join uc in _context.siger_project_user on program.createmid equals uc.mid 
                        join us in _context.siger_project_user on program.checkmid equals us.mid 
                        join s in _context.siger_project_product_route on program.process_code.ToInt() equals s.id
                        where program.projectid == projectId && program.id == programid &&
                              program.status == (int)RowState.Valid
                        select new ResponseProgramInfo
                        {
                            id = program.id,
                            program_code = program.program_code,
                            productid = program.productid,
                            createmid = program.createmid,
                            createtime = program.createtime,
                            create_remark = program.create_remark,
                            checkmid = program.checkmid,
                            checktime = program.checktime,
                            check_remark = program.check_remark,
                            checkinfo = program.checkinfo,
                            checkstatus = program.checkstatus,
                            file_url = program.file_url,
                            file_name = program.file_name,
                            projectid = program.projectid,
                            file_size = program.file_size,
                            productname = product.name,
                            productcode = product.drawingcode,
                            createname = uc.name,
                            checkname = us.name,
                            drawno = program.drawno,
                            workproccess = program.work_proccess,
                            processname = s.name,
                            processid = s.id,
                            guidcode=program.guid_code
                        }).FirstOrDefault();
            return data;
        }

        public IEnumerable<ResponseProgramInfo> GetProgramInfoById(int projectId, int programid)
        {
            var data = (from program in _context.siger_project_dnc_program
                        join product in _context.siger_project_product on program.productid equals product.id into tmp
                        from productInfo in tmp.DefaultIfEmpty()
                        join uc in _context.siger_project_user on program.createmid equals uc.mid into tmp1
                        from ucInfo in tmp1.DefaultIfEmpty()
                        join us in _context.siger_project_user on program.checkmid equals us.mid into re
                        from result in re.DefaultIfEmpty()
                        where program.projectid == projectId && program.id == programid &&
                              program.status == (int)RowState.Valid && program.program_type == (int)progromType.Main
                        select new ResponseProgramInfo
                        {
                            id = program.id,
                            program_code = program.program_code,
                            productid = program.productid,
                            createmid = program.createmid,
                            createtime = program.createtime,
                            create_remark = program.create_remark,
                            checkmid = program.checkmid,
                            checktime = program.checktime,
                            check_remark = program.check_remark,
                            checkinfo = program.checkinfo,
                            checkstatus = program.checkstatus,
                            file_url = program.file_url,
                            file_name = program.file_name,
                            projectid = program.projectid,
                            file_size = program.file_size,
                            productname = productInfo.name,
                            productcode = productInfo.drawingcode,
                            createname = ucInfo.name,
                            checkname = result.name,
                            drawno = program.drawno,
                            workproccess = program.work_proccess,
                            guidcode = program.guid_code
                        });
            return data;
        }

        public ResponseGetSectionMachine GetSectionMachine(int projectId, int sectionid)
        {
            var data = (from section in _context.siger_project_machine_attribution
                    join machine in _context.siger_project_machine on section.machine equals machine.id
                    where section.station == sectionid && section.attribution == 1 &&
                          machine.status == (int) RowState.Valid && machine.projectid == projectId
                    select new ResponseGetSectionMachine
                    {
                        id = machine.id,
                        title = machine.title,
                        attribute = machine.attribute
                    }
                ).FirstOrDefault();
            return data;
        }

       
        public IPagedCollectionResult<ResponsePguploadLists> GetPguploadlists(ResponseGetSectionMachine machine, DateTime starttime, DateTime endtime, int page, int pagesize)
        {
            var projectDnc = _context.siger_project_dnc.Where(f => f.machine_id == machine.id 
                                                                   && f.time >= UnixTimeHelper.ConvertDataTimeLong(starttime) 
                                                                   && f.time <= UnixTimeHelper.ConvertDataTimeLong(endtime));
            var query = from dnc in projectDnc
                        join program in _context.siger_project_dnc_program on dnc.program_id equals program.id.ToString() into programResult
                        from programData in programResult.DefaultIfEmpty()
                       join us in _context.siger_project_user on programData.createmid equals us.mid into userResult
                       from userData in userResult.DefaultIfEmpty()
                       join uc in _context.siger_project_user on programData.checkmid equals uc.mid into resultData
                       from r in resultData.DefaultIfEmpty()
                       orderby dnc.time
                       select new ResponsePguploadLists
                       {
                           id = dnc.id,
                           program_id = dnc.program_id,
                           machine_id = dnc.machine_id,
                           machine_name = machine.title,
                           user_id = dnc.user_id,
                           time = dnc.time != 0 ? UnixTimeHelper.ConvertIntDateTime(dnc.time) : "",
                           projectid = dnc.projectid,
                           file_content = dnc.file_content,
                           draw_number = dnc.draw_number,
                           action_type = dnc.action_type,
                           work_code = dnc.work_code,
                           work_name = dnc.work_name,
                           program_size = dnc.program_size,
                           program_type = dnc.program_type,
                           remarks = dnc.remarks,
                           download_type = dnc.download_type,
                           program_code = programData != null ? programData.program_code : "",
                           pgcreatetime = programData != null ? (programData.createtime != 0 ? UnixTimeHelper.ConvertIntDateTime(programData.createtime) : ""):"",
                           pgchecktime = programData != null ? (programData.checktime != 0 ? UnixTimeHelper.ConvertIntDateTime(programData.checktime) : "") :"",
                           file_url = programData != null? programData.file_url :"",
                           file_name = programData != null? programData.file_name:"",
                           pgcreatename = userData!=null ? userData.name :"",
                           pgcheckname = r!=null? r.name:"",
                       };
            var totalCount = query.Count();
            var entities = query.Skip((page - 1) * pagesize).Take(pagesize).ToList();

            return new PagedCollectionResult<ResponsePguploadLists>(entities, totalCount);
        }

        public IList<ResponseAllPrograms> GetPrograms(int ProjectID, string productValue, int checkstatus)
        {
            var programs = _context.siger_project_dnc_program.Where(f => f.checkstatus == checkstatus);
            var products = _context.siger_project_product.AsQueryable();
            if (!string.IsNullOrEmpty(productValue))
            {
                products = products.Where(f => f.name.Contains(productValue) || f.code.Contains(productValue));
            }
            return SearchProgram(ProjectID, programs, products);
        }

        private IList<ResponseAllPrograms> SearchProgram(int projectId, IQueryable<siger_project_dnc_program> programs, IQueryable<siger_project_product> products)
        {
           
            var data = from program in programs
                       join product in products on program.productid equals product.id into productData
                       from productDataInfo in productData.DefaultIfEmpty()
                       join uc in _context.siger_project_user on program.createmid equals uc.mid into user
                       from userInfo in user.DefaultIfEmpty()
                       join uk in _context.siger_project_user on program.checkmid equals uk.mid into userResult
                       from re in userResult.DefaultIfEmpty()
                       where program.projectid == projectId && program.status == (int)RowState.Valid &&
                             productDataInfo.status == (int)RowState.Valid && userInfo.status == (int)RowState.Valid && re.status == (int)RowState.Valid
                       orderby program.createtime descending
                       select new ResponseAllPrograms
                       {
                           id = program.id,
                           program_code = program.program_code,
                           productid = program.productid,
                           createmid = program.createmid,
                           createtime = program.createtime,
                           create_remark = program.create_remark,
                           checkmid = program.checkmid,
                           checktime = program.checktime,
                           check_remark = program.check_remark,
                           checkinfo = program.checkinfo,
                           checkstatus = program.checkstatus,
                           status = program.status,
                           file_url = program.file_url,
                           file_name = program.file_name,
                           projectid = program.projectid,
                           file_size = program.file_size,
                           productname = productDataInfo.name,
                           productcode = productDataInfo.drawingcode,
                           createname = userInfo.name,
                           checkname = re.name
                       };
            return data.ToList();
        }

        public IPagedCollectionResult<ResponseAllPrograms> SearchProgramEx(int ProjectID, string productValue, int checkstatus, int page, int pagesize)
        {

            var data = from program in _context.siger_project_dnc_program
                       join product in _context.siger_project_product on program.productid equals product.id into productData
                       from productDataInfo in productData.DefaultIfEmpty()
                       join uc in _context.siger_project_user on program.createmid equals uc.mid into user
                       from userInfo in user.DefaultIfEmpty()
                       join uk in _context.siger_project_user on program.checkmid equals uk.mid into userResult
                       from re in userResult.DefaultIfEmpty()
                       join s in _context.siger_project_product_route on program.process_code.ToInt() equals s.id into ss
                       from sp in ss.DefaultIfEmpty()
                       where program.projectid == ProjectID && program.status == (int)RowState.Valid && program.checkstatus == checkstatus &&
                             productDataInfo.status == (int)RowState.Valid && userInfo.status == (int)RowState.Valid && re.status == (int)RowState.Valid
                       orderby program.createtime descending
                       select new ResponseAllPrograms
                       {
                           id = program.id,
                           program_code = program.program_code,
                           productid = program.productid,
                           createmid = program.createmid,
                           createtime = program.createtime,
                           create_remark = program.create_remark,
                           checkmid = program.checkmid,
                           checktime = program.checktime,
                           check_remark = program.check_remark,
                           checkinfo = program.checkinfo,
                           checkstatus = program.checkstatus,
                           status = program.status,
                           file_url = program.file_url,
                           file_name = program.file_name,
                           projectid = program.projectid,
                           file_size = program.file_size,
                           productname = productDataInfo.name,
                           productcode = productDataInfo.drawingcode,
                           createname = userInfo.name,
                           checkname = re.name,
                           name= productDataInfo!=null? productDataInfo.name:"",
                           code = productDataInfo != null ? productDataInfo.code : "",
                           toll_gate_code = program.toll_gate_code,
                           process_name=sp.name
                       };
            Expression<Func<ResponseAllPrograms, bool>> productValueExpression = q => true;
            if (!string.IsNullOrEmpty(productValue))
            {
                productValueExpression = f => f.name.Contains(productValue) || f.code.Contains(productValue) || f.toll_gate_code.Contains(productValue);
            }

            var pre = productValueExpression;
            var entities = data.Where(pre).Skip((page - 1) * pagesize).Take(pagesize).ToList();
            var totalCount = data.Where(pre).Count();
            return new PagedCollectionResult<ResponseAllPrograms>(entities, totalCount);
        }

        public IList<ResponseAllPrograms> GetAllProgarm(int projectId, string keyword, int checkstatus,int page,int pageSize, out int totalCount)
        {
            var programs = _context.siger_project_dnc_program.Where(f => f.checkstatus == checkstatus);
            var products = _context.siger_project_product;
            var result = SearchProgram(projectId, programs, products);
            if (!string.IsNullOrEmpty(keyword))
                result = result.Where(f => f.program_code.Contains(keyword) || f.productname.Contains(keyword)).ToList();
            totalCount = result.Count;
            return result.Skip((page - 1) * pageSize).Take(pageSize).ToList();
        }

        public siger_project_dnc UploadProgram(int projectId, int userId, int machineid, int programid, ResponseProgramInfo programinfo,
            out string param)
        {
            //获取用户信息
            var user = _context.siger_project_user.FirstOrDefault(f => f.mid == userId);
            var path = FileUtility.GetTruePath(programinfo.file_url);
            var newDnc = new siger_project_dnc
            {
                program_id = programinfo.id.ToString(),//程序id
                machine_id = machineid,//设备id
                user_id = userId.ToString(),//操作人员mid
                work_code = user?.work_code ?? "",//工号
                work_name = user?.name ?? "",
                time = UnixTimeHelper.GetNow(),
                projectid = projectId,
                file_content = FileUtility.GetText(path),//文件内容
                draw_number = programinfo.productcode,//产品图纸号
                action_type = ((int)ActionTypeEnum.Upload).ToString(),
                program_type = programinfo.file_name.Split('.')[1],
                program_size = programinfo.file_size.ToDouble(),
                remarks = "",//上传备注
            };
            var arr = new DownloadProgramPara
            {
                machineName = newDnc.machine_id,
                programString = newDnc.file_content,
                programNumber = programinfo.program_code
            };
            param = JsonConvert.SerializeObject(arr);
            return newDnc;
        }

        public siger_project_dnc UploadProgramZip(int projectId, int userId, int machineid, int programid, ResponseProgramInfo programinfo)
        {
            //获取用户信息
            var user = _context.siger_project_user.FirstOrDefault(f => f.mid == userId);
            var newDnc = new siger_project_dnc
            {
                program_id = programinfo.id.ToString(),//程序id
                machine_id = machineid,//设备id
                user_id = userId.ToString(),//操作人员mid
                work_code = user?.work_code ?? "",//工号
                work_name = user?.name ?? "",
                time = UnixTimeHelper.GetNow(),
                projectid = projectId,
                file_content = programinfo.file_url,//文件内容
                draw_number = programinfo.productcode,//产品图纸号
                action_type = ((int)ActionTypeEnum.Upload).ToString(),
                program_type = programinfo.file_name.Split('.')[1],
                program_size = programinfo.file_size.ToDouble(),
                remarks = "",//上传备注
            };
            return newDnc;
        }

        public IEnumerable<ResponseProgramInfo> GetListByGuidCode(string guidcode,int projectid,string drawingcode)
        {
            var query = from s in _context.siger_project_dnc_program
                        where s.guid_code == guidcode && s.projectid == projectid && s.status == (int)RowState.Valid
                        && s.program_type==(int)progromType.Son
                        select new ResponseProgramInfo
                        {
                            id = s.id,
                            file_url = s.file_url,
                            productcode = drawingcode,
                            file_name = s.file_name,
                            file_size = s.file_size,
                            program_code=s.program_code,
                            productid = s.productid,
                            createmid = s.createmid,
                            createtime = s.createtime,
                            create_remark = s.create_remark,
                            checkmid = s.checkmid,
                            checktime = s.checktime,
                            check_remark = s.check_remark,
                            checkinfo = s.checkinfo,
                            checkstatus = s.checkstatus,
                            projectid = s.projectid,
                            //productname = productInfo.name,
                            //createname = ucInfo.name,
                            //checkname = result.name,
                            drawno = s.drawno,
                            workproccess = s.work_proccess,
                            guidcode = s.guid_code
                        };
            return query;

        }

        public void AddDnc(siger_project_dnc data)
        {
            _context.siger_project_dnc.Add(data);
            _context.SaveChanges();
        }

        public IEnumerable<ResponseAllPrograms> GetCheckProgram(int projectId, List<string> pros)
        {
            var programs = _context.siger_project_dnc_program.Where(f => pros.Contains(f.program_code) && f.status == (int)RowState.Valid);
            return SearchCheckProgram(programs, projectId);
        }

        public ResponseAllPrograms GetProgramCheckedInfo(int projectId, string programCode)
        {
            var programs = _context.siger_project_dnc_program.Where(f => f.program_code == programCode && f.status == (int)RowState.Valid);
            var result = SearchCheckProgram(programs, projectId).FirstOrDefault();
            return result;
        }

        private IEnumerable<ResponseAllPrograms> SearchCheckProgram(IQueryable<siger_project_dnc_program> programs, int ProjectID)
        {
            var data = from program in programs
                       join product in _context.siger_project_product on program.productid equals product.id into productData
                       from productDataInfo in productData.DefaultIfEmpty()
                       join uc in _context.siger_project_user on program.createmid equals uc.mid into user
                       from userInfo in user.DefaultIfEmpty()
                       join us in _context.siger_project_user on program.checkmid equals us.mid into userResult
                       from re in userResult.DefaultIfEmpty()
                       where program.checkstatus == (int)CheckState.Checked && program.projectid == ProjectID &&
                             productDataInfo.status == (int)RowState.Valid && userInfo.status == (int)RowState.Valid && re.status == (int)RowState.Valid
                       select new ResponseAllPrograms
                       {
                           id = program.id,
                           program_code = program.program_code,
                           productid = program.productid,
                           createmid = program.createmid,
                           createtime = program.createtime,
                           create_remark = program.create_remark,
                           checkmid = program.checkmid,
                           checktime = program.checktime,
                           check_remark = program.check_remark,
                           checkinfo = program.checkinfo,
                           checkstatus = program.checkstatus,
                           status = program.status,
                           file_url = program.file_url,
                           file_name = program.file_name,
                           projectid = program.projectid,
                           file_size = program.file_size,
                           productname = productDataInfo.name,
                           productcode = productDataInfo.drawingcode,
                           createname = userInfo.name,
                           checkname = re.name
                       };
            return data.ToList();
        }
        public IEnumerable<ResponseAllPrograms> GetCheckProgramDeleteList(List<string> pros)
        {
            var programs = _context.siger_project_dnc_program.Where(f => pros.Contains(f.program_code) &&
                                                                    f.checkstatus == (int)CheckState.Checked &&
                                                                    f.status == (int)RowState.Valid
                                                                    );
            var result = (from program in programs
                          join product in _context.siger_project_product
                          on program.productid equals product.id into products
                          from productInfo in products.DefaultIfEmpty()
                          select new ResponseAllPrograms
                          {
                              id = program.id,
                              program_code = program.program_code,
                              productid = program.productid,
                              createmid = program.createmid,
                              createtime = program.createtime,
                              create_remark = program.create_remark,
                              checkmid = program.checkmid,
                              checktime = program.checktime,
                              check_remark = program.check_remark,
                              checkinfo = program.checkinfo,
                              checkstatus = program.checkstatus,
                              status = program.status,
                              file_url = program.file_url,
                              file_name = program.file_name,
                              projectid = program.projectid,
                              file_size = program.file_size,
                              productname = productInfo.name,
                              productcode = productInfo.drawingcode,
                              drawno = program.drawno,
                              workprocess = program.work_proccess
                          }).ToList();
            return result;
        }
        public IEnumerable<ResponseAllPrograms> GetCheckProgramDeleteList(List<string> pros, int machineid)
        {
            var programs = _context.siger_project_dnc_program.Where(f => pros.Contains(f.program_code) &&
                                                                    f.checkstatus == (int)CheckState.Checked &&
                                                                    f.status == (int)RowState.Valid
                                                                    );
            var result = (from program in programs
                          join product in _context.siger_project_product
                          on program.productid equals product.id into products
                          from productInfo in products.DefaultIfEmpty()
                          select new ResponseAllPrograms
                          {
                              id = program.id,
                              program_code = program.program_code,
                              productid = program.productid,
                              createmid = program.createmid,
                              createtime = program.createtime,
                              create_remark = program.create_remark,
                              checkmid = program.checkmid,
                              checktime = program.checktime,
                              check_remark = program.check_remark,
                              checkinfo = program.checkinfo,
                              checkstatus = program.checkstatus,
                              status = program.status,
                              file_url = program.file_url,
                              file_name = program.file_name,
                              projectid = program.projectid,
                              file_size = program.file_size,
                              productname = productInfo.name,
                              productcode = productInfo.drawingcode
                          }).ToList();
            foreach (var item in result)
            {
                var uploadinfo = _context.siger_project_dnc.Where(f => f.program_id == item.id.ToString() &&
                                                              f.machine_id == machineid &&
                                                              f.action_type == "0").OrderBy(f => f.time).FirstOrDefault();
                if (uploadinfo != null)
                {
                    item.uploadname = string.IsNullOrEmpty(uploadinfo.work_name) ? "NA" : uploadinfo.work_name;
                    item.uploadtime = uploadinfo.time != 0 ? UnixTimeHelper.ConvertIntDateTime(uploadinfo.time) : "NA";
                    int.TryParse(item.file_size, out int size);
                    if (size == 0)
                        item.filesize = "NA";
                    else
                        item.filesize = FileUtility.GetFileSize(size);
                }
            }
            return result;
        }

        private class DownloadProgramPara
        {
            public int machineName { get; set; }
            public string programString { get; set; }
            public string programNumber { get; set; }
        }

        public string GetRegion(int sectionid, int ProjectID)
        {
            string result = "";
            siger_project_level_section data;
            if (sectionid != 0)
            {
                data = _context.siger_project_level_section.FirstOrDefault(f => f.id == sectionid && f.status == (int)RowState.Valid);
            }
            else
            {
                data = _context.siger_project_level_section.Where(f => f.projectid == ProjectID && f.status == (int)RowState.Valid).OrderBy(f => f.id).FirstOrDefault();
            }
            if (data != null)
                result = data.title;
            return result;
        }
        public int GetPgUploadCount(List<int> machineIdList, DateTime st, DateTime et)
        {
            try
            {
                var data = _context.siger_project_dnc.AsQueryable();
                if (st != null && et != null)
                {
                    var start = (int)UnixTimeHelper.ConvertDataTimeLong(st);
                    var end = (int)UnixTimeHelper.ConvertDataTimeLong(et);
                    data = data.Where(f => f.time >= start && f.time <= end);
                }
                var count = data.Count(f => f.action_type == ((int)actionType.Upload).ToString()
                                                                && machineIdList.Contains(f.machine_id));
                return count;
            }
            catch
            {
                throw;
            }
        }

        public List<ResponsegetPgUploadCount> GetPgUploadCountBymid(List<int> machineIdList, string type, DateTime starttime, DateTime endtime, int projectid)
        {
            var projectDNC = _context.siger_project_dnc.AsQueryable();
            if (starttime != null && endtime != null)
            {
                projectDNC = projectDNC.Where(f => f.time >= UnixTimeHelper.ConvertDataTimeLong(starttime) &&
                                                f.time <= UnixTimeHelper.ConvertDataTimeLong(endtime));
            }
            int.TryParse(type, out int typeValue);
            if (typeValue == 1)
            {
                var data = from dnc in projectDNC
                           join program in _context.siger_project_dnc_program
                           on dnc.program_id equals program.id.ToString() into programs
                           from programInfo in programs.DefaultIfEmpty()
                           join user in _context.siger_project_user on programInfo.createmid equals user.mid into resultData
                           from r in resultData.DefaultIfEmpty()
                           where machineIdList.Contains(dnc.machine_id) &&
                                 dnc.action_type == ((int)actionType.Upload).ToString() &&
                                 programInfo.status == (int)RowState.Valid &&
                                 r.status == (int)RowState.Valid &&
                                 dnc.projectid == projectid
                           select new
                           {
                               dnc.id,
                               programInfo.createmid,
                               r.name,
                           };
                var groupBy = data.GroupBy(f => f.createmid);
                var result = new List<ResponsegetPgUploadCount>();
                foreach (var item in groupBy)
                {
                    result.Add(new ResponsegetPgUploadCount
                    {
                        num = item.Count(),
                        NAME = item.First().name
                    });
                }
                return result;
            }
            else
            {
                var data = from dnc in projectDNC
                           join program in _context.siger_project_dnc_program
                           on dnc.program_id equals program.id.ToString() into programs
                           from programInfo in programs.DefaultIfEmpty()
                           join user in _context.siger_project_user on programInfo.checkmid equals user.mid into resultData
                           from r in resultData.DefaultIfEmpty()
                           where machineIdList.Contains(dnc.machine_id) &&
                                 dnc.action_type == ((int)actionType.Upload).ToString() &&
                                 programInfo.status == (int)RowState.Valid &&
                                 r.status == (int)RowState.Valid &&
                                 dnc.projectid == projectid
                           select new
                           {
                               dnc.id,
                               programInfo.checkmid,
                               r.name,
                           };
                var groupBy = data.GroupBy(f => f.checkmid);
                var result = new List<ResponsegetPgUploadCount>();
                foreach (var item in groupBy)
                {
                    result.Add(new ResponsegetPgUploadCount
                    {
                        num = item.Count(),
                        NAME = item.First().name
                    });
                }
                return result;
            }
        }

        public List<ResponsegetPgUploadCount> GetPgUploadCountByProduct(List<int> machineIdList, DateTime starttime, DateTime endtime, int projectId)
        {
            var projectDNC = _context.siger_project_dnc.AsQueryable();
            if (starttime != null && endtime != null)
            {
                projectDNC = projectDNC.Where(f => f.time >= UnixTimeHelper.ConvertDataTimeLong(starttime) &&
                                                f.time <= UnixTimeHelper.ConvertDataTimeLong(endtime));
            }
            var data = from dnc in projectDNC
                       join program in _context.siger_project_dnc_program
                       on dnc.program_id equals program.id.ToString() into programs
                       from programInfo in programs.DefaultIfEmpty()
                       join product in _context.siger_project_product on programInfo.productid
                       equals product.id into resultData
                       from r in resultData.DefaultIfEmpty()
                       where machineIdList.Contains(dnc.machine_id) &&
                             dnc.action_type == ((int)actionType.Upload).ToString() &&
                             programInfo.status == (int)RowState.Valid &&
                             r.status == (int)RowState.Valid &&
                             dnc.projectid == projectId
                       select new
                       {
                           dnc.id,
                           productid = r.id,
                           r.name,
                       };
            var groupBy = data.GroupBy(f => f.productid);
            var result = new List<ResponsegetPgUploadCount>();
            foreach (var item in groupBy)
            {
                result.Add(new ResponsegetPgUploadCount
                {
                    num = item.Count(),
                    NAME = HttpUtility.HtmlDecode(item.First().name)
                });
            }
            return result;
        }

        public List<ResponsePgHistoryCountByMid> GetPgHistoryCountBymid(int CID, int PID, List<int> machineIdList, string typeValue, DateTime starttime, DateTime endtime, int projectId)
        {
            var arr = GetChangeTime(machineIdList, starttime, endtime, out int num);
            var arrResult = new List<ResponsePgHistoryCountByMid>();
            if (arr.Any())
            {
                foreach (var item in arr)
                {
                    //获取程序号关联信息
                    var info = GetProgramCheckedInfo(PID, item.program_number);
                    int mid = 0;
                    string name = "";
                    if (arrResult.Exists(f => f.mid == info.checkmid))
                    {
                        if (typeValue == "1")
                        {
                            mid = info.createmid;
                            name = info.createname;
                        }
                        else
                        {
                            mid = info.checkmid;
                            name = info.checkname;
                        }
                    }
                    if (arrResult.Exists(f => f.mid == mid))
                    {
                        var tmp = arrResult.Find(f => f.mid == mid);
                        tmp.num++;
                    }
                    else
                    {
                        arrResult.Add(new ResponsePgHistoryCountByMid
                        {
                            mid = mid,
                            name = name,
                            num = 1
                        });
                    }
                }
            }
            return arrResult;
        }

        public List<ResponseJobProgram> GetChangeTime(List<int> machineids, DateTime starttime, DateTime endtime, out int total)
        {
            var machines = new List<string>();
            machineids.ForEach(f =>
            {
                machines.Add(f.ToString());
            });
            var data = _context.siger_project_dnc_job_program.Where(f => machines.Contains(f.machine_name) && f.time >= starttime &&
                                                                         f.time <= endtime && f.type == ChangeProgramType.Update.ToString().ToLower()).ToList();
            var resultData = new List<ResponseJobProgram>();
            if (data.Count != 0)
            {
                total = data.Count;
                foreach (var item in data)
                {
                    resultData.Add(new ResponseJobProgram
                    {
                        id = item.id,
                        id_old = item.id_old,
                        time = (int)UnixTimeHelper.ConvertDataTimeLong(item.time),
                        machine_name = item.machine_name,
                        program_number = item.program_number,
                        document = item.document == null ? "" : Encoding.ASCII.GetString(item.document),
                        type = item.type
                    });
                }
                return resultData;
            }
            total = 0;
            return resultData;
        }

        public List<ResponsePgHistoryCountByMid> GetPgHistoryCountByProduct(int CID, int PID, List<int> machineIdList, DateTime starttime, DateTime endtime, int projectId)
        {
            var arr = GetChangeTime(machineIdList, starttime, endtime, out int num);
            var arrResult = new List<ResponsePgHistoryCountByMid>();
            if (arr.Any())
            {
                foreach (var item in arr)
                {
                    //获取程序号关联信息
                    var info = GetProgramCheckedInfo(PID, item.program_number);
                    int mid = 0;
                    string name = "";
                    if (info != null)
                    {
                        if (arrResult.Exists(f => f.mid == info.checkmid))
                        {
                            mid = info.productid;   //存入创建人员
                            name = info.productname;
                        }
                        if (arrResult.Exists(f => f.mid == mid))
                        {
                            var tmp = arrResult.Find(f => f.mid == mid);
                            tmp.num++;
                        }
                        else
                        {
                            arrResult.Add(new ResponsePgHistoryCountByMid
                            {
                                mid = mid,
                                name = name,
                                num = 1
                            });
                        }
                    }
                }
            }
            return arrResult;
        }

        public MachineAttributeType GetMachineAttribute(int machineid)
        {
            var machine = _context.siger_project_machine.FirstOrDefault(f => f.id == machineid && f.status == (int)RowState.Valid && f.category == (int)MachineCategory.NC);
            if (machine != null)
            {
                return (MachineAttributeType)machine.attribute;
            }
            return MachineAttributeType.Normal;
        }

        public IEnumerable<siger_project_dnc_program> getAllCheckProgramDeleteList(List<string> pros, int projectid)
        {
            var programs = _context.siger_project_dnc_program.Where(f => pros.Contains(f.program_code) && f.projectid == projectid);
            return programs.ToList();
        }

        public IEnumerable<siger_project_dnc> GetDncs(int machineid, int projectid)
        {
            return _context.siger_project_dnc.Where(t => t.machine_id == machineid && t.projectid == projectid);
        }
    }
}