using Microsoft.AspNetCore.Mvc;
using Siger.Middlelayer.Common;
using Siger.Middlelayer.Repository;
using System.Linq;
using Siger.Middlelayer.QmsRepository.Repositories.Interface;
using Siger.Middlelayer.QmsRepository.Request;
using Siger.Middlelayer.Redis.Repositories;
using Siger.ApiCommon.Result;
using Siger.Middlelayer.Redis.RedisEntities;
using System.Collections.Generic;
using Siger.Middlelayer.QmsRepository.Response;
using System.Linq.Expressions;
using System;
using Siger.Middlelayer.Repository.Repositories.Interface;
using Siger.Middlelayer.Common.Extensions;
using Siger.Middlelayer.Repository.Extensions;
using Siger.Middlelayer.Repository.Response;
using Siger.Middlelayer.QmsRepository.Entities;
using Siger.Middlelayer.Log;
using Siger.ApiQMS.Utility;

namespace Siger.ApiQMS.Controllers
{
    public class ParameterConfigController : BaseController
    {
        private readonly IUnitOfWork _unitOfWork;
        private readonly ISigerProjectLevelSectionRepository _levelSectionRepository;
        private readonly ISigerProjectLevelRepository _levelRepository;
        private readonly IInspectStandardRepository _standardRepository;
        private readonly ISigerProjectMachineRepository _machineRepository;
        private readonly ISigerUserRepository _userRepository;
        private readonly ISigerDict _sigerDict;
        private readonly IDefaultInfoConfigRepository _defaultInfoConfig;
        private readonly ISigerProjectMachineAttributionRepository _machineAttributionRepository;
        private readonly IParameterMaintainConfigRepository _parameterMaintain;
        private readonly ISigerProjectProductRepository _productRepository;
        public ParameterConfigController(IUnitOfWork unitOfWork, ISigerProjectLevelSectionRepository levelSectionRepository,
            ISigerProjectLevelRepository levelRepository, IInspectStandardRepository standardRepository,
            ISigerProjectMachineRepository machineRepository, ISigerUserRepository userRepository, ISigerDict sigerDict,
            IDefaultInfoConfigRepository defaultInfoConfig, ISigerProjectMachineAttributionRepository machineAttributionRepository,
            IParameterMaintainConfigRepository parameterMaintain, ISigerProjectProductRepository productRepository)
        {
            _unitOfWork = unitOfWork;
            _levelSectionRepository = levelSectionRepository;
            _levelRepository = levelRepository;
            _standardRepository = standardRepository;
            _machineRepository = machineRepository;
            _userRepository = userRepository;
            _sigerDict = sigerDict;
            _defaultInfoConfig = defaultInfoConfig;
            _machineAttributionRepository = machineAttributionRepository;
            _parameterMaintain = parameterMaintain;
            _productRepository = productRepository;
        }

        #region DefaultInfo_Config表配置

        [HttpGet]
        public IActionResult GetPageList(string key, int sectionid, int machineid, string field, string configtype, string starttime, string endtime, int page, int pagesize)
        {
            Expression<Func<siger_qms_defaultinfo_config, bool>> projectExpression = q => q.projectid == ProjectId && q.status == (int)RowState.Valid;
            Expression<Func<siger_qms_defaultinfo_config, bool>> keyExpression = q => true;
            if (!string.IsNullOrEmpty(key))
            {
                keyExpression = q => q.key.Contains(key);
            }
            Expression<Func<siger_qms_defaultinfo_config, bool>> machineExpression = q => true;
            if (machineid > 0)
            {
                machineExpression = q => q.machineid == machineid;
            }
            var sectionIds = new List<int>();
            if (sectionid > 0)
            {
                sectionIds = _levelSectionRepository.GetLevelSectionIds(sectionid, ProjectId).ToList();
            }
            Expression<Func<siger_qms_defaultinfo_config, bool>> sectionExpression = q => true;
            if (sectionIds.Any())
            {
                sectionExpression = q => sectionIds.Contains(q.sectionid);
            }
            Expression<Func<siger_qms_defaultinfo_config, bool>> typeExpression = q => true;
            if (!string.IsNullOrEmpty(field))
            {
                typeExpression = q => q.field == field;
            }
            Expression<Func<siger_qms_defaultinfo_config, bool>> configtypeExpression = q => true;
            if (!string.IsNullOrEmpty(configtype))
            {
                configtypeExpression = q => q.iscfg == configtype.ToInt();
            }
            Expression<Func<siger_qms_defaultinfo_config, bool>> timeExpression = q => true;
            if (!string.IsNullOrEmpty(starttime) && !string.IsNullOrEmpty(endtime))
            {
                var stime = starttime.ToDateTime();
                var etime = endtime.ToDateTime();
                timeExpression = q => (q.changetime <= etime && q.changetime >= stime);
            }
            
            var expression = keyExpression.And(machineExpression).And(sectionExpression).And(typeExpression)
                    .And(configtypeExpression).And(timeExpression).And(projectExpression);
            var list = _defaultInfoConfig.GetPagedList(page, pagesize, expression, "changetime");

            var resList = new List<ResponseGetParameterConfig>();
            var machines = _machineRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var users = _userRepository.GetList(t => t.status == (int)RowState.Valid).ToList();
            var sections = _levelSectionRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            foreach (var item in list.Data)
            {
                var machine_id = _machineAttributionRepository.Get(t => t.projectid == ProjectId && t.station == item.sectionid &&
                    t.status == (int)RowState.Valid && t.attribution == (int)MachineAttributionEnum.equipment)?.machine ?? 0;
                var machine = machines.FirstOrDefault(t => t.id == machine_id);
                var user = users.FirstOrDefault(t => t.id == item.userid);
                resList.Add(new ResponseGetParameterConfig
                {
                    key = item.key,
                    machineID = item.machineid,
                    machineName = machine?.title ?? "",
                    type = item.type,
                    field = item.field,
                    SectionID = item.sectionid,
                    SectionName = ChannelSectionHelper.GetChannelSection(item.sectionid, sections),
                    userID = item.userid,
                    userName = user?.nickname ?? "",
                    changeTime = item.changetime.ToString(ParameterConstant.DateTimeFormat),
                    enable = item.enable,
                    iscfg = item.iscfg,
                    description = item.description ?? "",
                });
            }

            return new PagedObjectResult(resList, list.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult ChangeEnable([FromBody]RequestChangeEnable req)
        {
            if (!req.keys.Any())
            {
                throw new BadRequestException(RequestEnum.SelectData);
            }
            var configs = _defaultInfoConfig.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid && 
                req.keys.Contains(t.key)).ToList();            
            foreach (var key in req.keys)
            {
                var entity = configs.FirstOrDefault(t => t.key == key);
                if(entity != null && entity.enable != req.enable && (req.enable == 0 || req.enable == 1))
                {
                    entity.enable = req.enable;
                    _defaultInfoConfig.Update(entity);                    
                }
            }
            if (_unitOfWork.Commit() > 0)
            {
                try
                {
                    var repository = new QMSDefaultInfoConfigRepository(CompanyId, ProjectId, false);
                    try
                    {
                        foreach (var key in req.keys)
                        {
                            UpdateRedisParameterEnable(repository, key, req.enable);
                        }
                        repository.Dispose();
                    }
                    catch
                    {
                        repository.Dispose();
                    }
                }
                catch(Exception ex)
                {
                    Logger.WriteLineError(ex.ToString());
                }
                return new ObjectResult(CommonEnum.Succefull);
            }                       
            throw new BadRequestException(CommonEnum.Fail);
        }

        private void UpdateRedisParameterEnable(QMSDefaultInfoConfigRepository repository, string key, int enable)
        {
            var config = repository.GetSingleByKey(key);
            if(config != null)
            {
                if (config.enable != enable && (enable == 0 || enable == 1))
                {
                    config.iscfg = 1;
                    config.enable = enable;
                    config.changeTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat);
                    repository.SetItemInfoConfig(key, config);
                }
            }
            else
            {
                var model = _defaultInfoConfig.Get(t => t.key == key && t.projectid == ProjectId && t.status == (int)RowState.Valid);
                if(model != null && model.iscfg == 1)
                {
                    var section = _levelSectionRepository.Get(t => t.projectid == ProjectId && t.status == (int)RowState.Valid &&
                        t.id == model.sectionid);
                    config = new QMSDefaultInfoConfig
                    {
                        machineID = model.machineid,
                        type = model.type,
                        field = model.field,
                        SectionID = model.sectionid,
                        SectionName = section?.title ?? "",
                        enable = enable,
                        iscfg = 1,
                        changeTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat),
                    };
                    repository.SetItemInfoConfig(key, config);
                }                
            }
        }

        [HttpPost]
        public IActionResult Update([FromBody]RequestParameterConfig req)
        {
            if (string.IsNullOrEmpty(req.key) || string.IsNullOrEmpty(req.field))
            {
                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 machine = _standardRepository.GetMachineBySectionId(req.SectionID, ProjectId);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.SectionMachineNull);
            }

            var qmsParameter = _sigerDict.GetDictValue(ProjectId, AccDictCost.QmsParameter, req.field);
            if (string.IsNullOrEmpty(qmsParameter))
            {
                throw new BadRequestException(RequestEnum.ParameterTypeNotFound);
            }
            var entity = _defaultInfoConfig.Get(t => t.key == req.key && t.projectid == ProjectId && t.status == (int)RowState.Valid);
            if(entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            entity.sectionid = section.id;
            entity.machineid = machine.id;
            entity.type = qmsParameter;
            entity.field = req.field;
            entity.iscfg = req.iscfg;
            entity.userid = UserId;
            entity.changetime = DateTime.Now;
            entity.description = req.description ?? "";
            _defaultInfoConfig.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                if (req.iscfg == 1)
                {
                    var config = new QMSDefaultInfoConfig
                    {
                        machineID = machine.id,
                        type = qmsParameter,
                        field = req.field,
                        SectionID = req.SectionID,
                        SectionName = section.title,
                        iscfg = req.iscfg,
                        changeTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat)
                    };
                    SetConfig(config, req.key);
                }
                else
                {
                    DeleteConfig(req.key);
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        private void SetConfig(QMSDefaultInfoConfig config, string key)
        {
            try
            {
                var repository = new QMSDefaultInfoConfigRepository(CompanyId, ProjectId, false);
                try
                {
                    var configs = repository.GetAllCofigs();
                    var rmSatet = configs.Remove(key);
                    if (configs.Any() && rmSatet && (configs.Values.FirstOrDefault(t => t.field == config.field &&
                        t.SectionID == config.SectionID && t.machineID == config.machineID) != null))
                    {
                        throw new BadRequestException(RequestEnum.ParameterTypeIsExsit);
                    }

                    repository.SetItemInfoConfig(key, config);
                    repository.Dispose();
                }
                catch
                {                    
                    repository.Dispose();
                }
            }
            catch(Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        private void DeleteConfig(string key)
        {
            try
            {
                var repository = new QMSDefaultInfoConfigRepository(CompanyId, ProjectId, false);
                try
                {
                    var config = repository.GetSingleByKey(key);
                    if(config != null)
                    {
                        repository.DeleteConfig(key);
                    }
                    
                    repository.Dispose();
                }
                catch
                {
                    repository.Dispose();
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
        }

        [HttpGet]
        public IActionResult GetTypeList()
        {
            var dicts = _sigerDict.GetList(t => t.projectId == ProjectId && t.status == (int)RowState.Valid && t.cat == AccDictCost.QmsParameter)
                .Select(t => new ResponseKeyValue(t.dkey, t.dval)).ToList();
            return new ObjectResult(dicts);
        }

        #endregion

        #region ParameterMaintain_Config配置表

        [HttpGet]
        public IActionResult GetParamterPageList(string key, int sectionid, int productid, int itemid, int machineid, string status, string starttime, string endtime, int page, int pagesize)
        {
            Expression<Func<siger_qms_parametermaintain_config, bool>> projectExpression = q => q.projectid == ProjectId;
            Expression<Func<siger_qms_parametermaintain_config, bool>> keyExpression = q => true;
            if (!string.IsNullOrEmpty(key))
            {
                keyExpression = q => (q.value.Contains(key) || q.result.Contains(key));
            }
            Expression<Func<siger_qms_parametermaintain_config, bool>> productExpression = q => true;
            if (productid > 0)
            {
                productExpression = q => q.productid == productid;
            }
            Expression<Func<siger_qms_parametermaintain_config, bool>> statusExpression = q => true;
            if (!string.IsNullOrEmpty(status))
            {
                statusExpression = q => q.status == status.ToInt();
            }
            Expression<Func<siger_qms_parametermaintain_config, bool>> itemExpression = q => true;
            if (itemid > 0)
            {
                itemExpression = q => q.itemid == itemid;
            }
            Expression<Func<siger_qms_parametermaintain_config, bool>> machineExpression = q => true;
            if (machineid > 0)
            {
                machineExpression = q => q.machineid == machineid;
            }
            var sectionIds = new List<int>();
            if (sectionid > 0)
            {
                sectionIds = _levelSectionRepository.GetLevelSectionIds(sectionid, ProjectId).ToList();
            }
            Expression<Func<siger_qms_parametermaintain_config, bool>> sectionExpression = q => true;
            if (sectionIds.Any())
            {
                sectionExpression = q => sectionIds.Contains(q.sectionid);
            }
            Expression<Func<siger_qms_parametermaintain_config, bool>> timeExpression = q => true;
            if (!string.IsNullOrEmpty(starttime) && !string.IsNullOrEmpty(endtime))
            {
                var stime = starttime.ToDateTime();
                var etime = endtime.ToDateTime();
                timeExpression = q => (q.changetime <= etime && q.changetime >= stime);
            }

            var expression = keyExpression.And(sectionExpression).And(timeExpression).And(productExpression).And(itemExpression)
                    .And(projectExpression).And(statusExpression).And(machineExpression);
            var list = _parameterMaintain.GetPagedList(page, pagesize, expression, "changetime");

            var resList = new List<ResponseParameterMaintainConfig>();
            var machines = _machineRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var users = _userRepository.GetList(t => t.status == (int)RowState.Valid).ToList();
            var sections = _levelSectionRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var products = _productRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            var standards = _standardRepository.GetList(t => t.projectid == ProjectId && t.status == (int)RowState.Valid).ToList();
            foreach (var item in list.Data)
            {
                var product = products.FirstOrDefault(t => t.id == item.productid);
                var machine_id = _machineAttributionRepository.Get(t => t.projectid == ProjectId && t.station == item.sectionid &&
                    t.status == (int)RowState.Valid && t.attribution == (int)MachineAttributionEnum.equipment)?.machine ?? 0;
                var machine = machines.FirstOrDefault(t => t.id == machine_id);
                var user = users.FirstOrDefault(t => t.id == item.userid);
                var standard = standards.FirstOrDefault(t => t.id == item.itemid);
                resList.Add(new ResponseParameterMaintainConfig
                {
                    id = item.id,
                    machineID = item.machineid,
                    machineName = machine?.title ?? "",
                    SectionID = item.sectionid,
                    SectionName = ChannelSectionHelper.GetChannelSection(item.sectionid, sections),
                    value = item.value,
                    result = item.result,
                    itemID = item.itemid,
                    itemName = standard?.item ?? "",
                    productID = item.productid,
                    productName = product?.name ?? "",
                    userID = item.userid,
                    userName = user?.nickname ?? "",
                    changeTime = item.changetime.ToString(ParameterConstant.DateTimeFormat),
                    status = item.status//是否停用0->停用1->启用
                });
            }

            return new PagedObjectResult(resList, list.Total, page, pagesize);
        }

        [HttpPost]
        public IActionResult EndEnable([FromBody]RequestDeleteParameter req)
        {
            if(req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.SelectData);
            }

            var items = _standardRepository.GetList(t => t.projectid == ProjectId &&
                t.status == (int)RowState.Valid && t.inspection == 1).ToList();
            var entities = _parameterMaintain.GetList(t => t.projectid == ProjectId && 
                t.status == (int)RowState.Valid && req.ids.Contains(t.id)).ToList();
            if (!entities.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach (var model in entities)
            {
                model.status = (int)RowState.Invalid;
                
                var item = items.FirstOrDefault(t => t.id == model.itemid);
                if (item != null)
                {
                    item.inspection = 0;
                    _standardRepository.Update(item);
                }
                _parameterMaintain.Update(model);                
            }
            if (_unitOfWork.Commit() > 0)
            {
                try
                {
                    var repository = new QMSParameterMaintainConfigRepository(CompanyId, ProjectId, false);
                    try
                    {
                        foreach (var model in entities)
                        {
                            repository.DeleteByKey($"{model.sectionid}_{model.productid}_{model.value}_{model.result}");
                        }
                        repository.Dispose();
                    }
                    catch
                    {
                        repository.Dispose();
                    }                    
                }
                catch(Exception ex)
                {
                    Logger.WriteLineError(ex.ToString());
                }
                return new ObjectResult(CommonEnum.Succefull);//只要mysql中操作成功即可，如果redis没成功让同步线程来同步
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpPost]
        public IActionResult StartEnable([FromBody]RequestDeleteParameter req)
        {
            if (req.ids == null || !req.ids.Any())
            {
                throw new BadRequestException(RequestEnum.SelectData);
            }

            var items = _standardRepository.GetList(t => t.projectid == ProjectId &&
                t.status == (int)RowState.Valid).ToList();
            var entities = _parameterMaintain.GetList(t => t.projectid == ProjectId &&
                t.status == (int)RowState.Invalid && req.ids.Contains(t.id));
            if (!entities.Any())
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }
            foreach (var model in entities)
            {
                model.status = (int)RowState.Valid;
                var item = items.FirstOrDefault(t => t.id == model.itemid && t.inspection == 0);
                if (item != null)
                {
                    item.inspection = 1;
                    _standardRepository.Update(item);
                }
                _parameterMaintain.Update(model);
            }
            if (_unitOfWork.Commit() > 0)
            {
                try
                {
                    var repository = new QMSParameterMaintainConfigRepository(CompanyId, ProjectId, false);
                    try
                    {                        
                        var products = _productRepository.GetList(t => t.projectid == ProjectId &&
                            t.status == (int)RowState.Valid).ToList();
                        var sections = _levelSectionRepository.GetList(t => t.projectid == ProjectId &&
                            t.status == (int)RowState.Valid).ToList();
                        foreach (var model in entities)
                        {
                            var item = items.FirstOrDefault(t => t.id == model.itemid);
                            if (item == null)
                            {
                                continue;
                            }
                            var product = products.FirstOrDefault(t => t.id == model.productid);
                            var section = sections.FirstOrDefault(t => t.id == model.sectionid);
                            var entity = new QMSParameterMaintainConfig
                            {
                                ItemID = model.itemid,
                                ItemName = item.item_en,
                                ProductID = model.productid,
                                ProductName = product?.name ?? "",
                                SectionID = model.sectionid,
                                SectionName = section?.title ?? "",
                                machineID = model.machineid,
                                changeTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat),
                                downlimit = item.min_value,
                                uplimit = item.max_value
                            };
                            repository.SetConfig($"{model.sectionid}_{model.productid}_{model.value}_{model.result}", entity);                                                        
                        }
                        repository.Dispose();
                    }
                    catch
                    {
                        repository.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    Logger.WriteLineError(ex.ToString());
                }
                return new ObjectResult(CommonEnum.Succefull);//只要mysql中操作成功即可，如果redis没成功让同步线程来同步
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpPost]
        public IActionResult AddParameter([FromBody]RequestAddParameterMaintainConfig req)
        {
            if (string.IsNullOrEmpty(req.Value) || string.IsNullOrEmpty(req.Result))
            {
                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 machine = _standardRepository.GetMachineBySectionId(req.SectionID, ProjectId);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.SectionMachineNull);
            }

            var item = _standardRepository.Get(t => t.id == req.ItemID && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid);
            if (item == null)
            {
                throw new BadRequestException(RequestEnum.CheckItemNotFound);
            }

            var product = _productRepository.Get(t => t.id == req.ProductID && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid);
            if (product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }

            var exsit = _parameterMaintain.Get(t => t.projectid == ProjectId &&
                t.status == (int)RowState.Valid && t.productid == req.ProductID && t.sectionid == req.SectionID &&
                t.value == req.Value && t.result == req.Result);
            if (exsit != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            var entity = new siger_qms_parametermaintain_config
            {
                sectionid = section.id,
                machineid = machine.id,
                itemid = req.ItemID,
                itemname = item.item_en,
                value = req.Value,
                result = req.Result,
                userid = UserId,
                productid = req.ProductID,
                changetime = DateTime.Now,
                projectid = ProjectId
            };
            if (item.inspection == 0)
            {
                item.inspection = 1;
                _standardRepository.Update(item);
            }
            _parameterMaintain.Insert(entity);
            if (_unitOfWork.Commit() > 0)
            {
                var config = new QMSParameterMaintainConfig
                {
                    machineID = machine.id,
                    ProductID = req.ProductID,
                    ProductName = product.name,
                    SectionID = req.SectionID,
                    SectionName = section.title,
                    ItemID = req.ItemID,
                    ItemName = item.item_en,
                    changeTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat),
                    uplimit = item.max_value,
                    downlimit = item.min_value,
                };
                try
                {
                    var repository = new QMSParameterMaintainConfigRepository(CompanyId, ProjectId);
                    repository.SetConfig($"{config.SectionID}_{config.ProductID}_{req.Value}_{req.Result}", config);
                }
                catch (Exception ex)
                {
                    Logger.WriteLineError(ex.ToString());
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpPost]
        public IActionResult UpdateParameter([FromBody]RequestParameterMaintainConfig req)
        {
            if (string.IsNullOrEmpty(req.Value) || string.IsNullOrEmpty(req.Result))
            {
                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 machine = _standardRepository.GetMachineBySectionId(req.SectionID, ProjectId);
            if (machine == null)
            {
                throw new BadRequestException(RequestEnum.SectionMachineNull);
            }

            var entity = _parameterMaintain.Get(t => t.id == req.id && t.projectid == ProjectId);
            if (entity == null)
            {
                throw new BadRequestException(CommonEnum.RecordNotFound);
            }

            var item = _standardRepository.Get(t => t.id == req.ItemID && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid);
            if(item == null)
            {
                throw new BadRequestException(RequestEnum.CheckItemNotFound);
            }

            var product = _productRepository.Get(t => t.id == req.ProductID && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid);
            if (product == null)
            {
                throw new BadRequestException(RequestEnum.ProductNotFound);
            }

            var exsit = _parameterMaintain.Get(t => t.id != req.id && t.projectid == ProjectId &&
                t.status == (int)RowState.Valid && t.productid == req.ProductID && t.sectionid == req.SectionID &&
                t.value == req.Value && t.result == req.Result);
            if(exsit != null)
            {
                throw new BadRequestException(CommonEnum.RecordExits);
            }

            entity.sectionid = section.id;
            entity.machineid = machine.id;
            entity.itemid = req.ItemID;
            entity.itemname = item.item_en;
            entity.value = req.Value;
            entity.result = req.Result;
            entity.userid = UserId;
            entity.productid = req.ProductID;
            entity.changetime = DateTime.Now;
            if(item.inspection == 0)
            {
                item.inspection = 1;
                _standardRepository.Update(item);
            }
            _parameterMaintain.Update(entity);
            if (_unitOfWork.Commit() > 0)
            {
                var config = new QMSParameterMaintainConfig
                {
                    machineID = machine.id,
                    ProductID = req.ProductID,
                    ProductName = product.name,
                    SectionID = req.SectionID,
                    SectionName = section.title,
                    ItemID = req.ItemID,
                    ItemName = item.item_en,
                    changeTime = DateTime.Now.ToString(ParameterConstant.DateTimeFormat),
                    uplimit = item.max_value,
                    downlimit = item.min_value,
                };
                try
                {
                    var repository = new QMSParameterMaintainConfigRepository(CompanyId, ProjectId);
                    repository.SetConfig($"{config.SectionID}_{config.ProductID}_{req.Value}_{req.Result}", config);
                }
                catch(Exception ex)
                {
                    Logger.WriteLineError(ex.ToString());
                }
                return new ObjectResult(CommonEnum.Succefull);
            }
            else
            {
                throw new BadRequestException(CommonEnum.Fail);
            }
        }

        [HttpGet]
        public IActionResult GetParameterKeys()
        {
            var res = new List<ResponseKeyValue>();

            try
            {
                var repository = new QMSDefaultInfoConfigRepository(CompanyId, ProjectId);
                res = repository.GetAllCofigs().Select(t => new ResponseKeyValue(t.Key, t.Key)).ToList();                
            }
            catch(Exception ex)
            {
                Logger.WriteLineError(ex.ToString());
            }
            return new ObjectResult(res);
        }

        #endregion
    }
}