//
//  WorkOrderConfiguratorViewController.swift
//  iPOS
//
//  Created by bbc on 22/11/2017.
//  Copyright © 2017 BBC. All rights reserved.
//

import Foundation
import UIKit
import AVKit

enum rowTypeEnum: String {
    case frame     = "FRM"
    case leftLens  = "LNL"
    case rightLens = "LNR"
    case glasses   = "GL"
    case extra     = "SRV"
    case other     = "OTH"
    case defaultService     = "SRD"
}

enum glassesDistanceTypeEnum: String {
    case far = "F"
    case near = "N"
    case intermediate = "I"
    case far_intermediate = "FI"
    case far_near = "FN"
    case near_intermediate = "NI"
    case far_near_intermediate = "FNI"
}

enum DiscountsMode: Int {
    case ManualPrices = 0
    case PromoPrices = 1
    case None = 2
}

protocol WorkOrderConfiguratorViewControllerDelegate {
    func saveConfigurator()
}

class WorkOrderConfiguratorViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate, PriceChangeDelegate, IProductSelectorListener, ScannerViewControllerDelegate, CartItemEditCustomCellDelegate, ClinicalStatusViewContollerDelegate{
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var viewFrame: UIView!
    @IBOutlet weak var viewRightLens: UIView!
    @IBOutlet weak var viewLeftLens: UIView!
    @IBOutlet weak var lfKIT: UILabel!
    @IBOutlet weak var lfFrame: UILabel!
    @IBOutlet weak var ivFrame: UIImageView!
    @IBOutlet weak var lfFrameName: UILabel!
    @IBOutlet weak var lfFrameCode: UILabel!
    @IBOutlet weak var lfFrameGrossValue: UILabel!
    @IBOutlet weak var lfFrameNetValue: UILabel!
    @IBOutlet weak var btFrameMoreActions: UIButton!
    
    @IBOutlet weak var lfRightLens: UILabel!
    @IBOutlet weak var lfRightLensName: UILabel!
    @IBOutlet weak var lfRightLensCode: UILabel!
    @IBOutlet weak var lfRighLensGrossValue: UILabel!
    @IBOutlet weak var lfRightLensNetValue: UILabel!
    @IBOutlet weak var btRightLensMoreActions: UIButton!
    
    @IBOutlet weak var lfLeftLens: UILabel!
    @IBOutlet weak var lfLeftLensName: UILabel!
    @IBOutlet weak var lfLeftLensCode: UILabel!
    @IBOutlet weak var lfLeftLensGrossValue: UILabel!
    @IBOutlet weak var lfLeftLensNetValue: UILabel!
    @IBOutlet weak var btLeftLensMoreActions: UIButton!
    
    @IBOutlet weak var lfExtra: UILabel!
    @IBOutlet weak var btAddExtraServices: UIButton!
    @IBOutlet weak var tvExtraTreatments: UITableView!
    
    @IBOutlet weak var tvCustomGlasses: UITableView!
    
    @IBOutlet weak var allowSendToFactory: UISwitch!
    @IBOutlet weak var lfAllowSendToFactory: UILabel!
    @IBOutlet weak var btTotalOrder: UIButton!
    
    @IBOutlet weak var lfGlassesClinicalStatus: UILabel!
    
    @IBOutlet weak var sgPriceMode: UISegmentedControl!
    var enableManualMode: Bool = false
    var enablePromoMode: Bool = false
    var discountMode: Int = DiscountsMode.None.rawValue
    var canApplyPromoEngine = false
    
    var glassesDistanceType: String = glassesDistanceTypeEnum.far.rawValue
    
    var order: WorkOrder = WorkOrder()
    
    var clinicalStatus: ClinicalStatus?
    var orderDetailGlasses: WorkOrderDetailGlasses?
    
    var itemTemplate: ItemTemplate = ItemTemplate()
    var barcodeInfo: WSBarcodeInfo = WSBarcodeInfo()
    
    var glasses: WorkOrderDetail = WorkOrderDetail()
    var frame: WorkOrderDetail? = nil
    var rightLens: WorkOrderDetail? = nil
    var leftLens: WorkOrderDetail? = nil
    var extras: [WorkOrderDetail] = [WorkOrderDetail]()
    var defaultService: [WorkOrderDetail] = [WorkOrderDetail]()
    
    var isNewConfigurator: Bool = true
    
    var framesProducerLines: [WSFramesProducerLinesView] = [WSFramesProducerLinesView]()
    var lensProducerLines: [WSLensProducerLinesView] = [WSLensProducerLinesView]()
    var servicesProducerLines: [WSTreatmentsProducerLinesView] = [WSTreatmentsProducerLinesView]()
    
    var producerId: Int!
    var producerLineId: Int!
    
    var rowType: String = String()
    
    var parentFiscalExpenseTypeId: Int? = nil
    var parentMedicalDevice: Bool? = false
    var parentVatId: Int? = nil
    var parentVatRate: Double? = nil
    
    var delegate: IProductSelectorListener!
    
    var kitContainsFrame = false
    var kitContainsLeftLens = false
    var kitContainsRightLens = false
    var kitMinRequiredQuantity: Double = 0
    var kitDefaultServiceRequiredQuantity: Double = 0;
    
    var indexToShow:Int?
    var indexToHide:Int?
    
    var productAction: String = ""
    
    var isOrderChanged: Bool = false
    
    var frameCriteria: String = ""
    var rightLensCriteria: String = ""
    var leftLensCriteria: String = ""
    var extraCriteria: String = ""
    var defaultServiceCriteria : String = ""
    var defaultServiceProductId: String = ""
    var kitHasPrice = false
    
    var configuratorDelegate: WorkOrderConfiguratorViewControllerDelegate?
    
    var isTextFieldEditing = false
    var features: [Features] = [Features]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegateTable()
        self.createSaveButon()
        self.resetLabelText()
        self.createViewLayout()
        self.setTableViewStyle()
        self.longGesture()
        self.createLeftBackButton()
        
        self.order = State.workOrder.clone()
        
        self.initConfigurator()
        self.adjustLayoutComformToSelectedKIT()
        self.loadFeatures()
        self.lfAllowSendToFactory.text =  Util.getString("SendReportToFactory")
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
        tvCustomGlasses.addGestureRecognizer(tap)
    }
    
    func initConfigurator(){
        if self.isNewConfigurator{
            self.createNewGlasses()
        }
        else{
            self.initExistingOrderDetail()
            if let allowSendToFactory = self.glasses.orderDetailGlasses?.AllowSendToFactory {
                self.allowSendToFactory.isOn = allowSendToFactory
            }
        }
        self.initOrderDetailGlasses()
            
        if self.glasses.orderDetailGlasses?.AllowSendToFactory == nil {
            self.glasses.orderDetailGlasses?.AllowSendToFactory = self.allowSendToFactory.isOn
        }
    
        self.loadKit()
        
        if glasses.SaleState != EnumDetailSaleState.NotConfirmed.rawValue {
            self.tvCustomGlasses.isUserInteractionEnabled = false
            self.allowSendToFactory.isEnabled = false
        }
    }
        
    func setTableViewStyle(){
        self.tvCustomGlasses.allowsSelection = false
        self.tvCustomGlasses.separatorStyle = .none
    }
    
    func loadFeatures() {
        State.loadCustomProduct(productId: self.itemTemplate.productId)
        {
            productResult in
            if let prod = productResult
            {
                State.loadFeatures(familyId: prod.productFamilyId, subfamilyId: prod.productSubfamilyId, completionHandler: { result in
                    if let features = result {
                        if features.isEmpty{
                            self.allowSendToFactory.isHidden = true
                            self.lfAllowSendToFactory.isHidden = true
                        }
                        else {
                            for feature in features{
                                if feature.isVisible == true{
                                    self.features.append(feature)
                                        
                                    if feature.defaultValueId != nil {
                                        for value in feature.featureValues{
                                            if value.isVisible == true{
                                                if feature.defaultValueId == value.featureValueId {
                                                    if !self.glasses.Customizations.contains(where: { $0.FeatureId == feature.featureId}) {
                                                        
                                                        self.addFeatureValue(feature: feature, featureValue: value.value)
                                                    }
                                                }
                                                    
                                            }
                                        }
                                    }
                                }
                            }
                            
                            self.tvCustomGlasses.reloadData()
                        }
                    }
                })
            }
        }
    }
    
    func loadKit(){
        if(self.itemTemplate.price != nil && self.itemTemplate.price != 0){
            self.kitHasPrice = true
            self.discountMode = DiscountsMode.None.rawValue
        }
        else{
            self.kitHasPrice = false
            self.enablePromoMode = false
            self.enableManualMode = false
            
            let orderDetailsChildsCollection = self.order.getChildCollection(parentId: self.glasses.OrderDetailId)
            for child in orderDetailsChildsCollection{
                if let discounts = child.discounts{
                    for discount in discounts{
                        if discount.DiscountType == enumDiscountTypes.PR.rawValue || discount.DiscountType == enumDiscountTypes.PC.rawValue{
                            self.enablePromoMode = true
                        }
                        else if discount.DiscountType == enumDiscountTypes.MA.rawValue || discount.DiscountType == enumDiscountTypes.MC.rawValue{
                            self.enableManualMode = true
                        }
                    }
                }
            }
            if self.enablePromoMode{
                self.setPromoDiscountMode()
            }
            else if self.enableManualMode{
                self.setManualMode()
            }
            else{
                if settings.storeSetupSettings.WorkOrderDefaultState == "AUTO"{
                    self.setPromoDiscountMode()
                }
                else{
                    self.setManualMode()
                }
            }
        }
    }
    
    func setPromoDiscountMode(){
        self.sgPriceMode.selectedSegmentIndex = 0
        self.discountMode = DiscountsMode.PromoPrices.rawValue
        self.canApplyPromoEngine = true
        self.lfFrameNetValue.isUserInteractionEnabled = false
        self.lfFrameGrossValue.isUserInteractionEnabled = false
        self.lfRightLensNetValue.isUserInteractionEnabled = false
        self.lfRighLensGrossValue.isUserInteractionEnabled = false
        self.lfLeftLensNetValue.isUserInteractionEnabled = false
        self.lfLeftLensGrossValue.isUserInteractionEnabled = false
        self.deselectRow()
        
        for detail in self.order.OrderDetail{
            detail.canApplyPromotions = true
        }
    }
    
    func setManualMode(){
        self.sgPriceMode.selectedSegmentIndex = 1
        self.discountMode = DiscountsMode.ManualPrices.rawValue
        self.canApplyPromoEngine = true
        self.lfFrameNetValue.isUserInteractionEnabled = true
        self.lfFrameGrossValue.isUserInteractionEnabled = true
        self.lfRightLensNetValue.isUserInteractionEnabled = true
        self.lfRighLensGrossValue.isUserInteractionEnabled = true
        self.lfLeftLensNetValue.isUserInteractionEnabled = true
        self.lfLeftLensGrossValue.isUserInteractionEnabled = true
        self.deselectRow()
        
        for detail in self.order.OrderDetail{
            detail.canApplyPromotions = false
        }
    }
    
    func initOrderDetailGlasses(){
        self.lfGlassesClinicalStatus.baselineAdjustment = .alignCenters
        self.lfGlassesClinicalStatus.adjustsFontSizeToFitWidth = true
        if let orderDetailGlasses = self.orderDetailGlasses{
            
            if let distance =  orderDetailGlasses.GlassesDistanceType{
                self.glassesDistanceType = distance
            }
            
            self.glasses.orderDetailGlasses = orderDetailGlasses
            
            self.orderDetailGlassesLensDistanceTypeLayout()
            
            self.lfGlassesClinicalStatus.text = orderDetailGlasses.getRX()
        }
        else if let clinicalStatus = self.clinicalStatus{
            self.orderDetailGlasses = clinicalStatus.getOrderDetailGlasses(orderDetailId: UUID.init(uuidString: self.glasses.OrderDetailId)!)
            
            if let distance =  self.orderDetailGlasses?.GlassesDistanceType{
                self.glassesDistanceType = distance
            }
            
            self.glasses.orderDetailGlasses = self.orderDetailGlasses
            
            self.clinicalStatusLensDistanceTypeLayout()
            
            self.lfGlassesClinicalStatus.text = self.orderDetailGlasses?.getRX()
        }
    }
    
    func orderDetailGlassesLensDistanceTypeLayout(){
        var leftDistance = ""
        if self.orderDetailGlasses?.LensLeftIsFar == true{
            leftDistance += glassesDistanceTypeEnum.far.rawValue
        }
        if self.orderDetailGlasses?.LensLeftIsNear == true{
            leftDistance += glassesDistanceTypeEnum.near.rawValue
        }
        if self.orderDetailGlasses?.LensLeftIsIntermediate == true{
            leftDistance += glassesDistanceTypeEnum.intermediate.rawValue
        }
        
        if leftDistance != ""{
            self.lfLeftLens.text = "OS" + "(\(Util.getString(leftDistance)))"
        }
        
        var rightDistance = ""
        if self.orderDetailGlasses?.LensRightIsFar == true{
            rightDistance += glassesDistanceTypeEnum.far.rawValue
        }
        if self.orderDetailGlasses?.LensRightIsNear == true{
            rightDistance += glassesDistanceTypeEnum.near.rawValue
        }
        if self.orderDetailGlasses?.LensRightIsIntermediate == true{
            rightDistance += glassesDistanceTypeEnum.intermediate.rawValue
        }
        
        if rightDistance != ""{
            self.lfRightLens.text = "OD" + "(\(Util.getString(rightDistance)))"
        }
    }
    
    func clinicalStatusLensDistanceTypeLayout(){
        var leftDistance = ""
        var rightDistance = ""
        switch self.glassesDistanceType {
        case glassesDistanceTypeEnum.far.rawValue:
            leftDistance = Util.getString("F")
            rightDistance = Util.getString("F")
            self.orderDetailGlasses?.LensRightIsFar = true
            self.orderDetailGlasses?.LensLeftIsFar = true
            break
        case glassesDistanceTypeEnum.near.rawValue:
            leftDistance = Util.getString("N")
            rightDistance = Util.getString("N")
            self.orderDetailGlasses?.LensRightIsNear = true
            self.orderDetailGlasses?.LensLeftIsNear = true
            break
        case glassesDistanceTypeEnum.intermediate.rawValue:
            leftDistance = Util.getString("I")
            rightDistance = Util.getString("I")
            self.orderDetailGlasses?.LensRightIsIntermediate = true
            self.orderDetailGlasses?.LensLeftIsIntermediate = true
            break
        case glassesDistanceTypeEnum.far_near.rawValue:
            leftDistance = Util.getString("FN")
            rightDistance = Util.getString("FN")
            self.orderDetailGlasses?.LensRightIsFar = true
            self.orderDetailGlasses?.LensLeftIsFar = true
            self.orderDetailGlasses?.LensRightIsNear = true
            self.orderDetailGlasses?.LensLeftIsNear = true
            break
        case glassesDistanceTypeEnum.far_intermediate.rawValue:
            leftDistance = Util.getString("FI")
            rightDistance = Util.getString("FI")
            self.orderDetailGlasses?.LensRightIsFar = true
            self.orderDetailGlasses?.LensLeftIsFar = true
            self.orderDetailGlasses?.LensRightIsIntermediate = true
            self.orderDetailGlasses?.LensLeftIsIntermediate = true
            break
        case glassesDistanceTypeEnum.near_intermediate.rawValue:
            leftDistance = Util.getString("NI")
            rightDistance = Util.getString("NI")
            self.orderDetailGlasses?.LensRightIsNear = true
            self.orderDetailGlasses?.LensLeftIsNear = true
            self.orderDetailGlasses?.LensRightIsIntermediate = true
            self.orderDetailGlasses?.LensLeftIsIntermediate = true
            break
        default:
            leftDistance = Util.getString("F")
            rightDistance = Util.getString("F")
            self.orderDetailGlasses?.LensRightIsFar = true
            self.orderDetailGlasses?.LensLeftIsFar = true
            break
        }
        
        self.lfLeftLens.text = "OS" + "(\(leftDistance))"
        self.lfRightLens.text = "OD" + "(\(rightDistance))"
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.deselectRow()
    }
    
    func deselectRow(){
        if let index = self.tvExtraTreatments.indexPathForSelectedRow{
            self.tvExtraTreatments.deselectRow(at: index, animated: false)
            self.indexToHide = index.row + 1
            self.indexToShow = nil
            self.tvExtraTreatments.beginUpdates()
            self.tvExtraTreatments.endUpdates()
        }
    }
    
    var kitExtraTreatmentsQuantity: Double{
        get{
            var quantity: Double = 0
            let orderDetailsChildsCollection = self.order.getChildCollection(parentId: self.glasses.OrderDetailId)
            for child in orderDetailsChildsCollection{
                if child.RowType == rowTypeEnum.extra.rawValue{
                    quantity += Double(child.OrderedQuantity)
                }
            }
            return quantity
        }
    }
    var kitDefaultServicesQuantity: Double{
        get{
            var quantity: Double = 0
            let orderDetailsChildsCollection = self.order.getChildCollection(parentId: self.glasses.OrderDetailId)
            for child in orderDetailsChildsCollection{
                if child.ProductCode == self.defaultServiceProductId{
                    quantity += Double(child.OrderedQuantity)
                }
            }
            return quantity
        }
    }
    var defaultServiceProductName: String{
        get{
            var productName: String = ""
            let orderDetailsChildsCollection = self.order.getChildCollection(parentId: self.glasses.OrderDetailId)
            for child in orderDetailsChildsCollection{
                if(child.ProductCode == self.defaultServiceProductId){
                    productName = child.ProductName!
                }
            }
            return productName
        }
    }
    var defaultServicePrice: Double{
        get{
            var price: Double = 0
            let orderDetailsChildsCollection = self.order.getChildCollection(parentId: self.glasses.OrderDetailId)
            for child in orderDetailsChildsCollection{
                if(child.ProductCode == self.defaultServiceProductId){
                    price = child.NetRowValueVatIncluded
                }
            }
            return price
        }
    }
    
    func createLeftBackButton(){
        let backButton = UIBarButtonItem(title: Util.getString("Back"), style: .plain, target: self, action: #selector(backButtonPressed))
        self.navigationItem.leftBarButtonItem = backButton
        self.navigationItem.leftItemsSupplementBackButton = false
    }
    
    @objc func backButtonPressed(){
        if self.isOrderChanged{
            Util.AlertYesNo(viewController: self, title: "iPOS", message: Util.getString("Are you sure you want to cancel? All changes will be lost!"), actionYes: {
                _ = self.navigationController?.popViewController(animated: true)
            }, actionNo: {
                return
            })
        }
        else{
            _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
    func createNewGlasses(){
        self.rowType = rowTypeEnum.glasses.rawValue
        self.createItem(barcodeInfo: barcodeInfo)
        self.createGlassesLayout()
    }
    
    func adjustLayoutComformToSelectedKIT(){
        self.adjustFrameLayout(isUserInteractionEnabled: false, alpha: 0.3)
        self.adjustLeftLensLayout(isUserInteractionEnabled: false, alpha: 0.3)
        self.adjustRightLensLayout(isUserInteractionEnabled: false, alpha: 0.3)
        self.adjustExtraLayout(isUserInteractionEnabled: false, alpha: 0.3)
        
        for itemTemplateDetail in self.itemTemplate.itemTemplateDetails{
            if itemTemplateDetail.rowType == rowTypeEnum.frame.rawValue{
                self.kitContainsFrame = true
                self.frameCriteria = itemTemplateDetail.productsCriteria
                self.adjustFrameLayout(isUserInteractionEnabled: true, alpha: 1)
            }
            else if itemTemplateDetail.rowType == rowTypeEnum.leftLens.rawValue{
                self.kitContainsLeftLens = true
                self.leftLensCriteria = itemTemplateDetail.productsCriteria
                self.adjustLeftLensLayout(isUserInteractionEnabled: true, alpha: 1)
            }
            else if itemTemplateDetail.rowType == rowTypeEnum.rightLens.rawValue{
                self.kitContainsRightLens = true
                self.rightLensCriteria = itemTemplateDetail.productsCriteria
                self.adjustRightLensLayout(isUserInteractionEnabled: true, alpha: 1)
            }
            else if itemTemplateDetail.rowType == rowTypeEnum.extra.rawValue{
                self.extraCriteria = itemTemplateDetail.productsCriteria
                self.adjustExtraLayout(isUserInteractionEnabled: true, alpha: 1)
                self.kitMinRequiredQuantity = itemTemplateDetail.minQuantity
            }
            else if itemTemplateDetail.rowType == rowTypeEnum.defaultService.rawValue{
                var criteriaProductCode = ""
                if let range = itemTemplateDetail.productsCriteria.range(of: "'") {
                    let startIndex = range.upperBound
                    let endIndex = itemTemplateDetail.productsCriteria.index(before: itemTemplateDetail.productsCriteria.endIndex)
                    criteriaProductCode = String(itemTemplateDetail.productsCriteria[startIndex..<endIndex])
                }
                self.defaultServiceCriteria = itemTemplateDetail.productsCriteria
                self.adjustExtraLayout(isUserInteractionEnabled: true, alpha: 1)
                self.kitDefaultServiceRequiredQuantity = itemTemplateDetail.minQuantity
                self.defaultServiceProductId = criteriaProductCode
            }
        }
    }
    
    func adjustFrameLayout(isUserInteractionEnabled: Bool, alpha: CGFloat){
        self.viewFrame.isUserInteractionEnabled = isUserInteractionEnabled
        self.btFrameMoreActions.isUserInteractionEnabled = isUserInteractionEnabled
        self.viewFrame.alpha = alpha
        self.btFrameMoreActions.alpha = alpha
        self.lfFrame.alpha = alpha
    }
    
    func adjustLeftLensLayout(isUserInteractionEnabled: Bool, alpha: CGFloat){
        self.viewLeftLens.isUserInteractionEnabled = isUserInteractionEnabled
        self.btLeftLensMoreActions.isUserInteractionEnabled = isUserInteractionEnabled
        self.viewLeftLens.alpha = alpha
        self.btLeftLensMoreActions.alpha = alpha
        self.lfLeftLens.alpha = alpha
    }
    
    func adjustRightLensLayout(isUserInteractionEnabled: Bool, alpha: CGFloat){
        self.viewRightLens.isUserInteractionEnabled = isUserInteractionEnabled
        self.btRightLensMoreActions.isUserInteractionEnabled = isUserInteractionEnabled
        self.viewRightLens.alpha = alpha
        self.btRightLensMoreActions.alpha = alpha
        self.lfRightLens.alpha = alpha
    }
    
    func adjustExtraLayout(isUserInteractionEnabled: Bool, alpha: CGFloat){
        self.tvExtraTreatments.isUserInteractionEnabled = isUserInteractionEnabled
        self.btAddExtraServices.isUserInteractionEnabled = isUserInteractionEnabled
        self.tvExtraTreatments.alpha = alpha
        self.btAddExtraServices.alpha = alpha
        self.lfExtra.alpha = alpha
    }
    
    func createViewLayout(){
        self.title = Util.getString("Configurator")
        self.sgPriceMode.setTitle(Util.getString("AutomaticPrices"), forSegmentAt: 0)
        self.sgPriceMode.setTitle(Util.getString("ManualPrices"), forSegmentAt: 1)
                
        self.lfKIT.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.lfKIT.layer.borderWidth = 1
        self.lfKIT.layer.cornerRadius = 10
        
        self.viewFrame.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.viewFrame.layer.borderWidth = 1
        self.viewFrame.layer.cornerRadius = 10
        
        self.viewLeftLens.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.viewLeftLens.layer.borderWidth = 1
        self.viewLeftLens.layer.cornerRadius = 10
        
        self.viewRightLens.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.viewRightLens.layer.borderWidth = 1
        self.viewRightLens.layer.cornerRadius = 10
        
        self.tvExtraTreatments.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.tvExtraTreatments.layer.borderWidth = 1
        self.tvExtraTreatments.layer.cornerRadius = 10
        
        self.lfGlassesClinicalStatus.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.lfGlassesClinicalStatus.layer.borderWidth = 1
        self.lfGlassesClinicalStatus.layer.cornerRadius = 10
        
        self.tvCustomGlasses.layer.borderColor = UIColor.groupTableViewBackground.cgColor
        self.tvCustomGlasses.layer.borderWidth = 1
        self.tvCustomGlasses.layer.cornerRadius = 10
    }
    
    func resetLabelText(){
        self.lfKIT.text = nil
        
        self.lfFrameName.text = nil
        self.lfFrameCode.text = nil
        self.lfFrameGrossValue.text = nil
        self.lfFrameNetValue.text = nil
        
        self.lfLeftLensName.text = nil
        self.lfLeftLensCode.text = nil
        self.lfLeftLensGrossValue.text = nil
        self.lfLeftLensNetValue.text = nil
        
        self.lfRightLensName.text = nil
        self.lfRightLensCode.text = nil
        self.lfRighLensGrossValue.text = nil
        self.lfRightLensNetValue.text = nil
    }
    
    func delegateTable(){
        self.tvExtraTreatments.delegate = self
        self.tvExtraTreatments.dataSource = self
        self.tvCustomGlasses.delegate = self
        self.tvCustomGlasses.dataSource = self
    }
    
    func createSaveButon(){
        let save = UIBarButtonItem(title: Util.getString("Apply"), style: UIBarButtonItem.Style.plain, target: self, action: #selector(saveConfigurator))
        self.navigationItem.rightBarButtonItem = save
    }
    
    @objc func saveConfigurator(){
        self.isWorkOrderComplete{
            isComplete in
            if isComplete{
                if self.isOrderChanged{
                    State.checkOrderAlreadyHaveRVSAction(orderDetailId: self.glasses.OrderDetailId) { result in
                        if let orderActionId = result {
                            let message = Util.getString("RemoveExistingRVSAction")
                            Util.AlertWithOneActions(viewController: self, title: "", message: message, firstActionTitle: Util.getString("Confirm"), firstAction: {
                                State.removeExistingRVSAction(actionId: orderActionId, completionHandler: { result in
                                    if result?.resultCode == 0 {
                                        self.applyConfiguratorChanges()
                                    }
                                    else{
                                        Util.GeneralAlert(viewController: self, message: result?.resultMessage?.description ?? "")
                                    }
                                })
                            })
                        }else{
                            self.applyConfiguratorChanges()
                        }
                    }}
                else{
                    self.applyConfiguratorChanges()
                }
            }
            else{
                self.applyConfiguratorChanges()
            }
        }
    }
    func applyConfiguratorChanges(){
        if (self.validateFields() == false){
            return
        }
        
        if settings.storeSetupSettings.clientName == "NAU!" {
            if (self.ValidateNauCustomizations() == false){
                return
            }
        }
        
        self.updateParentRow()
        self.calculateDetailsTotals()
        self.recalculateTotals()
        self.order.recalculate()
        self.saveOrderDetailGlasses()

        State.workOrder = self.order
        _ = self.navigationController?.popViewController(animated: true)
        self.configuratorDelegate?.saveConfigurator()
    }
    
    func saveOrderDetailGlasses(){
        self.glasses.orderDetailGlasses = self.orderDetailGlasses
    }
    
    func updateParentRow(){
        if let discounts = self.glasses.discounts{
            if discounts.count > 0 {
                var manualDiscountTotalValue: Double = 0
                var lastManualDiscount: WorkOrderDetailDiscounts? = nil
                
                for discount in discounts{
                    if discount.DiscountType == enumDiscountTypes.MA.rawValue{
                        manualDiscountTotalValue += discount.DiscountValue ?? 0
                        lastManualDiscount = discount
                    }
                }
                
                if let lastDiscout = lastManualDiscount{
                    for var detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
                        self.order.clearOrderDetailDiscount(orderDetail: &detail, discountType: .MA)
                    }
                    
                    self.distributeDiscountOnChildren(discountValue: manualDiscountTotalValue, discountType: .MA, discountCauseId: lastDiscout.DiscountCauseId!, promotionId: nil)
                }
            }
        }
    }
    
    func isWorkOrderComplete(completion: @escaping (Bool) -> Void){
        var isComplete = true
        if self.frame == nil && self.kitContainsFrame{
            Util.GeneralAlert(viewController: self, message: Util.getString("SelectFrame"))
            completion(false)
            return
        }
        if self.leftLens == nil && kitContainsLeftLens{
            Util.GeneralAlert(viewController: self, message: Util.getString("SelectLeftLens"))
            completion(false)
            return
        }
        if self.rightLens == nil && kitContainsRightLens{
            Util.GeneralAlert(viewController: self, message: Util.getString("SelectRightLens"))
            completion(false)
            return
        }
        if self.kitExtraTreatmentsQuantity < self.kitMinRequiredQuantity{
            let message = String.init(format: Util.getString("KitMinQtyRequired"), "\(self.kitMinRequiredQuantity.rounded(toPlaces: 0))")
            Util.GeneralAlert(viewController: self, message: message)
            completion(false)
            return
        }
        if let orderDetailGlasses = self.glasses.orderDetailGlasses{
            if orderDetailGlasses.FilterCategory == nil || orderDetailGlasses.FilterCategory == ""{
                Util.AlertOperationNotAllowed(viewController: self, message: Util.getString("FilterCategoryIsMandatory"))
                completion(false)
                return
            }
        }
        if self.kitDefaultServicesQuantity < self.kitDefaultServiceRequiredQuantity
        {
                let message = String.init(format: Util.getString("KitSRDMinQtyRequired"), "\(self.kitDefaultServiceRequiredQuantity.rounded(toPlaces: 0))")
                Util.AlertYesNo(viewController: self, title: "", message: message,
                                actionYes: {
                    State.LoadBarcodeInfo(productCode: self.defaultServiceProductId) { result in
                        if result == nil {
                            NetworkController.AlertConnectionError(viewController: self)
                            completion(true)
                        } else if result == true {
                            if let barcodeInfo = State.barcodeInfo {
                                barcodeInfo.quantity = self.kitDefaultServiceRequiredQuantity - self.kitDefaultServicesQuantity
                                self.rowType = rowTypeEnum.defaultService.rawValue
                                //let tempShoppingCart = glasses()
                                self.createItem(barcodeInfo: barcodeInfo)
                                self.calculateDetailsTotals()
                                self.recalculateTotals()
                                self.saveConfigurator()
                                self.saveOrderDetailGlasses()
                                self.recalculateAndReturnToCurrentView()
                                Util.GeneralAlert(viewController: self, message: String.init(format:"Product %@ added. Price: %@. Total Order Value: %@", self.defaultServiceProductName, String(describing: self.defaultServicePrice), String(describing: self.glasses.NetRowValueVatIncluded)))
                                completion(false) // Indicate success
                            }
                        }
                        
                    }
                },
                   actionNo: {
                    completion(false)
                })
                return
            }
            completion(true)
        }
    
    
    
    
    
    func initExistingOrderDetail(){
        self.parentFiscalExpenseTypeId = glasses.FiscalExpenseTypeId
        self.parentMedicalDevice = glasses.MedicalDevice
        self.parentVatId = glasses.VatId
        self.parentVatRate = glasses.VatRate
        
        if let glasses = self.order.OrderDetail.first(where: {$0.OrderDetailId == self.glasses.OrderDetailId}){
            self.glasses = glasses
        }
        
        self.createGlassesLayout()
        
        for orderDetail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            orderDetail.itemTemplateCode = self.itemTemplate.code
            if orderDetail.RowType == rowTypeEnum.frame.rawValue{
                self.frame = orderDetail
                self.createFrameLayout()
            }
            else if orderDetail.RowType == rowTypeEnum.leftLens.rawValue{
                self.leftLens = orderDetail
                self.createLeftLensLayout()
            }
            else if orderDetail.RowType == rowTypeEnum.rightLens.rawValue{
                self.rightLens = orderDetail
                self.createRightLensLayout()
            }
            else if orderDetail.RowType == rowTypeEnum.extra.rawValue{
                self.extras.append(orderDetail)
            }
            else if orderDetail.RowType == rowTypeEnum.defaultService.rawValue{
                self.extras.append(orderDetail)
            }
            
            
        }
        
        self.tvExtraTreatments.reloadData()
        
        self.refreshUI()
    }
    
    func createGlassesLayout(){
        self.lfKIT.text = self.itemTemplate.name
    }
    
    func createFrameLayout(){
        self.lfFrameName.text = self.frame?.ProductName!
        self.lfFrameCode.text = self.frame?.ProductCode!
        
        State.LoadProductImageIcon(productCode: self.frame!.ProductCode!, completionHandler: { response in
            if let productImage = response{
                self.ivFrame.image = productImage
            }
        })
        
        var netValue:Double = 0
        var grossValue:Double = 0
        var discountValue:Double = 0
        
        if let dv = frame?.internalDiscountsTotalValue{
            discountValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(dv)
        }
        
        if let nv = frame?.NetRowValueVatIncluded{
            netValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(nv)
        }
        
        if let gv = frame?.GrossUnitValueVatIncluded{
            grossValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(gv)
        }
        
        netValue = grossValue - discountValue
        
        if netValue.isLess(than: grossValue){
            self.lfFrameNetValue.textColor = UIColor.red
            self.lfFrameNetValue.text = Util.DoubleToStringWithTwoDecimals(netValue) + " " + settings.userSettings.defaultCurrency
            let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToStringWithTwoDecimals(grossValue) + " \(settings.userSettings.defaultCurrency)")
            attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
            
            let attributedStringDiscount: NSMutableAttributedString = NSMutableAttributedString(string: "(" + Util.DoubleToStringWithTwoDecimals(discountValue * (-1) ) + " " +  settings.userSettings.defaultCurrency + ")")
            
            let combination = NSMutableAttributedString()
            combination.append(attributeString)
            combination.append(attributedStringDiscount)
            
            self.lfFrameGrossValue.isHidden = false
            self.lfFrameGrossValue.attributedText = combination
        }
        else{
            self.lfFrameGrossValue.isHidden = true
            self.lfFrameNetValue.text = Util.DoubleToStringWithTwoDecimals(netValue) + " " + settings.userSettings.defaultCurrency
            self.lfFrameNetValue.textColor = UIColor.black
        }
    }
    
    func createRightLensLayout(){
        self.lfRightLensName.text = self.rightLens?.ProductName!
        self.lfRightLensCode.text = self.rightLens?.ProductCode!
        
        var netValue:Double = 0
        var grossValue:Double = 0
        var discountValue:Double = 0
        
        if let dv = rightLens?.internalDiscountsTotalValue{
            discountValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(dv)
        }
        
        if let nv = rightLens?.NetRowValueVatIncluded{
            netValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(nv)
        }
        
        if let gv = rightLens?.GrossUnitValueVatIncluded{
            grossValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(gv)
        }
        
        netValue = grossValue - discountValue
        
        if netValue.isLess(than: grossValue){
            self.lfRightLensNetValue.textColor = UIColor.red
            self.lfRightLensNetValue.text = Util.DoubleToStringWithTwoDecimals(netValue) + " " + settings.userSettings.defaultCurrency
            let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToStringWithTwoDecimals(grossValue) + " \(settings.userSettings.defaultCurrency)")
            attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
            let attributedStringDiscount: NSMutableAttributedString = NSMutableAttributedString(string:  "(" + Util.DoubleToStringWithTwoDecimals(discountValue * (-1)) + " " +  settings.userSettings.defaultCurrency + ")")
            
            let combination = NSMutableAttributedString()
            combination.append(attributeString)
            combination.append(attributedStringDiscount)
            
            self.lfRighLensGrossValue.isHidden = false
            self.lfRighLensGrossValue.attributedText = combination
        }
        else{
            self.lfRighLensGrossValue.isHidden = true
            self.lfRightLensNetValue.text = Util.DoubleToStringWithTwoDecimals(netValue) + " " + settings.userSettings.defaultCurrency
            self.lfRightLensNetValue.textColor = UIColor.black
        }
    }
    
    func createLeftLensLayout(){
        self.lfLeftLensName.text = self.leftLens?.ProductName!
        self.lfLeftLensCode.text = self.leftLens?.ProductCode!
        
        var netValue:Double = 0
        var grossValue:Double = 0
        var discountValue:Double = 0
        
        if let dv = leftLens?.internalDiscountsTotalValue{
            discountValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(dv)
        }
        
        if let nv = leftLens?.NetRowValueVatIncluded{
            netValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(nv)
        }
        
        if let gv = leftLens?.GrossUnitValueVatIncluded{
            grossValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(gv)
        }
        
        netValue = grossValue - discountValue
        
        if netValue.isLess(than: grossValue){
            self.lfLeftLensNetValue.textColor = UIColor.red
            self.lfLeftLensNetValue.text = Util.DoubleToStringWithTwoDecimals(netValue) + " " + settings.userSettings.defaultCurrency
            let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToStringWithTwoDecimals(grossValue) + " \(settings.userSettings.defaultCurrency)")
            attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
            let attributedStringDiscount: NSMutableAttributedString = NSMutableAttributedString(string:  "(" + Util.DoubleToStringWithTwoDecimals(discountValue * (-1)) + " " +  settings.userSettings.defaultCurrency + ")")
            
            let combination = NSMutableAttributedString()
            combination.append(attributeString)
            combination.append(attributedStringDiscount)
            
            self.lfLeftLensGrossValue.isHidden = false
            self.lfLeftLensGrossValue.attributedText = combination
        }
        else{
            self.lfLeftLensGrossValue.isHidden = true
            self.lfLeftLensNetValue.text = Util.DoubleToStringWithTwoDecimals(netValue) + " " + settings.userSettings.defaultCurrency
            self.lfLeftLensNetValue.textColor = UIColor.black
        }
    }
    
    func createItem(barcodeInfo: WSBarcodeInfo){
        let item = WorkOrderDetail()
        
        if(self.discountMode == DiscountsMode.ManualPrices.rawValue){
            item.canApplyPromotions = false
        }
        else{
            item.canApplyPromotions = true
        }
        
        item.OrderId = self.order.OrderId
        item.OrderedQuantity = 1
        item.SaleState = 1
        item.OperationType = "V"
        item.PrintType = "F"
        item.UnitOfMeasureName = barcodeInfo.UnitOfMeasure
        item.StyleId = barcodeInfo.StyleId!
        item.OriginalPrice = barcodeInfo.SalePrice
        item.GrossUnitValueVatIncluded = barcodeInfo.SalePrice
        item.NetRowValueVatIncluded = barcodeInfo.SalePrice
        item.ProductName = barcodeInfo.Name
        item.ProductCode = barcodeInfo.Code
        item.Barcode = barcodeInfo.Barcode
        item.OrderDetailRowNumber = self.order.getNextDetailRowNumber()
        item.itemTemplateCode = self.itemTemplate.code
//        if(item.ProductCode == "MNTDEF"){
//            self.rowType = rowTypeEnum.defaultService.rawValue
//        }
            
        if self.rowType == rowTypeEnum.glasses.rawValue{
            self.parentFiscalExpenseTypeId = barcodeInfo.FiscalExpenseTypeId
            self.parentMedicalDevice = barcodeInfo.MedicalDevice
            self.parentVatId = barcodeInfo.WOVatId
            self.parentVatRate = barcodeInfo.WOVatRate
            item.VatId = barcodeInfo.WOVatId
            item.VatRate = barcodeInfo.WOVatRate
            let netValueVatExcluded = (barcodeInfo.SalePrice / (1 + barcodeInfo.WOVatRate!)).rounded(toPlaces: 2)
            item.VatValue =  (netValueVatExcluded * barcodeInfo.WOVatRate!).rounded(toPlaces: 2)
            item.PrintType = "N"
        }
        else{
            item.FiscalExpenseTypeId = self.parentFiscalExpenseTypeId
            item.MedicalDevice = self.parentMedicalDevice
            
            if(settings.storeSetupSettings.useGlassesVatOnComponents){
                item.VatId = self.parentVatId
                item.VatRate = self.parentVatRate
                let netValueVatExcluded = (barcodeInfo.SalePrice / (1 + barcodeInfo.WOVatRate!)).rounded(toPlaces: 2)
                item.VatValue =  (netValueVatExcluded * barcodeInfo.WOVatRate!).rounded(toPlaces: 2)
            }
            else{
                item.VatId = barcodeInfo.WOVatId
                item.VatRate = barcodeInfo.WOVatRate
                let netValueVatExcluded = (barcodeInfo.SalePrice / (1 + barcodeInfo.WOVatRate!)).rounded(toPlaces: 2)
                item.VatValue =  (netValueVatExcluded * barcodeInfo.WOVatRate!).rounded(toPlaces: 2)
            }
            
            item.OperationType = "D"
        }
        
        if self.rowType == rowTypeEnum.glasses.rawValue{
            self.glasses = WorkOrderDetail()
            self.glasses = item.clone()
            self.glasses.itemTemplateId = self.itemTemplate.itemTemplateId
            self.glasses.RowType = rowTypeEnum.glasses.rawValue
            
            if let existingGlasses = self.getComponent(rowType: rowTypeEnum.glasses.rawValue){
                self.glasses.OrderDetailId = existingGlasses.OrderDetailId
                self.glasses.OrderDetailRowNumber = existingGlasses.OrderDetailRowNumber
                self.replaceExistingComponent(newComponent: self.glasses)
            }
            else{
                self.order.OrderDetail.append(glasses)
            }
        }
        else if self.rowType == rowTypeEnum.frame.rawValue{
            self.frame = WorkOrderDetail()
            self.frame = item.clone()
            self.frame?.RowType = rowTypeEnum.frame.rawValue
            self.frame?.ParentOrderDetailId = self.glasses.OrderDetailId
            
            if let existingFrame = self.getComponent(rowType: rowTypeEnum.frame.rawValue){
                self.frame?.OrderDetailId = existingFrame.OrderDetailId
                self.frame?.OrderDetailRowNumber = existingFrame.OrderDetailRowNumber
                self.replaceExistingComponent(newComponent: self.frame!)
            }
            else{
                self.order.OrderDetail.append(frame!)
            }
            
            State.loadFeaturesForProduct(productId: barcodeInfo.ProductId) { result in
                if let frameFeatures = result {
                    if frameFeatures.count > 0 {
                        State.loadFeatures(familyId: barcodeInfo.productFamilyId, subfamilyId: barcodeInfo.productSubfamilyId, completionHandler: { result in
                            if let features = result{
                                if let caliberFeature = features.first(where: {$0.name == "Calibro"}){
                                    if let fv = frameFeatures.first(where: {$0.featureId == caliberFeature.featureId}){
                                        if let value = Double(fv.featureValue){
                                            self.orderDetailGlasses?.LensLength = value
                                        }
                                    }
                                }
                                if let bridgeFeature = features.first(where: {$0.name == "Ponte"}){
                                    if let fv = frameFeatures.first(where: {$0.featureId == bridgeFeature.featureId}){
                                        if let value = Double(fv.featureValue){
                                            self.orderDetailGlasses?.Bridge = value
                                        }
                                    }
                                }
                            }
                        })
                    }
                }
            }
        }
        else if self.rowType == rowTypeEnum.leftLens.rawValue{
            self.leftLens = WorkOrderDetail()
            self.leftLens = item.clone()
            self.leftLens?.RowType = rowTypeEnum.leftLens.rawValue
            self.leftLens?.ParentOrderDetailId = self.glasses.OrderDetailId
            
            if let existingLeftLens = self.getComponent(rowType: rowTypeEnum.leftLens.rawValue){
                self.leftLens?.OrderDetailId = existingLeftLens.OrderDetailId
                self.leftLens?.OrderDetailRowNumber = existingLeftLens.OrderDetailRowNumber
                self.replaceExistingComponent(newComponent: self.leftLens!)
            }
            else{
                self.order.OrderDetail.append(leftLens!)
            }
        }
        else if self.rowType == rowTypeEnum.rightLens.rawValue{
            self.rightLens = WorkOrderDetail()
            self.rightLens = item.clone()
            self.rightLens?.RowType = rowTypeEnum.rightLens.rawValue
            self.rightLens?.ParentOrderDetailId = self.glasses.OrderDetailId
            
            if let existingRightLens = self.getComponent(rowType: rowTypeEnum.rightLens.rawValue){
                self.rightLens?.OrderDetailId = existingRightLens.OrderDetailId
                self.rightLens?.OrderDetailRowNumber = existingRightLens.OrderDetailRowNumber
                self.replaceExistingComponent(newComponent: self.rightLens!)
            }
            else{
                self.order.OrderDetail.append(rightLens!)
            }
        }
        else if self.rowType == rowTypeEnum.extra.rawValue{
            let extra = item.clone()
            extra.RowType = rowTypeEnum.extra.rawValue
            extra.ParentOrderDetailId = self.glasses.OrderDetailId
            self.order.OrderDetail.append(extra)
            self.extras.append(extra)
            self.tvExtraTreatments.reloadData()
        }
        else if self.rowType == rowTypeEnum.defaultService.rawValue{
            let defaultService = item.clone()
            defaultService.RowType = rowTypeEnum.defaultService.rawValue
            defaultService.ParentOrderDetailId = self.glasses.OrderDetailId
            defaultService.OrderedQuantity = kitDefaultServiceRequiredQuantity - kitDefaultServicesQuantity
            defaultService.RowType = rowTypeEnum.extra.rawValue
            self.order.OrderDetail.append(defaultService)
            self.extras.append(defaultService)
            self.tvExtraTreatments.reloadData()
        }
        
        self.isOrderChanged = true
        self.refreshUI()
    }
    
    func refreshUI(){
        self.calculateDetailsTotals()
        self.recalculateKitPrice()
        self.clearKitDiscounts()
        self.distributeKitDiscountOnChildren()
        self.recalculateTotals()
        self.updateTotal()
        
        if self.frame != nil {
            self.createFrameLayout()
        }
        if self.leftLens != nil {
            self.createLeftLensLayout()
        }
        if self.rightLens != nil {
            self.createRightLensLayout()
        }
        self.tvExtraTreatments.reloadData()
    }
    
    func recalculateKitPrice(){
        if self.kitHasPrice == false{
            self.calculateVariableKitPrice()
        }
        else{
            self.calculateFixKitPrice()
        }
    }
    
    func calculateVariableKitPrice(){
        var totalPrice: Double = 0
        var totalDiscount: Double = 0
        
        for detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            totalPrice += detail.GrossUnitValueVatIncluded * detail.OrderedQuantity
            if let dv = detail.DiscountValue{
                totalDiscount += dv
            }
        }
        
        self.glasses.GrossUnitValueVatIncluded = totalPrice
        self.glasses.NetRowValueVatIncluded = totalPrice - totalDiscount
    }
    
    func calculateFixKitPrice(){
        
    }
    
    func calculateDetailsTotals(){
        for var detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            self.calculateDetailTotal(orderDetail: &detail)
        }
    }
    
    func calculateDetailTotal(orderDetail: inout WorkOrderDetail){
        let discountValue: Double = orderDetail.DiscountValue ?? 0
        self.order.clearOrderDetailDiscount(orderDetail: &orderDetail, discountType: enumDiscountTypes.KC)
        
        if let kitComponentPrice = self.getKitComponentPrice(detail: orderDetail){
            self.setComponentPriceFromKit(kitComponentPrice: kitComponentPrice, detail: &orderDetail)
        }
        
        orderDetail.NetRowValueVatIncluded = orderDetail.OrderedQuantity * orderDetail.GrossUnitValueVatIncluded - discountValue
        if let vatRate = orderDetail.VatRate {
            let netValueVatExcluded = (orderDetail.NetRowValueVatIncluded / (1 + vatRate)).rounded(toPlaces: 2)
            orderDetail.VatValue =  (netValueVatExcluded * vatRate).rounded(toPlaces: 2)
        }
        
        for var child in self.order.getChildCollection(parentId: orderDetail.OrderDetailId){
            self.calculateDetailTotal(orderDetail: &child)
        }
    }
    
    func setComponentPriceFromKit(kitComponentPrice: Double, detail: inout WorkOrderDetail){
        if detail.GrossUnitValueVatIncluded > kitComponentPrice{
            let discount = (detail.GrossUnitValueVatIncluded - kitComponentPrice) * detail.OrderedQuantity
            self.setNewDiscountForComponent(detail: &detail, discountValue: discount)
        }
        else{
            detail.GrossUnitValueVatIncluded = kitComponentPrice
        }
    }
    
    func getKitComponentPrice(detail: WorkOrderDetail) -> Double?{
        var price: Double? = nil
        for item in self.itemTemplate.itemTemplateDetails{
            if item.rowType == detail.RowType && item.price != nil{
                price = item.price!
                detail.IsOriginalPriceChanged = true
                detail.applyPromoEngine = false
                return price
            }
            else{
                detail.applyPromoEngine = true
            }
        }
        return nil
    }
    
    func clearKitDiscounts(){
        self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.KT)
        for detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            let discount = detail.DiscountValue ?? 0
            detail.NetRowValueVatIncluded = detail.grossRowValueVatIncluded - discount
        }
    }
    
    func recalculateTotals(){
        self.glasses.NetRowValueVatIncluded = 0
        self.glasses.GrossUnitValueVatIncluded = 0
        self.glasses.DiscountValue = 0
        
        for detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            self.glasses.NetRowValueVatIncluded += detail.NetRowValueVatIncluded
            self.glasses.GrossUnitValueVatIncluded += detail.GrossUnitValueVatIncluded * detail.OrderedQuantity
            if let discountValue = detail.DiscountValue{
                self.glasses.DiscountValue! += discountValue
            }
        }
        
        self.glasses.VatValue = self.glasses.vatValue
    }
    
    func updateTotal(){
        var title = Util.getString("Total") + ": " + Util.DoubleToStringWithPointSeparator(0) + settings.userSettings.defaultCurrency
        if self.kitHasPrice {
            title = Util.getString("Total") + ": " + Util.DoubleToStringWithPointSeparator(self.glasses.NetRowValueVatIncluded) + settings.userSettings.defaultCurrency
        }
        else{
            var totalPrice: Double = 0
            var totalExtra: Double = 0
            for detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
                if detail.RowType == rowTypeEnum.extra.rawValue{
                    totalExtra += detail.grossRowValueVatIncluded
                }
                else{
                    totalPrice += detail.grossRowValueVatIncluded
                }
            }
            
            let discountValue = self.getInternalDiscountsTotalValue()
            let subtotal: Double = totalPrice + totalExtra - discountValue
            
            title = Util.getString("Total") + ": " + Util.DoubleToStringWithPointSeparator(subtotal - self.glasses.kitExternalDiscountsTotalValue) + settings.userSettings.defaultCurrency
        }
        self.btTotalOrder.setTitle(title, for: .normal)
    }
    
    func longGesture(){
        //Long press gestures
        let frameLongPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(frameLongPressAction))
        frameLongPress.minimumPressDuration = 0.5
        frameLongPress.delegate = self
        self.viewFrame.addGestureRecognizer(frameLongPress)
        
        let rightLensLongPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(rightLensLongPressAction))
        rightLensLongPress.minimumPressDuration = 0.5
        rightLensLongPress.delegate = self
        self.viewRightLens.addGestureRecognizer(rightLensLongPress)
        
        let leftLensLongPress:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(leftLensLongPressAction))
        leftLensLongPress.minimumPressDuration = 0.5
        leftLensLongPress.delegate = self
        self.viewLeftLens.addGestureRecognizer(leftLensLongPress)
        
        // Tap gestures
        let frameLongTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(frameTap))
        frameLongTap.delegate = self
        self.viewFrame.addGestureRecognizer(frameLongTap)
        
        let leftLensLongTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(leftLensTap))
        leftLensLongTap.delegate = self
        self.viewLeftLens.addGestureRecognizer(leftLensLongTap)
        
        let rightLensLongTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rightLensTap))
        rightLensLongTap.delegate = self
        self.viewRightLens.addGestureRecognizer(rightLensLongTap)
        
        let lfFrameNetValueTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(framePriceTap))
        let lfFrameGrossValueTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(framePriceTap))
        lfFrameNetValueTap.delegate = self
        lfFrameGrossValueTap.delegate = self
        self.lfFrameNetValue.isUserInteractionEnabled = true
        self.lfFrameGrossValue.isUserInteractionEnabled = true
        self.lfFrameNetValue.addGestureRecognizer(lfFrameNetValueTap)
        self.lfFrameGrossValue.addGestureRecognizer(lfFrameGrossValueTap)
        
        let lfLeftLensNetValueTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(leftLensPriceTap))
        let lfLeftLensGrossValueTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(leftLensPriceTap))
        lfLeftLensNetValueTap.delegate = self
        lfLeftLensGrossValueTap.delegate = self
        self.lfLeftLensNetValue.isUserInteractionEnabled = true
        self.lfLeftLensGrossValue.isUserInteractionEnabled = true
        self.lfLeftLensNetValue.addGestureRecognizer(lfLeftLensNetValueTap)
        self.lfLeftLensGrossValue.addGestureRecognizer(lfLeftLensGrossValueTap)
        
        let lfRightLensNetValueTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rightLensPriceTap))
        let lfRightLensGrossValueTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(rightLensPriceTap))
        lfRightLensNetValueTap.delegate = self
        lfRightLensGrossValueTap.delegate = self
        self.lfRightLensNetValue.isUserInteractionEnabled = true
        self.lfRighLensGrossValue.isUserInteractionEnabled = true
        self.lfRightLensNetValue.addGestureRecognizer(lfRightLensNetValueTap)
        self.lfRighLensGrossValue.addGestureRecognizer(lfRightLensGrossValueTap)
        
        let clinicalStatusTap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(clinicalStatusTapAction))
        clinicalStatusTap.delegate = self
        self.lfGlassesClinicalStatus.addGestureRecognizer(clinicalStatusTap)
        
        let clinicalStatusLongTap:UILongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(clinicalStatusLongPressAction))
        clinicalStatusLongTap.minimumPressDuration = 0.5
        clinicalStatusLongTap.delegate = self
        self.lfGlassesClinicalStatus.addGestureRecognizer(clinicalStatusLongTap)
        self.lfGlassesClinicalStatus.isUserInteractionEnabled = true
    }
    
    @objc func frameTap(){
        if self.frame == nil{
            self.productAction = "select"
            self.rowType = rowTypeEnum.frame.rawValue
            self.selectProduct(productFamilyCodes: ["MNT"], criteriaXPO: self.frameCriteria, title: Util.getString("Frame"))
        }
        else{
            self.productAction = "view"
            self.rowType = rowTypeEnum.frame.rawValue
            self.openProductDetailViewController(styleId: self.frame!.StyleId)
        }
    }
    
    @objc func leftLensTap(){
        if self.leftLens == nil{
            self.productAction = "select"
            self.rowType = rowTypeEnum.leftLens.rawValue
            self.selectProduct(productFamilyCodes: ["LOF"], criteriaXPO: self.leftLensCriteria, title: Util.getString("Left Lens"))
        }
        else{
            self.productAction = "view"
            self.rowType = rowTypeEnum.leftLens.rawValue
            self.openProductDetailViewController(styleId: self.leftLens!.StyleId)
        }
    }
    
    @objc func rightLensTap(){
        if self.rightLens == nil{
            self.productAction = "select"
            self.rowType = rowTypeEnum.rightLens.rawValue
            self.selectProduct(productFamilyCodes: ["LOF"], criteriaXPO: self.rightLensCriteria, title: Util.getString("Right Lens"))
        }
        else{
            self.productAction = "view"
            self.rowType = rowTypeEnum.rightLens.rawValue
            self.openProductDetailViewController(styleId: self.rightLens!.StyleId)
        }
    }
    
    func openProductDetailViewController(styleId: Int){
        State.LoadBarcodeInfo(styleId: styleId, completionHandler: {result in
            if result == nil {
                NetworkController.AlertConnectionError(viewController: self)
            }
            else if result == true{
                if let barcodeInfo = State.barcodeInfo {
                    let tempShoppingCart = ShoppingCart()
                    tempShoppingCart.addItem(barcodeInfo: barcodeInfo)
                    tempShoppingCart.recalculate(completionHandler: {
                        let productDetailViewController = (self.storyboard?.instantiateViewController(withIdentifier: "productDetailViewController") as! ProductDetailViewController)
                        productDetailViewController.cartItem = tempShoppingCart.cartItems[0]
                        productDetailViewController.delegate = self
                        self.navigationController?.pushViewController(productDetailViewController, animated: true)
                    })
                }
                else{
                    NetworkController.AlertConnectionError(viewController: self)
                }
            }
            else {
                Util.GeneralAlert(viewController: self, message: Util.getString("This product does not have a barcode!"))
            }
        })
    }
    
    func productSelected(barcodeInfo: WSBarcodeInfo, viewController: UIViewController) {
        if self.canAddProductToCart(barcodeInfo: barcodeInfo, viewController: viewController){
            self.createItem(barcodeInfo: barcodeInfo)
            
            self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                self.isOrderChanged = true
                
                if self.rowType == rowTypeEnum.frame.rawValue {
                    self.createFrameLayout()
                }
                else if self.rowType == rowTypeEnum.leftLens.rawValue {
                    self.createLeftLensLayout()
                }
                else if self.rowType == rowTypeEnum.rightLens.rawValue {
                    self.createRightLensLayout()
                }
                else if self.rowType == rowTypeEnum.extra.rawValue {
                    self.tvExtraTreatments.reloadData()
                }
                else if self.rowType == rowTypeEnum.defaultService.rawValue {
                    self.tvExtraTreatments.reloadData()
                }
                
                self.refreshUI()
                
                self.returnToWorkOrderConfiguratorTabBar()
            })
        }
    }
    
    func returnToWorkOrderConfiguratorTabBar(){
        if let nc = self.navigationController {
            for i in 0..<nc.viewControllers.count{
                if (nc.viewControllers[i].isKind(of: WOGlassesConfiguratorTabBarController.self)){
                    if  let viewController = self.navigationController?.viewControllers[i]{
                        _ = self.navigationController?.popToViewController(viewController, animated: false)
                        break
                    }
                    else{
                        _ = self.navigationController?.popViewController(animated: true)
                    }
                }
            }
        }else{
            _ = self.navigationController?.popViewController(animated: true)
        }
    }
    
    func canAddProductToCart(barcodeInfo: WSBarcodeInfo, viewController: UIViewController) -> Bool{
        if barcodeInfo.IsWorkOrderSaleEnabled != true{
            Util.GeneralAlertAutoDismiss(viewController: viewController, message: Util.getString("Article cannot be sold in work order."), time: 2.0)
            return false
        }
        return true
    }
    
    func addButtonText() -> String {
        return Util.getString("Add to WO")
    }
    
    func isbagButtonVisible() -> Bool {
        return false
    }
    
    func productAddedCount() -> Int {
        return 0
    }
    
    func isTabBarVisible() -> Bool {
        if self.productAction == "select"{
            return true
        }
        else if self.productAction == "view"{
            return false
        }
        return false
    }
    
    @objc func framePriceTap(){
        if let frame = self.frame{
            if(allowModifyComponentDiscountAndPrice(component: frame)){
                self.rowType = rowTypeEnum.frame.rawValue
                self.changeDiscount(orderDetail: frame)
            }
        }
    }
    
    @objc func leftLensPriceTap(){
        if let leftLens = self.leftLens{
            if(allowModifyComponentDiscountAndPrice(component: leftLens)){
                self.rowType = rowTypeEnum.leftLens.rawValue
                self.changeDiscount(orderDetail: leftLens)
            }
        }
    }
    
    @objc func rightLensPriceTap(){
        if let rightLens = self.rightLens{
            if(allowModifyComponentDiscountAndPrice(component: rightLens)){
                self.rowType = rowTypeEnum.rightLens.rawValue
                self.changeDiscount(orderDetail: rightLens)
            }
        }
    }
    
    func selectProduct(productFamilyCodes: [String], criteriaXPO: String, title: String){
        let productViewController = self.storyboard?.instantiateViewController(withIdentifier: "productViewController") as! ProductViewController
        State.productsFilterResponse = ProductsFilterResponse()
        productViewController.title =  title
        productViewController.delegate = self
        productViewController.criteriaXPO = criteriaXPO
        productViewController.selectedFamilyCodes = productFamilyCodes
        self.navigationController?.pushViewController(productViewController, animated: true)
    }
    
    @objc func frameLongPressAction(sender: UILongPressGestureRecognizer) {
        if sender.state == UIGestureRecognizer.State.began{
            self.productAction = "select"
            self.rowType = rowTypeEnum.frame.rawValue
            self.selectProduct(productFamilyCodes: ["MNT"], criteriaXPO: self.frameCriteria, title: Util.getString("Frames"))
        }
    }
    
    @objc func rightLensLongPressAction(sender: UILongPressGestureRecognizer) {
        if sender.state == UIGestureRecognizer.State.began{
            self.productAction = "select"
            self.rowType = rowTypeEnum.rightLens.rawValue
            self.selectProduct( productFamilyCodes: ["LOF"], criteriaXPO: self.rightLensCriteria, title: Util.getString("Right Lens"))
        }
    }
    
    @objc func leftLensLongPressAction(sender: UILongPressGestureRecognizer) {
        if sender.state == UIGestureRecognizer.State.began{
            self.productAction = "select"
            self.rowType = rowTypeEnum.leftLens.rawValue
            self.selectProduct(productFamilyCodes: ["LOF"], criteriaXPO: leftLensCriteria, title: Util.getString("Left Lens"))
        }
    }
    
    func openPopUp(_ dataSource: [INameable], _ dataSourceType: String, _ title: String ) {
        let popupSelectorViewController = self.storyboard?.instantiateViewController(withIdentifier: "popupSelectorViewController") as! PopupSelectorViewController
        popupSelectorViewController.shouldBeSearchBarHidden = false
        popupSelectorViewController.itemSelectedCallback = selectedValue
        popupSelectorViewController.dataSource = dataSource
        popupSelectorViewController.dataSourceType = dataSourceType
        popupSelectorViewController.title = title
        let nav = UINavigationController(rootViewController: popupSelectorViewController)
        nav.modalPresentationStyle = UIModalPresentationStyle.fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
    func selectedValue(item: AnyObject, parentItem: AnyObject?){
        if item.isKind(of: DiscountCauses.self){
            let discountCause = item as! DiscountCauses
            if let orderDetail = self.changeDiscountForOrderDetail{
                var item: PriceChangeItem = PriceChangeItem()
                
                if orderDetail.RowType == rowTypeEnum.glasses.rawValue{
                    item = orderDetail.convertGlassesToPriceChangeItem()
                }
                else{
                    item = orderDetail.convertToPriceChangeItem()
                }
                
                item.discountCause = discountCause
                
                if(discountCause.isFixedDiscount){
                    self.applyFixedDiscount(item: item, discountCause: discountCause)
                }
                else{
                    let dialog: PriceChangeDialog = PriceChangeDialog(item: item, delegate: self)
                    dialog.show(viewController: self)
                }
            }
        }
    }
    
    func applyFixedDiscount(item: PriceChangeItem, discountCause: DiscountCauses){
        let result: PriceChangeResult = PriceChangeResult(item: item)
        result.discountCause = discountCause
        
        let discountValue = item.grossUnitValue - Util.applyDiscount(grossValue: item.grossUnitValue, discountPercent: discountCause.maxDiscount)
        let newPrice = (item.grossUnitValue - discountValue).rounded(toPlaces: 2)
        
        if item.grossUnitValue >= newPrice{
            result.netRowValueVatIncluded = newPrice
        }
        else{
            result.grossUnitValueVatIncluded = newPrice
        }
        result.discountValue = discountValue * item.quantity
        result.discountPercentage = Double(discountCause.maxDiscount * 100).rounded(toPlaces: 2)
        result.effectCategory = "PD%"
        result.canApplyPromotions = false
        
        self.handlePriceChangeResult(result: result)
    }
    
    func recalculateAndReturnToCurrentView(){
        self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
            self.isOrderChanged = true
            
            if self.rowType == rowTypeEnum.frame.rawValue {
                self.createFrameLayout()
            }
            else if self.rowType == rowTypeEnum.leftLens.rawValue {
                self.createLeftLensLayout()
            }
            else if self.rowType == rowTypeEnum.rightLens.rawValue {
                self.createRightLensLayout()
            }
            else if self.rowType == rowTypeEnum.extra.rawValue {
                self.tvExtraTreatments.reloadData()
            }
            else if self.rowType == rowTypeEnum.defaultService.rawValue {
                self.tvExtraTreatments.reloadData()
            }
            
            self.refreshUI()
            
            _ = self.navigationController?.popViewController(animated: true)
        })
    }
    
    func getComponent(rowType: String) -> WorkOrderDetail? {
        for detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            if detail.RowType == rowType{
                return detail
            }
        }
        return nil
    }
    
    func replaceExistingComponent(newComponent: WorkOrderDetail){
        for i in 0..<self.order.OrderDetail.count {
            if self.order.OrderDetail[i].OrderDetailId == newComponent.OrderDetailId {
                self.order.OrderDetail[i] = newComponent
                break
            }
        }
    }
    
    func removeExistingItem(existingItem: WorkOrderDetail){
        for i in 0..<self.order.OrderDetail.count {
            if self.order.OrderDetail[i].OrderDetailId == existingItem.OrderDetailId {
                self.order.OrderDetail.remove(at: i)
                break
            }
        }
    }
    
    @IBAction func btFrameMoreActions_Click(_ sender: Any) {
        self.rowType = rowTypeEnum.frame.rawValue
        self.moreOptionsAlert()
    }
    
    @IBAction func btRightLensMoreActions_Click(_ sender: Any) {
        self.rowType = rowTypeEnum.rightLens.rawValue
        self.moreOptionsAlert()
    }
    
    @IBAction func btLeftLensMoreActions_Click(_ sender: Any) {
        self.rowType = rowTypeEnum.leftLens.rawValue
        self.moreOptionsAlert()
    }
    
    func moreOptionsAlert(){
        var alert = UIAlertController()
        if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
            alert = UIAlertController(title: nil, message: nil, preferredStyle: .alert)
        }
        else{
            alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        }
        
        let addNewProductAction = UIAlertAction(title: Util.getString("Scan"), style: .default, handler: {(_) in
            self.openScannerBarcode()
        })
        addNewProductAction.setValue(Util.resizeImage(sourceImage: UIImage.init(named: "barcodeScanner.png")!, newWidth: 25, newHeight: 25), forKey: "image")
        alert.addAction(addNewProductAction)
        
        if self.rowType == rowTypeEnum.rightLens.rawValue{
            if let rightLens = self.rightLens, self.leftLens == nil, kitContainsLeftLens{
                alert.addAction(UIAlertAction(title: Util.getString("Duplicate"), style: .default, handler: {(_) in
                    let clone = rightLens.clone()
                    clone.OrderDetailId = UUID().uuidString
                    clone.RowType = rowTypeEnum.leftLens.rawValue
                    clone.OrderDetailRowNumber = self.order.getNextDetailRowNumber()
                    if let discounts  = clone.discounts{
                        for discount in discounts{
                            discount.OrderDiscountId = UUID()
                            discount.OrderDetailId = UUID.init(uuidString: clone.OrderDetailId)!
                        }
                    }
                    self.leftLens = clone
                    self.order.OrderDetail.append(self.leftLens!)
                    
                    self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                        self.refreshUI()
                    })
                }))
            }
            if self.rightLens != nil{
                alert.addAction(UIAlertAction(title: Util.getString("ChangeDistance"), style: .default, handler: {(_) in
                    self.changeLensDistanceType(rowType: rowTypeEnum.rightLens, title: "OD")
                }))
            }
        }
        
        if self.rowType == rowTypeEnum.leftLens.rawValue{
            if let leftLens = self.leftLens, self.rightLens == nil, kitContainsRightLens{
                alert.addAction(UIAlertAction(title: Util.getString("Duplicate"), style: .default, handler: {(_) in
                    let clone = leftLens.clone()
                    clone.OrderDetailId = UUID().uuidString
                    clone.RowType = rowTypeEnum.rightLens.rawValue
                    clone.OrderDetailRowNumber = self.order.getNextDetailRowNumber()
                    if let discounts  = clone.discounts{
                        for discount in discounts{
                            discount.OrderDiscountId = UUID()
                            discount.OrderDetailId = UUID.init(uuidString: clone.OrderDetailId)!
                        }
                    }
                    self.rightLens = clone
                    self.order.OrderDetail.append(self.rightLens!)
                    
                    self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                        self.refreshUI()
                    })
                }))
            }
            if self.leftLens != nil{
                alert.addAction(UIAlertAction(title: Util.getString("ChangeDistance"), style: .default, handler: {(_) in
                    self.changeLensDistanceType(rowType: rowTypeEnum.leftLens, title: "OS")
                }))
            }
        }
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            return
        }))
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func resetLeftDistance(){
        self.orderDetailGlasses?.LensLeftIsFar = false
        self.orderDetailGlasses?.LensLeftIsNear = false
        self.orderDetailGlasses?.LensLeftIsIntermediate = false
    }
    
    func resetRightDistance(){
        self.orderDetailGlasses?.LensRightIsFar = false
        self.orderDetailGlasses?.LensRightIsNear = false
        self.orderDetailGlasses?.LensRightIsIntermediate = false
    }
    
    func changeLensDistanceType(rowType: rowTypeEnum, title: String){
        let alert = UIAlertController(title: title, message: "", preferredStyle: .alert)
        
        alert.addAction(UIAlertAction(title: Util.getString("Far"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()
                
                self.orderDetailGlasses?.LensRightIsFar = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()

                self.orderDetailGlasses?.LensLeftIsFar = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        alert.addAction(UIAlertAction(title: Util.getString("Near"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()

                self.orderDetailGlasses?.LensRightIsNear = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()

                self.orderDetailGlasses?.LensLeftIsNear = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        alert.addAction(UIAlertAction(title: Util.getString("Intermedio"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()
                
                self.orderDetailGlasses?.LensRightIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()
                
                self.orderDetailGlasses?.LensLeftIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        alert.addAction(UIAlertAction(title: Util.getString("Far-Near"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()
                
                self.orderDetailGlasses?.LensRightIsFar = true
                self.orderDetailGlasses?.LensRightIsNear = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()
                
                self.orderDetailGlasses?.LensLeftIsFar = true
                self.orderDetailGlasses?.LensLeftIsNear = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        alert.addAction(UIAlertAction(title: Util.getString("Far-Intermedio"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()
                
                self.orderDetailGlasses?.LensRightIsFar = true
                self.orderDetailGlasses?.LensRightIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()
                
                self.orderDetailGlasses?.LensLeftIsFar = true
                self.orderDetailGlasses?.LensLeftIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        alert.addAction(UIAlertAction(title: Util.getString("Near-Intermedio"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()
                
                self.orderDetailGlasses?.LensRightIsNear = true
                self.orderDetailGlasses?.LensRightIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()
                
                self.orderDetailGlasses?.LensLeftIsNear = true
                self.orderDetailGlasses?.LensLeftIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        alert.addAction(UIAlertAction(title: Util.getString("Far-Near-Intermedio"), style: .default, handler: {(_) in
            if rowType == rowTypeEnum.rightLens{
                self.resetRightDistance()
                
                self.orderDetailGlasses?.LensRightIsFar = true
                self.orderDetailGlasses?.LensRightIsNear = true
                self.orderDetailGlasses?.LensRightIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
            else if rowType == rowTypeEnum.leftLens{
                self.resetLeftDistance()
                
                self.orderDetailGlasses?.LensLeftIsFar = true
                self.orderDetailGlasses?.LensLeftIsNear = true
                self.orderDetailGlasses?.LensLeftIsIntermediate = true
                self.orderDetailGlassesLensDistanceTypeLayout()
            }
        }))
        
        alert.addAction(UIAlertAction(title: Util.getString("Cancel"), style: .destructive, handler: {(_) in
            return
        }))
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func openScannerBarcode(){
        let scannerViewController = self.storyboard?.instantiateViewController(withIdentifier: "scannerViewController") as! ScannerViewController
        scannerViewController.delegate = self
        scannerViewController.isSlideButtonVisible = false
        self.navigationController?.pushViewController(scannerViewController, animated: true)
    }
    
    func barcodeFound(barcode: String, captureSession: AVCaptureSession) {
        State.LoadBarcodeInfo(barcode: barcode, completionHandler: {
            if let barcodeInfo = State.barcodeInfo {
                if self.rowType == rowTypeEnum.frame.rawValue{
                    self.decodeBarcodeAsFrame(barcodeInfo: barcodeInfo, barcode: barcode, captureSession: captureSession)
                }
                else if self.rowType == rowTypeEnum.rightLens.rawValue{
                    self.decodeBarcodeAsRightLens(barcodeInfo: barcodeInfo, barcode: barcode, captureSession: captureSession)
                }
                else if self.rowType == rowTypeEnum.leftLens.rawValue{
                    self.decodeBarcodeAsLeftLens(barcodeInfo: barcodeInfo, barcode: barcode, captureSession: captureSession)
                }
            }
            else{
                Util.scannedBarcodeNotFoundAlert(code: barcode, message: Util.getString("Barcode not found!"), viewController: self, captureSession: captureSession)
            }
        })
    }
    
    func decodeBarcodeAsFrame(barcodeInfo: WSBarcodeInfo, barcode: String, captureSession: AVCaptureSession){
        if barcodeInfo.productFamilyCode == productFamilyCodeEnum.montature.rawValue{
            if self.frame == nil {
                self.createItem(barcodeInfo: barcodeInfo)
                self.recalculateAndReturnToCurrentView()
            }
            else{
                Util.AlertYesNo(viewController: self, title: "", message: "You already have a frame.Do you want to replace it?", actionYes: {
                    self.createItem(barcodeInfo: barcodeInfo)
                    self.recalculateAndReturnToCurrentView()
                }) {
                    _ = self.navigationController?.popViewController(animated: true)
                }
            }
        }
        else{
            Util.scannedBarcodeNotFoundAlert(code: barcode, message: "This product is not a frame.Please use a valid barcode for this type of component!", viewController: self, captureSession: captureSession)
        }
    }
    
    func decodeBarcodeAsRightLens(barcodeInfo: WSBarcodeInfo, barcode: String, captureSession: AVCaptureSession){
        if barcodeInfo.productFamilyCode == productFamilyCodeEnum.lenti_oftalmiche.rawValue{
            if self.rightLens == nil {
                self.createItem(barcodeInfo: barcodeInfo)
                self.recalculateAndReturnToCurrentView()
            }
            else{
                Util.AlertYesNo(viewController: self, title: "", message: "You already have a right lens.Do you want to replace it?", actionYes: {
                    self.createItem(barcodeInfo: barcodeInfo)
                    self.recalculateAndReturnToCurrentView()
                }) {
                    _ = self.navigationController?.popViewController(animated: true)
                }
            }
        }
        else{
            Util.scannedBarcodeNotFoundAlert(code: barcode, message: "This product is not a lens.Please use a valid barcode for this type of component!", viewController: self, captureSession: captureSession)
        }
    }
    
    func decodeBarcodeAsLeftLens(barcodeInfo: WSBarcodeInfo, barcode: String, captureSession: AVCaptureSession){
        if barcodeInfo.productFamilyCode == productFamilyCodeEnum.lenti_oftalmiche.rawValue{
            if self.leftLens == nil {
                self.createItem(barcodeInfo: barcodeInfo)
                self.recalculateAndReturnToCurrentView()
            }
            else{
                Util.AlertYesNo(viewController: self, title: "", message: "You already have a left lens.Do you want to replace it?", actionYes: {
                    self.createItem(barcodeInfo: barcodeInfo)
                    self.recalculateAndReturnToCurrentView()
                }) {
                    _ = self.navigationController?.popViewController(animated: true)
                }
            }
        }
        else{
            Util.scannedBarcodeNotFoundAlert(code: barcode, message: "This product is not a lens.Please use a valid barcode for this type of component!", viewController: self, captureSession: captureSession)
        }
    }
    
    var changeDiscountForOrderDetail: WorkOrderDetail? = nil
    func changeDiscount(orderDetail: WorkOrderDetail){
        State.loadDiscountCauses(filterString: nil, completionHandler: { result in
            if let discountCauses = result {
                self.changeDiscountForOrderDetail = orderDetail
                self.openPopUp(discountCauses, "DiscountCauses", "Discount Causes")
            }
        })
    }
    
    func onApplay(result: PriceChangeResult) {
        self.handlePriceChangeResult(result: result)
    }
    
    func onClear(result: PriceChangeResult) {
        self.handlePriceChangeResult(result: result)
    }
    
    func onCancel() {
        return
    }
    
    func handlePriceChangeResult(result: PriceChangeResult){
        //var item = WorkOrderDetail()
        if rowType == rowTypeEnum.frame.rawValue{
            //item = frame!
            //item.importPriceChanges(result: result)
            self.setNewDiscountForFrame(result: result)
            self.createFrameLayout()
        }
        else if rowType == rowTypeEnum.rightLens.rawValue{
            //item = rightLens!
            //item.importPriceChanges(result: result)
            self.setNewDiscountForLens(result: result, lens: &rightLens!)
            self.createRightLensLayout()
        }
        else if rowType == rowTypeEnum.leftLens.rawValue{
            //item = leftLens!
            //item.importPriceChanges(result: result)
            self.setNewDiscountForLens(result: result, lens: &leftLens!)
            self.createLeftLensLayout()
        }
        else if rowType == rowTypeEnum.extra.rawValue{
            if var extra = self.order.OrderDetail.first(where: {$0.OrderDetailRowNumber == result.rowNumber}){
                //item = extra
                //item.importPriceChanges(result: result)
                self.setNewDiscountForForExtra(result: result, extra: &extra)
                
                self.indexToHide = result.rowNumber * 2 + 1
                self.indexToShow = nil
            }
        }
        else if rowType == rowTypeEnum.glasses.rawValue{
            //item = glasses
            //item.importPriceChanges(result: result)
            self.setNewDiscountForGlasses(result: result)
        }
        
        self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
            self.isOrderChanged = true
            self.refreshUI()
        })
    }
    
    func setNewDiscountForGlasses(result: PriceChangeResult){
        self.glasses.IsOriginalPriceChanged = true
        self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.MA)
        if result.discountValue > 0 {
            self.order.addOrderDetailDiscount(orderDetail: &self.glasses, discountCauseId: result.discountCause.discountCauseId, discountValue: result.discountValue, discountType: enumDiscountTypes.MA, promotionId: nil)
        }
    }
    
    func clearDiscountForGlasses(){
        self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.MA)
        self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
            self.isOrderChanged = true
            self.refreshUI()
        })
    }
    
    func setNewDiscountForComponent(detail: inout WorkOrderDetail, discountValue: Double){
        self.order.clearOrderDetailDiscount(orderDetail: &detail, discountType: enumDiscountTypes.KC)
        self.order.addOrderDetailDiscount(orderDetail: &detail, discountCauseId: -5, discountValue: discountValue, discountType: enumDiscountTypes.KC, promotionId: nil)
    }
    
    func setNewDiscountForFrame(result: PriceChangeResult){
        self.order.clearOrderDetailDiscount(orderDetail: &self.frame!, discountType: enumDiscountTypes.MC)
        if result.discountValue > 0 {
            self.order.addOrderDetailDiscount(orderDetail: &self.frame!, discountCauseId: result.discountCause.discountCauseId, discountValue: result.discountValue, discountType: enumDiscountTypes.MC, promotionId: nil)
        }
        else{
            //self.frame!.importPriceChanges(result: result)
        }
    }
    
    func setNewDiscountForLens(result: PriceChangeResult, lens: inout WorkOrderDetail){
        self.order.clearOrderDetailDiscount(orderDetail: &lens, discountType: enumDiscountTypes.MC)
        if result.discountValue > 0 {
            self.order.addOrderDetailDiscount(orderDetail: &lens, discountCauseId: result.discountCause.discountCauseId, discountValue: result.discountValue, discountType: enumDiscountTypes.MC, promotionId: nil)
        }
        else{
            //lens.importPriceChanges(result: result)
        }
    }
    
    func setNewDiscountForForExtra(result: PriceChangeResult, extra: inout WorkOrderDetail){
        self.order.clearOrderDetailDiscount(orderDetail: &extra, discountType: enumDiscountTypes.MC)
        if result.discountValue > 0 {
            self.order.addOrderDetailDiscount(orderDetail: &extra, discountCauseId: result.discountCause.discountCauseId, discountValue: result.discountValue, discountType: enumDiscountTypes.MC, promotionId: nil)
        }
        else{
            //extra.importPriceChanges(result: result)
        }
    }
    
    @IBAction func btAddExtraServices_Click(_ sender: Any) {
        self.productAction = "select"
        self.rowType = rowTypeEnum.extra.rawValue
        self.selectProduct(productFamilyCodes: ["SRV","TRT"], criteriaXPO: self.extraCriteria, title: Util.getString("Extra"))
    }
    
    @IBAction func btTotalOrder_Click(_ sender: Any) {
        self.showTotalInfoAlert()
    }
    
    func showTotalInfoAlert(){
        var message = ""
        
        var totalPrice: Double = 0
        var totalExtra: Double = 0
        for detail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            if detail.RowType == rowTypeEnum.extra.rawValue{
                totalExtra += detail.grossRowValueVatIncluded
            }
            else{
                totalPrice += detail.grossRowValueVatIncluded
            }
        }
        
        message.append(Util.getString("SingleGlasses") + ": "  + Util.DoubleToStringWithTwoDecimals(totalPrice) + settings.userSettings.defaultCurrency)
        
        message.append("\n")
        message.append(Util.getString("Extra") + ": " + Util.DoubleToStringWithTwoDecimals(totalExtra) + settings.userSettings.defaultCurrency)
        
        let discountValue = self.getInternalDiscountsTotalValue()
        let subtotal: Double = totalPrice + totalExtra - discountValue
        message.append("\n")
        message.append(Util.getString("ComponentDiscount") + ": "  + Util.DoubleToStringWithTwoDecimals(discountValue) + settings.userSettings.defaultCurrency)
        
        message.append("\n")
        message.append(Util.getString("Subtotal") + ": "  + Util.DoubleToStringWithTwoDecimals(subtotal) + settings.userSettings.defaultCurrency)
        
        message.append("\n")
        message.append(Util.getString("Discount") + ": "  + Util.DoubleToStringWithTwoDecimals(self.glasses.kitExternalDiscountsTotalValue) + settings.userSettings.defaultCurrency)
        
        var title = Util.getString("Total") + ": " + Util.DoubleToStringWithPointSeparator(0) + settings.userSettings.defaultCurrency
        if self.kitHasPrice {
            title = Util.getString("Total") + ": " + Util.DoubleToStringWithPointSeparator(self.glasses.NetRowValueVatIncluded) + settings.userSettings.defaultCurrency
        }
        else{
            title = Util.getString("Total") + ": " + Util.DoubleToStringWithPointSeparator(subtotal - self.glasses.kitExternalDiscountsTotalValue) + settings.userSettings.defaultCurrency
        }
        
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        let addDiscount = UIAlertAction(title: Util.getString("AddDiscount"), style: .default, handler : { (action) -> Void in
            self.rowType = rowTypeEnum.glasses.rawValue
            self.changeDiscount(orderDetail: self.glasses)
        })
        
        let clearDiscount = UIAlertAction(title: Util.getString("ClearDiscount"), style: .default, handler : { (action) -> Void in
            self.clearDiscountForGlasses()
        })
        
        if self.discountMode == DiscountsMode.ManualPrices.rawValue{
            alert.addAction(addDiscount)
            alert.addAction(clearDiscount)

            if self.glasses.kitExternalDiscountsTotalValue == 0 {
                alert.actions[1].isEnabled = false
            }
        }
        
        let OKAction = UIAlertAction(title: "OK", style: .default, handler : { (action) -> Void in
            return
        })
        alert.addAction(OKAction)
        self.present(alert, animated: true, completion: nil)
    }
    
    func getInternalDiscountsTotalValue() -> Double{
        var discountValue: Double = 0
        let orderDetailsChildsCollection = self.order.getChildCollection(parentId: self.glasses.OrderDetailId)
        for child in orderDetailsChildsCollection{
            if let discounts = child.discounts{
                for discount in discounts{
                    if discount.DiscountType == enumDiscountTypes.PR.rawValue || discount.DiscountType == enumDiscountTypes.MA.rawValue{
                        continue
                    }
                    else{
                        if let dv = discount.DiscountValue{
                            discountValue += dv
                        }
                    }
                }
            }
        }
        return discountValue
    }
    
    // ---- TableView Extra Services
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if tableView == tvExtraTreatments{
            return self.extras.count * 2
        }else {
            return self.features.count
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if tableView == tvExtraTreatments{
            if let indexPaths = tableView.indexPathsForSelectedRows{
                for index in indexPaths{
                    if index != indexPath{
                        self.indexToHide = index.row + 1
                        tableView.deselectRow(at: index, animated: false)
                    }
                }
            }
            self.indexToShow = indexPath.row + 1
            tableView.beginUpdates()
            tableView.endUpdates()
        
            self.rowType = rowTypeEnum.extra.rawValue
        }
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        if tableView == tvExtraTreatments{
            if tableView.indexPathsForSelectedRows == nil{
                self.indexToHide = indexPath.row + 1
                self.indexToShow = nil
                tableView.beginUpdates()
                tableView.endUpdates()
            }
        
            self.rowType = ""
            
        }
    }
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{
        if tableView == tvExtraTreatments {
            if self.indexToHide != nil || self.indexToShow != nil{
                if self.indexToHide != nil{
                    if self.indexToHide == indexPath.row{
                        self.indexToHide = nil
                        return 0.0
                    }
                }
                if self.indexToShow != nil{
                    if self.indexToShow == indexPath.row{
                        return 40.0
                    }
                }
                if ((indexPath.row % 2) != 0){
                    return 0.0
                }
            }
            else if ((indexPath.row % 2) != 0){
                return 0.0
            }
            return 72.0
        }
        else if tableView == tvCustomGlasses {
            return 45.0
        }
        
        return 0 // should never happen
    }
    
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath?{
        if tableView == tvExtraTreatments {
            if ((indexPath.row % 2) == 0){
                return indexPath
            }
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if tableView == tvExtraTreatments {
            if ((tableView.indexPathForSelectedRow == nil) && ((indexPath.row % 2) == 0)) {
                return true
            }
        }
        return false
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if tableView == tvExtraTreatments {
            if (indexPath.row % 2) == 0 || indexPath.row == 0 {
                let cellHeader = tvExtraTreatments.dequeueReusableCell(withIdentifier: "CellWorkOrderHeaders") as! WorkOrderDetailCustomCell
                
                let extra = self.extras[indexPath.row / 2]
                
                cellHeader.wOHcode.text = extra.ProductCode
                cellHeader.wOHname.text = extra.ProductName
                
                cellHeader.wOHState.image = extra.getDetailRowType()
                
                cellHeader.quantityVar = extra.OrderedQuantity
                cellHeader.wOHquantity.text = extra.OrderedQuantity.description + " x "
                
                let discountValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(extra.internalDiscountsTotalValue)
                var netRowValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(extra.NetRowValueVatIncluded)
                let grossRowValue = Util.DoubleToDoubleRoundedWithTwoDecimalPlaces(extra.GrossUnitValueVatIncluded * extra.OrderedQuantity)
                
                netRowValue = grossRowValue - discountValue
                
                if(netRowValue.isLess(than: grossRowValue)){
                    let attributeString: NSMutableAttributedString =  NSMutableAttributedString(string: Util.DoubleToString(extra.GrossUnitValueVatIncluded) + " \(settings.userSettings.defaultCurrency)")
                    attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSMakeRange(0, attributeString.length))
                    cellHeader.wOHStatus.textColor = UIColor.red
                    
                    let attributedStringDiscount: NSMutableAttributedString = NSMutableAttributedString(string: "(" + Util.DoubleToStringWithTwoDecimals(discountValue * (-1) ) + " " +  settings.userSettings.defaultCurrency + ")")
                    
                    let combination = NSMutableAttributedString()
                    combination.append(attributeString)
                    combination.append(attributedStringDiscount)
                    
                    cellHeader.wOHprice.attributedText = combination
                }
                else{
                    cellHeader.wOHprice.attributedText = nil
                    cellHeader.wOHprice.text = Util.DoubleToString(extra.GrossUnitValueVatIncluded) + " \(settings.userSettings.defaultCurrency)"
                    cellHeader.wOHStatus.textColor = UIColor.black
                }
                cellHeader.wOHStatus.text = Util.DoubleToString(netRowValue) + " \(settings.userSettings.defaultCurrency)"
                
                return cellHeader
            }
            else{
                let cell = self.tvExtraTreatments.dequeueReusableCell(withIdentifier: "Cell2")! as! CartItemEditCustomCell
                cell.rowNumber = indexPath.row
                cell.delegate = self
                
                if self.discountMode == DiscountsMode.PromoPrices.rawValue{
                    cell.btDiscount.isHidden = true
                }
                else{
                    cell.btDiscount.isHidden = false
                }
                
                return cell
            }
        }
        else //if tableView == tvCustomGlasses
        {
            let cell = self.tvCustomGlasses.dequeueReusableCell(withIdentifier: "CellFeatures") as! CustomGlassesFeaturesCell
            
            let feature = self.features[indexPath.row]
            let customization = self.findValue(feature: feature)
            
            cell.tfGlassesFeatures.text = customization.FeatureValue
            cell.feature = feature
            cell.workOrderConfig = self
                
            return cell
        }
    }
    
    
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if tableView == tvExtraTreatments {
            if editingStyle == .delete {
                let extra = self.extras[indexPath.row / 2]
                self.removeExistingItem(existingItem: extra)
                self.extras.remove(at: indexPath.row / 2)
                
                var index = indexPath
                index.row += 1
                self.tvExtraTreatments.deleteRows(at: [index, indexPath], with: .fade)
                
                self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                    self.isOrderChanged = true
                    self.refreshUI()
                })
            }
        }
    }

    func addFeatureValue(feature: Features, featureValue: String){
        var alreadyExist: Bool = false
        
        for customization in self.glasses.Customizations {
            if customization.FeatureId == feature.featureId{
                customization.FeatureValue = featureValue
                alreadyExist = true
                break
            }
        }
            
        if alreadyExist == false {
            let customization: WorkOrderDetailCustomizations = WorkOrderDetailCustomizations()
                
            customization.OrderDetailCustomizationId = UUID().description
            customization.OrderDetailId = glasses.OrderDetailId
            customization.FeatureId = feature.featureId
            customization.FeatureValue = featureValue
            customization.Feature = feature
                
            self.glasses.Customizations.append(customization)
        }
    }
    
    func findValue(feature: Features) -> WorkOrderDetailCustomizations {
        var customization = WorkOrderDetailCustomizations()
        if self.glasses.Customizations.count > 0 {
            for cust in self.glasses.Customizations {
                if cust.FeatureId == feature.featureId{
                    customization = cust
                    break
                }
            }
        }

        return customization
    }
    
    func ValidateNauCustomizations() -> Bool {
        
        /* For Nau use a custom validation.
         Feature "Testo Asta" should be empty when "Inc. Terminale interno sx" = "Nulla" and "Inc. Asta esterna sx" in ("Nulla", "Logo NAU!")
         
         The possible ids from the feature, in the database, will be as follows:
         79 - Testo iniziali Asta
         88 - Inc. Terminale Interno sx
         89 - Inc. Asta esterno sx
         */
        
        var testoAsta: String = ""
        var incTerminaleInterno: String = ""
        var incAstaEsterna: String = ""
        
        for customization in self.glasses.Customizations{
            if customization.Feature.code == "NM7" {
                testoAsta = customization.FeatureValue!
            }
            
            if customization.Feature.code == "NM8" {
                incTerminaleInterno = customization.FeatureValue!
            }
            
            if customization.Feature.code == "NM5" {
                incAstaEsterna = customization.FeatureValue!
            }
        }
        
        if !testoAsta.isEmpty{
            if incTerminaleInterno == "Nulla" && (incAstaEsterna == "Nulla" || incAstaEsterna == "Logo NAU!"){
                Util.GeneralAlert(viewController: self, message: Util.getString("WorkOrderConfiguratorValidateNauCustomization"))
                return false
            }
        }
        
        return true
    }
    
    func validateFields() -> Bool {
        for feature in self.features {
            var hasValue: Bool = false
            if feature.isRequired == true{
                for cust in self.glasses.Customizations{
                    if feature.featureId == cust.FeatureId && !cust.FeatureValue.isNullOrEmpty {
                        hasValue = true
                        break
                    }
                }
                
                if hasValue == false{
                    Util.GeneralAlert(viewController: self, message: Util.getString("CustomFeatureRequired"))
                    return false
                }
            }
        }
        
        return true
    }
       
    
    @IBAction func allowSendToFactory_valueChange(_ sender: Any) {
        self.glasses.orderDetailGlasses?.AllowSendToFactory = self.allowSendToFactory.isOn
    }
    
    @objc func dismissKeyboard(){
        view.endEditing(true)
    }
    
    func minusButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = self.tvExtraTreatments.indexPathForSelectedRow{
                
                let extra = extras[indexPath.row / 2]
                
                if let cell = tvExtraTreatments.cellForRow(at: indexPath) as? WorkOrderDetailCustomCell {
                    if cell.quantityVar > 1{
                        if indexPath.row + 1 == row{
                            cell.quantityVar -= 1
                            cell.wOHquantity.text = cell.quantityVar.description + " x "
                            
                            if extra.canApplyPromotions == false{
                                //extra.DiscountValue! -= extra.DiscountValue! / extra.OrderedQuantity
                            }
                            
                            extra.OrderedQuantity -= 1
                            
                            self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                                self.isOrderChanged = true
                                self.refreshUI()
                                self.tvExtraTreatments.selectRow(at: indexPath, animated: false, scrollPosition: .none)
                            })
                        }
                    }
                }
            }
        }
    }
    
    func plusButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = tvExtraTreatments.indexPathForSelectedRow{
               
                let extra = extras[indexPath.row / 2]
            
                if let cell = tvExtraTreatments.cellForRow(at: indexPath) as? WorkOrderDetailCustomCell {
                    if indexPath.row + 1 == row{
                        cell.quantityVar += 1
                        cell.wOHquantity.text = cell.quantityVar.description + " x "
                        
                        if extra.canApplyPromotions == false{
                            //extra.DiscountValue! += extra.DiscountValue! / extra.OrderedQuantity
                        }
                        
                        extra.OrderedQuantity += 1
                        
                        self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                            self.isOrderChanged = true
                            self.refreshUI()
                            self.tvExtraTreatments.selectRow(at: indexPath, animated: false, scrollPosition: .none)
                        })
                    }
                }
            }
        }
    }
    
    func displayButtonAction(rowNumber: Int?) {
        if let row = rowNumber{
            if let indexPath = tvExtraTreatments.indexPathForSelectedRow{
                let extra = extras[indexPath.row / 2]
                
                if indexPath.row + 1 == row{
                    self.productAction = "view"
                    self.rowType = rowTypeEnum.extra.rawValue
                    self.openProductDetailViewController(styleId: extra.StyleId)
                }
            }
        }
    }
    
    func discountButtonAction(rowNumber: Int?){
        if let row = rowNumber{
            if let indexPath = tvExtraTreatments.indexPathForSelectedRow{
                let extra = extras[indexPath.row / 2]
                
                 if(allowModifyComponentDiscountAndPrice(component: extra)){
                    if indexPath.row + 1 == row{
                        self.changeDiscount(orderDetail: extra)
                    }
                }
            }
        }
    }
    
    @objc private func clinicalStatusTapAction() {
        let clinicalStatusViewContoller = self.storyboard?.instantiateViewController(withIdentifier: "history") as! ClinicalStatusViewContoller
        clinicalStatusViewContoller.delegate = self
        clinicalStatusViewContoller.contact = State.workOrder.contact
        clinicalStatusViewContoller.isAddNewCSEnable = false
        clinicalStatusViewContoller.isSlideMenuEnabled = false
        clinicalStatusViewContoller.loadRecentClinicalStatus = false
        clinicalStatusViewContoller.prescriptionType = "GL"
        self.navigationController?.pushViewController(clinicalStatusViewContoller, animated: true)
    }
    
    @objc func clinicalStatusLongPressAction(sender: UILongPressGestureRecognizer) {
        if sender.state == UIGestureRecognizer.State.began{
            self.editOrderDetailGlasses()
        }
    }
    
    func editOrderDetailGlasses(){
        //ToDo
    }
    
    func selectedClinicalStatus(clinicalStatus: ClinicalStatus) {
        self.clinicalStatus = clinicalStatus
        
        self.orderDetailGlasses = clinicalStatus.getOrderDetailGlasses(orderDetailId: UUID.init(uuidString: self.glasses.OrderDetailId)!)
        if let distance =  self.orderDetailGlasses?.GlassesDistanceType{
            self.glassesDistanceType = distance
        }
        
        self.glasses.orderDetailGlasses = self.orderDetailGlasses
        self.glasses.orderDetailGlasses?.AllowSendToFactory = self.allowSendToFactory.isOn
        self.replaceExistingComponent(newComponent: self.glasses)
        
        self.lfGlassesClinicalStatus.text = self.orderDetailGlasses?.getRX()
        self.clinicalStatusLensDistanceTypeLayout()
        
        self.navigationController?.popViewController(animated: true)
    }
    
    func distributeKitDiscountOnChildren(){
        if self.glasses.getNumberOfChild() > 0 && self.kitHasPrice{
            let discount = self.glasses.childrenTotalGrossValue.rounded(toPlaces: 2) - self.glasses.GrossUnitValueVatIncluded.rounded(toPlaces: 2)
            if discount > 0 {
                self.distributeDiscountOnChildren(discountValue: discount, discountType: .KT, discountCauseId: -5, promotionId: nil)
            }
        }
    }
    
    func distributeDiscountOnChildren(discountValue: Double, discountType: enumDiscountTypes, discountCauseId: Int, promotionId: Int?){
        var remainingDiscount = discountValue.rounded(toPlaces: 2)
        if remainingDiscount == 0 {
            return
        }
        var childrenSum: Double = 0
        var mostExpensiveChild: WorkOrderDetail? = nil
        for child in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            childrenSum += child.grossRowValueVatIncluded.rounded(toPlaces: 2)
            
            if mostExpensiveChild == nil {
                mostExpensiveChild = child
            }
            else{
                if child.grossRowValueVatIncluded > mostExpensiveChild!.grossRowValueVatIncluded{
                    mostExpensiveChild = child
                }
            }
        }
        
        let totalValueToDistributeProportionally = remainingDiscount
        for var child in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            if let mostExpensiveChild = mostExpensiveChild{
                if child.OrderDetailId == mostExpensiveChild.OrderDetailId{
                    continue
                }
            }
            var discount = ((child.grossRowValueVatIncluded / childrenSum) * totalValueToDistributeProportionally).rounded(toPlaces: 2)
            if discount > 0 {
                if discount > child.NetRowValueVatIncluded.rounded(toPlaces: 2){
                    discount = child.NetRowValueVatIncluded.rounded(toPlaces: 2)
                }
                remainingDiscount = remainingDiscount.rounded(toPlaces: 2) - discount.rounded(toPlaces: 2)
                self.order.addOrderDetailDiscount(orderDetail: &child, discountCauseId: discountCauseId, discountValue: discount, discountType: discountType, promotionId: nil)
            }
        }
        
        if remainingDiscount > 0 && mostExpensiveChild != nil {
            var discountToApply: Double = 0
            if var mostExpensiveChild = mostExpensiveChild{
                if mostExpensiveChild.NetRowValueVatIncluded.rounded(toPlaces: 2) > remainingDiscount.rounded(toPlaces: 2){
                    discountToApply = remainingDiscount.rounded(toPlaces: 2)
                    remainingDiscount = 0
                }
                else{
                    discountToApply = mostExpensiveChild.NetRowValueVatIncluded.rounded(toPlaces: 2)
                    remainingDiscount = remainingDiscount.rounded(toPlaces: 2) - mostExpensiveChild.NetRowValueVatIncluded.rounded(toPlaces: 2)
                }
                self.order.addOrderDetailDiscount(orderDetail: &mostExpensiveChild, discountCauseId: discountCauseId, discountValue: discountToApply, discountType: discountType, promotionId: nil)
            }
        }
    }
    
    @IBAction func sgPriceMode_ValueChanged(_ sender: Any) {
        if self.sgPriceMode.selectedSegmentIndex == 0{
            if self.discountMode == DiscountsMode.ManualPrices.rawValue{
                self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.MA)
                self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.MC)
                self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.FP)
                
                self.resetPriceToOriginalPrice()
                self.setPromoDiscountMode()
                self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                    self.refreshUI()
                })
            }
        }
        else if self.sgPriceMode.selectedSegmentIndex == 1{
            if self.discountMode == DiscountsMode.PromoPrices.rawValue{
                self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.PC)
                self.order.clearOrderDetailDiscount(orderDetail: &self.glasses, discountType: enumDiscountTypes.PR)
                
                self.resetPriceToOriginalPrice()
                self.setManualMode()
                self.order.recalculate(canApplyPromoEngine: self.canApplyPromoEngine, completionHandler: {
                    self.refreshUI()
                })
            }
        }
    }
    
    func resetPriceToOriginalPrice(){
        for orderDetail in self.order.getChildCollection(parentId: self.glasses.OrderDetailId){
            if self.order.originalVatChanged == false{
                orderDetail.GrossUnitValueVatIncluded = orderDetail.OriginalPrice!
            }
            else{
                if let vatRate = orderDetail.VatRate {
                    let netValueVatExcluded = (orderDetail.NetRowValueVatIncluded / (1 + vatRate)).rounded(toPlaces: 2)
                    orderDetail.VatValue =  (netValueVatExcluded * vatRate).rounded(toPlaces: 2)
                }
                orderDetail.DiscountValue = 0
                orderDetail.NetRowValueVatIncluded = orderDetail.GrossUnitValueVatIncluded * orderDetail.OrderedQuantity
            }
        }
    }
    
    func allowModifyComponentDiscountAndPrice(component: WorkOrderDetail) -> Bool{
        if discountMode != DiscountsMode.ManualPrices.rawValue{
            return false
        }
        
        if component.applyPromoEngine == false{
            Util.GeneralAlert(viewController: self, message: Util.getString("PriceAlreadySet"))
            return false
        }
        
        return true
    }
}
