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

namespace Siger.ApiQMS.Controllers
{
    public class InspectStandardMaterialController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly IInspectStandardMaterialRepository _inspectStandard;
        private readonly IInspectUnhealthyRepository _inspectUnhealthy;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        private readonly ISigerTrMaterialsRepository _materialsRepository;
        private readonly IInspectStandardCategoryRepository _standardCategoryRepository;
        private readonly IInspectStandardItemRepository _standardItemRepository;
        public InspectStandardMaterialController(IUnitOfWork unitOfWork, IInspectStandardMaterialRepository inspectStandard,
            IInspectUnhealthyRepository inspectUnhealthy, ISigerProjectLevelSectionRepository levelSectionRepository, 
            ISigerProjectLevelRepository levelRepository, ISigerTrMaterialsRepository materialsRepository,
            IInspectStandardCategoryRepository standardCategoryRepository, IInspectStandardItemRepository standardItemRepository)
        {
            _unitOfWork = unitOfWork;
            _inspectStandard = inspectStandard;
            _inspectUnhealthy = inspectUnhealthy;
            _materialsRepository = materialsRepository;
            _levelSectionRepository = levelSectionRepository;
            _levelRepository = levelRepository;
            _standardCategoryRepository = standardCategoryRepository;
            _standardItemRepository = standardItemRepository;
        }

        [HttpGet]
        public IActionResult GetPageList(int materialid, int sectionid, int page,int pagesize)
        {
            var sectionIds = new List<int>();
            if(sectionid > 0)
            {
                sectionIds = _levelSectionRepository.GetLevelSectionIds(sectionid, ProjectId).ToList();
            }
            var data = new List<RepsonseInspectStandardMaterial>();
            var res = _inspectStandard.GetPagedList(materialid, sectionIds, ProjectId, page, pagesize);
            var levelSections = _levelSectionRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            foreach(var item in res.Data)
            {
                var model = Mapper<RepsonseInspectStandardMaterial, RepsonseInspectStandardMaterial>.Map(item);
                model.section_value = ChannelSectionHelper.GetChannelSection(item.sectionid, levelSections);
                data.Add(model);
            }
            return new PagedObjectResult(data, res.Total, page, pagesize);
        }

        [HttpGet]
        public IActionResult GetStandard(int id)
        {
            var standard = _inspectStandard.GetData(id, ProjectId);
            if(standard != null)
            {
                var sections = new List<int>();
                var sectionIds = GetSectionIds(sections, standard.sectionid);
                sectionIds.Reverse();
                standard.sectionids = sectionIds;
            }
            return new ObjectResult(standard ?? new RepsonseInspectStandardMaterial());
        }

        private List<int> GetSectionIds(List<int> sectionIds, int parentId)
        {
            var section = _levelSectionRepository.Get(t => t.id == parentId && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if(section != null)
            {
                sectionIds.Add(section.id);
                return GetSectionIds(sectionIds, section.parentid);
            }
            else
            {
                return sectionIds;
            }
        }

        [HttpPost]
        public IActionResult Delete([FromBody]RequestDeleteParameter req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }
            var models = _inspectStandard.GetList(t =>
                req.ids.Contains(t.id) && t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            if (!models.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var isDelSuccess = false;
            var Ids = models.Select(q => q.id).ToList();
            var updatedIds = new List<int>();
            foreach (var model in models)
            {
                model.status = (int)RowState.Invalid;
                _inspectStandard.Update(model);
                var items = _inspectStandard.GetList(t =>
                    t.projectid == ProjectId && t.status == (int)RowState.Valid && t.sectionid == model.sectionid
                    && t.materialid == model.materialid && !Ids.Contains(t.id) && !updatedIds.Contains(t.id)).OrderBy(t => t.seq).ToList();
                updatedIds.AddRange(items.Select(t => t.id).ToList());
                if (items.Any())
                {
                    int i = 1;
                    foreach (var item in items)
                    {
                        item.seq = i;
                        _inspectStandard.Update(item);
                        i++;
                    }
                }
                if (_unitOfWork.Commit() > 0)
                {
                    isDelSuccess = true;
                }
            }
            if (isDelSuccess)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult AddStandard([FromBody]RequestAddInspectStandardMaterial req)
        {
            if (req.materialid <= 0 || req.sectionid <= 0 || string.IsNullOrEmpty(req.item) ||
                (req.value_type == (int)CheckType_Status.V && string.IsNullOrEmpty(req.max_value) &&
                 string.IsNullOrEmpty(req.min_value)) || string.IsNullOrEmpty(req.standard))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            if (string.IsNullOrEmpty(req.max_value) && !string.IsNullOrEmpty(req.min_value) && req.value_type == (int)ValueTypeStatus.V)
            {
                req.max_value = QmsLimitValue.MaxValue;
            }
            if (!string.IsNullOrEmpty(req.max_value) && string.IsNullOrEmpty(req.min_value) && req.value_type == (int)ValueTypeStatus.V)
            {
                req.min_value = QmsLimitValue.MinValue;
            }
            var max = req.max_value.ToDouble();
            var min = req.min_value.ToDouble();
            if (req.value_type == (int)CheckType_Status.V)
            {
                if (max < min)
                {
                    throw new BadRequestException(RequestEnum.MaxMinError);
                }
            }
            if (req.item.Length > 200)
            {
                throw new BadRequestException(RequestEnum.InspectItemExceedWordLimit);
            }
            if (req.standard.Length > 200)
            {
                throw new BadRequestException(RequestEnum.InspectStandardExceedWordLimit);
            }
            if((req.value_category.ToInt() == (int)ValueCategory.Maxmin && string.IsNullOrEmpty(req.range)) || req.seq.ToInt() <= 0 ||
                (req.value_type == (int)ValueTypeStatus.V && req.value_category.ToInt() <= 0))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var maxLevel = _levelRepository.GetList(t => t.status == (int)RowState.Valid && t.projectid == ProjectId).Max(q => q.id);
            var section = _levelSectionRepository.Get(t => t.status == (int)RowState.Valid && t.projectid == ProjectId && t.id == req.sectionid);
            if(section == null || section.levelid != maxLevel)
            {
                throw new ServerException(1052);
            }

            var material = _materialsRepository.Get(t =>
                t.id == req.materialid && t.status == (int)RowState.Valid && t.projectId == ProjectId);
            if (material == null)
            {
                throw new BadRequestException(RequestEnum.MaterialNotExist);
            }

            var unhealthyCode = _inspectUnhealthy.Get(t =>
                t.id == req.unhealthy_id && t.status == (int)RowState.Valid && t.projectid == ProjectId);
            if (unhealthyCode == null)
            {
                throw new BadRequestException(RequestEnum.UnhealthyCodeNotFound);
            }

            var category = _standardCategoryRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.id == req.categoryid);
            if(category == null)
            {
                throw new BadRequestException(RequestEnum.CategoryNotNull);
            }

            var queryItem = _inspectStandard.Get(t =>
                t.materialid == req.materialid && t.sectionid == req.sectionid &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid && t.item == req.item);
            if (queryItem != null)
            {
                throw new BadRequestException(RequestEnum.InspectItemRepeat);
            }

            var querySeq = _inspectStandard.Get(t => t.sectionid == req.sectionid && t.materialid == req.materialid &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid && t.seq == req.seq.ToInt());
            if(querySeq != null)
            {
                throw new BadRequestException(RequestEnum.ItemSeqExsit);
            }

            var time = UnixTimeHelper.GetNow();
            //var totoals = _inspectStandard.GetList(t => t.sectionid == req.sectionid && t.materialid == req.materialid && t.projectid == ProjectId && t.status == (int)RowState.Valid).Count();
            var model = new siger_qms_inspection_standard_material
            {
                materialid = material.id,
                sectionid = req.sectionid,
                standard = req.standard ?? "",
                seq = req.seq.ToInt(),//totoals > 0 ? totoals + 1 : 1,
                item = req.item,
                unit = req.value_type == (int)ValueTypeStatus.O ? "" : req.unit ?? "",
                max_value = req.value_type == (int)ValueTypeStatus.O ? 0 : Math.Round(max, 4),
                min_value = req.value_type == (int)ValueTypeStatus.O ? 0 : Math.Round(min, 4),
                unhealthy_desc = unhealthyCode.name ?? "",
                value_type = req.value_type,
                create_mid = UserId,
                create_time = time,
                update_mid = UserId,
                update_time = time,
                projectid = ProjectId,
                status = (int)RowState.Valid,
                unhealthy_id = unhealthyCode.id,
                unhealthy_code = unhealthyCode.code,
                value_category = req.value_category.ToInt(),
                categoryid = req.categoryid,
                range = req.range.ToDouble()
            };
            _inspectStandard.Insert(model);
            if (_unitOfWork.Commit() > 0)
            {
                return new ObjectResult(CommonEnum.Succefull);
            }
            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpPost]
        public IActionResult EditStandard([FromBody]RequestEditInspectStandardMaterial req)
        {
            var model = _inspectStandard.Get(t => t.id == req.id && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (model == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            if (string.IsNullOrEmpty(req.item) ||
                (req.value_type == (int)CheckType_Status.V && string.IsNullOrEmpty(req.max_value) 
                && string.IsNullOrEmpty(req.min_value)) || string.IsNullOrEmpty(req.standard))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            if (string.IsNullOrEmpty(req.max_value) && !string.IsNullOrEmpty(req.min_value) && req.value_type == (int)ValueTypeStatus.V)
            {
                req.max_value = QmsLimitValue.MaxValue;
            }
            if (!string.IsNullOrEmpty(req.max_value) && string.IsNullOrEmpty(req.min_value) && req.value_type == (int)ValueTypeStatus.V)
            {
                req.min_value = QmsLimitValue.MinValue;
            }
            var max = req.max_value.ToDouble();
            var min = req.min_value.ToDouble();
            if (req.value_type == (int)CheckType_Status.V)
            {
                if (max < min)
                {
                    throw new BadRequestException(RequestEnum.MaxMinError);
                }
            }
            if (req.item.Length > 200)
            {
                throw new BadRequestException(RequestEnum.InspectItemExceedWordLimit);
            }
            if (req.standard.Length > 200)
            {
                throw new BadRequestException(RequestEnum.InspectStandardExceedWordLimit);
            }
            if ((req.value_category.ToInt() == (int)ValueCategory.Maxmin && string.IsNullOrEmpty(req.range)) || req.seq.ToInt() <= 0 ||
                (req.value_type == (int)ValueTypeStatus.V && req.value_category.ToInt() <= 0))
            {
                throw new BadRequestException(RequestEnum.ParameterMiss);
            }

            var maxLevel = _levelRepository.GetList(t => t.status == (int)RowState.Valid && t.projectid == ProjectId).Max(q => q.id);
            var section = _levelSectionRepository.Get(t => t.status == (int)RowState.Valid && t.projectid == ProjectId && t.id == req.sectionid);
            if (section == null || section.levelid != maxLevel)
            {
                throw new ServerException(1052);
            }

            var material = _materialsRepository.Get(t =>
                t.id == req.materialid && t.status == (int)RowState.Valid && t.projectId == ProjectId);
            if (material == null)
            {
                throw new BadRequestException(RequestEnum.MaterialNotExist);
            }

            var unhealthyCode = _inspectUnhealthy.Get(t =>
                t.id == req.unhealthy_id && t.status == (int)RowState.Valid && t.projectid == ProjectId);
            if(unhealthyCode == null)
            {
                throw new BadRequestException(RequestEnum.UnhealthyCodeNotFound);
            }

            var category = _standardCategoryRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                t.id == req.categoryid);
            if (category == null)
            {
                throw new BadRequestException(RequestEnum.CategoryNotNull);
            }

            var queryItem = _inspectStandard.Get(t =>
                t.materialid == req.materialid && t.sectionid == req.sectionid &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid && t.item == req.item && t.id != model.id);
            if (queryItem != null)
            {
                throw new BadRequestException(RequestEnum.InspectItemRepeat);
            }

            var querySeq = _inspectStandard.Get(t => t.sectionid == req.sectionid && t.materialid == req.materialid &&
                t.projectid == ProjectId && t.status == (int)RowState.Valid && t.seq == req.seq.ToInt() && t.id != req.id);
            if (querySeq != null)
            {
                throw new BadRequestException(RequestEnum.ItemSeqExsit);
            }

            var time = UnixTimeHelper.GetNow();
            model.standard = req.standard ?? "";
            model.item = req.item;
            model.unit = req.value_type == (int)ValueTypeStatus.O ? "" : req.unit ?? "";
            model.max_value = req.value_type == (int)ValueTypeStatus.O ? 0 : Math.Round(max, 4);
            model.min_value = req.value_type == (int)ValueTypeStatus.O ? 0 : Math.Round(min, 4);
            model.unhealthy_code = unhealthyCode.code ?? "";
            model.unhealthy_desc = unhealthyCode.name ?? "";
            model.value_type = req.value_type;
            model.update_mid = UserId;
            model.update_time = time;
            model.unhealthy_id = req.unhealthy_id;
            model.materialid = material.id;
            model.sectionid = req.sectionid;
            model.seq = req.seq.ToInt();
            model.value_category = req.value_category.ToInt();
            model.categoryid = req.categoryid;
            model.range = req.range.ToDouble();

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

        [HttpGet]
        public IActionResult ExportExcelStandard(int materialid, int sectionid)
        {
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);

            var sectionIds = new List<int>();
            if (sectionid > 0)
            {
                sectionIds = _levelSectionRepository.GetLevelSectionIds(sectionid, ProjectId).ToList();
            }
            var data = _inspectStandard.GetDataList(materialid, sectionIds, ProjectId).ToList();
            if (!data.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            var levelSections = _levelSectionRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var dataList = new List<InspectionStandardMaterialTemplate>();
            foreach (var item in data)
            {
                dataList.Add(new InspectionStandardMaterialTemplate
                {
                    materialpn = item.materialpn,
                    materialname = item.materialname,
                    materialspec = item.materialspec,
                    section = ChannelSectionHelper.GetChannelSection(item.sectionid, levelSections),
                    seq = item.seq,
                    item = item.item,
                    standard = item.standard,
                    value_type = item.value_type.ToString(),
                    unit = item.value_type == (int)ValueTypeStatus.V ? item.unit : "",
                    max_value = item.value_type == (int)ValueTypeStatus.V ? (item.max_value.ToStr() == QmsLimitValue.MaxValue ? "" : item.max_value.ToStr()) : "",
                    min_value = item.value_type == (int)ValueTypeStatus.V ? (item.min_value.ToStr() == QmsLimitValue.MinValue ? "" : item.min_value.ToStr()) : "",
                    unhealthy_code = item.unhealthy_code,
                    unhealthy_category = item.unhealthy_category_name,
                    unhealthy_name = item.unhealthy_name,
                    update_mid = item.update_mid,
                    update_time = item.update_time,
                    category = item.categoryname,
                    value_category = item.value_category.ToStr(),
                    range = item.range.ToStr(),
                });
            }
            if (dataList.Any())
            {
                EpPlusExcelHelper<InspectionStandardMaterialTemplate> helper = null;
                try
                {
                    helper = new EpPlusExcelHelper<InspectionStandardMaterialTemplate>();
                    var temporaryFileName = $"物料检验标准维护信息_InspectionStandardInfo_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                    helper.GenerateExcel(dataList, Path.Combine(rootDir, temporaryFileName));
                    return new ObjectResult($"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}");
                }
                catch (Exception e)
                {
                    Logger.WriteLineError("Export Inspection Standard Info failed, error:" + e);
                    throw new BadRequestException(RequestEnum.ExportFailed);
                }
                finally
                {
                    helper?.Dispose();
                }
            }

            throw new BadRequestException(CommonEnum.Fail);
        }

        [HttpGet]
        public IActionResult GetTemplate()
        {
            

            return new ObjectResult(CreateInspectionStandardTemplate());
        }

        private string CreateInspectionStandardTemplate()
        {
            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(InspectStandardMaterialLevelTemplate), _levelRepository.GetProjectLanguage(ProjectId)));
            var rootDir = FileSystemHelper.GetPhysicalFolders(FileSystemHelper.CommonFileSetting.PhysicalFolder, FileSystemHelper.ExportFileName);
            var temporaryFileName = $"InspectionStandardTemplate_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var fileName = Path.Combine(rootDir, temporaryFileName);
            helper.GenerateExcel(columnNames, fileName);
            
            return $"{FileSystemHelper.CommonFileSetting.RequestPath}/{FileSystemHelper.ExportFileName}/{temporaryFileName}";
        }

        [HttpGet]
        public IActionResult GetMaterialsBySectionId(string sectionid, string reverselevel = "1")
        {
            if (reverselevel.ToInt() != 1 && reverselevel.ToInt() != 2)
            {
                return new ObjectResult(new List<ResponseIdName>());
            }
            var levels = _levelRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).OrderByDescending(t => t.id).ToList();
            var levelSection = _levelSectionRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid && t.id == sectionid.ToInt());
            if (!levels.Any() || levels.Count <= 2 || levelSection == null)
            {
                return new ObjectResult(new List<ResponseIdName>());
            }
            var sectionIds = new List<int>();
            if (reverselevel.ToInt() == 1)
            {
                if (levels[0].id != levelSection.levelid)
                {
                    return new ObjectResult(new List<ResponseIdName>());
                }
                sectionIds.Add(sectionid.ToInt());
            }
            else if (reverselevel.ToInt() == 2)
            {
                if (levels[1].id > levelSection.levelid)
                {
                    return new ObjectResult(new List<ResponseIdName>());
                }
                sectionIds = _levelSectionRepository.GetLevelSectionIds(sectionid.ToInt(), ProjectId).ToList();
            }
            var materialIds = _inspectStandard.GetList(t => sectionIds.Contains(t.sectionid) && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid).Select(t => t.materialid).ToList();
            var materials = _materialsRepository.GetList(t => materialIds.Contains(t.id) && t.projectId == ProjectId &&
                t.status == (int)RowState.Valid).Select(t => new
                {
                    t.id,
                    t.name,
                    t.pn,
                    t.spec
                }).ToList();

            return new ObjectResult(materials);
        }

        /// <summary>
        /// 从检验项目表取工位得到产线结构
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetSectionTree()
        {
            var itemSectionIds = _inspectStandard.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid)
                .Select(t => t.sectionid).ToList();
            var levels = _levelRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var maxLevel = levels.Max(q => q.id);
            var sections = _levelSectionRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid);
            var itemSections = sections.Where(t => itemSectionIds.Contains(t.id) && t.levelid == maxLevel).ToList();
            var inSections = new List<siger_project_level_section>();
            foreach (var section in itemSections)
            {
                var parentSections = new List<siger_project_level_section>();
                int pid = section.parentid;
                foreach (var level in levels)
                {
                    if (level.id == maxLevel)
                    {
                        parentSections.Add(section);
                        pid = section.parentid;
                    }
                    else
                    {
                        var parentSection = sections.FirstOrDefault(t => t.id == pid);
                        if (parentSection != null)
                        {
                            pid = parentSection.parentid;
                            parentSections.Add(parentSection);
                        }
                    }
                }
                inSections.AddRange(parentSections);
            }
            inSections = inSections.GroupBy(t => t.id).Select(t => t.FirstOrDefault()).ToList();

            var resp = ChannelSectionHelper.GetSectionChildren(0, ProjectId, maxLevel, inSections);
            return new ObjectResult(resp);
        }

        [HttpGet]
        public IActionResult GetItemLevelSection(int reverselevel, int parentid)
        {
            var levels = _levelRepository.GetList(t => t.status == (int)RowState.Valid && t.projectid == ProjectId).OrderByDescending(t => t.id).ToList();
            if (levels.Count < reverselevel)
            {
                throw new BadRequestException(RequestEnum.LevelNotFound);
            }
            var res = _levelSectionRepository.GetSectionIdNamesByLevel(levels[reverselevel - 1].id, parentid, ProjectId).ToList();
            if (reverselevel == 2)
            {
                var itemSectionIds = _inspectStandard.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid)
                        .Select(t => t.sectionid).ToList();
                var channelIds = _levelSectionRepository.GetList(t => itemSectionIds.Contains(t.id)).Select(t => t.parentid).ToList();
                res = res.Where(t => channelIds.Contains(t.id)).ToList();
            }
            if (reverselevel == 1)
            {
                var itemSectionIds = _inspectStandard.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                        res.Select(q => q.id).Contains(t.sectionid)).Select(t => t.sectionid).ToList();
                res = res.Where(t => itemSectionIds.Contains(t.id)).ToList();
            }
            return new ObjectResult(res);
        }

        /// <summary>
        /// 编辑页面获取详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetDetails(int materialid, int sectionid, string number)
        {
            var res = new ResponseDataCollectionDetailList();
            var standards = _inspectStandard.GetList(t =>
                t.materialid == materialid && t.sectionid == sectionid && t.projectid == ProjectId
                && t.status == (int)RowState.Valid).ToList();
            var categorys = _standardCategoryRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                standards.Select(q => q.categoryid).Contains(t.id)).ToList();
            var standardItems = _standardItemRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                categorys.Select(q => q.id).Contains(t.categoryid)).ToList();
            foreach (var standard in standards)
            {
                var quantity = 0;
                var category = categorys.FirstOrDefault(t => t.id == standard.categoryid);
                if(category != null)
                {
                    var items = standardItems.Where(t => t.categoryid == category.id).ToList();
                    if (!items.Any())
                    {
                        continue;
                    }
                    foreach (var item in items)
                    {
                        if ((item.upperlimit.HasValue && item.lowerlimit.HasValue && number.ToInt() <= item.upperlimit && number.ToInt() >= item.lowerlimit ||
                            item.upperlimit.HasValue && !item.lowerlimit.HasValue && number.ToInt() <= item.upperlimit ||
                            !item.upperlimit.HasValue && item.lowerlimit.HasValue && number.ToInt() >= item.lowerlimit) &&
                            quantity < item.samplequantity)
                        {
                            quantity = item.samplequantity;
                        }
                    }
                }
                var model = new ResponseDataCollectionDetails
                {
                    id = 0,
                    itemid = standard.id,
                    max_value = standard.max_value,
                    min_value = standard.min_value,
                    result = "",
                    value = null,
                    item = standard.item,
                    standard = standard.standard,
                    checktype = standard.value_type,
                    valuecategory = standard.value_category,
                    range = standard.range,
                    samplequantity = quantity
                };
                res.details.Add(model);
            }
            res.quantity = res.details.Any() ? res.details.Max(t => t.samplequantity) : 0;
            return new ObjectResult(res);
        }

        [HttpGet]
        public IActionResult GetStandardMaterials(string sectionid, string distinct = "0")
        {
            var materialIds = new List<int>();
            var sectionIds = new List<int>();
            if (sectionid.ToInt() > 0)
            {
                sectionIds = _levelSectionRepository.GetLevelSectionIds(sectionid.ToInt(), ProjectId).ToList();
            }
            var data = _inspectStandard.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if (sectionid.ToInt() > 0)
            {
                data = data.Where(t => sectionIds.Contains(t.sectionid));
            }
            materialIds = data.Select(t => t.materialid).Distinct().ToList();
            var res = _materialsRepository.GetList(t => t.projectId == ProjectId && t.status == (int)RowState.Valid &&
                materialIds.Contains(t.id)).Select(q => new
                {
                    q.id,
                    q.name,
                    q.spec,
                    q.pn
                }).ToList();

            res = distinct.ToInt() > 0 ? res.GroupBy(t => t.name).Select(t => t.FirstOrDefault()).ToList() : res;
            return new ObjectResult(res);
        }
    }
}