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

namespace Siger.ApiTLM.Controllers
{
    public class ToolInfoController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IToolLifeCategoryRepository _categoryRepository;
        private readonly ISigerProjectParameterRepository _parameterRepository;
        private readonly ISigerProjectParameterExtendRepository _extendRepository;
        private readonly IToolLifeCategoryPrameterRepository _categoryPrameterRepository;

        private readonly IToolLifeToolRepository _toolRepository;
        private readonly IToolLifeToolParameterRepository _toolParameterRepository;
        private readonly IToolLifeToolInstallRepository _toolInstallRepository;
        public ToolInfoController(IUnitOfWork unitOfWork, IToolLifeCategoryRepository categoryRepository,
            IToolLifeCategoryPrameterRepository categoryPrameterRepository,
            ISigerProjectParameterRepository parameterRepository,
            ISigerProjectParameterExtendRepository extendRepository,
            IToolLifeToolRepository toolRepository, IToolLifeToolParameterRepository toolParameterRepository,
            IToolLifeToolInstallRepository toolInstallRepository)
        {
            _unitOfWork = unitOfWork;
            _categoryRepository = categoryRepository;
            _categoryPrameterRepository = categoryPrameterRepository;
            _extendRepository = extendRepository;
            _parameterRepository = parameterRepository;
            _toolRepository = toolRepository;
            _toolParameterRepository = toolParameterRepository;
            _toolInstallRepository = toolInstallRepository;
        }

        [HttpGet]
        public IActionResult GetToolTree(int type, string keyword)
        {
            var categories = _categoryRepository.GetAllCategories(ProjectId, (TlmSettingCategory)type);

            var entities = new List<ToolCategoryTree>();
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                var cateGories = categories.Where(t => t.name.Contains(keyword));
                foreach (var category in cateGories)
                {
                    var cates = GetParentCategories(category.parent, categories).ToList();
                    if (category.name.Contains(keyword))
                    {
                        cates.Add(category);
                    }
                    foreach (var cate in cates)
                    {
                        entities.Add(new ToolCategoryTree
                        {
                            id = cate.id,
                            pid = cate.parent,
                            name = cate.name,
                            code = cate.code,
                            title = cate.name
                        });
                    }
                }
                entities = entities.GroupBy(t => t.id).Select(t => t.FirstOrDefault()).ToList();
            }
            else
            {
                foreach (var category in categories)
                {
                    entities.Add(new ToolCategoryTree
                    {
                        id = category.id,
                        pid = category.parent,
                        name = category.name,
                        code = category.code,
                        title = category.name
                    });
                }
            }

            return new ObjectResult(ConvertToTreeForTpm(entities, type));
        }

        private IEnumerable<siger_project_toollife_category> GetParentCategories(int parentId, IEnumerable<siger_project_toollife_category> categories)
        {
            var query = categories.Where(t => t.id == parentId);

            return query.ToList().Concat(query.ToList().SelectMany(t => GetParentCategories(t.parent, categories)));
        }

        private ToolCategoryTree ConvertToTreeForTpm(IEnumerable<ToolCategoryTree> models, int type)
        {
            var section = new Dictionary<int, ToolCategoryTree>();
            foreach (var item in models)
            {
                section.Add(item.id, item);
            }

            var name = "刀具类型";
            switch (type)
            {
                case 1:
                    break;
                case 2:
                    name = "刀柄类型";
                    break;
                case 3:
                    name = "附件类型";
                    break;
            }
            var result = new ToolCategoryTree
            {
                id = 0,
                pid = 0,
                code = "",
                name = name, //刀柄类型，附件类型
                title = name
            };
            var tools = _toolRepository.GetToolList(models.Select(m => m.id).ToList(), (TlmSettingCategory)type,
                ProjectId);
            var response = new List<ToolCategoryTree>();
            foreach (var item in section.Values)
            {
                var typeTools = tools.Where(q => q.category_id == item.id);
                if (typeTools.Any())
                {
                    foreach (var tool in typeTools.ToList())
                    {
                        var toolItem = new ToolCategoryTree
                        {
                            name = tool.name,
                            toolid = tool.id,
                            id = tool.id,
                            title = tool.name
                        };
                        item.children.Add(toolItem);
                    }
                }
                if (item.pid == 0)
                {
                    response.Add(item);
                }
                else
                {
                    if (section.ContainsKey(item.pid))
                    {
                        section[item.pid].AddChilrden(item);
                    }
                }
            }

            result.children = response;
            return result;
        }

        [HttpPost]
        public IActionResult Add([FromBody]RequestAddToolInfo request)
        {
            if (string.IsNullOrWhiteSpace(request.toolid)) //新增
            {
                var partNoExist = _toolRepository.IsExist(q => q.project_id == ProjectId && q.part_no == request.partno
                                                               && q.material_id == request.material_id && request.material_id > 0 &&
                                                               q.status == (int)RowState.Valid);
                if (partNoExist)
                {
                    throw new BadRequestException(RequestEnum.PartNoIsExist);
                }
                var numberExist = _toolRepository.IsExist(q => q.project_id == ProjectId && q.number == request.number && q.status == (int)RowState.Valid);
                if (numberExist)
                {
                    throw new BadRequestException(RequestEnum.NumberIsExist);
                }

                var material = _toolRepository.GetMaterial(request.material_id, request.partno, ProjectId);
                if (material == null)
                {
                    throw new BadRequestException(RequestEnum.MaterialNotExist);
                }

                request.name = material.name;
                request.material_id = material.id;
                request.partno = material.pn;

                if (_toolRepository.AddToolInfo(request, ProjectId))
                {
                    return new ObjectResult(CommonEnum.Succefull);
                }
                throw new BadRequestException(CommonEnum.Fail);
            }

            return Edit(request);
        }

        private IActionResult Edit(RequestAddToolInfo request)
        {
            var id = request.toolid.ToInt();

            var entity = _toolRepository.Get(q => q.project_id == ProjectId && q.id == id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var partNoExist = _toolRepository.IsExist(q => q.project_id == ProjectId && (q.part_no == request.partno &&
                              q.material_id == request.material_id && request.material_id > 0) && q.status == (int)RowState.Valid && q.id != id);
            if (partNoExist)
            {
                throw new BadRequestException(RequestEnum.PartNoIsExist);
            }
            var numberExist = _toolRepository.IsExist(q => q.project_id == ProjectId && q.number == request.number
                                                                                     && q.status == (int)RowState.Valid && q.id != id);
            if (numberExist)
            {
                throw new BadRequestException(RequestEnum.NumberIsExist);
            }
            var material = _toolRepository.GetMaterial(request.material_id, request.partno, ProjectId);
            if (material == null)
            {
                throw new BadRequestException(RequestEnum.MaterialNotExist);
            }

            request.name = material.name;
            request.material_id = material.id;

            entity.category_name = request.category_name;
            entity.image = !string.IsNullOrWhiteSpace(request.image) ? request.image : entity.image;
            entity.video = !string.IsNullOrWhiteSpace(request.video) ? request.video : entity.video;
            entity.number = request.number;
            entity.part_no = material.pn;
            entity.material_id = material.id;
            entity.name = material.name;
            entity.grind_type = request.grind_type.ToInt();
            entity.grind = request.grind.ToInt();
            entity.grind_times = request.grind_times.ToInt();
            entity.use_times = request.use_times.ToInt();
            entity.image_name = string.IsNullOrEmpty(request.image) ? "" : (request.image_name ?? "");
            entity.need_test = request.need_test;
            entity.need_detection = request.need_detection.ToInt();
            _toolRepository.Update(entity);

            var toolParas = _toolParameterRepository.GetList(q => q.tool_id == entity.id && q.status == (int)RowState.Valid).ToList();
            foreach (var keyValue in request.paraValue)
            {
                if (keyValue == null)
                {
                    continue;
                }
                var para = toolParas.FirstOrDefault(q => q.parameter_id == keyValue.key.ToInt());
                if (para != null && para.parameter_value != keyValue.value)
                {
                    //修改
                    para.parameter_value = keyValue.value ?? "";
                    _toolParameterRepository.Update(para);
                }
            }
            //新增
            foreach (var keyValue in request.paraValue)
            {
                if (keyValue == null)
                {
                    continue;
                }
                var para = toolParas.FirstOrDefault(q => q.parameter_id == keyValue.key.ToInt());
                if (para == null)
                {
                    var newPara = new siger_project_toollife_tool_parameter
                    {
                        parameter_id = keyValue.key.ToInt(),
                        parameter_value = keyValue.value ?? "",
                        project_id = ProjectId,
                        tool_id = entity.id
                    };
                    _toolParameterRepository.Insert(newPara);
                }
            }
            //删除
            foreach (var keyValue in toolParas)
            {
                var para = request.paraValue.FirstOrDefault(q => q.key == keyValue.parameter_id.ToString());
                if (para == null)
                {
                    _toolParameterRepository.Delete(keyValue);
                }
            }

            _unitOfWork.Commit();
            return new ObjectResult(CommonEnum.Succefull);
        }

        [HttpGet]
        public IActionResult GetItem(int id)
        {
            var response = new ResponeGetToolItem();
            var entity = _toolRepository.Get(q => q.project_id == ProjectId && q.id == id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                return new ObjectResult(response);
            }

            response = Mapper<siger_project_toollife_tool, ResponeGetToolItem>.Map(entity);

            var paramters = _toolParameterRepository.GetList(q => q.tool_id == entity.id && q.status == (int)RowState.Valid);
            if (paramters.Any())
            {
                var ids = paramters.Select(q => q.parameter_id).ToList();
                var paras = _parameterRepository.GetList(q => ids.Contains(q.id) && q.status == (int)RowState.Valid);
                foreach (var parameter in paras.ToList())
                {
                    var value = paramters.FirstOrDefault(q => q.parameter_id == parameter.id);
                    if (value == null)
                    {
                        continue;
                    }

                    var paraValue = value.parameter_value;
                    if (parameter.type == 2) //下拉框
                    {
                        var extend = _extendRepository.Get(q => q.parameter_id == parameter.id && q.key == value.parameter_value);
                        if (extend != null)
                        {
                            paraValue = extend.value;
                        }
                    }
                    if (parameter.category == ParameterCategory.Geometry.ToString())
                    {
                        response.GeometryParameter.Add(new ToolParamterInfo
                        {
                            code = parameter.code,
                            name = parameter.name,
                            para_id = parameter.id,
                            unit = parameter.unit,
                            value = paraValue
                        });
                    }
                    if (parameter.category == ParameterCategory.Technology.ToString())
                    {
                        response.TechnologyParameter.Add(new ToolParamterInfo
                        {
                            code = parameter.code,
                            name = parameter.name,
                            para_id = parameter.id,
                            unit = parameter.unit,
                            value = paraValue
                        });
                    }
                }
            }

            return new ObjectResult(response);
        }

        [HttpPost]
        public IActionResult Delete(int id)
        {
            var entity = _toolRepository.Get(q => q.project_id == ProjectId && q.id == id && q.status == (int)RowState.Valid);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            entity.status = (int)RowState.Invalid;
            _toolRepository.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        /// <summary>
        /// 根据类型获取类型参数
        /// </summary>
        /// <param name="categoryId"></param>
        /// <param name="type">1:添加 2：修改</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetCategoryParameterList(int categoryId, int type)
        {
            if (type == 2)
            {
                var entity = _toolRepository.Get(q => q.project_id == ProjectId && q.id == categoryId && q.status == (int)RowState.Valid);
                if (entity == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }

                var categoryParameters =
                    _categoryPrameterRepository.GetList(
                        q => q.category_id == entity.category_id && q.status == (int)RowState.Valid).ToList();

                var toolParameterValues = _toolParameterRepository.GetList(q =>
                    q.tool_id == entity.id && q.project_id == ProjectId && q.status == (int)RowState.Valid).ToList();

                var response = new ResponseGetCategoryParameter
                {
                    GeometryParameter = GetParamters(ParameterCategory.Geometry, categoryParameters, toolParameterValues),
                    TechnologyParameter = GetParamters(ParameterCategory.Technology, categoryParameters, toolParameterValues),
                };
                return new ObjectResult(response);
            }
            else
            {
                var entity = _categoryRepository.Get(q => q.project_id == ProjectId && q.id == categoryId && q.status == (int)RowState.Valid);
                if (entity == null)
                {
                    throw new BadRequestException(CommonEnum.RecordNotFound);
                }

                var categoryParameters =
                    _categoryPrameterRepository.GetList(
                        q => q.category_id == entity.id && q.status == (int)RowState.Valid).ToList();

                var response = new ResponseGetCategoryParameter
                {
                    GeometryParameter = GetParamters(ParameterCategory.Geometry, categoryParameters, null),
                    TechnologyParameter = GetParamters(ParameterCategory.Technology, categoryParameters, null),
                };
                return new ObjectResult(response);
            }
        }

        private List<ParameterInfo> GetParamters(ParameterCategory category, IList<siger_project_toollife_category_parameter> parameters,
            IList<siger_project_toollife_tool_parameter> toolParameterValues)
        {
            var ids = parameters.Where(q => q.parameter_category == category.ToString()).Select(m => m.parameter_id);

            var result = new List<ParameterInfo>();
            var paras = _parameterRepository.GetList(q => ids.Contains(q.id) &&
                                                          q.category == category.ToString() && q.status == (int)RowState.Valid
                                                          && (q.module == Module.Tlm.ToString().ToLower() ||
                                                          q.module == $"{Module.Tlm.ToString().ToLower()}s") &&
                                                          q.project_id == ProjectId).ToList();
            foreach (var para in paras)
            {
                var parameter = new ParameterInfo
                {
                    code = para.code,
                    name = para.name,
                    id = para.id,
                    type = para.type,
                    unit = para.unit
                };
                if (parameter.type == 2)
                {
                    parameter.selectValue = GetParameterCode(parameter.id);
                }

                var value = toolParameterValues?.FirstOrDefault(q => q.parameter_id == para.id);
                if (value != null)
                {
                    parameter.code = value.parameter_value;
                }

                result.Add(parameter);
            }

            return result;
        }

        private List<RequestKeyValue> GetParameterCode(int paraId)
        {
            var result = new List<RequestKeyValue>();
            var extends = _extendRepository.GetList(q =>
                q.parameter_id == paraId && q.project_id == ProjectId &&
                q.status == (int)RowState.Valid);
            if (extends.Any())
            {
                foreach (var extend in extends.ToList())
                {
                    result.Add(new RequestKeyValue
                    {
                        key = extend.key,
                        value = extend.value
                    });
                }
            }
            return result;
        }

        [HttpGet]
        public IActionResult GetAllTools(int type)
        {
            var entities = _toolRepository.GetToolList(new List<int>(), 0, ProjectId).ToList();

            return new ObjectResult(entities);
        }

        [HttpGet]
        public IActionResult GetMaterials(string category, string name, string cutter_number, string product_id, string route, string tool_code)
        {
            var materials = _toolRepository.GetMaterials(
                new RequestGetMaterial
                {
                    category = category,
                    cutter_number = cutter_number,
                    name = name,
                    product_id = product_id,
                    projectid = ProjectId,
                    route = route,
                    tool_code = tool_code
                }).ToList();
            return new ObjectResult(materials);
        }

        [HttpGet]
        public IActionResult GetMaterialList(string material_id, string part_no,int count)
        {
            var res = _toolRepository.GetMaterialList(material_id.ToInt(), part_no,count, ProjectId).ToList();
            return new ObjectResult(res);
        }

        /// <summary>
        /// 物料信息获取
        /// </summary>
        /// <param name="material_id">物料id</param>
        /// <param name="part_no">物料编号</param>
        /// <param name="name">物料名称</param>
        /// <param name="count">取出个数（默认为0）</param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialListEx(string material_id, string part_no, string name, int count)
        {
            var res = _toolRepository.GetMaterialListEx(material_id.ToInt(), part_no, name, count, ProjectId).ToList();
            return new ObjectResult(res);
        }

        /// <summary>
        /// 扫描批次号/序号获取物料供应商和物料状态
        /// </summary>
        /// <param name="serial_number"></param>
        /// <param name="machineid"></param>
        /// <param name="cutter_number"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetToolMaterialInfos(string serial_number, string machineid, string cutter_number)
        {
            var res = new ResponseGetToolMaterialInfos();
            siger_wms_stock stock;
            if (!string.IsNullOrWhiteSpace(serial_number))
            {
                res.serial_number = serial_number;
                stock = _toolRepository.GetStockTrace(serial_number, 0, ProjectId);
                if (stock == null)
                {
                    throw new BadRequestException(RequestEnum.StockNotExist);
                }
            }
            else if (machineid.ToInt() > 0 && !string.IsNullOrEmpty(cutter_number))
            {
                var toolInstall = _toolInstallRepository.GetList(t =>
                        t.machine_code == machineid && t.cutter_number == cutter_number && t.project_id == ProjectId &&
                        t.status == (int)RowState.Valid).OrderByDescending(t => t.uninstall_time).FirstOrDefault();
                if (toolInstall != null)
                {
                    res.serial_number = toolInstall.tool_code;
                    stock = _toolRepository.GetStockTrace(toolInstall.tool_code, 0, ProjectId);
                    if (stock == null)
                    {
                        throw new BadRequestException(RequestEnum.StockNotExist);
                    }
                }
                else
                {
                    throw new BadRequestException(CommonEnum.NoData);
                }
            }
            else
            {
                throw new BadRequestException(RequestEnum.SelectData);
            }

            var tool = _toolRepository.Get(t =>
                t.material_id == stock.material_id && t.project_id == ProjectId && t.status == (int)RowState.Valid);
            if (tool == null)
            {
                throw new BadRequestException(RequestEnum.ToolNotFound);
            }
            if (tool.grind == (int)NeedGrindStatus.Yes)
            {
                res.MaterialStatus.Add(new ResponseKeyValue(((int)StorageCategory.Grinding).ToString(), EnumHelper.GetEnumDesc(StorageCategory.Grinding)));
                res.MaterialStatus.Add(new ResponseKeyValue(((int)StorageCategory.Recovery).ToString(), EnumHelper.GetEnumDesc(StorageCategory.Recovery)));
                res.MaterialStatus.Add(new ResponseKeyValue(((int)StorageCategory.Abandonment).ToString(), EnumHelper.GetEnumDesc(StorageCategory.Abandonment)));
            }
            else
            {
                res.MaterialStatus.Add(new ResponseKeyValue(((int)StorageCategory.Recovery).ToString(), EnumHelper.GetEnumDesc(StorageCategory.Recovery)));
                res.MaterialStatus.Add(new ResponseKeyValue(((int)StorageCategory.Abandonment).ToString(), EnumHelper.GetEnumDesc(StorageCategory.Abandonment)));
            }

            res.part_no = tool.part_no;
            res.material_id = tool.material_id;
            res.material_name = _toolRepository.GetMaterial(res.material_id, res.part_no, ProjectId)?.name ?? "";
            res.grind = tool.grind;
            res.supplier_id = stock.businessid;
            res.supplier = _toolRepository.GetSupplier(res.supplier_id, ProjectId)?.name ?? "";

            return new ObjectResult(res);
        }

        /// <summary>
        /// 获取物料和供应商下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetMaterialSuppliers(string material_id, string part_no, string supplier_id, int count, string name)
        {
            var res = new List<ResponseGetMaterialList>();

            var materials = _toolRepository.GetToolMaterialList(material_id.ToInt(), part_no, name, ProjectId).ToList();

            foreach (var material in materials)
            {
                var suppliers = _toolRepository.GetSuppliersByPartNo(material.id, material.part_no, ProjectId).ToList();
                foreach (var supplier in suppliers)
                {
                    if (res.Count(t => t.supplier_id == supplier.id && t.id == material.id) > 0)
                    {
                        continue;
                    }
                    material.supplier = supplier.name;
                    material.supplier_id = supplier.id;
                    var model = Mapper<ResponseGetMaterialList, ResponseGetMaterialList>.Map(material);
                    res.Add(model);
                }
            }

            if (supplier_id.ToInt() > 0)
            {
                res = res.Where(t => t.supplier_id == supplier_id.ToInt()).ToList();
            }
            if (count != 0)
            {
                res = res.Take(count).ToList();
            }
            return new ObjectResult(res);
        }

        /// <summary>
        /// 更换归还页面点击更换获取需要更换的物料信息
        /// </summary>
        /// <param name="material_id"></param>
        /// <param name="supplier_id"></param>
        /// <param name="serial_number"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetStockToolMaterials(string material_id, string supplier_id, string serial_number)
        {
            var stocks = _toolRepository.GetStokcs(material_id.ToInt(), supplier_id.ToInt(), serial_number, ProjectId).ToList();
            return new ObjectResult(stocks.ToList());
        }

        [HttpPost]
        public IActionResult ExportToolInfo([FromBody]RequestExportToolInfo request)
        {
            var toolCates = _categoryRepository.GetList(t => t.name.Contains(request.name) && t.categorys == request.category &&
                t.project_id == ProjectId && t.status == (int)RowState.Valid).ToList();
            var responses = _toolRepository.GetToolInfos(toolCates.Select(t => t.id).ToList(), request.name, TlmSettingCategory.Cutter, ProjectId).ToList();

            if (!responses.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

           
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var temporaryFileName = $"ToolInfo{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);

            var helper = new EpPlusExcelHelper<ToolInfoList>();
            try
            {
                var list = new List<ToolInfoList>();
                var index = 1;
                foreach (var tool in responses)
                {
                    var toolCate = _categoryRepository.Get(t => t.id == tool.category_id && t.project_id == ProjectId && t.status == (int)RowState.Valid);
                    var entity = new ToolInfoList
                    {
                        Category = toolCate?.name ?? "",
                        CategoryCode = toolCate?.code ?? "",
                        ToolCode = tool.number,
                        ToolName = tool.name,
                        PartNo = tool.part_no,
                        IsGrind = tool.grind > 0 ? EnumHelper.GetEnumDesc((NeedGrindStatus)tool.grind) : "",
                        GrindTimes = tool.grind_times.ToString(),
                        GrindType = tool.grind_type > 0 ? EnumHelper.GetEnumDesc((GrindTypeStatus)tool.grind_type) : "",
                        UseTimes = tool.use_times.ToString(),
                        need_test = tool.need_test == 1 ? "是" : tool.need_test == 2 ? "否" : "",
                        need_detection = tool.need_detection == 1 ? "是" : tool.need_detection == 2 ? "否" : "",
                    };
                    list.Add(entity);
                    index++;
                }

                helper.GenerateExcel(list, fileName);
                return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
            }
            catch (Exception e)
            {
                Logger.WriteLineError("ExportToolInfo failed, error: " + e.Message);
                throw new BadRequestException(RequestEnum.ExportFailed);
            }
            finally
            {
                helper.Dispose();
            }
        }

    }
}