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

namespace Siger.ApiConfig.Controller
{
    public class MachineController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectMachineRepository _projectMachineRepository;
        private readonly ISigerProjectLevelSectionMachineRepository _levelSectionMachineRepository;
        private readonly ISigerProjectMachineTypeRepository _projectMachineTypeRepository;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectMachineExtendRepository _machineExtendRepository;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;
        private readonly ISigerProjectMachineNodeRepository _machineNodeRepository;

        public MachineController(IUnitOfWork unitOfWork, ISigerProjectMachineRepository projectMachineRepository,
            ISigerProjectLevelSectionMachineRepository levelSectionMachineRepository,
            ISigerProjectMachineTypeRepository projectMachineTypeRepository, ISigerProjectLevelSectionRepository levelSectionRepository,
            ISigerProjectMachineExtendRepository machineExtendRepository, ISigerProjectMachineAttributionRepository machineAttributionRepository
            , ISigerProjectMachineNodeRepository machineNodeRepository)
        {
            _unitOfWork = unitOfWork;
            _projectMachineRepository = projectMachineRepository;
            _levelSectionMachineRepository = levelSectionMachineRepository;
            _projectMachineTypeRepository = projectMachineTypeRepository;
            _levelSectionRepository = levelSectionRepository;
            _machineExtendRepository = machineExtendRepository;
            _machineAttributionRepository = machineAttributionRepository;
            _machineNodeRepository = machineNodeRepository;
        }

        [HttpGet]
        public IActionResult SelectMachine(string typeid, string machinetype1, string code, string factory, string made_date,
            string attribution, int page = 1, int pagesize = PageSize)
        {
            var parentType = machinetype1.ToInt();
            var childType = typeid.ToInt();
            IList<int> typeIds = new List<int>();
            if (parentType != 0 && childType == 0)
            {
                typeIds = _projectMachineTypeRepository.GetMachineTypeIds(parentType, ProjectId);
            }

            var list = _projectMachineRepository.GetPagedMachines(childType, parentType, code, factory, made_date, ProjectId, attribution, typeIds, page, pagesize);

            var response = new List<ResponseGetResponseMachineList>();
            foreach (var responseGetMachine in list.Data)
            {
                var machine = Mapper<Machine, ResponseGetResponseMachineList>.Map(responseGetMachine);

                machine.current = GetMachineStatus(responseGetMachine.current_status);
                machine.made_date = UnixTimeHelper.GetDateTime(responseGetMachine.made_date);
                machine.stas = GetAllTitle(responseGetMachine.section_id);

                response.Add(machine);
            }
            return new PagedObjectResult(response, list.Total, page, pagesize);
        }

        [HttpGet]
        public IActionResult ExportMachine(string typeid, string machinetype1, string code, string factory, string made_date,
            string attribution, int page = 1, int pagesize = PageSize)
        {
            var parentType = machinetype1.ToInt();
            var childType = typeid.ToInt();
            IList<int> typeIds = new List<int>();
            if (parentType != 0 && childType == 0)
            {
                typeIds = _projectMachineTypeRepository.GetMachineTypeIds(parentType, ProjectId);
            }

            var list = _projectMachineRepository.GetPagedMachines(childType, parentType, code, factory, made_date, ProjectId, attribution, typeIds, page, pagesize);

            var response = new List<ResponseGetResponseMachineList>();
            foreach (var responseGetMachine in list.Data)
            {
                var machine = Mapper<Machine, ResponseGetResponseMachineList>.Map(responseGetMachine);

                machine.current = GetMachineStatus(responseGetMachine.current_status);
                machine.made_date = UnixTimeHelper.GetDateTime(responseGetMachine.made_date);
                machine.stas = GetAllTitle(responseGetMachine.section_id);

                response.Add(machine);
            }
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var temporaryFileName = $"machine_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            var helper = new EpPlusExcelHelper<ImportMachineList>();
            try
            {
                var datalist = new List<ImportMachineList>();
                foreach (var item in response)
                {
                    var data = Mapper<ResponseGetResponseMachineList, ImportMachineList>.Map(item);
                    data.attribution = EnumHelper.EnumToList<MachineAttributionEnum>().FirstOrDefault(f => f.EnumValue == item.attribution)?.Description ?? "";
                    datalist.Add(data);
                }
                helper.GenerateExcel(datalist, fileName);
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("Export repairs failed, error: " + e.Message);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper.Dispose();
            }
        }

        [HttpGet]
        public IActionResult SelectExtendMachine(string typeid, string machinetype1, string code, string factory, string made_date,
            string machineidarr, int page = 1, int pagesize = PageSize)
        {
            var parentType = machinetype1.ToInt();
            var childType = typeid.ToInt();
            IList<int> typeIds = new List<int>();
            if (parentType != 0 && childType == 0)
            {
                typeIds = _projectMachineTypeRepository.GetMachineTypeIds(parentType, ProjectId);
            }

            var list = _projectMachineRepository.GetPagedMachines(childType, parentType, code, factory, made_date, ProjectId, machineidarr, typeIds, page, pagesize);

            var response = new List<ResponseGetResponseExtendMachineList>();
            var machineIds = list.Data.Select(t => t.id).ToList();
            var extendMachines = _machineExtendRepository.GetList(t =>
                machineIds.Contains(t.machine_id)).ToList();
            foreach (var responseGetMachine in list.Data)
            {
                var machine = Mapper<Machine, ResponseGetResponseExtendMachineList>.Map(responseGetMachine);

                machine.current = GetMachineStatus(responseGetMachine.current_status);
                machine.made_date = UnixTimeHelper.GetDateTime(responseGetMachine.made_date);
                machine.stas = GetAllTitle(responseGetMachine.section_id);

                var extendMachine = extendMachines.FirstOrDefault(t => t.machine_id == machine.id);
                machine.machine_shortname = extendMachine?.machine_shortname ?? "";
                machine.machine_name = extendMachine?.machine_name ?? "";
                machine.typical_application = extendMachine?.typical_application ?? "";
                response.Add(machine);
            }
            return new PagedObjectResult(response, list.Total, page, pagesize);
        }

        private string GetMachineStatus(int current_status)
        {
            try
            {
                var status = (MachineStatus)current_status;

                return status.ToDescription();
            }
            catch
            {
                return string.Empty;
            }
        }

        [HttpGet]
        public IActionResult GetMachines(int id)
        {
            var entity = _projectMachineRepository.GetMachines(id, ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            entity.station = GetAllTitle(entity.section_id);
            entity.current = GetMachineStatus(entity.current_status);

            var list = new List<ResponseGetResponseMachines> { entity };
            return new ObjectResult(list);
        }

        [HttpGet]
        public IActionResult GetExtendMachines(int id)
        {
            var entity = _projectMachineRepository.GetExtendMachines(id, ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            entity.station = GetAllTitle(entity.section_id);
            entity.current = GetMachineStatus(entity.current_status);

            var list = new List<ResponseGetResponseExtendMachines> { entity };
            return new ObjectResult(list);
        }

        [HttpGet]
        public IActionResult GetMachineidItem(int id)
        {
            var section =
                _levelSectionMachineRepository.Get(q => q.section_id == id && q.status == (int)RowState.Valid);
            if (section != null)
            {
                var machine = _projectMachineRepository.Get(q =>
                    q.id == section.machine_id && q.projectid == ProjectId && q.status == (int)RowState.Valid);
                if (machine != null)
                {
                    return new ObjectResult(machine.title);
                }
            }
            throw new BadRequestException(RequestEnum.MachineNotFound);
        }

        [HttpGet]
        public IActionResult GetMachineItem(int id)
        {
            var machineIds = _levelSectionRepository.GetLevelSectionMachineIds(id, ProjectId);
            var machines = _projectMachineRepository.GetList(q => machineIds.Contains(q.id) && q.status == (int)RowState.Valid).ToList();

            var response = new List<ResponseGetResponseMachineItem>();
            foreach (var machine in machines)
            {
                var res = Mapper<siger_project_machine, ResponseGetResponseMachineItem>.Map(machine);
                if (!string.IsNullOrEmpty(res.title))
                {
                    var titles = res.title.Split('-');
                    res.title1 = titles[titles.Length - 1];
                }
                else
                {
                    res.title1 = string.Empty;
                }

                var section = _levelSectionMachineRepository.Get(q => q.machine_id == machine.id);
                if (section != null)
                {
                    res.section_id = section.section_id;
                    res.station = GetAllTitle(section.section_id);
                }
                response.Add(res);
            }
            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult GetMachineInfo(int id)
        {
            var entity = _projectMachineRepository.GetMachineInfo(id);
            if (entity == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var response = Mapper<MachineInfo, ResponseGetResponseMachineInfo>.Map(entity);

            response.station = GetAllTitle(entity.section_id);

            return new ObjectResult(new List<ResponseGetResponseMachineInfo> { response });
        }

        [HttpGet]
        public IActionResult GetExtendMachineInfo(int id)
        {
            var entity = _projectMachineRepository.GetExtendMachineInfo(id);
            if (entity == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var response = Mapper<ExtendMachineInfo, ResponseGetResponseExtendMachines>.Map(entity);

            response.station = GetAllTitle(entity.section_id);

            return new ObjectResult(new List<ResponseGetResponseExtendMachines> { response });
        }

        private string GetAllTitle(int sectionId)
        {
            var titles = _levelSectionRepository.GetLevelSectionTitles(sectionId, ProjectId);
            var list = titles.ToList();
            return list.Any() ? string.Join('-', list) : string.Empty;
        }

        [HttpPost]
        public IActionResult AddExtendMachine([FromBody] RequestAddMachine request)
        {
            var sectionMachine = _levelSectionMachineRepository.Get(q => q.section_id == request.sectionid && q.status == (int)RowState.Valid);
            if (sectionMachine != null)
            {
                throw new BadRequestException(RequestEnum.SectionMachineHasExist);
            }

            var entity = _projectMachineRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.code == request.code);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.CodeHasExist);
            }

            var mid = request.mid.ToInt();
            entity = _projectMachineRepository.Get(q => q.projectid == ProjectId && q.id == mid && q.status == (int)RowState.Valid);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.IdHasExist);
            }

            var machine = new siger_project_machine
            {
                id = mid,
                code = request.code,
                factory = request.factory,
                factory_code = request.factory_code,
                model = request.model,
                made_date = request.made_date,
                typeid = request.typeid.ToInt(),
                ip = ServerIpAddress,
                mid = UserId,
                projectid = ProjectId,
                attribute = (int)request.attribute,
                machinelevel = request.machinelevel.ToInt(),
                time = UnixTimeHelper.GetNow(),
                title = request.title,
                tool_count = request.tool_count.ToInt(),
                category = request.category.ToInt() > 0 ? request.category.ToInt() : (int)MachineCategory.NC,
            };
            if (!string.IsNullOrEmpty(request.image))
            {
                machine.image = request.image;
            }
            _projectMachineRepository.Insert(machine);

            if (_unitOfWork.Commit() <= 0)
            {
                throw new BadRequestException(CommonEnum.SystemExcetion);
            }
            else
            {
                var extendMachine = _machineExtendRepository.Get(t => t.machine_id == mid);
                if (extendMachine == null)
                {
                    var extendmachine = new siger_project_machine_extend
                    {
                        machine_id = mid,
                        machine_name = request.machine_name,
                        typical_application = request.typical_application,
                        inside_diameter = request.inside_diameter,
                        outside_diameter = request.outside_diameter,
                        radial_load = request.radial_load,
                        axial_load = request.axial_load,
                        pressure = request.pressure,
                        speed = request.speed,
                        temperature = request.temperature,
                        rotation = request.rotation,
                        sample_lubrication = request.sample_lubrication,
                        oil_hydraulic = request.oil_hydraulic,
                        oil_lubrication = request.oil_lubrication,
                        signal_monitor = request.signal_monitor,
                        position = request.position,
                        machine_size = request.machine_size,
                        machine_shortname = request.machine_shortname,
                        responsor = request.responsor
                    };
                    _machineExtendRepository.Insert(extendmachine);
                }
                else
                {
                    extendMachine.machine_name = request.machine_name;
                    extendMachine.typical_application = request.typical_application;
                    extendMachine.inside_diameter = request.inside_diameter;
                    extendMachine.outside_diameter = request.outside_diameter;
                    extendMachine.radial_load = request.radial_load;
                    extendMachine.axial_load = request.axial_load;
                    extendMachine.pressure = request.pressure;
                    extendMachine.speed = request.speed;
                    extendMachine.temperature = request.temperature;
                    extendMachine.rotation = request.rotation;
                    extendMachine.sample_lubrication = request.sample_lubrication;
                    extendMachine.oil_hydraulic = request.oil_hydraulic;
                    extendMachine.oil_lubrication = request.oil_lubrication;
                    extendMachine.signal_monitor = request.signal_monitor;
                    extendMachine.position = request.position;
                    extendMachine.machine_size = request.machine_size;
                    extendMachine.machine_shortname = request.machine_shortname;
                    extendMachine.responsor = request.responsor;
                    _machineExtendRepository.Update(extendMachine);
                }

                _unitOfWork.Commit();
            }

            var levelSectionMachine = new siger_project_level_section_machine
            {
                section_id = request.sectionid,
                machine_id = mid
            };
            _levelSectionMachineRepository.Insert(levelSectionMachine);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult AddMachine([FromBody] RequestAddMachine request)
        {
            var entity = _projectMachineRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.code == request.code);
            if (entity != null)
            {
                throw new BadRequestException(RequestEnum.CodeHasExist);
            }

            try
            {
                var machine = new siger_project_machine
                {
                    //id = mid,
                    code = request.code,
                    factory = request.factory,
                    factory_code = request.factory_code,
                    model = request.model,
                    made_date = request.made_date,
                    typeid = request.typeid.ToInt(),
                    ip = ServerIpAddress,
                    sorting=request.sorting,
                    mid = UserId,
                    projectid = ProjectId,
                    attribute = (int)request.attribute,
                    machinelevel = request.machinelevel.ToInt(),
                    time = UnixTimeHelper.GetNow(),
                    title = request.title,

                    tool_count = request.tool_count.ToInt(),
                    category = request.category.ToInt() > 0 ? request.category.ToInt() : (int)MachineCategory.NC,
                    attribution = (int)request.attribution
                };
                if (!string.IsNullOrEmpty(request.image))
                {
                    machine.image = request.image;
                }
                _projectMachineRepository.Insert(machine);

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

        [HttpGet]
        public IActionResult GetNextMachineId()
        {
            var lastmachine = _projectMachineRepository.GetList().OrderByDescending(q => q.id).FirstOrDefault();

            return new ObjectResult(lastmachine?.id + 1 ?? 1);
        }

        [HttpPost]
        public IActionResult EditExtendMachine([FromBody] RequestUpdateMachine request)
        {
            var entity = _projectMachineRepository.Get(request.machineid);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }
            var isExist = _projectMachineRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.code == request.code
                                                             && q.id != request.machineid);
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.CodeHasExist);
            }
            entity.code = request.code;
            entity.factory = request.factory;
            entity.factory_code = request.factory_code;
            entity.model = request.model;
            entity.made_date = request.made_date;
            entity.typeid = request.typeid.ToInt();
            entity.attribute = (int)request.attribute;
            entity.tool_count = request.tool_count.ToInt();
            entity.machinelevel = request.machinelevel.ToInt();
            entity.category = request.category.ToInt() > 0 ? request.category.ToInt() : (int)MachineCategory.NC;
            if (!string.IsNullOrEmpty(request.image))
            {
                entity.image = request.image;
            }
            entity.title = request.title;

            var extendMachine = _machineExtendRepository.Get(t => t.machine_id == request.machineid);
            _projectMachineRepository.Update(entity);
            if (extendMachine == null)
            {
                var extendMachineModel = new siger_project_machine_extend
                {
                    machine_id = request.machineid,
                    machine_name = request.machine_name,
                    typical_application = request.typical_application,
                    inside_diameter = request.inside_diameter,
                    outside_diameter = request.outside_diameter,
                    radial_load = request.radial_load,
                    axial_load = request.axial_load,
                    pressure = request.pressure,
                    speed = request.speed,
                    temperature = request.temperature,
                    rotation = request.rotation,
                    sample_lubrication = request.sample_lubrication,
                    oil_hydraulic = request.oil_hydraulic,
                    oil_lubrication = request.oil_lubrication,
                    signal_monitor = request.signal_monitor,
                    position = request.position,
                    machine_size = request.machine_size,
                    machine_shortname = request.machine_shortname,
                    responsor = request.responsor
                };
                _machineExtendRepository.Insert(extendMachineModel);
            }
            else
            {
                extendMachine.machine_name = request.machine_name;
                extendMachine.typical_application = request.typical_application;
                extendMachine.inside_diameter = request.inside_diameter;
                extendMachine.outside_diameter = request.outside_diameter;
                extendMachine.radial_load = request.radial_load;
                extendMachine.axial_load = request.axial_load;
                extendMachine.pressure = request.pressure;
                extendMachine.speed = request.speed;
                extendMachine.temperature = request.temperature;
                extendMachine.rotation = request.rotation;
                extendMachine.sample_lubrication = request.sample_lubrication;
                extendMachine.oil_hydraulic = request.oil_hydraulic;
                extendMachine.oil_lubrication = request.oil_lubrication;
                extendMachine.signal_monitor = request.signal_monitor;
                extendMachine.position = request.position;
                extendMachine.machine_size = request.machine_size;
                extendMachine.machine_shortname = request.machine_shortname;
                extendMachine.responsor = request.responsor;
                _machineExtendRepository.Update(extendMachine);
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult EditMachine([FromBody] RequestUpdateMachine request)
        {
            var entity = _projectMachineRepository.Get(request.machineid);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }
            var isExist = _projectMachineRepository.Get(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.code == request.code
                                                             && q.id != request.machineid);
            if (isExist != null)
            {
                throw new BadRequestException(RequestEnum.CodeHasExist);
            }
            entity.code = request.code;
            entity.factory = request.factory;
            entity.factory_code = request.factory_code;
            entity.model = request.model;
            entity.made_date = request.made_date;
            entity.typeid = request.typeid.ToInt();
            entity.attribute = (int)request.attribute;
            entity.tool_count = request.tool_count.ToInt();
            entity.machinelevel = request.machinelevel.ToInt();
            entity.category = request.category.ToInt() > 0 ? request.category.ToInt() : (int)MachineCategory.NC;
            entity.attribution = (int)request.attribution;
            entity.sorting = request.sorting;
            if (!string.IsNullOrEmpty(request.image))
            {
                entity.image = request.image;
            }
            entity.title = request.title;
            _projectMachineRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                var attrData = _machineAttributionRepository.Get(f => f.machine == request.machineid && f.attribution.Equals((int)request.attribution) && f.projectid == ProjectId && f.sparepart_id == 0);
                if (attrData != null)
                {
                    attrData.name = request.title;
                    _machineAttributionRepository.Update(attrData);
                    if (_unitOfWork.Commit() > 0)
                    {
                        return new ObjectResult(CommonEnum.Succefull);
                    }
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult DeleteExtendMachine(int id)
        {
            var entity = _projectMachineRepository.Get(id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var levelSectionMachine = _levelSectionMachineRepository.Get(q => q.machine_id == id);
            var extendMachine = _machineExtendRepository.Get(t => t.machine_id == id);
            if (levelSectionMachine != null)
            {
                _levelSectionMachineRepository.Delete(levelSectionMachine);
            }

            if (extendMachine != null)
            {
                _machineExtendRepository.Delete(extendMachine);
            }

            _projectMachineRepository.Delete(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult DeleteMachine(int id)
        {
            var entity = _projectMachineRepository.Get(id);
            if (entity == null || entity.status != (int)RowState.Valid)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            var levelSectionMachine = _levelSectionMachineRepository.Get(q => q.machine_id == id);
            if (levelSectionMachine != null)
            {
                _levelSectionMachineRepository.Delete(levelSectionMachine);
            }

            _projectMachineRepository.Delete(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult DeleteMachines([FromBody]RequestDeleteEntities request)
        {
            if (request.ids == null || !request.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            foreach (var id in request.ids)
            {
                var entity = _projectMachineRepository.Get(id);
                if (entity != null)
                {
                    var levelSectionMachine = _machineAttributionRepository.Get(q => q.machine == id && q.status == (int)RowState.Valid);
                    if (levelSectionMachine != null)
                    {
                        throw new BadRequestException(ConfigEnum.MahcineCanNotDelete);
                    }
                    _projectMachineRepository.Delete(entity);
                    //delete node info
                    var nodeinfo = _machineNodeRepository.GetList(f => f.machine == id && f.status == (int)RowState.Valid && f.projectid == ProjectId).ToList();
                    if (nodeinfo.Any())
                    {
                        nodeinfo.ForEach(f => { f.status = (int)RowState.Invalid; _machineNodeRepository.Update(f); });
                    }
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpPost]
        public IActionResult DeleteExtendMachines([FromBody]RequestDeleteEntities request)
        {
            if (request.ids == null || !request.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterError);
            }
            foreach (var id in request.ids)
            {
                var entity = _projectMachineRepository.Get(id);
                if (entity != null)
                {
                    var levelSectionMachine = _levelSectionMachineRepository.Get(q => q.machine_id == id);
                    if (levelSectionMachine != null)
                    {
                        _levelSectionMachineRepository.Delete(levelSectionMachine);
                    }
                    var extendMachine = _machineExtendRepository.Get(t => t.machine_id == id);
                    if (extendMachine != null)
                    {
                        _machineExtendRepository.Delete(extendMachine);
                    }
                    _projectMachineRepository.Delete(entity);
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.SystemExcetion);
        }

        [HttpGet]
        public IActionResult Getmachineid(int id)
        {
            var entity =
                _levelSectionMachineRepository.Get(q => q.machine_id == id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            return new ObjectResult(entity);
        }

        [HttpGet]
        public IActionResult GetmachineidBySection(int id)
        {
            if (id == 0)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var entity = _machineAttributionRepository.Get(q => q.station == id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var machine = _projectMachineRepository.Get(f => f.id == entity.machine);
            if (machine == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var result = Mapper<siger_project_machine_attribution, ResponseGetmachineidBySection>.Map(entity);
            result.section_id = entity.station;
            result.title = machine.title;
            result.machine_id = machine.id;
            result.attribute = machine.attribute;
            return new ObjectResult(result);
        }

        [HttpGet]
        public IActionResult GetSectionMachine(int sectionid)
        {
            var data = _levelSectionMachineRepository.GetSectionMachine(ProjectId, sectionid);
            return new ObjectResult(data);
        }


        [HttpGet]
        public IActionResult GetAllMachines(int sectionId)
        {
            var machineIds = _projectMachineRepository.GetLevelSectionMachineIds(sectionId, ProjectId);
            if (!machineIds.Any())
            {
                return new ObjectResult(CommonEnum.Succefull);
            }

            var machines = _projectMachineRepository.GetList(q => machineIds.Contains(q.id))
                .Select(m => new
                {
                    m.id,
                    m.typeid,
                    m.title
                }).ToList();
            return new ObjectResult(machines);
        }

        [HttpGet]
        public IActionResult GetToolQrCodes(int id)
        {
            if (id == 0)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var entity = _projectMachineRepository.Get(q => q.id == id && q.status == (int)RowState.Valid && q.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var response = new List<ResponseMachineToolQrCode>();
            if (entity.tool_count > 0)
            {
                var prefix = string.Empty;
                var dicts = _projectMachineRepository.GetDictKeyValues(ProjectId, AccDictCost.ToolPrefix).FirstOrDefault();
                if (dicts != null)
                {
                    prefix = dicts.value;
                }

                for (var i = 1; i <= entity.tool_count; i++)
                {
                    response.Add(new ResponseMachineToolQrCode
                    {
                        machine_type = entity.typeid,
                        mid = id,
                        tool_number = $"{prefix}{i:D2}"
                    });
                }
            }

            return new ObjectResult(response);

        }

        [HttpGet]
        public IActionResult GetToolNumbers(int machineTypeId)
        {
            var entities = _projectMachineRepository.GetList(q => q.typeid == machineTypeId && q.status == (int)RowState.Valid && q.projectid == ProjectId);
            if (!entities.Any())
            {
                throw new BadRequestException(RequestEnum.MachineToolCountNotFound);
            }
            var response = new List<string>();
            var maxCount = entities.Max(q => q.tool_count);
            if (maxCount == 0)
            {
                throw new BadRequestException(RequestEnum.MachineToolCountNotFound);
            }

            var prefix = string.Empty;
            var dicts = _projectMachineRepository.GetDictKeyValues(ProjectId, AccDictCost.ToolPrefix).FirstOrDefault();
            if (dicts != null)
            {
                prefix = dicts.value;
            }

            for (var i = 1; i <= maxCount; i++)
            {
                response.Add($"{prefix}{i:D2}");
            }

            return new ObjectResult(response);
        }

        [HttpGet]
        public IActionResult ListAllMachines(string name, int count)
        {
            var machines = _projectMachineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid).OrderBy(m => m.title)
                .Select(m => new
                {
                    m.id,
                    name = m.title,
                    m.code
                }).ToList();
            if (!string.IsNullOrWhiteSpace(name))
            {
                machines = machines.Where(f => f.name.Contains(name)).ToList();
            }
            if (count != 0)
            {
                machines = machines.Take(count).ToList();
            }
            return new ObjectResult(machines);
        }

        /// <summary>
        /// 根据资产编号获取设备id
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult GetMachineIdByCode([FromBody]RequestGetMachineIdByCode req)
        {
            if (string.IsNullOrWhiteSpace(req.code))
            {
                throw new BadRequestException(RequestEnum.CodeIsEmpty);
            }
            var machine = _projectMachineRepository.Get(t => t.code == req.code && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.MachineNotFound);
            }

            return new ObjectResult(machine.id);
        }

        /// <summary>
        /// 根据设备id获取设备名称
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMachineNameById(int id)
        {
            var machine = _projectMachineRepository.Get(t => t.id == id && t.projectid == ProjectId && t.status == (int)RowState.Valid);

            return new ObjectResult(machine?.title ?? "");
        }


        [HttpGet]
        public IActionResult ListNCMachines(string name, int count = 0)
        {
            var machines = _projectMachineRepository.GetList(q => q.projectid == ProjectId && q.status == (int)RowState.Valid && q.category == (int)MachineCategory.NC).OrderBy(m => m.title)
                .Select(m => new
                {
                    m.id,
                    name = m.title,
                    m.code
                }).ToList();
            if (!string.IsNullOrWhiteSpace(name))
            {
                machines = machines.Where(f => f.name.Contains(name)).ToList();
            }
            if (count != 0)
            {
                machines = machines.Take(count).ToList();
            }
            return new ObjectResult(machines);
        }

        /// <summary>
        /// 手机app端检查设备有效性
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CheckVaildMachine([FromBody]RequestCheckMachine req)
        {
            Expression<Func<siger_project_machine, bool>> funCode = f => true;
            if (!string.IsNullOrEmpty(req.code))
            {
                funCode = f => f.code.Equals(req.code);
            }
            Expression<Func<siger_project_machine, bool>> funId = f => true;
            if (req.id != 0)
            {
                funId = f => f.id.Equals(req.id);
            }
            Expression<Func<siger_project_machine, bool>> funName = f => true;
            if (!string.IsNullOrEmpty(req.name))
            {
                funName = f => f.title.Equals(req.name);
            }
            Expression<Func<siger_project_machine, bool>> funCommon = f => f.projectid.Equals(ProjectId) && f.status == (int)RowState.Valid;
            var predicate = funCode.And(funId).And(funName).And(funCommon);
            var machine = _projectMachineRepository.Get(predicate);
            if (machine != null)
            {
                if (machine.attribution != 1)
                {
                    throw new BadRequestException(ConfigEnum.AndonCanNotTrigger);
                }
                var ret = Mapper<siger_project_machine, ResponseCheckMachine>.Map(machine);
                ret.station = _machineAttributionRepository.Get(f => f.machine == machine.id && f.status == (int)RowState.Valid && f.projectid == ProjectId && f.attribution == 1)?.station ?? 0;
                ret.station_name = GetAllTitle(ret.station);
                return new ObjectResult(ret);
            }
            throw new BadRequestException(CommonEnum.NoData);
        }


        /// <summary>
        /// 手机app端检查设备有效性
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult CheckVaildMachineForTpm([FromBody]RequestCheckMachine req)
        {
            Expression<Func<siger_project_machine, bool>> funCode = f => true;
            if (!string.IsNullOrEmpty(req.code))
            {
                funCode = f => f.code.Equals(req.code);
            }
            Expression<Func<siger_project_machine, bool>> funId = f => true;
            if (req.id != 0)
            {
                funId = f => f.id.Equals(req.id);
            }
            Expression<Func<siger_project_machine, bool>> funName = f => true;
            if (!string.IsNullOrEmpty(req.name))
            {
                funName = f => f.title.Equals(req.name);
            }
            Expression<Func<siger_project_machine, bool>> funCommon = f => f.projectid.Equals(ProjectId) && f.status == (int)RowState.Valid;
            var predicate = funCode.And(funId).And(funName).And(funCommon);
            var machine = _projectMachineRepository.Get(predicate);
            if (machine != null)
            {
                var ret = Mapper<siger_project_machine, ResponseCheckMachine>.Map(machine);
                ret.station = _machineAttributionRepository.Get(f => f.machine == machine.id && f.status == (int)RowState.Valid && f.projectid == ProjectId)?.station ?? 0;
                ret.station_name = GetAllTitle(ret.station);
                return new ObjectResult(ret);
            }
            throw new BadRequestException(CommonEnum.NoData);
        }
        [HttpGet]
        public IActionResult GetSectionMachineByCode(string code)
        {
            var data = _projectMachineRepository.GetSectionMachineByCode(code, ProjectId);
            if (data==null)
            {
                throw new BadRequestException(ConfigEnum.MachineNotFound);
            }
            return new ObjectResult(data);
        }
    }
}