using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Siger.ApiCommon.Result;
using Siger.ApiCommon.Utilities;
using Siger.ApiTPM.Result;
using Siger.ApiTPM.Utilities;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Common.AppSettings;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Common.Helpers;
using Siger.Middlelayer.Common.ModuleEnum;
using Siger.Middlelayer.Log;
using Siger.Middlelayer.Repository;
using Siger.Middlelayer.Repository.Data;
using Siger.Middlelayer.Repository.Data.Tpm;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Entities;
using Siger.Middlelayer.TpmRepository.Repositories.Interface;
using Siger.Middlelayer.TpmRepository.Request;
using Siger.Middlelayer.TpmRepository.Response;
using Siger.Middlelayer.Utility.Helpers;
using Siger.Middlelayer.Utility.ImportEntities;
using MachineStatus = Siger.ApiTPM.Result.MachineStatus;
using Siger.ApiCommon.Filters;

namespace Siger.ApiTPM.Controllers
{
    public class PlanController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IPlanTimeRepository _planTime;
        private readonly IPlanRepository _plan;
        private readonly IPlanItemRepository _planItem;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectLevelSectionMachineRepository _levelSectionMachineRepository;
        private readonly ISigerProjectUserRepository _userRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        private readonly IPlanRecordRepository _planRecord;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;
        private readonly IPlanReportToleranceRepository _planReportTolerance;

        public PlanController(IUnitOfWork unitOfWork, IPlanTimeRepository planTime, IRepairRepository repairRepository, IPlanRepository plan,
             ISigerProjectLevelSectionRepository levelSectionRepository, ISigerProjectLevelSectionMachineRepository levelSectionMachineRepository,
             IPlanItemRepository planItem, ISigerProjectUserRepository userRepository, ISigerProjectMachineRepository machineRepository,
             ISigerProjectLevelRepository levelRepository, IPlanRecordRepository planRecord, ISigerProjectMachineAttributionRepository machineAttributionRepository
            , IPlanReportToleranceRepository planReportTolerance)
        {
            _unitOfWork = unitOfWork;
            _planTime = planTime;
            _levelSectionRepository = levelSectionRepository;
            _levelSectionMachineRepository = levelSectionMachineRepository;
            _plan = plan;
            _planItem = planItem;
            _userRepository = userRepository;
            _machineRepository = machineRepository;
            _levelRepository = levelRepository;
            _planRecord = planRecord;
            _machineAttributionRepository = machineAttributionRepository;
            _planReportTolerance = planReportTolerance;
        }

        [HttpGet]
        public IActionResult GetlistPlanstatus(int mode, int sectionID, int page = 1, int pagesize = 10)
        {
            var machineIds = _machineRepository.GetLevelSectionMachineIds(sectionID, ProjectId).ToList();
            var datalist = new List<GetListPlanStatus>();
            if (machineIds.Any())
            {
                var datas = _planTime.GetPagedlistPlanstatus(mode, machineIds, ProjectId, page, pagesize);
                if (datas.Data.Any())
                {
                    foreach (var item in datas.Data)
                    {
                        var planstatus = _planTime
                            .GetListPlanstatusInfo(item.mode, item.machineid, item.information, ProjectId).ToList();
                        if (planstatus.Any())
                        {
                            item.num = planstatus.Count;
                            item.planInfo = planstatus;
                            item.utime = item.num - 1 > 0 ? planstatus[item.num - 1].utime : item.utime;
                            var names = planstatus.Select(t => t.name).Where(t => !string.IsNullOrEmpty(t)).Distinct()
                                .ToList();
                            item.name = string.Join(',', names);
                        }

                        var location = new MachineLocationHelper(ProjectId, _plan);
                        item.station = string.Join('-', location.GetPositionByMachineId(item.machineid));
                        item.status = "1134";

                        datalist.Add(item);
                    }
                }
                return new PagedObjectResult(datalist, datas.Total, page, pagesize);
            }
            return new PagedObjectResult(datalist, 0, page, pagesize);
        }

        [HttpGet]
        public IActionResult GetMachinePlanState(int modetype)
        {
            var responses = new List<ResponseGetMachineRepairState>();
            var lines = _levelSectionRepository.GetAccLines(ProjectId).ToList();
            if (!lines.Any())
            {
                return new ObjectResult(responses);
            }
            var levelSectionNames = _levelSectionMachineRepository.GetLastSection(ProjectId).ToList();
            var nowTime = UnixTimeHelper.GetTodayUnix();
            var machines = _machineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.attribution < 4).ToList();
            var levelSections = _machineAttributionRepository.GetList(q => machines.Select(m => m.id).Contains(q.machine) && q.attribution < 4 && q.status == (int)RowState.Valid).ToList();
            var planinformations = _planTime.GetPlanInformationByMachineIds(modetype, machines.Select(q => q.id), 0, nowTime + 86399, ProjectId).ToList();
            var timelt = planinformations.Where(t => t.information == (int)PlanStatus.UnExecuted && t.instruction_time < nowTime).ToList();
            var timeIds = timelt.Select(t => t.id).ToList();
            if (timelt.Any())
            {
                var times = _planTime.GetList(t => timeIds.Contains(t.id)).ToList();
                if (times.Any())
                {
                    foreach (var plantime in times)
                    {
                        plantime.information = (int)PlanStatus.Overdue;
                        _planTime.Update(plantime);
                    }
                    _unitOfWork.Commit();
                }
            }
            planinformations = _planTime.GetPlanInformationByMachineIds(modetype, machines.Select(q => q.id), 0, nowTime + 86399, ProjectId).ToList();
            foreach (var item in lines)
            {
                var response = new ResponseGetMachineRepairState
                {
                    line = _levelSectionRepository.GetSectionString(ProjectId, item.id).TrimStart(new char[] { '-', '>' })
                };
                var machineids = _machineRepository.GetAttributionMachineIds(item.id, ProjectId).OrderBy(m => m).Distinct().ToList();
                foreach (var machineid in machineids)
                {
                    var mach = machines.FirstOrDefault(q => q.id == machineid);
                    if (mach == null) continue;
                    var machine = new MachineRepairState
                    {
                        id = machineid,
                        name = mach.title
                    };
                    var section = levelSections.FirstOrDefault(q => q.machine == machineid);
                    if (section == null)
                    {
                        machine.state = 0; //未绑定
                    }
                    else
                    {
                        var sectionName = levelSectionNames.FirstOrDefault(q => q.id == section.station);
                        if (sectionName != null)
                        {
                            machine.section_name = sectionName.title;
                        }

                        var machineRepair = planinformations.Where(q => q.machineid == machineid).OrderByDescending(q => q.information).FirstOrDefault();
                        machine.state = machineRepair != null ? machineRepair.information : (int)PlanStatus.Normal;
                    }
                    response.machine.Add(machine);
                }

                responses.Add(response);
            }

            return new ObjectResult(responses);
        }

        [HttpGet]
        public IActionResult GetLevelSectionTree(int modetype)
        {
            var response = new LevelSectionTreeForTpmResult();

            var nowTime = UnixTimeHelper.GetTodayUnix();

            var list = _levelSectionRepository.GetLevelSectionTree(ProjectId);

            var lastSections = _levelSectionMachineRepository.GetLastSection(ProjectId).ToList();
            var lastSectionIds = lastSections.Select(m => m.id).ToList();
            var levelSections = _machineAttributionRepository.GetList(q => list.Select(m => m.id).Contains(q.station) && q.attribution < 4).ToList();

            var machineStatusList = new List<int>();
            var machineIds = _machineRepository.GetAttributionMachineIds(0, ProjectId).Distinct().ToList();
            var planinformations = _planTime
                .GetPlanInformationByMachineIds(modetype, machineIds, 0,
                    nowTime + 86399, ProjectId).ToList();
            var timelt = planinformations
                .Where(t => t.information == (int)PlanStatus.UnExecuted && t.instruction_time < nowTime).ToList();
            var timeIds = timelt.Select(t => t.id).ToList();
            if (timelt.Any())
            {
                var times = _planTime.GetList(t => timeIds.Contains(t.id)).ToList();
                if (times.Any())
                {
                    foreach (var plantime in times)
                    {
                        plantime.information = (int)PlanStatus.Overdue;
                        _planTime.Update(plantime);
                    }
                    _unitOfWork.Commit();
                }
            }
            foreach (var levelSection in list)
            {
                if (lastSectionIds.Contains(levelSection.id))
                {
                    var isBindMachine = 0;
                    var machineStatus = 8;
                    var sections = lastSections.Where(q => q.id == levelSection.id).ToList();
                    if (sections.Any())
                    {
                        foreach (var section in sections)
                        {
                            var machines = levelSections.Where(t => t.station == section.id);
                            if (machines.Any())
                            {
                                foreach (var machine in machines)
                                {
                                    var planinformation = planinformations.Where(t => t.machineid == machine.machine).ToList();
                                    if (!planinformation.Any())
                                    {
                                        isBindMachine = 1;
                                        machineStatus = 8;
                                    }
                                    else
                                    {
                                        if (planinformation.Count(t => t.information == (int)PlanStatus.Overdue) > 0)
                                        {
                                            isBindMachine = 1;
                                            machineStatus = 3;
                                        }
                                        else if (planinformation.Count(t => t.information == (int)PlanStatus.UnExecuted) > 0)
                                        {
                                            isBindMachine = 1;
                                            machineStatus = 2;
                                        }
                                        else
                                        {
                                            isBindMachine = 1;
                                            machineStatus = 8;
                                        }
                                    }
                                    machineStatusList.Add(machineStatus);
                                }
                            }
                            else
                            {
                                machineStatusList.Add(0); // 未绑定
                            }
                        }
                    }
                    else
                    {
                        isBindMachine = 0;
                        machineStatus = 0;
                        machineStatusList.Add(0); // 未绑定
                    }
                    response.sectionTree.Add(new ResponseLevelSectionTree
                    {
                        id = levelSection.id,
                        name = levelSection.name,
                        open = true,
                        pid = levelSection.pid,
                        isBindMachine = isBindMachine,
                        machineStatus = machineStatus,
                        isleaf = true
                    });
                }
                else
                {
                    response.sectionTree.Add(new ResponseLevelSectionTree
                    {
                        id = levelSection.id,
                        name = levelSection.name,
                        open = true,
                        pid = levelSection.pid,
                        isleaf = false
                    });
                }
            }

            response.status.Add(new MachineStatus
            {
                icon = "glyphicon glyphicon-thumbs-up",
                color = "",
                name = "100200",//EnumHelper.GetEnumDesc(PlanStatus.Normal),
                status = 8,
                count = response.sectionTree.Count(m => m.machineStatus == 8) - machineStatusList.Count(t => t == 0)
            });
            response.status.Add(new MachineStatus
            {
                icon = "glyphicon glyphicon-wrench",
                color = "",
                name = "1134",//EnumHelper.GetEnumDesc(PlanStatus.Overdue),
                status = 3,
                count = response.sectionTree.Count(m => m.machineStatus == 3)
            });
            //response.status.Add(new MachineStatus
            //{
            //    icon = "glyphicon glyphicon-question-sign",
            //    color = "",
            //    name = "1135",//"未绑定",
            //    status = 0,
            //    count = machineStatusList.Count(t => t == 0)
            //});
            response.status.Add(new MachineStatus
            {
                icon = "glyphicon glyphicon-copy",
                color = "",
                name = "1133",//EnumHelper.GetEnumDesc(PlanStatus.UnExecuted),
                status = 2,
                count = response.sectionTree.Count(m => m.machineStatus == 2)
            });

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetPlanForm(int mode)
        {
            var starttime = UnixTimeHelper.GetTodayUnix();
            var machineIds = _machineRepository.GetAttributionMachineIds(0, ProjectId);
            var resdata = _planTime.GetPlanFormTotal(machineIds, mode, starttime, ProjectId, UserId);
            return new ObjectResult(resdata);
        }

        [HttpGet]
        public IActionResult SearchPlanTime(int sectionid, int modeType, int value_type, int severity_level,
            int instruction_cycle, int datetype, int department, int person,
            int gt, int lt, string status, int state, int creator, int page = 1, int pagesize = 10)
        {
            var machineIds = _machineRepository.GetAttributionMachineIds(sectionid, ProjectId);
            if (!machineIds.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var resdata = _plan.GetPagedlistsSearchPlan(machineIds, modeType, value_type, severity_level,
                instruction_cycle, datetype, department, person, gt, lt, status.ToInt(), ProjectId, page, pagesize, state, creator);

            var res = new List<GetListSearchPlan>();
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            foreach (var p in resdata.Data)
            {
                var levelsection = _plan.GetLevelSectionByMachineId(p.machineid, ProjectId);
                var position = locationHelper.GetPositionByMachineId(p.machineid);
                p.stas = string.Join('-', position);
                p.station = levelsection == null ? "" : levelsection.title;

                #region 参数赋值

                if (p.instruction_cycle == 1)
                {
                    p.instruction_cycle1 = "1101"; // "";
                }
                else if (p.instruction_cycle == 7)
                {
                    p.instruction_cycle1 = "1136"; // "";
                }
                else if (p.instruction_cycle == 14)
                {
                    p.instruction_cycle1 = "1137"; // "";
                }
                else if (p.instruction_cycle == 30)
                {
                    p.instruction_cycle1 = "1138"; // "";
                }
                else if (p.instruction_cycle == 60)
                {
                    p.instruction_cycle1 = "1139"; // "";
                }
                else if (p.instruction_cycle == 90)
                {
                    p.instruction_cycle1 = "1140"; // "";
                }
                else if (p.instruction_cycle == 180)
                {
                    p.instruction_cycle1 = "1141"; // "";
                }
                else if (p.instruction_cycle == 365)
                {
                    p.instruction_cycle1 = "1142"; // "";
                }

                if (p.date_rang == (int)DateRangStatus.Always)
                {
                    p.date_rang_str = "200151"; // "";
                }
                else if (p.date_rang == (int)DateRangStatus.Custom)
                {
                    var str = UnixTimeHelper.ConvertIntDate(p.starttime) == string.Empty
                        ? UnixTimeHelper.ConvertIntDate(p.endtime)
                        : (UnixTimeHelper.ConvertIntDate(p.starttime) + "/" + UnixTimeHelper.ConvertIntDate(p.endtime));
                    p.date_rang_str = str; // "200162";
                }
                else if (p.date_rang == (int)DateRangStatus.Number)
                {
                    p.date_rang_str = p.count.ToString(); //"执行" + p.count + "次";//"200162"+p.count+ "200163";
                }
                else
                {
                    p.date_rang_str = "-";
                }

                #endregion
                p.creator = _userRepository.Get(f => f.mid == p.create_mid)?.name ?? "";
                res.Add(p);
            }

            return new PagedObjectResult(res, resdata.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult DeletePlan([FromBody]RequestIdsArry arry)
        {
            if (!arry.ids.Any())
            {
                throw new BadRequestException(RequestEnum.IdIsEmpty);
            }
            foreach (var p in arry.ids)
            {
                var plan = _plan.Get(t =>
                    t.id == p && t.projectid == ProjectId && t.status > 0);
                if (plan != null)
                {
                    plan.status = (int)RowState.Invalid;
                    _plan.Update(plan);
                    var planitem = _planItem.Get(t =>
                        t.id == plan.itemid && t.projectid == ProjectId && t.status > 0);
                    if (planitem != null)
                    {
                        planitem.status = (int)RowState.Invalid;
                        _planItem.Update(planitem);
                    }

                    var plantimes = _planTime.GetList(t =>
                        t.planid == plan.id && t.projectid == ProjectId && t.status == (int)RowState.Valid);

                    if (plantimes.Any())
                    {
                        foreach (var item in plantimes)
                        {
                            item.status = (int)RowState.Invalid;
                            _planTime.Update(item);
                        }
                    }
                }
            }
            if (_unitOfWork.Commit() > 0)
                return new ObjectResult(CommonEnum.Succefull);

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetonePlanTime(int id)
        {
            var plantime = _planTime.GetOnePlanTime(id, ProjectId);
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            plantime.locations = string.Join('-', locationHelper.GetPositionByMachineId(plantime.machineid));
            return new ObjectResult(new List<GetListPlanStatus>() { plantime });
        }

        [HttpGet]
        public IActionResult GetonePlan(int id)
        {
            var bes = new List<GetListPlanItem>();
            var res = _planItem.GetOnePlanItem(id, ProjectId).ToList();
            if (res.Any())
            {
                var p = res.ToList()[0];
                if (!string.IsNullOrEmpty(p.first_instruction_time) && p.first_instruction_time != "0")
                {
                    p.first_instruction_time_date = UnixTimeHelper.ConvertStringDateTime(p.first_instruction_time)
                        .ToString(ParameterConstant.DateFormat);
                }
                if (p.date_rang == (int)DateRangStatus.Always)
                {
                    p.date_rang_str = "200151";// "";
                }
                else if (p.date_rang == (int)DateRangStatus.Custom)
                {
                    if (p.starttime > 0 && p.endtime > 0)
                    {
                        p.date_rang_str = UnixTimeHelper.ConvertIntDate(p.starttime) + " - " +
                                          UnixTimeHelper.ConvertIntDate(p.endtime);
                    }
                    else
                    {
                        p.date_rang_str = "";
                    }
                }
                else if (p.date_rang == (int)DateRangStatus.Number)
                {
                    if (p.count > 0)
                    {
                        p.date_rang_str = p.count.ToString();
                    }
                    else
                    {
                        p.date_rang_str = "";
                    }
                }
                else
                {
                    p.date_rang_str = "-";
                }
                bes.Add(p);
                return new ObjectResult(bes);
            }
            return new ObjectResult(bes);
        }

        [HttpGet]
        public IActionResult GetonePlanTimeUser(int id)
        {
            var res = new GetListPlanItem();
            var planitem = _planItem.GetOnePlanItem(id, ProjectId).ToList();
            if (planitem.Any())
            {
                res = planitem.ToList()[0];
            }
            if (!string.IsNullOrEmpty(res.instruction_mid))
            {
                var mids = res.instruction_mid.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (mids != null && mids.Any())
                {
                    var depart = _userRepository.Get(t =>
                        mids.Contains(t.mid.ToString()) && t.status == (int)RowState.Valid &&
                        t.projectid == ProjectId);
                    if (depart != null)
                    {
                        res.departid = depart.sectionid.ToString();
                        var users = _userRepository.GetList(t =>
                            t.status == (int)RowState.Valid && t.projectid == ProjectId &&
                            t.sectionid == depart.sectionid);
                        foreach (var user in users)
                        {
                            res.users.Add(new IdText
                            {
                                id = user.mid,
                                text = user.name
                            });
                        }
                    }
                    res.user = mids.Any() ? mids.ToList() : new List<string>();
                }
            }

            if (res.date_rang == (int)DateRangStatus.Always)
            {
                res.date_rang_str = "200151";//"";
            }
            else if (res.date_rang == (int)DateRangStatus.Custom)
            {
                if (res.starttime > 0 && res.endtime > 0)
                {
                    res.date_rang_str = UnixTimeHelper.ConvertIntDate(res.starttime) + "/" +
                                        UnixTimeHelper.ConvertIntDate(res.endtime) + "200162";
                }
                else
                {
                    res.date_rang_str = "-";
                }
            }
            else if (res.date_rang == (int)DateRangStatus.Number)
            {
                if (res.count > 0)
                {
                    res.date_rang_str = res.count.ToString();//"执行" + res.count + "次";//"200162" + res.count + "200163";
                }
                else
                {
                    res.date_rang_str = "-";
                }
            }
            else
            {
                res.date_rang_str = "-";
            }

            res.first_instruction_time = !string.IsNullOrEmpty(res.first_instruction_time) &&
                                         res.first_instruction_time.ToInt() > 0
                ? UnixTimeHelper.ConvertIntDate(res.first_instruction_time.ToInt())
                : "";
            return new ObjectResult(res);
        }

        [HttpPost]
        public IActionResult AddMachineIdPlan([FromBody]RequestAddPlan res)
        {
            if (!string.IsNullOrEmpty(res.content) && res.instruction_cycle > 0 && res.standard_time > 0 && !string.IsNullOrEmpty(res.first_instruction_time))
            {
                var planitem = new siger_project_plan_item();
                var machine = _machineRepository.Get(t => t.id == res.machineid && t.projectid == ProjectId && t.status == (int)RowState.Valid);
                if (machine == null)
                {
                    throw new BadRequestException(RequestEnum.MachineNotFound);
                }

                planitem.machineid = machine.id;

                int dateRang = res.date_rang.ToInt();
                //判断开始时间是否在时间范围之外
                var starttime = DateTime.TryParse(res.starttime, out DateTime _)
                    ? UnixTimeHelper.ConvertDataTimeLong(res.starttime.ToDateTime())
                    : 0;
                var endtime = DateTime.TryParse(res.endtime, out DateTime _)
                    ? UnixTimeHelper.ConvertDataTimeLong(res.endtime.ToDateTime())
                    : 0;
                var firstInstructionTime = DateTime.TryParse(res.first_instruction_time, out DateTime _)
                    ? UnixTimeHelper.ConvertDataTimeLong(res.first_instruction_time.ToDateTime())
                    : 0;
                if (dateRang == (int)DateRangStatus.Custom)
                {
                    if (starttime > firstInstructionTime || firstInstructionTime > endtime)
                    {
                        throw new BadRequestException(RequestEnum.PlanTimeError);
                    }
                }

                planitem.projectid = ProjectId;
                planitem.content = res.content;
                if (res.value_type == 1)
                {
                    planitem.value_type = res.value_type;
                }
                else
                {
                    planitem.value_type = res.value_type;
                    planitem.up_limit = res.up_limit.ToStr();
                    planitem.lower_limit = res.lower_limit.ToStr();
                }

                planitem.mode = res.modeType;
                planitem.unit = res.unit;
                planitem.severity_level = res.severity_level;
                planitem.failure_mode = res.failure_mode;
                planitem.standard_time = res.standard_time;
                planitem.instruction_cycle = res.instruction_cycle;
                planitem.work_instruction_url = res.work_instruction_url;
                planitem.work_instruction_name = res.work_instruction_name;
                //         planitem.result_demo_url = res.result_demo_url;
                planitem.status = (int)RowState.Valid;
                planitem.create_mid = UserId;
                planitem.create_time = (int)UnixTimeHelper.ConvertDataTimeLong(DateTime.Now);
                planitem.remark = res.remark;
                planitem.maintain_tool = res.maintain_tool ?? "";
                planitem.maintain_sparepart = res.maintain_sparepart ?? "";
                planitem.maintain_method = res.maintain_method ?? "";
                planitem.hit_item = res.hit_item ?? "";
                planitem.faulttype = res.faulttype.ToInt();

                var itemId = _planItem.GetItemIdMax();

                if (itemId >= 0)
                {
                    itemId = itemId + 1;
                    planitem.id = itemId;
                    _planItem.Insert(planitem);
                }
                else
                {
                    throw new BadRequestException(CommonEnum.Fail);
                }
                if (itemId > 0)
                {
                    var plan = new siger_project_plan
                    {
                        machineid = machine.id,
                        itemid = itemId,
                        instruction_cycle = res.instruction_cycle
                    };
                    //plan.first_instruction_time = first_instruction_time.ToString();
                    if (dateRang == (int)DateRangStatus.Custom)
                    {
                        plan.date_rang = dateRang;
                        plan.starttime = (int)starttime;
                        plan.endtime = (int)endtime;
                    }
                    else if (dateRang == (int)DateRangStatus.Number)
                    {
                        plan.date_rang = dateRang;
                        plan.count = res.count.ToInt();
                    }
                    else
                    {
                        plan.date_rang = dateRang;
                    }
                    plan.status = (int)RowState.Valid;
                    plan.projectid = ProjectId;
                    //plan.instruction_mid = UserId.ToString();
                    plan.first_instruction_time = string.IsNullOrEmpty(res.first_instruction_time)
                        ? ""
                        : UnixTimeHelper.ConvertDataTimeLong(res.first_instruction_time.ToDateTime()).ToString();
                    var planId = _planItem.GetPlanIdMax();
                    if (planId >= 0)
                    {
                        planId = planId + 1;
                        plan.id = planId;
                        plan.itemid = itemId;
                        _plan.Insert(plan);
                    }
                    else
                    {
                        throw new BadRequestException(CommonEnum.Fail);
                    }
                    if (planId > 0)
                    {
                        //一直执行
                        var insertList = new List<siger_project_plan_time>();
                        if (dateRang == (int)DateRangStatus.Always)
                        {
                            for (var i = firstInstructionTime;
                                i <= (firstInstructionTime + 31536000);
                                i += (plan.instruction_cycle * 86400))
                            {
                                insertList.Add(new siger_project_plan_time
                                {
                                    projectid = ProjectId,
                                    status = (int)RowState.Valid,
                                    planid = planId,
                                    //instruction_mid = UserId,
                                    original_instruction_time = 0,
                                    information = (int)PlanStatus.UnExecuted,
                                    instruction_time = (int)i
                                });
                            }
                        }
                        else if (dateRang == (int)DateRangStatus.Custom)//按执行日期范围执行
                        {
                            if (starttime <= firstInstructionTime && firstInstructionTime <= endtime)
                            {
                                for (var i = firstInstructionTime;
                                    i <= endtime;
                                    i += (plan.instruction_cycle * 86400))
                                {
                                    insertList.Add(new siger_project_plan_time
                                    {
                                        projectid = ProjectId,
                                        status = (int)RowState.Valid,
                                        planid = planId,
                                        //instruction_mid = UserId,
                                        original_instruction_time = 0,
                                        information = (int)PlanStatus.UnExecuted,
                                        instruction_time = (int)i
                                    });
                                }
                            }
                        }
                        else if (dateRang == (int)DateRangStatus.Number)//按指定次数执行
                        {
                            if (res.count.ToInt() > 0)
                            {
                                for (var i = 0; i < res.count.ToInt(); i++)
                                {
                                    insertList.Add(new siger_project_plan_time
                                    {
                                        projectid = ProjectId,
                                        status = (int)RowState.Valid,
                                        planid = planId,
                                        //instruction_mid = UserId,
                                        original_instruction_time = 0,
                                        information = (int)PlanStatus.UnExecuted,
                                        instruction_time = (int)firstInstructionTime
                                    });
                                    firstInstructionTime += plan.instruction_cycle * 86400;
                                }
                            }
                        }
                        _planTime.Insert(insertList);
                        if (_unitOfWork.Commit() > 0)
                            return new ObjectResult(CommonEnum.Succefull);
                        throw new BadRequestException(CommonEnum.Fail);
                    }
                }
            }
            else
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditItem([FromBody]RequestEditPlan res)
        {
            var starttime = DateTime.TryParse(res.endtime, out DateTime _)
                ? (int)UnixTimeHelper.ConvertDataTimeLong(res.starttime.ToDateTime())
                : 0;
            var endtime = DateTime.TryParse(res.endtime, out DateTime _)
                ? (int)UnixTimeHelper.ConvertDataTimeLong(res.endtime.ToDateTime())
                : 0;
            var firsttime = DateTime.TryParse(res.first_instruction_time, out DateTime _)
                ? (int)UnixTimeHelper.ConvertDataTimeLong(res.first_instruction_time.ToDateTime())
                : 0;
            var firstInstructionTime = firsttime.ToString();
            var dateRang = res.date_rang.ToInt();
            var count = res.count;
            var baseModel = res.Base != null && res.Base.Any() ? res.Base[0] : new BaseModel();
            if (firsttime == 0)
            {
                throw new ServerException(1143);//时间错误
            }

            if (dateRang == (int)DateRangStatus.Custom && (starttime > firsttime || firsttime > endtime))
            {
                throw new BadRequestException(RequestEnum.PlanTimeError); //判断开始时间是否在时间范围之外
            }

            var ress = _plan.Get(
                t => t.id == res.planid && t.status > 0 && t.projectid == ProjectId);
            if (ress != null)
            {
                var cycle = ress.instruction_cycle;
                if (cycle == baseModel.instruction_cycle && firstInstructionTime == ress.first_instruction_time
                                                         && dateRang == ress.date_rang && starttime == ress.starttime &&
                                                         endtime == ress.endtime && count.ToInt() == ress.count)
                {
                    var planitem = _planItem.Get(t =>
                        t.id == ress.itemid && t.status > 0 && t.projectid == ProjectId);
                    if (planitem != null)
                    {
                        planitem.content = baseModel.content;
                        planitem.failure_mode = baseModel.failure_mode;
                        planitem.instruction_cycle = baseModel.instruction_cycle;
                        planitem.lower_limit = baseModel.lower_limit;
                        planitem.remark = baseModel.remark;
                        planitem.severity_level = baseModel.severity_level;
                        planitem.standard_time = baseModel.standard_time;
                        planitem.unit = baseModel.unit;
                        planitem.up_limit = baseModel.up_limit;
                        planitem.value_type = baseModel.value_type;
                        planitem.work_instruction_name = baseModel.work_instruction_name;
                        planitem.work_instruction_url = baseModel.work_instruction_url;
                        planitem.maintain_tool = baseModel.maintain_tool ?? "";
                        planitem.maintain_sparepart = baseModel.maintain_sparepart ?? "";
                        planitem.maintain_method = baseModel.maintain_method ?? "";
                        planitem.hit_item = baseModel.hit_item ?? "";
                        planitem.faulttype = res.mode;
                        _planItem.Update(planitem);
                    }

                    var plan = _plan.Get(t =>
                        t.id == res.planid && t.status > 0 && t.projectid == ProjectId);
                    if (plan != null)
                    {
                        plan.instruction_cycle = baseModel.instruction_cycle;
                        _plan.Update(plan);
                    }
                }
                else
                {
                    var time = UnixTimeHelper.GetTodayUnix();
                    //if (firsttime < time)
                    //{
                    //    firsttime = time + 84600;
                    //}

                    if (dateRang == (int)DateRangStatus.Always)
                    {
                        var plan = _plan.Get(t =>
                            t.id == res.planid && t.status > 0 && t.projectid == ProjectId);
                        if (plan != null)
                        {
                            plan.instruction_cycle = baseModel.instruction_cycle;
                            plan.first_instruction_time = res.typemode.ToInt() == 3 ? firstInstructionTime : plan.first_instruction_time;
                            plan.date_rang = dateRang;
                            plan.starttime = 0;
                            plan.endtime = 0;
                            plan.count = 0;
                            _plan.Update(plan);
                        }
                    }
                    else if (dateRang == (int)DateRangStatus.Custom)
                    {
                        var plan = _plan.Get(t =>
                            t.id == res.planid && t.status > 0 && t.projectid == ProjectId);
                        if (plan != null)
                        {
                            plan.instruction_cycle = baseModel.instruction_cycle;
                            plan.first_instruction_time = res.typemode.ToInt() == 3 ? firstInstructionTime : plan.first_instruction_time;
                            plan.date_rang = dateRang;
                            plan.starttime = starttime;
                            plan.endtime = endtime;
                            plan.count = 0;
                            _plan.Update(plan);
                        }
                    }
                    else if (dateRang == (int)DateRangStatus.Number)
                    {
                        var plan = _plan.Get(t =>
                            t.id == res.planid && t.status > 0 && t.projectid == ProjectId);
                        if (plan != null)
                        {
                            plan.instruction_cycle = baseModel.instruction_cycle;
                            plan.first_instruction_time = res.typemode.ToInt() == 3 ? firstInstructionTime : plan.first_instruction_time;
                            plan.date_rang = dateRang;
                            plan.starttime = 0;
                            plan.endtime = 0;
                            plan.count = count.ToInt();
                            _plan.Update(plan);
                        }
                    }

                    var planitem = _planItem.Get(t =>
                        t.id == ress.itemid && t.status > 0 && t.projectid == ProjectId);
                    if (planitem != null)
                    {
                        planitem.content = baseModel.content;
                        planitem.failure_mode = baseModel.failure_mode;
                        planitem.instruction_cycle = baseModel.instruction_cycle;
                        planitem.lower_limit = baseModel.lower_limit;
                        planitem.remark = baseModel.remark;
                        planitem.severity_level = baseModel.severity_level;
                        planitem.standard_time = baseModel.standard_time;
                        planitem.unit = baseModel.unit;
                        planitem.up_limit = baseModel.up_limit;
                        planitem.value_type = baseModel.value_type;
                        planitem.work_instruction_name = baseModel.work_instruction_name;
                        planitem.work_instruction_url = baseModel.work_instruction_url;
                        planitem.maintain_sparepart = baseModel.maintain_sparepart ?? "";
                        planitem.maintain_tool = baseModel.maintain_tool ?? "";
                        planitem.maintain_method = baseModel.maintain_method ?? "";
                        planitem.hit_item = baseModel.hit_item ?? "";
                        _planItem.Update(planitem);
                    }

                    var plantimes = _planTime.GetList(t =>
                        t.planid == res.planid && t.status == (int)RowState.Valid && t.projectid == ProjectId &&
                        t.information >= 2);
                    if (plantimes.Any())
                    {
                        foreach (var times in plantimes)
                        {
                            times.status = (int)RowState.Invalid;
                            _planTime.Update(times);
                        }
                    }
                    //一直执行
                    if (dateRang == (int)DateRangStatus.Always)
                    {
                        for (var i = firsttime; i <= (firsttime + 31536000); i += (ress.instruction_cycle * 86400))
                        {
                            _planTime.Insert(new siger_project_plan_time
                            {
                                projectid = ProjectId,
                                status = (int)RowState.Valid,
                                //instruction_mid = UserId,
                                instruction_time = i,
                                planid = res.planid,
                                information = (int)PlanStatus.UnExecuted
                            });
                        }
                    }
                    else if (dateRang == (int)DateRangStatus.Custom)//按执行日期范围执行
                    {
                        if (starttime <= firsttime && firsttime <= endtime)
                        {
                            for (var i = firsttime; i <= endtime; i += (baseModel.instruction_cycle * 86400))
                            {
                                _planTime.Insert(new siger_project_plan_time
                                {
                                    projectid = ProjectId,
                                    status = (int)RowState.Valid,
                                    //instruction_mid = UserId,
                                    instruction_time = i,
                                    planid = res.planid,
                                    information = (int)PlanStatus.UnExecuted
                                });
                            }
                        }
                    }
                    else if (dateRang == (int)DateRangStatus.Number)//按指定次数执行
                    {
                        if (count.ToInt() > 0)
                        {
                            for (var i = 0; i < count.ToInt(); i++)
                            {
                                _planTime.Insert(new siger_project_plan_time
                                {
                                    projectid = ProjectId,
                                    status = (int)RowState.Valid,
                                    //instruction_mid = UserId,
                                    instruction_time = firsttime,
                                    planid = res.planid,
                                    information = (int)PlanStatus.UnExecuted
                                });
                                firsttime += baseModel.instruction_cycle * 86400;
                            }
                        }
                    }
                }
                if (_unitOfWork.Commit() > 0)
                    return new ObjectResult(CommonEnum.Succefull);
                throw new BadRequestException(CommonEnum.Fail);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult AllPlanTime(string status = "1", int page = 1, int pagesize = 10)
        {
            var res = new List<GetListSearchPlan>();
            var topSection = _plan.GetTopLevelSection(ProjectId);
            if (topSection == null)
            {
                return new PagedObjectResult(res, 0, page, pagesize);
            }
            var machineIds = _machineRepository.GetLevelSectionMachineIds(topSection.id, ProjectId).ToList();
            if (!machineIds.Any())
            {
                return new PagedObjectResult(res, 0, page, pagesize);
            }

            var resdata =
                _plan.GetPagedlistsSearchPlan(machineIds, 0, 0, 0, 0, 0, 0, 0, 0, 0, status.ToInt(), ProjectId, page, pagesize, 0);
            if (resdata.Data.Any())
            {
                var locationHelper = new MachineLocationHelper(ProjectId, _plan);
                foreach (var p in resdata.Data)
                {
                    var levelsection = _plan.GetLevelSectionByMachineId(p.machineid, ProjectId);
                    p.stas = string.Join('-', locationHelper.GetPositionByMachineId(p.machineid));
                    p.station = levelsection == null ? "" : levelsection.title;
                    #region 参数赋值

                    if (p.instruction_cycle == 1)
                    {
                        p.instruction_cycle1 = "1101";// "";
                    }
                    else if (p.instruction_cycle == 7)
                    {
                        p.instruction_cycle1 = "1136";// "";
                    }
                    else if (p.instruction_cycle == 14)
                    {
                        p.instruction_cycle1 = "1137";// "";
                    }
                    else if (p.instruction_cycle == 30)
                    {
                        p.instruction_cycle1 = "1138";// "";
                    }
                    else if (p.instruction_cycle == 60)
                    {
                        p.instruction_cycle1 = "1139";// "";
                    }
                    else if (p.instruction_cycle == 90)
                    {
                        p.instruction_cycle1 = "1140";// "";
                    }
                    else if (p.instruction_cycle == 180)
                    {
                        p.instruction_cycle1 = "1141";// "";
                    }
                    else if (p.instruction_cycle == 365)
                    {
                        p.instruction_cycle1 = "1142";// "";
                    }

                    if (p.date_rang == (int)DateRangStatus.Always)
                    {
                        p.date_rang_str = "200151";// "";
                    }
                    else if (p.date_rang == (int)DateRangStatus.Custom)
                    {
                        var str = UnixTimeHelper.ConvertIntDate(p.starttime) + "/" +
                                  UnixTimeHelper.ConvertIntDate(p.endtime);
                        p.date_rang_str = str;//str + "执行";// "200162";
                    }
                    else if (p.date_rang == (int)DateRangStatus.Number)
                    {
                        p.date_rang_str = p.count.ToString();//"执行" + p.count + "次";//"200162"+p.count+ "200163";
                    }
                    else
                    {
                        p.date_rang_str = "-";
                    }

                    #endregion

                    res.Add(p);
                }
            }
            return new PagedObjectResult(res, resdata.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult EditPlanTime([FromBody]RequestAddPlanTime res)
        {
            var userids = string.Empty;
            if (res.instruction_mid != null && res.instruction_mid.Any())
            {
                userids = string.Join(',', res.instruction_mid);
            }

            foreach (var p in res.plannid)
            {
                var plan = _plan.Get(t =>
                    t.id == p && t.status > 0 && t.projectid == ProjectId);
                if (plan != null)
                {
                    plan.instruction_mid = userids.TrimStart(',');
                    _plan.Update(plan);
                    var ptimes = _planTime.GetList(t =>
                        t.planid == plan.id && t.information == (int)PlanStatus.UnExecuted &&
                        t.projectid == ProjectId && t.status == (int)RowState.Valid);
                    if (ptimes.Any())
                    {
                        foreach (var time in ptimes)
                        {
                            time.instruction_mid = (res.instruction_mid != null && res.instruction_mid.Any())
                                ? res.instruction_mid[0].ToInt()
                                : 0;
                            _planTime.Update(time);
                        }
                    }
                }
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetPlanTime(int planid)
        {
            var res = new List<GetListPlanStatus>();
            var nowtime = UnixTimeHelper.GetTodayUnix();
            var plan = _plan.Get(t => t.id == planid && t.status == (int)RowState.Valid && t.projectid == ProjectId);
            if (plan != null)
            {
                var result = _planTime.GetPlanTimeItem(0, nowtime, plan.id, ProjectId);
                res = result.Take(3).ToList();
            }
            return new ObjectResult(res);
        }

        [HttpPost]
        public IActionResult DeletePlantimes([FromBody] ReuqestDeletePlanTimes res)
        {
            var planid = res.planid;
            if (planid != null && planid.Any())
            {
                foreach (var p in planid)
                {
                    var times = _planTime.Get(t =>
                        t.id == p && t.status == (int)RowState.Valid && t.projectid == ProjectId);
                    if (times != null)
                    {
                        times.status = (int)RowState.Invalid;
                        _planTime.Update(times);
                    }
                }
                if (_unitOfWork.Commit() > 0)
                    return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// dateadjustment.html点击查询接口
        /// </summary>
        /// <param name="baseModel"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetlistthirdPlanItem([FromBody]listthirdPlanItem baseModel)
        {
            var valuePairs = new List<KeyValuePair<string, object>>();
            var resList = new List<GetListThirtyPlanItem>();
            int page = baseModel.page;
            int pagesize = baseModel.pagesize;
            int total = 0;
            if (baseModel != null)
            {
                var machineIdArr = baseModel.machineidarr;
                if (machineIdArr.Any())
                {
                    var startTime = string.IsNullOrEmpty(baseModel.stime)
                        ? UnixTimeHelper.GetTodayUnix() - 1
                        : UnixTimeHelper.ConvertDataTimeLong(baseModel.stime.ToDateTime());
                    var endTime = string.IsNullOrEmpty(baseModel.etime)
                        ? (startTime + 2592001)
                        : UnixTimeHelper.ConvertDataTimeLong(baseModel.etime.ToDateTime());

                    if (baseModel.person > 0)
                    {
                        baseModel.persons = new List<int> { baseModel.person };
                    }
                    else if (baseModel.department > 0)
                    {
                        baseModel.persons = _plan.GetUserIdsByDepartment(baseModel.department, ProjectId).ToList();
                    }
                    var bes = _planTime.GetPagedlistthirdPlanItem(baseModel, machineIdArr.ToList(), (int)startTime,
                        (int)endTime, ProjectId, page, pagesize, 2);
                    if (bes.Data != null && bes.Data.Any())
                    {
                        var locationHelper = new MachineLocationHelper(ProjectId, _plan);
                        var machineids = bes.Data.Select(q => q.machineid).Distinct().ToList();
                        var stations = locationHelper.GetPositionByMachineId(machineids);
                        foreach (var p in bes.Data)
                        {
                            if (!string.IsNullOrWhiteSpace(p.name))
                            {
                                var userids = p.name.Split(',').Select(q => q.ToInt()).ToList();
                                var users = _userRepository.GetList(q => userids.Contains(q.mid)).ToList();
                                p.name = string.Join(",", users.Select(q => q.name).ToList());
                            }
                            //p.name = user?.name ?? "";
                            var user = _plan.GetUserByMid(p.mid);
                            p.department = user?.sectionid ?? 0;
                            var station = stations.FirstOrDefault(q => q.id == p.machineid);
                            p.station = station == null ? "" : station.title;
                            p.instruction_time_str = UnixTimeHelper.ConvertIntDate(p.instruction_time);
                            resList.Add(p);
                        }
                        total = bes.Total;
                    }
                }
            }
            return new ThirdPlanItemResult()
            {
                page = page,
                pagesize = pagesize,
                data = resList,
                timemenu = valuePairs,
                total = total
            };
        }

        /// <summary>
        /// dateadjustment.html点击日历接口
        /// </summary>
        /// <param name="res"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetlistPlanItem([FromBody]listthirdPlanItem res)
        {
            int page = res.page;
            int pagesize = res.pagesize;
            var valuePairs = new List<KeyValuePair<string, object>>();
            var resList = new List<GetListThirtyPlanItem>();
            if (res == null)
            {
                throw new BadRequestException(RequestEnum.NoNull);
            }

            var baseModel = res;
            var machineIdArr = baseModel.machineidarr;
            var timenum = baseModel.timenum;
            var startTime = UnixTimeHelper.ConvertDataTimeLong(timenum.ToDateTime());
            var endTime = startTime + 86399;

            if (baseModel.person > 0)
            {
                baseModel.persons = new List<int> { baseModel.person };
            }
            else if (baseModel.department > 0)
            {
                baseModel.persons = _plan.GetUserIdsByDepartment(baseModel.department, ProjectId).ToList();
            }
            var bes = _planTime.GetPagedlistthirdPlanItem(baseModel, machineIdArr.ToList(), (int)startTime,
                (int)endTime, ProjectId, page, pagesize, 1);
            if (bes.Data != null && bes.Data.Any())
            {
                var locationHelper = new MachineLocationHelper(ProjectId, _plan);
                foreach (var p in bes.Data)
                {
                    var timeDict =
                        new KeyValuePair<string, object>(UnixTimeHelper.ConvertIntDate(p.instruction_time), "");
                    valuePairs.Add(timeDict);
                    p.station = string.Join('-', locationHelper.GetPositionByMachineId(p.machineid));
                    p.instruction_time_str = UnixTimeHelper.ConvertIntDate(p.instruction_time);
                    var user = _plan.GetUserByMid(p.mid);
                    p.name = user?.name ?? "";
                    p.department = user?.sectionid ?? 0;
                    resList.Add(p);
                }
            }
            return new ThirdPlanItemResult
            {
                page = page,
                pagesize = pagesize,
                data = resList,
                timemenu = valuePairs,
                total = bes.Total
            };
        }

        [HttpGet]
        public IActionResult GetlistthirdPlanItemfirst(int page, int pagesize)
        {
            var valuePairs = new List<KeyValuePair<string, object>>();
            var resList = new List<GetListThirtyPlanItem>();
            var startTime = UnixTimeHelper.GetTodayUnix();
            var endTime = startTime + 2592000;
            var baseModel = new listthirdPlanItem();
            var bes = _planTime.GetPagedlistthirdPlanItem(baseModel, null, startTime, endTime, ProjectId, page,
                pagesize, 2);
            if (bes.Data != null && bes.Data.Any())
            {
                var locationHelper = new MachineLocationHelper(ProjectId, _plan);
                foreach (var p in bes.Data)
                {
                    var user = _plan.GetUserByMid(p.mid);
                    p.name = user?.name ?? "";
                    p.department = user?.sectionid ?? 0;
                    p.station = string.Join('-', locationHelper.GetPositionByMachineId(p.machineid));
                    resList.Add(p);
                }
            }
            return new ThirdPlanItemResult
            {
                page = page,
                pagesize = pagesize,
                data = resList,
                timemenu = valuePairs
            };
        }

        [HttpPost]
        public IActionResult EditPlansTime([FromBody] RequestlistthirdPlanItem res)
        {
            var ptimeid = res.ptimeid;
            var baseModel = res;
            var instructionTime = UnixTimeHelper.ConvertDataTimeLong(baseModel.instruction_time.ToDateTime());
            var time = UnixTimeHelper.GetTodayUnix();
            if (instructionTime < time)
            {
                throw new BadRequestException(RequestEnum.DateInvalid);
            }
            var instructionMid = !string.IsNullOrEmpty(baseModel.instruction_mid) ? baseModel.instruction_mid : "";
            if (ptimeid != null && ptimeid.Any())
            {
                var times = _planTime.GetList(t =>
                    ptimeid.Select(q => q.ToInt()).Contains(t.id) && t.status == (int)RowState.Valid &&
                    t.projectid == ProjectId).ToList();
                foreach (var id in ptimeid)
                {
                    var ress = times.FirstOrDefault(t => t.id == id.ToInt());
                    if (ress != null)
                    {
                        var next = _planTime.GetList(f => f.id > ress.id && f.planid == ress.planid, "id", false).FirstOrDefault();
                        if (next != null && next.instruction_time < (int)instructionTime)
                        {
                            throw new BadRequestException(TpmEnum.PlanTimeError);
                        }
                        ress.instruction_mid = instructionMid.ToInt();
                        ress.instruction_time = (int)instructionTime;
                        ress.information = (int)PlanStatus.UnExecuted;
                        _planTime.Update(ress);
                    }
                }
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult exportAll(int sectionid, int modeType, int value_type, int severity_level,
            int instruction_cycle, int datetype, int department, int person,
            int gt, int lt, string status, int state, int creator)
        {
           
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var machineIds = _machineRepository.GetAttributionMachineIds(sectionid, ProjectId);
            if (!machineIds.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var resdata = _plan.GetPagedlistsSearchPlan(machineIds, modeType, value_type, severity_level,
                instruction_cycle, datetype, department, person, gt, lt, status.ToInt(), ProjectId, 1, 99999, state, creator).Data;
            var res = new List<LevelPlanListForExport>();
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var translateHelper = new TranslateHelper(_plan.GetProjectLanguage(ProjectId) == (int)LanguageType.EN);
            foreach (var p in resdata)
            {
                var machine = _machineRepository.Get(p.machineid);
                if (machine == null)
                {
                    continue;
                }
                var stationposition = locationHelper.GetPositionByMachineId(p.machineid);
                p.stas = machine.title;
                p.station = string.Join('-', stationposition);

                #region 参数赋值

                if (p.instruction_cycle == 1)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Days);// "1101";
                }
                else if (p.instruction_cycle == 7)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Week);// "1136";
                }
                else if (p.instruction_cycle == 14)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.TwoWeeks);// "1137";
                }
                else if (p.instruction_cycle == 30)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Mouth);// "1138";
                }
                else if (p.instruction_cycle == 60)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.TwoMouths);// "1139";
                }
                else if (p.instruction_cycle == 90)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Quarter);// "1140";
                }
                else if (p.instruction_cycle == 180)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Halfayear);// "1141";
                }
                else if (p.instruction_cycle == 365)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Year);// "1142";
                }

                if (p.date_rang == (int)DateRangStatus.Always)
                {
                    p.date_rang_str = translateHelper.GetTranslateText(TranslateCnEnum.Executeallthetime);// 200151;
                }
                else if (p.date_rang == (int)DateRangStatus.Custom)
                {
                    var str = UnixTimeHelper.ConvertIntDate(p.starttime) == string.Empty
                        ? UnixTimeHelper.ConvertIntDate(p.endtime)
                        : (UnixTimeHelper.ConvertIntDate(p.starttime) + "/" + UnixTimeHelper.ConvertIntDate(p.endtime));
                    p.date_rang_str = str + translateHelper.GetTranslateText(TranslateCnEnum.Implementation);// "";
                }
                else if (p.date_rang == (int)DateRangStatus.Number)
                {
                    p.date_rang_str = translateHelper.GetTranslateText(TranslateCnEnum.Implementation) + p.count +
                                      translateHelper.GetTranslateText(TranslateCnEnum
                                          .Time); //"200162"+p.count+ "200163";
                }
                else
                {
                    p.date_rang_str = "-";
                }

                #endregion

                stationposition.Reverse();

                var name = "";
                if (!string.IsNullOrEmpty(p.instruction_mid_str))
                {
                    var mids = p.instruction_mid_str.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    if (mids.Any())
                    {
                        var nameArr = new List<string>();
                        foreach (var mid in mids)
                        {
                            var usermodel = _userRepository.Get(t => t.mid == mid.ToInt() && t.status == (int)RowState.Valid);
                            if (usermodel != null)
                            {
                                nameArr.Add(usermodel.name);
                            }
                        }
                        name = string.Join(',', nameArr.ToArray());
                    }
                }
                var states = string.Empty;
                if (p.state == 1)
                {
                    states = "已完成";
                }
                else if (p.state == 2)
                {
                    states = "待执行";
                }
                else if (p.state == 3)
                {
                    states = "逾期";
                }
                else if (p.state == 4)
                {
                    states = "执行中";
                }
                res.Add(new LevelPlanListForExport
                {
                    Location = p.station,
                    machine = machine.title,
                    content = p.content,
                    mode = p.mode == 1 ? "AM" : (p.mode == 2 ? "PM" : "CMP"),
                    value_type = p.value_type == 1 ? "勾选确定型" : "数值记录型",
                    unit = p.unit,
                    up_limit = p.value_type == 1 ? "" : p.up_limit,
                    lower_limit = p.value_type == 1 ? "" : p.lower_limit,
                    severity_level = GetCategory(p.severity_level),
                    failure_mode = p.failure_mode,
                    standard_time = p.standard_time,
                    date_rang = p.date_rang_str,
                    instruction_time = p.date_rang_str,
                    instruction_cycle = p.instruction_cycle1,
                    first_instruction_time = p.first_instruction_time,
                    remark = p.remark,
                    name = name,
                    actualtime = p.actual_standard_time,
                    work_order = "P" + p.id.ToStr(),
                    state = states
                });
            }

            if (res.Any())
            {
                EpPlusExcelHelper<LevelPlanListForExport> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<LevelPlanListForExport>();
                    var temporaryFileName = $"MaintenanceResult_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(res, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExportPlanRepair failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult exportAllSkf(int sectionid, int modeType, int value_type, int severity_level, int instruction_cycle, int datetype, int department, int person,
            int gt, int lt)
        {
            
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var machineIds = _machineRepository.GetLevelSectionMachineIds(sectionid, ProjectId);
            var resdata = _plan.GetlistsSearchPlan(machineIds, modeType, value_type, severity_level, instruction_cycle,
                datetype, department, person, gt, lt, ProjectId);

            var res = new List<LevelPlanListSkf>();
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var translateHelper = new TranslateHelper(_plan.GetProjectLanguage(ProjectId) == (int)LanguageType.EN);
            foreach (var p in resdata)
            {
                var machine = _machineRepository.Get(p.machineid);
                if (machine == null)
                {
                    continue;
                }
                var stationposition = locationHelper.GetPositionByMachineId(p.machineid);
                p.stas = machine.title;
                p.station = string.Join('-', stationposition);

                #region 参数赋值

                if (p.instruction_cycle == 1)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Days);// "1101";
                }
                else if (p.instruction_cycle == 7)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Week);// "1136";
                }
                else if (p.instruction_cycle == 14)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.TwoWeeks);// "1137";
                }
                else if (p.instruction_cycle == 30)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Mouth);// "1138";
                }
                else if (p.instruction_cycle == 60)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.TwoMouths);// "1139";
                }
                else if (p.instruction_cycle == 90)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Quarter);// "1140";
                }
                else if (p.instruction_cycle == 180)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Halfayear);// "1141";
                }
                else if (p.instruction_cycle == 365)
                {
                    p.instruction_cycle1 = translateHelper.GetTranslateText(TranslateCnEnum.Year);// "1142";
                }

                if (p.date_rang == (int)DateRangStatus.Always)
                {
                    p.date_rang_str = translateHelper.GetTranslateText(TranslateCnEnum.Executeallthetime);// 200151;
                }
                else if (p.date_rang == (int)DateRangStatus.Custom)
                {
                    var str = UnixTimeHelper.ConvertIntDate(p.starttime) + "/" +
                              UnixTimeHelper.ConvertIntDate(p.endtime);
                    p.date_rang_str = str + translateHelper.GetTranslateText(TranslateCnEnum.Implementation);// "";
                }
                else if (p.date_rang == (int)DateRangStatus.Number)
                {
                    p.date_rang_str = translateHelper.GetTranslateText(TranslateCnEnum.Implementation) + p.count +
                                      translateHelper.GetTranslateText(TranslateCnEnum
                                          .Time); //"200162"+p.count+ "200163";
                }
                else
                {
                    p.date_rang_str = "-";
                }

                #endregion

                stationposition.Reverse();

                var name = "";
                if (!string.IsNullOrEmpty(p.instruction_mid_str))
                {
                    var mids = p.instruction_mid_str.Split(',', StringSplitOptions.RemoveEmptyEntries);
                    if (mids.Any())
                    {
                        var nameArr = new List<string>();
                        foreach (var mid in mids)
                        {
                            var usermodel = _userRepository.Get(t => t.mid == mid.ToInt() && t.status == (int)RowState.Valid);
                            if (usermodel != null)
                            {
                                nameArr.Add(usermodel.name);
                            }
                        }
                        name = string.Join(',', nameArr.ToArray());
                    }
                }

                res.Add(new LevelPlanListSkf
                {
                    machine = machine.id,
                    content = p.content,
                    mode = p.mode,
                    value_type = p.value_type,
                    unit = p.unit,
                    up_limit = p.up_limit,
                    lower_limit = p.lower_limit,
                    severity_level = p.severity_level,
                    standard_time = p.standard_time,
                    date_rang = p.date_rang,
                    instruction_time = p.date_rang_str,
                    instruction_cycle = p.instruction_cycle,
                    first_instruction_time = p.first_instruction_time,
                    remark = p.remark,
                    name = name,
                });
            }

            if (res.Any())
            {
                EpPlusExcelHelper<LevelPlanListSkf> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<LevelPlanListSkf>();
                    var temporaryFileName = $"计划维护_PlanRepair_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(res, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("ExportPlanRepair failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult SearchStatistical([FromBody]RequestSearchStatistical res)
        {
            var stime = res.start_time.ToDateTime();
            var etime = res.end_time.ToDateTime();
            int starttime = (int)UnixTimeHelper.ConvertDataTimeLong(stime);
            int endtime = (int)UnixTimeHelper.ConvertDataTimeLong(etime);
            var start_month_date = stime.ToString(ParameterConstant.YearMonthFormat);
            var end_month_date = etime.ToString(ParameterConstant.YearMonthFormat);
            var res2 = _planTime.SearchPlanDay(res.mode, starttime, endtime, res.machineidarr.ToList(), ProjectId)
                .ToList();
            var x_data1 = new List<string>();
            var y_data1 = new List<int>();
            var y_data2 = new List<int>();
            var y_data3 = new List<string>();
            var result = new SearchStatisticalResult();
            var data = new SearchStatistical();
            if (res.Xtype.ToInt() == 1)
            {
                switch (res.x_id.ToLower())
                {
                    case "a":
                        res.x_id = "0";
                        break;
                    case "b":
                        res.x_id = "1";
                        break;
                    case "c":
                        res.x_id = "2";
                        break;
                    default:
                        res.x_id = "0";
                        break;
                }
                var xid = res.x_id.ToInt();
                var interal = DateTimeHelper.GetInteral(xid);
                var dates = DateTimeHelper.GetDateTimes(stime, etime, xid);
                var datas = new List<StatisticalModel>();
                for (var i = 0; i < dates.Count; i++)
                {
                    int start;
                    int end;
                    if (xid == 0 || xid == 1)
                    {
                        start = (int)UnixTimeHelper.ConvertDataTimeLong(dates[i]);
                        end = (int)UnixTimeHelper.ConvertDataTimeLong(dates[i].AddDays(interal).AddSeconds(-1));
                        var temp = res2.Where(f => f.instruction_time >= start && f.instruction_time <= end).ToList();
                        datas.Add(new StatisticalModel { tim = dates[i].ToString(ParameterConstant.DateFormat), les = temp.Count(t => t.information == (int)PlanStatus.Normal), total = temp.Count() });
                    }
                    else
                    {
                        start = (int)UnixTimeHelper.ConvertDataTimeLong(dates[i].AddDays(1 - dates[i].Day));
                        end = (int)UnixTimeHelper.ConvertDataTimeLong(dates[i].AddDays(1 - dates[i].Day).Date.AddMonths(1).AddSeconds(-1)); //到月底
                        var temp = res2.Where(f => f.instruction_time >= start && f.instruction_time <= end).ToList();
                        datas.Add(new StatisticalModel { tim = dates[i].ToString("yyyy-MM"), les = temp.Count(t => t.information == (int)PlanStatus.Normal), total = temp.Count() });
                    }
                }
                result.datas = datas;
            }
            else
            {
                var sectiondata = _levelSectionRepository.Get(f => f.id == res.sectionId);
                var levels = _levelSectionRepository.GetSectionFamilyList(res.sectionId, ProjectId);
                levels.Add(sectiondata);
                var datas = new List<StatisticalModel>();
                if (levels.Any())
                {
                    levels = levels.Where(f => f != null && f.levelid == res.x_id.ToInt()).ToList();
                    foreach (var level in levels)
                    {
                        var mids = _machineRepository.GetAttributionMachineList(new List<int> { level.id }, ProjectId, new List<int> { 1 }).Select(s => s.id);
                        var temp = res2.Where(f => mids.Contains(f.machineid)).ToList();
                        if (temp.Any())
                        {
                            datas.Add(new StatisticalModel { tim = level.title, les = temp.Count(t => t.information == (int)PlanStatus.Normal), total = temp.Count() });
                        }
                        else
                        {
                            datas.Add(new StatisticalModel { tim = level.title, les = 0, total = 0 });
                        }
                    }

                }
                result.datas = datas;
            }
            if (result.datas.Any())
            {
                result.data.x = result.datas.Select(s => s.tim).ToList();
                result.data.y1 = result.datas.Select(s => s.les).ToList();
                result.data.y2 = result.datas.Select(s => s.total).ToList();
            }
            return result;
        }

        [HttpGet]
        public IActionResult GetTemplate()
        {
            

            return new ObjectResult(CreateLevelPlanTemplate());
        }

        private string CreateLevelPlanTemplate()
        {
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                throw new BadRequestException(CommonEnum.GetCommCfgFailed);
            }
            var columnNames = new List<string>();
            var titles = _levelRepository.GetLevelTitles(0, ProjectId);
            columnNames.AddRange(titles);

            var helper = new EpPlusForTpmHelper();
            columnNames.AddRange(helper.GetTemplateColumns(typeof(LevelPlanList), _plan.GetProjectLanguage(ProjectId)));
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var temporaryFileName = $"LevelPlanTemplate_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            helper.GenerateExcel(columnNames, fileName);
            
            return $"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}";
        }

        [HttpGet]
        public IActionResult GetTemplateSkf()
        {
            var fileSetting = Config<FileSettings>.Get();
            if (fileSetting == null)
            {
                throw new BadRequestException(CommonEnum.GetCommCfgFailed);
            }
            var rootDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileSetting.FileSetting.PhysicalFolder);
            if (!Directory.Exists(rootDir))
            {
                throw new BadRequestException(ConfigEnum.DirectoryNotFound);
            }

            return new ObjectResult(CreateLevelPlanTemplateSkf());
        }

        private string CreateLevelPlanTemplateSkf()
        {
            
            var columnNames = new List<string>();
            //var titles = _levelRepository.GetLevelTitles(0, ProjectId);
            //columnNames.AddRange(titles);

            var helper = new EpPlusForTpmHelper();
            columnNames.AddRange(helper.GetTemplateColumns(typeof(LevelPlanListSkf), _plan.GetProjectLanguage(ProjectId)));
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var temporaryFileName = $"LevelPlanTemplate_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            helper.GenerateExcel(columnNames, fileName);
            
            return $"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}";
        }

        /// <summary>
        /// 启用禁用计划维护 1启用 2禁用
        /// </summary>
        /// <param name="planid"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PlanSwitch(int planid, int status)
        {
            var plan = _plan.Get(t => t.id == planid && t.projectid == ProjectId && t.status > 0);
            if (plan == null)
            {
                throw new BadRequestException(RequestEnum.RecordNull);
            }

            if (plan.status == status)
            {
                throw new BadRequestException(RequestEnum.InputValueError);
            }

            if (status == 2)
            {
                var item = _planItem.Get(t => t.id == plan.itemid && t.projectid == ProjectId && t.status > 0);
                var planTimes = _planTime.GetList(t => t.planid == planid && t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
                var timeIds = planTimes.Select(t => t.id).ToList();
                var records = _planRecord.GetList(t => timeIds.Contains(t.plan_time_id) && t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
                var recordTimeIds = records.Select(t => t.plan_time_id).ToList();
                if (item != null)
                {
                    item.status = status;
                    _planItem.Update(item);
                }
                plan.status = status;
                _plan.Update(plan);
                foreach (var time in planTimes)
                {
                    if (recordTimeIds.Contains(time.id))
                    {
                        time.status = status;
                    }
                    else
                    {
                        time.status = (int)RowState.Invalid;
                    }
                    _planTime.Update(time);
                }
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }
            else if (status == 1)
            {
                var item = _planItem.Get(t => t.id == plan.itemid && t.projectid == ProjectId && t.status > 0);
                var planTimes = _planTime.GetList(t => t.planid == planid && t.projectid == ProjectId && t.status == 2).ToList();

                var date = UnixTimeHelper.GetTodayUnix();
                var addTime = date - plan.first_instruction_time.ToInt();
                plan.first_instruction_time = date.ToString();
                if (plan.date_rang == (int)DateRangStatus.Custom)
                {
                    plan.starttime = plan.starttime + addTime;
                    plan.endtime = plan.endtime + addTime;
                }

                if (item != null)
                {
                    item.status = (int)RowState.Valid;
                    _planItem.Update(item);
                }
                plan.status = (int)RowState.Valid;
                _plan.Update(plan);
                if (planTimes.Any())
                {
                    var users = plan.instruction_mid.Split(',', StringSplitOptions.RemoveEmptyEntries).ToList();
                    var instruction_mid = users.Any() ? users.First().ToInt() : 0;
                    var insertList = new List<siger_project_plan_time>();
                    if (plan.date_rang == (int)DateRangStatus.Always)
                    {
                        for (var i = date; i <= (date + 31536000); i += (plan.instruction_cycle * 86400))
                        {
                            insertList.Add(new siger_project_plan_time
                            {
                                projectid = ProjectId,
                                status = (int)RowState.Valid,
                                planid = plan.id,
                                instruction_mid = instruction_mid,
                                original_instruction_time = 0,
                                information = (int)PlanStatus.UnExecuted,
                                instruction_time = (int)i
                            });
                        }
                    }
                    else if (plan.date_rang == (int)DateRangStatus.Custom)//按执行日期范围执行
                    {
                        if (plan.starttime <= date && date <= plan.endtime)
                        {
                            for (var i = date; i <= plan.endtime; i += (plan.instruction_cycle * 86400))
                            {
                                insertList.Add(new siger_project_plan_time
                                {
                                    projectid = ProjectId,
                                    status = (int)RowState.Valid,
                                    planid = plan.id,
                                    instruction_mid = instruction_mid,
                                    original_instruction_time = 0,
                                    information = (int)PlanStatus.UnExecuted,
                                    instruction_time = (int)i
                                });
                            }
                        }
                    }
                    else if (plan.date_rang == (int)DateRangStatus.Number)//按指定次数执行
                    {
                        if (plan.count > 0)
                        {
                            for (var i = 0; i < plan.count; i++)
                            {
                                insertList.Add(new siger_project_plan_time
                                {
                                    projectid = ProjectId,
                                    status = (int)RowState.Valid,
                                    planid = plan.id,
                                    instruction_mid = instruction_mid,
                                    original_instruction_time = 0,
                                    information = (int)PlanStatus.UnExecuted,
                                    instruction_time = date
                                });
                                date += plan.instruction_cycle * 86400;
                            }
                        }
                    }
                    _planTime.Insert(insertList);
                }
                if (_unitOfWork.Commit() > 0)
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }
            else
            {
                throw new BadRequestException(RequestEnum.InputValueError);
            }
        }



        /// <summary>
        /// 维护日历
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetCalendar([FromBody]RequestPlanCalendar req)
        {
            var pid = ProjectId;
            var ret = new List<ResponsePlanCalendar>();
            //获取当前月份的第一天
            var strDate = $"{req.time} 00:00:00";
            var nowDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
            DateTime.TryParse(strDate, out nowDate);
            //当月天数
            var days = DateTime.DaysInMonth(nowDate.Year, nowDate.Month);
            //当月第一天为周几
            var firstday = nowDate.DayOfWeek == 0 ? 7 : (int)nowDate.DayOfWeek;
            //当月最后一天为周几
            var lastday = nowDate.AddDays(days).AddSeconds(-1).DayOfWeek == 0 ? 7 : (int)(nowDate.AddDays(days).AddSeconds(-1)).DayOfWeek;
            //起始时间
            var startDay = nowDate.AddDays(1 - firstday);
            var endDay = nowDate.AddDays(days).AddSeconds(-1).Date.AddDays(7 - lastday);
            //时间列表
            var dateList = new List<DateTime>();
            while (startDay <= endDay)
            {
                dateList.Add(startDay);
                startDay = startDay.AddDays(1);
            }
            //拼接返回数据
            var unixstart = UnixTimeHelper.ConvertDataTimeLong(nowDate);
            var unixend = UnixTimeHelper.ConvertDataTimeLong(nowDate.AddMonths(1).AddSeconds(-1));
            var machineids = _machineRepository.GetAttributionMachineList(req.sectionid, pid, new List<int> { 1 }).Select(s => s.id);
            var planTimeData = _planTime.GetPlanInfoByTime((int)unixstart, (int)unixend, pid).Where(q => machineids.Contains(q.machineid));
            var machines = _machineRepository.GetMachineStationInfos(machineids, pid);
            foreach (var machine in machines)
            {
                var machineData = new ResponsePlanCalendar { machineid = machine.machineId, location = $"{machine.section_name}-{machine.station_name}-{machine.machine_name}" };
                var num = 1;
                foreach (var date in dateList)
                {
                    var time = (int)UnixTimeHelper.ConvertDataTimeLong(date);
                    var status = planTimeData.Where(f => f.machineid == machine.machineId && f.instruction_time >= time && f.instruction_time < time + 86400)
                        .OrderByDescending(q => q.time_status).FirstOrDefault()?.time_status ?? 0;
                    machineData.data.Add(new ResponseStatusList { date = date, num = num, status = status });
                    num++;
                }
                ret.Add(machineData);
            }
            return new ObjectResult(ret);
        }
        /// <summary>
        /// 获取某天某设备的全部计划
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetCalendarItem([FromBody]RequestPlanCalendarMachine req)
        {
            var pid = ProjectId;
            var ret = new List<ResponsePlanMachineItem>();
            if (!DateTime.TryParse(req.time, out var nowDate))
            {
                throw new BadRequestException(TpmEnum.TimeError);
            }
            var unixstart = UnixTimeHelper.ConvertDataTimeLong(nowDate);
            var unixend = UnixTimeHelper.ConvertDataTimeLong(nowDate.AddDays(1).AddSeconds(-1));
            var planTimeData = _planTime.GetPlanInfoByTime((int)unixstart, (int)unixend, pid).Where(f => f.machineid.Equals(req.machine));
            foreach (var item in planTimeData)
            {
                var plan = new ResponsePlanMachineItem
                {
                    id = item.id,
                    startTime = nowDate.ToString(ParameterConstant.DateFormat),
                    status = item.time_status
                };
                var itemData = _planItem.GetList(f => f.status == (int)RowState.Valid && f.projectid.Equals(pid) && f.id.Equals(item.itemid), "id");
                foreach (var da in itemData)
                {
                    plan.data.Add(new ResponsePlanMachineItemEx
                    {
                        item = da.content,
                        costTime = da.standard_time
                    });
                }
                ret.Add(plan);
            }
            return new ObjectResult(ret);
        }

        /// <summary>
        /// 更改设备的全部计划
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult ModifyCalendarItem([FromBody]RequestUpdateCalendarItem req)
        {
            if (req.items == null || !req.items.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            var pid = ProjectId;
            foreach (var item in req.items)
            {
                var model = _planTime.Get(f => f.status == (int)RowState.Valid && f.projectid.Equals(pid) && f.id.Equals(item.id));
                if (model == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }
                var today = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
                if (!DateTime.TryParse(item.time, out var nowDate))
                {
                    throw new BadRequestException(TpmEnum.TimeError);
                }
                if (today > nowDate)
                {
                    throw new BadRequestException(TpmEnum.CanNotUseThisTime);
                }
                //不能调整到下一次执行日期之后
                var nextTime = _planTime.GetList(q =>
                        q.planid == model.planid && q.projectid == pid && q.status == (int)RowState.Valid
                        && q.instruction_time > model.instruction_time)
                    .OrderBy(q => q.instruction_time).FirstOrDefault();
                if (nextTime != null && nextTime.instruction_time <= (int)UnixTimeHelper.ConvertDataTimeLong(nowDate))
                {
                    throw new BadRequestException(TpmEnum.CannotChangeToThisTime);
                }
                model.editor = UserId;
                model.edit_time = UnixTimeHelper.GetNow();
                model.original_instruction_time = model.instruction_time;
                model.instruction_time = (int)UnixTimeHelper.ConvertDataTimeLong(nowDate);
                _planTime.Update(model);
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }
        /// <summary>
        /// 获取修改记录
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetCalendarChanged([FromBody]RequestPlanCalendar req)
        {
            var ret = new List<ResponsePlanMachineChanged>();
            var pid = ProjectId;
            var strDate = $"{req.time} 00:00:00";
            if (!DateTime.TryParse(strDate, out var nowDate))
            {
                throw new BadRequestException(TpmEnum.TimeError);
            }
            var unixstart = UnixTimeHelper.ConvertDataTimeLong(nowDate);
            var days = DateTime.DaysInMonth(nowDate.Year, nowDate.Month);
            var unixend = UnixTimeHelper.ConvertDataTimeLong(nowDate.AddDays(days).AddSeconds(-1));
            var machineids = _machineRepository.GetAttributionMachineIds(req.sectionid, pid);
            var plan = _planTime.GetCalendarChanged(machineids, (int)unixstart, (int)unixend, pid, req.page, req.pagesize);
            return new PagedObjectResult(plan.Data, plan.Total);
        }

        [HttpGet]
        public IActionResult GetSelectedtolerance(int mode)
        {
            var selectRes = _planReportTolerance.GetList(t => t.status == (int)RowState.Valid && t.projectid == ProjectId && t.mode == mode).ToList();
            if (selectRes.Any())
            {
                foreach (var item in selectRes)
                {
                    item.type = GetCycleByType(item.type);
                }
                return new SelectedTimeResult()
                {
                    ret = 1,
                    msg = "1",
                    data = selectRes,
                };
            }

            throw new BadRequestException(CommonEnum.NoData);
        }

        [HttpPost]
        public IActionResult Edittolerance([FromBody]RequestPlanSetTime res)
        {
            if (res.data == null)
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }

            foreach (var p in res.data)
            {
                var reports = _planReportTolerance.Get(t =>
                    t.mode == p.mode &&
                    t.type == GetTypeByCycle(p.type)
                    && t.projectid == ProjectId && t.status == (int)RowState.Valid);
                if (reports != null)
                {
                    reports.space_time = p.space_time;
                    _planReportTolerance.Update(reports);
                }
                else
                {
                    _planReportTolerance.Insert(new siger_project_plan_report_tolerance
                    {
                        space_time = p.space_time,
                        create_mid = UserId,
                        create_time = UnixTimeHelper.GetNow(),
                        mode = p.mode,
                        type = GetTypeByCycle(p.type),
                        projectid = ProjectId
                    });
                }
            }

            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult ExportCalendarItem(string date, int type)
        {
            var resList = new List<PlanCalendarItem>();
            var startTime = (int)UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime());
            var endTime = 0;
            if (type == 1)
            {
                endTime = (int)UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime().AddYears(1).AddMilliseconds(-1));
            }
            else
            {
                endTime = (int)UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime().AddMonths(1).AddMilliseconds(-1));
            }

            var machineids = _machineRepository.GetAttributionMachineList(0, ProjectId, new List<int> { 1 })
                .Select(s => s.id);
            var datas = _planTime.GetPlanItems(machineids, startTime, endTime, ProjectId);
            if (!datas.Any())
            {
                throw new BadRequestException(CommonEnum.NoData);
            }

            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var stations = locationHelper.GetPositionByMachineId(machineids);
            var planTimeData = _planTime.GetPlanInfoByTime(startTime, endTime, ProjectId).Where(q => machineids.Contains(q.machineid));
            foreach (var p in datas)
            {
                var user = _plan.GetUserByMid(p.mid);
                var station = stations.FirstOrDefault(q => q.id == p.machineid);
                p.station = station == null ? "" : station.title;
                p.instruction_time_str = UnixTimeHelper.ConvertIntDate(p.instruction_time);
                var status = planTimeData
                              .Where(f => f.machineid == p.machineid && f.instruction_time >= startTime && f.instruction_time < startTime + 86400)
                                 .OrderByDescending(q => q.time_status).FirstOrDefault()
                              ?.time_status ?? 0;
                var item = new PlanCalendarItem
                {
                    Location = p.station,
                    content = p.content,
                    mode = p.mode == 1 ? "AM" : (p.mode == 2 ? "PM" : "CMP"),
                    severity_level = GetCategory(p.severity_level),
                    standard_time = p.standard_time,
                    name = user?.name ?? "",
                    time = p.utime,
                    status = status == (int)PlanStatus.Overdue ? "逾期" : (status == (int)PlanStatus.UnExecuted ? "未执行" : "正常")
                };
                resList.Add(item);
            }

            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            EpPlusExcelHelper<PlanCalendarItem> helper = null;
            try
            {
                helper = new EpPlusExcelHelper<PlanCalendarItem>();
                var temporaryFileName = $"Calendar_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                helper.GenerateExcel(resList, Path.Combine(rootDir, temporaryFileName));
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportPlanRepair failed, error:" + e);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper?.Dispose();
            }
        }

        [HttpGet]
        public IActionResult GetYearPlan(string date, int type)
        {
            var start = (int)UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime());
            var end = 0;
            if (type == 1)
            {
                end = (int)UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime().AddYears(1).AddMilliseconds(-1));
            }
            else
            {
                end = (int)UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime().AddMonths(1).AddMilliseconds(-1));
            }
            var responses = new List<ResponseGetYearPlan>();
            var planTimeData = _planTime.GetPlanInfoByTime(start, end, ProjectId);

            for (var dt = start; dt <= end; dt += 86400)
            {
                var plans = planTimeData.Where(f => f.instruction_time >= dt && f.instruction_time < dt + 86400);
                var response = new ResponseGetYearPlan
                {
                    date = UnixTimeHelper.ConvertIntDate(dt),
                    plancount = plans.Count()
                };
                responses.Add(response);
            }

            return new ObjectResult(responses);
        }

        /// <summary>
        /// 获取某天全部计划
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDayCalendarItem(string date)
        {
            var pid = ProjectId;
            var resList = new List<GetListThirtyPlanItem>();
            var unixstart = UnixTimeHelper.ConvertDataTimeLong(date);
            var unixend = UnixTimeHelper.ConvertDataTimeLong(date.ToDateTime().AddDays(1).AddSeconds(-1));
            var machineids = _machineRepository.GetAttributionMachineList(0, ProjectId, new List<int> { 1 }).Select(m => m.id);
            var locationHelper = new MachineLocationHelper(ProjectId, _plan);
            var stations = locationHelper.GetPositionByMachineId(machineids);
            var planTimeData = _planTime.GetDayPlanItem((int)unixstart, (int)unixend, pid);
            foreach (var item in planTimeData)
            {
                if (!string.IsNullOrWhiteSpace(item.name))
                {
                    var userids = item.name.Split(',').Select(q => q.ToInt()).ToList();
                    var users = _userRepository.GetList(q => userids.Contains(q.mid)).ToList();
                    item.name = string.Join(",", users.Select(q => q.name).ToList());
                }

                var station = stations.FirstOrDefault(q => q.id == item.machineid);
                item.station = station == null ? "" : station.title;
                item.instruction_time_str = UnixTimeHelper.ConvertIntDate(item.instruction_time);
                resList.Add(item);
            }

            return new ObjectResult(resList);
        }

        private int GetTypeByCycle(int days)
        {
            switch (days)
            {
                case 1:
                    return 1;
                case 2:
                    return 7;
                case 3:
                    return 14;
                case 4:
                    return 30;
                case 5:
                    return 60;
                case 6:
                    return 90;
                case 7:
                    return 180;
                case 8:
                    return 365;
                default:
                    return 0;
            }
        }

        private int GetCycleByType(int days)
        {
            switch (days)
            {
                case 1:
                    return 1;
                case 7:
                    return 2;
                case 14:
                    return 3;
                case 30:
                    return 4;
                case 60:
                    return 5;
                case 90:
                    return 6;
                case 180:
                    return 7;
                case 365:
                    return 8;
                default:
                    return 0;
            }
        }
    }
}