using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Repository.Data.Tpm;
using Siger.Middlelayer.Repository.Entities;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Paged;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.Share.Models;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Response;
using Siger.Middlelayer.Utility.ImportEntities;

namespace Siger.Middlelayer.TpmRepository.Repositories
{
    internal class PlanRepository : TpmRepositoryBase<siger_project_plan>, IPlanRepository
    {
        private readonly ApiTpmDbContext _context;
        public PlanRepository(ApiTpmDbContext context) : base(context)
        {
            _context = context;
        }

        public IPagedCollectionResult<GetListSearchPlan> GetPagedlistsSearchPlan(IEnumerable<int> machineIds, int modeType, int value_type, int severity_level, int instruction_cycle
            , int datetype, int department, int person, int gt, int lt, int status, int projectId, int page, int pagesize, int state, int creator)
        {
            var now = UnixTimeHelper.GetTodayUnix();
            var queryList = from t in _context.siger_project_plan
                            where t.projectid == projectId && t.status > 0
                            join pitem in _context.siger_project_plan_item on t.itemid equals pitem.id
                            where pitem.projectid == projectId && pitem.status > 0
                            join machine in _context.siger_project_machine on t.machineid equals machine.id into mm
                            from machine in mm.DefaultIfEmpty()
                            select new GetListSearchPlan
                            {
                                id = t.id,
                                type = pitem.type,
                                typeid = pitem.typeid,
                                machineid = pitem.machineid,
                                content = pitem.content ?? "",
                                value_type = pitem.value_type,
                                mode = pitem.mode,
                                unit = pitem.unit ?? "",
                                up_limit = pitem.up_limit ?? "",
                                lower_limit = pitem.lower_limit ?? "",
                                severity_level = pitem.severity_level,
                                failure_mode = pitem.failure_mode ?? "",
                                work_instruction_url = pitem.work_instruction_url ?? "",
                                result_demo_url = pitem.result_demo_url ?? "",
                                standard_time = pitem.standard_time,
                                instruction_cycle = pitem.instruction_cycle,
                                create_mid = pitem.create_mid,
                                create_time = pitem.create_time,
                                work_instruction_name = pitem.work_instruction_name ?? "",
                                planid = t.id,
                                machinetitle = machine == null ? "" : machine.title,
                                first_instruction_time = string.IsNullOrEmpty(t.first_instruction_time)
                                    ? "-"
                                    : UnixTimeHelper.ConvertStringDateTime(t.first_instruction_time)
                                        .ToString(ParameterConstant.DateFormat),
                                department = 0,
                                instruction_mid = t.instruction_mid,
                                remark = pitem.remark ?? "",
                                date_rang = t.date_rang,
                                starttime = t.starttime,
                                endtime = t.endtime,
                                count = t.count,
                                status = t.status,
                                faulttype = pitem.faulttype,
                                actual_standard_time = pitem.actual_standard_time,
                            };

            Expression<Func<GetListSearchPlan, bool>> valuetypeExpression = q => true;
            if (value_type != 0)
            {
                valuetypeExpression = q => q.value_type == value_type;
            }
            Expression<Func<GetListSearchPlan, bool>> creratorExpression = q => true;
            if (creator != 0)
            {
                creratorExpression = q => q.create_mid == creator;
            }
            Expression<Func<GetListSearchPlan, bool>> modeTypeExpression = q => true;
            if (modeType != 0)
            {
                modeTypeExpression = q => q.mode == modeType;
            }
            Expression<Func<GetListSearchPlan, bool>> severitylevelExpression = q => true;
            if (severity_level != 0)
            {
                valuetypeExpression = q => q.severity_level == severity_level;
            }
            Expression<Func<GetListSearchPlan, bool>> instructioncycleExpression = q => true;
            if (instruction_cycle != 0)
            {
                valuetypeExpression = q => q.instruction_cycle == instruction_cycle;
            }
            Expression<Func<GetListSearchPlan, bool>> departmentExpression = q => true;
            if (department != 0)
            {
                valuetypeExpression = q => q.department == department;
            }
            Expression<Func<GetListSearchPlan, bool>> personExpression = q => true;
            if (person != 0)
            {
                valuetypeExpression = q => q.instruction_mid.Contains(person.ToStr());
            }
            Expression<Func<GetListSearchPlan, bool>> datetypeExpression = q => true;
            if (datetype != 0)
            {
                valuetypeExpression = q => q.date_rang == datetype;
            }
            Expression<Func<GetListSearchPlan, bool>> machineidExpression = q => true;
            if (machineIds != null && machineIds.Any())
            {
                machineidExpression = q => machineIds.Contains(q.machineid);
            }
            Expression<Func<GetListSearchPlan, bool>> timeExpression = q => true;
            if (lt > 0 && !(gt > 0))
            {
                timeExpression = q => (q.standard_time >= lt);
            }
            else if (gt > 0 && !(lt > 0))
            {
                timeExpression = q => (q.standard_time <= gt);
            }
            else if (lt > 0 && gt > 0)
            {
                timeExpression = q => (q.standard_time >= lt && q.standard_time <= gt);
            }
            Expression<Func<GetListSearchPlan, bool>> statusExpression = q => true;
            if (status > 0)
            {
                statusExpression = q => q.status == status;
            }
            Expression<Func<GetListSearchPlan, bool>> statusState = q => true;
            if (state > 0)
            {
                //查询第一条状态是否为筛选状态
                var plans = new List<int>();
                var temp = (from pl in _context.siger_project_plan
                            join item in _context.siger_project_plan_item on pl.itemid equals item.id
                            where pl.projectid == projectId && pl.status != 0 && item.mode == 3
                            select pl.id).ToList();
                foreach (var planid in temp)
                {
                    var time = _context.siger_project_plan_time.Where(f => f.planid == planid && f.status != (int)RowState.Invalid).OrderByDescending(f => f.id);
                    var tempdata = time.FirstOrDefault();
                    if (tempdata == null)
                    {
                        continue;
                    }
                    if (state == 1 && state == tempdata.information)
                    {
                        plans.Add(planid);
                        continue;
                    }
                    else if (state == 2 && tempdata.instruction_time >= now)
                    {
                        if (tempdata.information != 1)
                        {
                            plans.Add(planid);
                        }
                        continue;
                    }
                    else if (state == 3 && tempdata.instruction_time < now && tempdata.information != 1)
                    {
                        plans.Add(planid);
                        continue;
                    }
                }
                if (state == 2)
                {
                    var tempPlanids = (from pl in _context.siger_project_plan
                                       join item in _context.siger_project_plan_item on pl.itemid equals item.id
                                       where pl.projectid == projectId && pl.status != 0 && (item.mode == 1 || item.mode == 2)
                                       select pl.id).ToList();
                    if (tempPlanids.Any())
                    {
                        plans.AddRange(tempPlanids);
                    }
                }
                statusState = f => plans.Contains(f.id);
            }
            var predicate = valuetypeExpression.And(modeTypeExpression).And(severitylevelExpression)
                .And(instructioncycleExpression).And(departmentExpression).And(personExpression)
                .And(datetypeExpression).And(machineidExpression).And(timeExpression).And(statusExpression).And(statusState).And(creratorExpression);

            var totalCount = queryList.Count(predicate);
            var entities = queryList.Where(predicate).OrderBy(o => o.first_instruction_time).Skip((page - 1) * pagesize).Take(pagesize).AsNoTracking().ToList();
            foreach (var item in entities)
            {
                //4【执行中】3【逾期】2【待执行】1【已完成】
                if (item.mode == 3)
                {
                    var temp = _context.siger_project_plan_time.OrderByDescending(f => f.id).FirstOrDefault(f => f.planid == item.planid && f.status != (int)RowState.Invalid);
                    if (temp != null)
                    {
                        if (temp.information == 1)
                        {
                            item.state = 1;
                        }
                        else
                        {
                            if (now > temp.instruction_time)
                            {
                                item.state = 3;
                            }
                            else
                            {
                                item.state = 2;
                            }
                        }
                    }
                }
                else
                {
                    item.state = 4;
                }

                if (!string.IsNullOrWhiteSpace(item.instruction_mid))
                {
                    var userids = item.instruction_mid.Split(',').Select(q => q.ToInt()).ToList();
                    var users = _context.siger_project_user.Where(q => userids.Contains(q.mid)).ToList();
                    item.name = string.Join(",", users.Select(q => q.name).ToList());
                }
            }
            return new PagedCollectionResult<GetListSearchPlan>(entities, totalCount);
        }

        public IEnumerable<GetListSearchPlan> GetlistsSearchPlan(IEnumerable<int> machineIds, int modeType, int value_type, int severity_level, int instruction_cycle
            , int datetype, int department, int person, int gt, int lt, int projectId)
        {
            var queryList = from t in _context.siger_project_plan
                            where t.projectid == projectId && t.status == (int)RowState.Valid
                            join pitem in _context.siger_project_plan_item on t.itemid equals pitem.id
                            where pitem.projectid == projectId && pitem.status == (int)RowState.Valid
                            join machine in _context.siger_project_machine on t.machineid equals machine.id
                            join u in _context.siger_project_user on (!string.IsNullOrEmpty(t.instruction_mid)
                                    ? t.instruction_mid.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[0].ToInt()
                                    : 0)
                                equals u.mid into uu
                            from users in uu.DefaultIfEmpty()
                            select new GetListSearchPlan
                            {
                                id = t.id,
                                type = pitem.type,
                                typeid = pitem.typeid,
                                machineid = pitem.machineid,
                                content = pitem.content,
                                value_type = pitem.value_type,
                                mode = pitem.mode,
                                unit = pitem.unit,
                                up_limit = pitem.up_limit,
                                lower_limit = pitem.lower_limit,
                                severity_level = pitem.severity_level,
                                failure_mode = pitem.failure_mode,
                                work_instruction_url = pitem.work_instruction_url,
                                result_demo_url = pitem.result_demo_url,
                                standard_time = pitem.standard_time,
                                instruction_cycle = pitem.instruction_cycle,
                                create_mid = pitem.create_mid,
                                create_time = pitem.create_time,
                                work_instruction_name = pitem.work_instruction_name,
                                planid = t.id,
                                name = users.name,
                                machinetitle = machine.title,
                                first_instruction_time = string.IsNullOrEmpty(t.first_instruction_time)
                                    ? "-"
                                    : UnixTimeHelper.ConvertStringDateTime(t.first_instruction_time)
                                        .ToString(ParameterConstant.DateFormat),
                                department = users.sectionid > 0 ? users.sectionid : 0,
                                instruction_mid = t.instruction_mid,
                                remark = pitem.remark,
                                date_rang = t.date_rang,
                                starttime = t.starttime,
                                endtime = t.endtime,
                                count = t.count,
                                maintain_sparepart = pitem.maintain_sparepart,
                                maintain_tool = pitem.maintain_tool,
                                maintain_method = pitem.maintain_method,
                                hit_item = pitem.hit_item
                            };

            Expression<Func<GetListSearchPlan, bool>> valuetypeExpression = q => true;
            if (value_type != 0)
            {
                valuetypeExpression = q => q.value_type == value_type;
            }
            Expression<Func<GetListSearchPlan, bool>> modeTypeExpression = q => true;
            if (modeType != 0)
            {
                modeTypeExpression = q => q.mode == modeType;
            }
            Expression<Func<GetListSearchPlan, bool>> severitylevelExpression = q => true;
            if (severity_level != 0)
            {
                valuetypeExpression = q => q.severity_level == severity_level;
            }
            Expression<Func<GetListSearchPlan, bool>> instructioncycleExpression = q => true;
            if (instruction_cycle != 0)
            {
                valuetypeExpression = q => q.instruction_cycle == instruction_cycle;
            }
            Expression<Func<GetListSearchPlan, bool>> departmentExpression = q => true;
            if (department != 0)
            {
                valuetypeExpression = q => q.department == department;
            }
            Expression<Func<GetListSearchPlan, bool>> personExpression = q => true;
            if (person != 0)
            {
                valuetypeExpression = q => q.instruction_mid.Contains(person.ToStr());
            }
            Expression<Func<GetListSearchPlan, bool>> datetypeExpression = q => true;
            if (datetype != 0)
            {
                valuetypeExpression = q => q.date_rang == datetype;
            }
            Expression<Func<GetListSearchPlan, bool>> machineidExpression = q => true;
            if (machineIds != null && machineIds.Any())
            {
                machineidExpression = q => machineIds.Contains(q.machineid);
            }
            Expression<Func<GetListSearchPlan, bool>> timeExpression = q => true;
            if (lt > 0 && !(gt > 0))
            {
                timeExpression = q => (q.standard_time >= lt);
            }
            else if (gt > 0 && !(lt > 0))
            {
                timeExpression = q => (q.standard_time <= gt);
            }
            else if (lt > 0 && gt > 0)
            {
                timeExpression = q => (q.standard_time >= lt && q.standard_time <= gt);
            }

            var predicate = valuetypeExpression.And(modeTypeExpression).And(severitylevelExpression)
                .And(instructioncycleExpression).And(departmentExpression).And(personExpression)
                .And(datetypeExpression).And(machineidExpression).And(timeExpression);

            return queryList.Where(predicate).AsNoTracking().ToList();
        }

        public CommonImportResult ImportLevelPlanList(IEnumerable<LevelPlanTemplate> types, int projectId, int userId, int levelCount)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var addPitemList = new List<siger_project_plan_item>();
            var addPtimeList = new List<siger_project_plan_time>();
            var addPlanList = new List<siger_project_plan>();
            var levelSections = _context.siger_project_level_section.Where(t => t.projectid == projectId && t.status == (int)RowState.Valid).ToList();
            var machines = (from q in _context.siger_project_machine
                            join s in _context.siger_project_machine_attribution on q.id equals s.machine
                            where q.projectid == projectId && q.status == (int)RowState.Valid
                            select new
                            {
                                q.id,
                                q.title,
                                q.typeid,
                                s.station
                            }).ToList();
            var users = _context.siger_project_user
                .Where(t => t.projectid == projectId && t.status == (int)RowState.Valid).ToList();
            foreach (var p in types)
            {
                if (p.sections == null || !p.sections.Any() || p.sections.Count != levelCount)
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.LineError}");
                }

                var pids = new List<int> { 0 };
                var machine = new siger_project_machine();
                foreach (var section in p.sections)
                {
                    var secs = levelSections.Where(t => t.title == section && pids.Contains(t.parentid)).ToList();
                    if (!secs.Any())
                    {
                        errors.Add($"{rowIndex + 1},{(int)RequestEnum.LineError}");
                    }
                    else
                    {
                        pids = secs.Select(t => t.id).ToList();
                    }

                    if (section == p.sections.Last())
                    {
                        if (pids.Count != 1)
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.LineError}");
                        }
                        var mchine = machines.FirstOrDefault(t => t.station == pids.First() && t.title == p.machine);
                        if (mchine == null)
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.SectionMachineNull}");
                        }
                        else
                        {
                            machine.id = mchine.id;
                            machine.title = mchine.title;
                            machine.typeid = mchine.typeid;
                        }
                    }
                }
                var machineid = machine.id > 0 ? machine.id : 0;
                var machineTypeId = machine.typeid > 0 ? machine.typeid : 0;

                if (machineid == 0)
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.MachineNotFound}");
                }

                if (string.IsNullOrEmpty(p.content) && !(p.mode > 0) && !(p.value_type > 0) && !(p.standard_time > 0) &&
                        !(p.date_rang > 0) && string.IsNullOrEmpty(p.first_instruction_time))
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.ParameterMiss}");
                }

                if (p.value_type != 1 && p.value_type != 2)
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.PlanValueTypeError}");
                }
                if (p.value_type == 2)
                {
                    if (!(p.lower_limit.ToInt() >= 0) || !(p.up_limit.ToInt() >= 0) ||
                        !(p.up_limit.ToInt() >= p.lower_limit.ToInt()))
                    {
                        errors.Add($"{rowIndex + 1},{(int)RequestEnum.UpperLowerError}");
                    }
                }

                var plancheck = _context.siger_project_plan_item.FirstOrDefault(t =>
                    t.machineid == machineid && t.status == (int)RowState.Valid && t.content == p.content &&
                    t.mode == p.mode && t.value_type == p.value_type && t.standard_time == p.standard_time &&
                    t.instruction_cycle == p.instruction_cycle && t.projectid == projectId);
                if (plancheck != null)
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.DataExist}");
                }
                else
                {
                    //判断开始时间是否在时间范围之外
                    long starttime = 0;
                    long endtime = 0;
                    var firstInstructionTime = DateTime.TryParse(p.first_instruction_time, out DateTime _)
                        ? UnixTimeHelper.ConvertDataTimeLong(p.first_instruction_time.ToDateTime()) : 0;
                    if (firstInstructionTime <= 0)
                    {
                        errors.Add($"{rowIndex + 1},{(int)RequestEnum.StartInstructTimeError}");
                    }
                    if (p.date_rang == 2)
                    {
                        var timeStr = p.instruction_time.Split('/');
                        if (timeStr.Any() && timeStr.Count() != 2)
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.InstructionCycleError}");
                            continue;
                        }
                        starttime = DateTime.TryParse(timeStr[0], out DateTime _)
                            ? UnixTimeHelper.ConvertDataTimeLong(timeStr[0].ToDateTime()) : 0;
                        endtime = DateTime.TryParse(timeStr[1], out DateTime _)
                            ? UnixTimeHelper.ConvertDataTimeLong(timeStr[1].ToDateTime()) : 0;
                        if (starttime > firstInstructionTime || firstInstructionTime > endtime)
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.StartInstructTimeError}");
                        }
                    }

                    var planitem = new siger_project_plan_item
                    {
                        projectid = projectId,
                        content = p.content
                    };
                    if (p.value_type == 1)
                    {
                        planitem.value_type = p.value_type;
                    }
                    else
                    {
                        planitem.value_type = p.value_type;
                        planitem.up_limit = p.up_limit;
                        planitem.lower_limit = p.lower_limit;
                    }

                    planitem.typeid = machineTypeId;
                    planitem.machineid = machineid;
                    planitem.id = rowIndex;
                    planitem.mode = p.mode;
                    planitem.unit = p.unit;
                    planitem.severity_level = p.severity_level;
                    planitem.failure_mode = p.failure_mode;
                    planitem.standard_time = p.standard_time;
                    planitem.instruction_cycle = p.instruction_cycle;
                    planitem.status = (int)RowState.Valid;
                    planitem.create_mid = userId;
                    planitem.create_time = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now);
                    planitem.remark = p.remark;
                    planitem.maintain_sparepart = "";
                    planitem.maintain_tool = "";
                    planitem.maintain_method = "";
                    planitem.hit_item = "";


                    addPitemList.Add(planitem);
                    if (rowIndex > 0)
                    {
                        var itemid = rowIndex;
                        var names = p.name.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        var plan = new siger_project_plan
                        {
                            id = rowIndex,
                            machineid = machineid,
                            itemid = itemid,
                            instruction_cycle = p.instruction_cycle,
                        };
                        var userIds = new List<int>();
                        foreach (var name in names)
                        {
                            var user = users.FirstOrDefault(t => t.name == name);
                            if (user != null)
                            {
                                userIds.Add(user.mid);
                            }
                        }
                        if (!userIds.Any())
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.UserNotFound}");
                        }

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

                        plan.instruction_mid = string.Join(",", userIds);
                        var instructionMid = userIds.First();
                        if (p.date_rang == 2)
                        {
                            plan.date_rang = p.date_rang;
                            plan.starttime = (int)starttime;
                            plan.endtime = (int)endtime;
                        }
                        else if (p.date_rang == 3)
                        {
                            plan.date_rang = p.date_rang;
                            plan.count = p.instruction_time.ToInt();
                        }
                        else
                        {
                            plan.date_rang = p.date_rang;
                        }
                        plan.status = (int)RowState.Valid;
                        plan.projectid = projectId;
                        plan.first_instruction_time = string.IsNullOrEmpty(p.first_instruction_time)
                            ? ""
                            : UnixTimeHelper.ConvertDataTimeLong(p.first_instruction_time.ToDateTime()).ToString();
                        addPlanList.Add(plan);
                        if (rowIndex > 0)
                        {
                            var planid = plan.id;
                            //一直执行
                            if (p.date_rang == 1)
                            {
                                for (var i = firstInstructionTime;
                                    i <= (firstInstructionTime + 31536000);
                                    i += (plan.instruction_cycle * 86400))
                                {
                                    addPtimeList.Add(new siger_project_plan_time
                                    {
                                        projectid = projectId,
                                        status = (int)RowState.Valid,
                                        planid = planid,
                                        original_instruction_time = 0,
                                        information = 2,
                                        instruction_time = (int)i,
                                        instruction_mid = instructionMid
                                    });
                                }
                            }
                            else if (p.date_rang == 2)//按执行日期范围执行
                            {
                                if (starttime <= firstInstructionTime && firstInstructionTime <= endtime)
                                {
                                    for (var i = firstInstructionTime;
                                        i <= endtime;
                                        i += (plan.instruction_cycle * 86400))
                                    {
                                        addPtimeList.Add(new siger_project_plan_time
                                        {
                                            projectid = projectId,
                                            status = (int)RowState.Valid,
                                            planid = planid,
                                            original_instruction_time = 0,
                                            information = 2,
                                            instruction_time = (int)i,
                                            instruction_mid = instructionMid
                                        });
                                    }
                                }
                            }
                            else if (p.date_rang == 3)//按指定次数执行
                            {
                                if (p.instruction_time.ToInt() > 0)
                                {
                                    for (var i = 0; i < p.instruction_time.ToInt(); i++)
                                    {
                                        addPtimeList.Add(new siger_project_plan_time
                                        {
                                            projectid = projectId,
                                            status = (int)RowState.Valid,
                                            planid = planid,
                                            original_instruction_time = 0,
                                            information = 2,
                                            instruction_time = (int)firstInstructionTime,
                                            instruction_mid = instructionMid
                                        });
                                        firstInstructionTime += plan.instruction_cycle * 86400;
                                    }
                                }
                            }
                        }
                    }
                }

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

            try
            {
                if (addPitemList.Any() && addPlanList.Any() && addPtimeList.Any())
                {
                    int rowindex = 1;
                    var itemCount = _context.siger_project_plan_item.Count();
                    var planCount = _context.siger_project_plan.Count();
                    var itemMax = itemCount > 0 ? _context.siger_project_plan_item.Max(t => t.id) : 0;
                    var planMax = planCount > 0 ? _context.siger_project_plan.Max(t => t.id) : 0;
                    foreach (var item in addPitemList)
                    {
                        var plan = addPlanList.FirstOrDefault(t => t.itemid == rowindex);
                        item.id = itemMax + rowindex;
                        if (plan != null)
                        {
                            var addtimelist = addPtimeList.Where(t => t.planid == rowindex);
                            plan.id = planMax + rowindex;
                            plan.itemid = item.id;
                            _context.siger_project_plan_item.Add(item);
                            _context.siger_project_plan.Add(plan);
                            foreach (var time in addtimelist)
                            {
                                time.planid = plan.id;
                                _context.siger_project_plan_time.Add(time);
                            }
                            _context.SaveChanges();
                        }

                        rowindex++;
                    }
                }
                else
                {
                    return new CommonImportResult(0, CommonEnum.NoData.ToString());
                }
                _context.SaveChanges();
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }

        public CommonImportResult ImportLevelPlanListSkf(IEnumerable<LevelPlanListSkf> types, int projectId, int userId, int levelCount)
        {
            var errors = new List<string>();
            var rowIndex = 1;
            var addPitemList = new List<siger_project_plan_item>();
            var addPtimeList = new List<siger_project_plan_time>();
            var addPlanList = new List<siger_project_plan>();
            var users = _context.siger_project_user
                .Where(t => t.projectid == projectId && t.status == (int)RowState.Valid).ToList();
            foreach (var p in types)
            {
                if (!_context.siger_project_machine.Any(f => f.projectid == projectId && f.status != 0 && f.id == p.machine))
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.MachineNotFound}");
                    continue;
                }
                if (string.IsNullOrEmpty(p.content) && !(p.mode > 0) && !(p.value_type > 0) && !(p.standard_time > 0) &&
                        !(p.date_rang > 0) && string.IsNullOrEmpty(p.first_instruction_time))
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.ParameterMiss}");
                    continue;
                }
                if (p.value_type != 1 && p.value_type != 2)
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.PlanValueTypeError}");
                    continue;
                }
                if (p.value_type == 2)
                {
                    if (!(p.lower_limit.ToInt() >= 0) || !(p.up_limit.ToInt() >= 0) ||
                        !(p.up_limit.ToInt() >= p.lower_limit.ToInt()))
                    {
                        errors.Add($"{rowIndex + 1},{(int)RequestEnum.UpperLowerError}");
                        continue;
                    }
                }

                var faultId = 0;
                if (!string.IsNullOrWhiteSpace(p.faultmode))
                {
                    var mode = _context.siger_project_machine_fault.FirstOrDefault(q => q.title == p.faultmode && q.projectid == projectId && q.status == (int)RowState.Valid);
                    if (mode == null)
                    {
                        errors.Add($"{rowIndex + 1},{(int)RequestEnum.FaultModeNotFound}");
                        continue;
                    }

                    faultId = mode.id;
                }

                var plancheck = _context.siger_project_plan_item.FirstOrDefault(t =>
                    t.machineid == p.machine && t.status == (int)RowState.Valid && t.content == p.content &&
                    t.mode == p.mode && t.value_type == p.value_type && t.standard_time == p.standard_time &&
                    t.instruction_cycle == p.instruction_cycle && t.projectid == projectId);
                if (plancheck != null)
                {
                    errors.Add($"{rowIndex + 1},{(int)RequestEnum.DataExist}");
                }
                else
                {
                    //判断开始时间是否在时间范围之外
                    long starttime = 0;
                    long endtime = 0;
                    var firstInstructionTime = DateTime.TryParse(p.first_instruction_time, out DateTime _)
                        ? UnixTimeHelper.ConvertDataTimeLong(p.first_instruction_time.ToDateTime()) : 0;
                    if (firstInstructionTime <= 0)
                    {
                        errors.Add($"{rowIndex + 1},{(int)RequestEnum.StartInstructTimeError}");
                    }
                    if (p.date_rang == 2)
                    {
                        var timeStr = p.instruction_time.Split('/');
                        if (timeStr.Any() && timeStr.Count() != 2)
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.InstructionCycleError}");
                            continue;
                        }
                        starttime = DateTime.TryParse(timeStr[0], out DateTime _)
                            ? UnixTimeHelper.ConvertDataTimeLong(timeStr[0].ToDateTime()) : 0;
                        endtime = DateTime.TryParse(timeStr[1], out DateTime _)
                            ? UnixTimeHelper.ConvertDataTimeLong(timeStr[1].ToDateTime()) : 0;
                        if (starttime > firstInstructionTime || firstInstructionTime > endtime)
                        {
                            errors.Add($"{rowIndex + 1},{(int)RequestEnum.StartInstructTimeError}");
                        }
                    }

                    var planitem = new siger_project_plan_item
                    {
                        projectid = projectId,
                        content = p.content
                    };
                    if (p.value_type == 1)
                    {
                        planitem.value_type = p.value_type;
                    }
                    else
                    {
                        planitem.value_type = p.value_type;
                        planitem.up_limit = p.up_limit;
                        planitem.lower_limit = p.lower_limit;
                    }
                    var machinedata = _context.siger_project_machine.First(f => f.id == p.machine && f.status != 0 && f.projectid == projectId);
                    planitem.typeid = machinedata.typeid;
                    planitem.machineid = machinedata.id;
                    planitem.id = rowIndex;
                    planitem.mode = p.mode;
                    planitem.unit = p.unit;
                    planitem.severity_level = p.severity_level;
                    //planitem.failure_mode = p.failure_mode;
                    planitem.standard_time = p.standard_time;
                    planitem.instruction_cycle = p.instruction_cycle;
                    planitem.status = (int)RowState.Valid;
                    planitem.create_mid = userId;
                    planitem.create_time = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now);
                    planitem.remark = p.remark;
                    planitem.maintain_sparepart = p.maintain_sparepart;
                    planitem.maintain_tool = p.maintain_tool;
                    //planitem.hit_item = p.hit_item;
                    //planitem.maintain_method = p.maintain_method;
                    planitem.faulttype = faultId;

                    addPitemList.Add(planitem);
                    if (rowIndex > 0)
                    {
                        var itemid = rowIndex;

                        var plan = new siger_project_plan
                        {
                            machineid = p.machine,
                            itemid = itemid,
                            instruction_cycle = p.instruction_cycle,
                        };

                        var instructionMid = 0;
                        if (!string.IsNullOrWhiteSpace(p.name))
                        {
                            var names = p.name.Split(new[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            var userIds = new List<int>();
                            foreach (var name in names)
                            {
                                var user = users.FirstOrDefault(t => t.name == name);
                                if (user != null)
                                {
                                    userIds.Add(user.mid);
                                }
                            }
                            if (!userIds.Any())
                            {
                                errors.Add($"{rowIndex + 1},{(int)RequestEnum.UserNotFound}");
                            }
                            if (errors.Any())
                            {
                                return new CommonImportResult(0, string.Join(";", errors));
                            }

                            plan.instruction_mid = string.Join(",", userIds);
                            instructionMid = userIds.First();
                        }

                        if (p.date_rang == 2)
                        {
                            plan.date_rang = p.date_rang;
                            plan.starttime = (int)starttime;
                            plan.endtime = (int)endtime;
                        }
                        else if (p.date_rang == 3)
                        {
                            plan.date_rang = p.date_rang;
                            plan.count = p.instruction_time.ToInt();
                        }
                        else
                        {
                            plan.date_rang = p.date_rang;
                        }
                        plan.status = (int)RowState.Valid;
                        plan.projectid = projectId;
                        plan.first_instruction_time = string.IsNullOrEmpty(p.first_instruction_time)
                            ? ""
                            : UnixTimeHelper.ConvertDataTimeLong(p.first_instruction_time.ToDateTime()).ToString();
                        addPlanList.Add(plan);
                        if (rowIndex > 0)
                        {
                            var planid = rowIndex;
                            //一直执行
                            if (p.date_rang == 1)
                            {
                                for (var i = firstInstructionTime;
                                    i <= (firstInstructionTime + 31536000);
                                    i += (plan.instruction_cycle * 86400))
                                {
                                    addPtimeList.Add(new siger_project_plan_time
                                    {
                                        projectid = projectId,
                                        status = (int)RowState.Valid,
                                        planid = planid,
                                        original_instruction_time = 0,
                                        information = 2,
                                        instruction_time = (int)i,
                                        instruction_mid = instructionMid
                                    });
                                }
                            }
                            else if (p.date_rang == 2)//按执行日期范围执行
                            {
                                if (starttime <= firstInstructionTime && firstInstructionTime <= endtime)
                                {
                                    for (var i = firstInstructionTime;
                                        i <= endtime;
                                        i += (plan.instruction_cycle * 86400))
                                    {
                                        addPtimeList.Add(new siger_project_plan_time
                                        {
                                            projectid = projectId,
                                            status = (int)RowState.Valid,
                                            planid = planid,
                                            original_instruction_time = 0,
                                            information = 2,
                                            instruction_time = (int)i,
                                            instruction_mid = instructionMid
                                        });
                                    }
                                }
                            }
                            else if (p.date_rang == 3)//按指定次数执行
                            {
                                if (p.instruction_time.ToInt() > 0)
                                {
                                    for (var i = 0; i < p.instruction_time.ToInt(); i++)
                                    {
                                        addPtimeList.Add(new siger_project_plan_time
                                        {
                                            projectid = projectId,
                                            status = (int)RowState.Valid,
                                            planid = planid,
                                            original_instruction_time = 0,
                                            information = 2,
                                            instruction_time = (int)firstInstructionTime,
                                            instruction_mid = instructionMid
                                        });
                                        firstInstructionTime += plan.instruction_cycle * 86400;
                                    }
                                }
                            }
                        }
                    }
                }

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

            try
            {
                if (!addPitemList.Any() || !addPlanList.Any() || !addPtimeList.Any())
                {
                    return new CommonImportResult(0, CommonEnum.NoData.ToString());
                }
                int rowindex = 1;
                foreach (var item in addPitemList)
                {
                    var plan = addPlanList.FirstOrDefault(t => t.itemid == rowindex);
                    if (plan == null)
                    {
                        continue;
                    }
                    var planItem = new siger_project_plan_item
                    {
                        type = item.type,
                        typeid = item.typeid,
                        machineid = item.machineid,
                        content = item.content,
                        value_type = item.value_type,
                        mode = item.mode,
                        unit = item.unit,
                        up_limit = item.up_limit,
                        lower_limit = item.lower_limit,
                        severity_level = item.severity_level,
                        failure_mode = item.failure_mode,
                        work_instruction_url = item.work_instruction_url,
                        result_demo_url = item.result_demo_url,
                        standard_time = item.standard_time,
                        instruction_cycle = item.instruction_cycle,
                        create_mid = item.create_mid,
                        create_time = item.create_time,
                        remark = item.remark,
                        work_instruction_name = item.work_instruction_name,
                        projectid = item.projectid,
                        maintain_tool = item.maintain_tool,
                        maintain_sparepart = item.maintain_sparepart,
                        hit_item = item.hit_item,
                        maintain_method = item.maintain_method,
                        faulttype = item.faulttype,
                    };
                    _context.siger_project_plan_item.Add(planItem);
                    if (_context.SaveChanges() <= 0)
                    {
                        return new CommonImportResult(0, CommonEnum.Fail.ToString());
                    }

                    plan.itemid = planItem.id;
                    _context.siger_project_plan.Add(plan);
                    if (_context.SaveChanges() <= 0)
                    {
                        return new CommonImportResult(0, CommonEnum.Fail.ToString());
                    }

                    var addtimelist = addPtimeList.Where(t => t.planid == rowindex);
                    foreach (var time in addtimelist)
                    {
                        time.planid = plan.id;
                        _context.siger_project_plan_time.Add(time);
                    }
                    if (_context.SaveChanges() <= 0)
                    {
                        return new CommonImportResult(0, CommonEnum.Fail.ToString());
                    }

                    rowindex++;
                }
                return new CommonImportResult(1, "1");
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 兼容被禁用的已执行记录
        /// </summary>
        /// <param name="machineIds"></param>
        /// <param name="modeType"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="severity_level"></param>
        /// <param name="projectId"></param>
        /// <param name="page"></param>
        /// <param name="pagesize"></param>
        /// <param name="toexcel"></param>
        /// <returns></returns>
        public IPagedCollectionResult<GetListSearchPlan> GetlistPlanResultItem(IEnumerable<int> machineIds, int modeType, int startTime,
            int endTime, int severity_level, int projectId, int page, int pagesize, int toexcel)
        {
            var rowState = (int)RowState.Valid;
            var querys = from t in _context.siger_project_plan_item
                         where t.status == rowState && t.projectid == projectId
                         join plan in _context.siger_project_plan on t.id equals plan.itemid
                         where plan.projectid == projectId && plan.status == rowState
                         join ptime in _context.siger_project_plan_time on plan.id equals ptime.planid
                         where ptime.status > 0 && ptime.information == (int)PlanStatus.Normal
                         join machine in _context.siger_project_machine on t.machineid equals machine.id
                         select new GetListSearchPlan
                         {
                             id = plan.id,
                             type = t.type,
                             typeid = t.typeid,
                             machineid = t.machineid,
                             content = t.content,
                             value_type = t.value_type,
                             mode = t.mode,
                             unit = t.unit,
                             up_limit = t.up_limit,
                             lower_limit = t.lower_limit,
                             severity_level = t.severity_level,
                             failure_mode = t.failure_mode,
                             work_instruction_url = t.work_instruction_url,
                             result_demo_url = t.result_demo_url,
                             standard_time = t.standard_time,
                             instruction_cycle = t.instruction_cycle,
                             create_mid = t.create_mid,
                             create_time = t.create_time,
                             work_instruction_name = t.work_instruction_name,
                             planid = plan.id,
                             machinetitle = machine.title,
                             first_instruction_time = string.IsNullOrEmpty(plan.first_instruction_time)
                                 ? "-"
                                 : UnixTimeHelper.ConvertStringDateTime(plan.first_instruction_time)
                                     .ToString(ParameterConstant.DateFormat),
                             instruction_time = ptime.instruction_time,
                             instruction_time_str = ptime.instruction_time > 0
                                 ? UnixTimeHelper.ConvertIntDate(ptime.instruction_time)
                                 : "",
                             timeid = ptime.id,
                             actual_standard_time = t.actual_standard_time,
                             instruction_mid_str = plan.instruction_mid
                         };
            Expression<Func<GetListSearchPlan, bool>> machineidExpression = q => true;
            if (machineIds != null && machineIds.Any())
            {
                machineidExpression = q => machineIds.Contains(q.machineid);
            }
            Expression<Func<GetListSearchPlan, bool>> modeTypeExpression = q => true;
            if (modeType != 0)
            {
                modeTypeExpression = q => q.mode == modeType;
            }
            Expression<Func<GetListSearchPlan, bool>> timeExpression = q => true;
            if (startTime > 0 && endTime > 0)
            {
                timeExpression = q => (q.instruction_time <= endTime && q.instruction_time >= startTime);
            }
            Expression<Func<GetListSearchPlan, bool>> levelExpression = q => true;
            if (severity_level > 0)
            {
                levelExpression = q => q.severity_level == severity_level;
            }

            var predicate = machineidExpression.And(modeTypeExpression).And(timeExpression).And(levelExpression);
            var dataList = querys.Where(predicate).ToList();
            var groupList = dataList.GroupBy(t => t.id).Select(t => t.FirstOrDefault()).ToList();
            if (toexcel == 0)
            {
                var totalCount = groupList.Count;
                var entities = groupList.Skip((page - 1) * pagesize).Take(pagesize).ToList();

                return new PagedCollectionResult<GetListSearchPlan>(entities, totalCount);
            }
            else
            {
                var entities = groupList.ToList();
                return new PagedCollectionResult<GetListSearchPlan>(entities, 0);
            }
        }

        public IEnumerable<GetPlanResult> GetlistPlanOneResultItem(int plantimeid, int startTime, int endTime, int projectId)
        {
            var now = UnixTimeHelper.GetNow();
            var queryList = from t in _context.siger_project_plan_record
                            join p in _context.siger_project_plan on t.planid equals p.id
                            join pitem in _context.siger_project_plan_item on p.itemid equals pitem.id
                            join u in _context.siger_project_user on t.actual_mid equals u.mid into uu
                            from users in uu.DefaultIfEmpty()
                            join pt in _context.siger_project_plan_time on t.plan_time_id equals pt.id
                            where t.projectid == projectId && t.status == (int)RowState.Valid
                                                           && t.planid == plantimeid
                            orderby t.create_time
                            select new GetPlanResult
                            {
                                planid = t.planid,
                                plan_time_id = t.plan_time_id,
                                itemid = t.itemid,
                                value = t.value,
                                create_time = t.create_time,
                                create_mid = t.create_mid,
                                actual_mid = t.actual_mid,
                                id = t.id,
                                imgurl = t.imgurl,
                                sparepartout = t.sparepartout,
                                time = UnixTimeHelper.ConvertIntDate(t.create_time),
                                name = users.name,
                                value_type = pitem.value_type,
                                up = pitem.up_limit,
                                lower = pitem.lower_limit,
                                machineid = p.machineid,
                                mode = pitem.mode,
                                hit_type = pt.hit_type,
                                keep_remark = pt.keep_remark ?? "",
                                standard_time = pitem.standard_time,
                                corepair = t.corepairer,
                                act_standard_time = t.actual_standard_time,
                                information = pt.information,
                                instruction_mid = pt.instruction_mid == 0 ? t.actual_mid : pt.instruction_mid,
                                instruction_time = pt.instruction_time,
                                //state=pt.instruction_mid!=0?1:pt.instruction_time>=now?2:3
                            };

            return queryList.AsNoTracking().ToList();
        }

        public IEnumerable<PlanAppItemList> GetListAppIndexItem(IEnumerable<int> machineIds, int information, int todayTime, int projectId)
        {
            var queryList = from t in _context.siger_project_plan
                            join pitem in _context.siger_project_plan_item on t.itemid equals pitem.id
                            join ptime in _context.siger_project_plan_time on t.id equals ptime.planid
                            join machine in _context.siger_project_machine on t.machineid equals machine.id
                            where t.projectid == projectId && t.status == (int)RowState.Valid && pitem.projectid == projectId &&
                                  pitem.status == (int)RowState.Valid
                                  && ptime.status == (int)RowState.Valid && ptime.information > information
                            select new PlanAppItemList
                            {
                                id = t.id,
                                type = pitem.type,
                                typeid = pitem.typeid,
                                machineid = pitem.machineid,
                                content = pitem.content,
                                value_type = pitem.value_type,
                                mode = pitem.mode,
                                unit = pitem.unit,
                                up_limit = pitem.up_limit,
                                lower_limit = pitem.lower_limit,
                                severity_level = pitem.severity_level,
                                failure_mode = pitem.failure_mode,
                                work_instruction_url = pitem.work_instruction_url,
                                result_demo_url = pitem.result_demo_url,
                                standard_time = pitem.standard_time,
                                instruction_cycle = pitem.instruction_cycle,
                                create_mid = pitem.create_mid,
                                create_time = pitem.create_time,
                                work_instruction_name = pitem.work_instruction_name,
                                planid = t.id,
                                machinetitle = machine.title,
                                first_instruction_time = UnixTimeHelper.ConvertStringDateTime(t.first_instruction_time)
                                    .ToString(ParameterConstant.DateFormat),
                                instruction_mid = ptime.instruction_mid.ToStr(),
                                remark = pitem.remark,
                                date_rang = t.date_rang,
                                starttime = t.starttime,
                                endtime = t.endtime,
                                instruction_mid_str = t.instruction_mid,
                                information = ptime.information,
                                timeid = ptime.id,
                                instruction_time = ptime.instruction_time
                            };
            Expression<Func<PlanAppItemList, bool>> todaytimeExpression = q => true;
            if (todayTime > 0)
            {
                todaytimeExpression = q => q.instruction_time < todayTime;
            }
            Expression<Func<PlanAppItemList, bool>> machineExpression = q => true;
            if (machineIds.Any())
            {
                machineExpression = q => (machineIds.Contains(q.machineid));
            }
            var predicate = todaytimeExpression.And(machineExpression);

            return queryList.Where(predicate).GroupBy(t => t.timeid).Select(t => t.FirstOrDefault()).ToList();
        }

        public bool InsertPlanSign(siger_project_plan_sign planSign)
        {
            _context.Add(planSign);
            return _context.SaveChanges() > 0;
        }

        public IEnumerable<siger_project_plan_sign> GetTodayPlanSigns(int machineId, int userId, int projectId)
        {
            var time = UnixTimeHelper.GetTodayUnix();
            var signs = _context.siger_project_plan_sign.Where(t => t.machine_id == machineId && t.create_mid == userId &&
                    t.projectid == projectId && t.create_time >= time && t.status == (int)RowState.Valid);
            return signs;
        }

        public IEnumerable<siger_project_plan_sign> GetPlanSigns(int userId, int projectId)
        {
            var signs = _context.siger_project_plan_sign.Where(t => (t.create_mid == userId || userId == 0) && t.projectid == projectId &&
                    t.status == (int)RowState.Valid);
            return signs;
        }

        public IEnumerable<ResponsePlanTime> GetPlanCostTime(int projectid, int start, int end)
        {
            var recordData = from record in _context.siger_project_plan_record
                             join plan in _context.siger_project_plan on record.planid equals plan.id
                             where record.projectid.Equals(projectid) && record.status == (int)RowState.Valid
                             && record.create_time >= start && record.create_time <= end
                             select new ResponsePlanTime
                             {
                                 EndTime = record.create_time,
                                 Uid = record.actual_mid,
                                 Mid = plan.machineid
                             };
            recordData = from record in recordData
                         group record by new { record.Uid, record.Mid } into temp
                         from record in temp
                         select record;
            var signData = from sign in _context.siger_project_plan_sign
                           join record in recordData on
                           new { Mid = sign.machine_id, Uid = sign.create_mid } equals new { record.Mid, record.Uid } into temp
                           from record in temp.DefaultIfEmpty()
                           where sign.projectid.Equals(projectid) && sign.status == (int)RowState.Valid
                             && sign.create_time >= start && sign.create_time <= end
                           select new ResponsePlanTime
                           {
                               EndTime = record.EndTime,
                               Uid = record.Uid,
                               Mid = record.Mid,
                               StartTime = sign.create_time
                           };
            return signData.ToList();

        }

        public List<ResponseIdTitle> GetMachineNames(IEnumerable<int> machineIds, int projectId)
        {
            var names = new List<ResponseIdTitle>();
            var query = from q in _context.siger_project_machine_attribution
                        join l in _context.siger_project_level_section on q.station equals l.id
                        join pl in _context.siger_project_level_section on l.parentid equals pl.id
                        join m in _context.siger_project_machine on q.machine equals m.id
                        where machineIds.Contains(q.machine) && q.projectid == projectId &&
                              q.status == (int)RowState.Valid && m.status == (int)RowState.Valid
                        select new MachineData
                        {
                            lastSectionTitle = l.title,
                            lastSecondSectionTitle = pl.title,
                            machine_name = m.title,
                            machine_id = m.id
                        };
            if (query.AsEnumerable().Any())
            {
                foreach (var station in query.AsEnumerable().ToList())
                {
                    var response = new ResponseIdTitle
                    {
                        id = station.machine_id,
                        title = $"{station.lastSecondSectionTitle}-{station.lastSectionTitle}-{station.machine_name}"
                    };
                    names.Add(response);
                }
            }
            return names;
        }

        public List<string> GetMachineNames(int machineId, int projectId)
        {
            var names = new List<string>();
            var query = from q in _context.siger_project_machine_attribution
                        join l in _context.siger_project_level_section on q.station equals l.id
                        join pl in _context.siger_project_level_section on l.parentid equals pl.id
                        join m in _context.siger_project_machine on q.machine equals m.id
                        where q.machine == machineId && q.projectid == projectId &&
                              q.status == (int)RowState.Valid && m.status == (int)RowState.Valid
                        select new MachineData
                        {
                            lastSectionTitle = l.title,
                            lastSecondSectionTitle = pl.title,
                            machine_name = m.title
                        };
            if (query.FirstOrDefault() != null)
            {
                var station = query.First();
                names.Add(station.lastSecondSectionTitle);
                names.Add(station.lastSectionTitle);
                names.Add(station.machine_name);
            }

            return names;
        }

        public IEnumerable<AllPlan> GetAllPlans(int projectId, int start, int end)
        {
            var queryList = from t in _context.siger_project_plan_time
                            where t.projectid == projectId && t.instruction_time >= start && t.instruction_time <= end
                            join p in _context.siger_project_plan on t.planid equals p.id
                            where t.projectid == projectId && t.status > 0
                            join pitem in _context.siger_project_plan_item on p.itemid equals pitem.id
                            where pitem.projectid == projectId && pitem.status > 0 && pitem.mode != 1
                            select new AllPlan
                            {
                                id = t.id,
                                content = pitem.content ?? "",
                                standard_time = pitem.standard_time,
                                machine_id = pitem.machineid,
                                name = t.instruction_mid.ToStr(),
                                severity_level = pitem.severity_level
                            };
            var list = queryList.AsEnumerable();
            var responses = new List<AllPlan>();
            foreach (var allPlan in list)
            {
                var plan = new AllPlan
                {
                    id = allPlan.id,
                    content = allPlan.content,
                    standard_time = allPlan.standard_time,
                    machinetitle = allPlan.machinetitle,
                    severity_level = allPlan.severity_level
                };
                if (!string.IsNullOrWhiteSpace(allPlan.name))
                {
                    var names = allPlan.name.Split(',').Distinct();
                    plan.mids = names.ToList();
                    plan.name = string.Join(",",
                        _context.siger_project_user.Where(q => names.Contains(q.mid.ToString())).Select(m => m.name)
                            .ToList());
                }

                plan.machinetitle = GetMachineParentName(allPlan.machine_id, projectId);
                responses.Add(plan);
            }

            return responses;
        }
    }
}
