angular.module('fasit').directive('fbBildHantering', function () { 'use strict'; var controller = ['$scope', '$element', '$rootScope', '$upload', '$filter', 'motivService', 'naeromraadeService', 'bilduppladdningService', 'navigationService', 'sideDrawerService', 'utskriftService', 'uiService', '$timeout', '$document', '$window', 'logService', 'kommentarService', function ( $scope: fb.IFbBildHanteringScope, $element: ng.IAugmentedJQuery, $rootScope: ng.IRootScopeService, $upload: any, $filter: ng.IFilterService, motivService: fb.IMotivService, naeromraadeService: fb.INaeromraadeService, bilduppladdningService: fb.IBilduppladdningService, navigationService: fb.INavigationService, sideDrawerService: fb.ISideDrawerService, utskriftService: fb.IUtskriftService, uiService: fb.IUIService, $timeout: ng.ITimeoutService, $document: ng.IDocumentService, $window: ng.IWindowService, logService: fb.ILogService, kommentarService: fb.IKommentarService ) { const draggedMotivListTag: string = 'draggedMotivList'; var $translate = $filter('translate'); // Gridlayout var gridStateLastMoveStepDirection = 0; $scope.harKommentarer = harKommentarer; $scope.harOloestaKommentarer = harOloestaKommentarer; $scope.kommentarTraadar = kommentarService.getKundportalKommentarerPerTyp( $scope.changetrackId.value, fb.FasITDomain.KundportalKommentarTyp.BILDER ); function applyTransform(boxTransforms: { box: HTMLElement; transform: string; zIndex: number; noAnimation: boolean }[]) { _.forEach(boxTransforms, function (ta) { ta.box.classList.remove('animation'); if (!ta.noAnimation) { ta.box.classList.add('animation'); } ta.box.style.zIndex = ta.zIndex + ''; ta.box.style['webkitTransform'] = ta.transform; ta.box.style['MozTransform'] = ta.transform; ta.box.style['msTransform'] = ta.transform; ta.box.style['OTransform'] = ta.transform; ta.box.style.transform = ta.transform; }); } function getBoxPixelWidth(width: string) { var bp = uiService.getCurrentBreakpoint(); var ret: number; switch (width) { case 'big': switch (bp) { case fb.FasITDomain.Breakpoints.lg: case fb.FasITDomain.Breakpoints.xl: ret = 425; break; default: ret = 355; } break; case 'medium': switch (bp) { case fb.FasITDomain.Breakpoints.lg: case fb.FasITDomain.Breakpoints.xl: ret = 320; break; default: ret = 255; } break; case 'small': switch (bp) { case fb.FasITDomain.Breakpoints.lg: case fb.FasITDomain.Breakpoints.xl: ret = 255; break; default: ret = 180; } break; case 'xsmall': switch (bp) { case fb.FasITDomain.Breakpoints.lg: case fb.FasITDomain.Breakpoints.xl: ret = 160; break; default: ret = 120; } break; default: ret = 0; break; } return ret; } function getAvailableWidth(gridContainer: ng.IAugmentedJQuery) { while (gridContainer.length > 0) { var width = gridContainer.width(); if (width !== null && width > 0) { return width; } gridContainer = gridContainer.parent(); } return 0; } function updateGridLayout(gridContainer: ng.IAugmentedJQuery, motiv: fb.MotivObjekt[], changeDirection: number, noAnimation?: boolean) { var motivById = _.groupBy(motiv, function (m) { return m.MotivId.value; }); var existingBoxes = gridContainer.find('.drop-bin').toArray(); var removedBoxesEl = _.filter(existingBoxes, function (box: HTMLElement) { return _.isUndefined(motivById[box.getAttribute('data-motiv-id')]); }); var boxesEl = _.filter(existingBoxes, function (box: HTMLElement) { return !_.isUndefined(motivById[box.getAttribute('data-motiv-id')]); }); var boxesSorted = _.sortBy(boxesEl, function (box: HTMLElement) { var linkedMotiv = motivById[box.getAttribute('data-motiv-id')][0]; var index = motiv.indexOf(linkedMotiv); return index; }); var availableWidth = getAvailableWidth(gridContainer); var x = 0; var y = 0; var currentRowHeight = 0; var totalHeight = 0; var transformAnimations = []; var spacing = 15; _.forEach(removedBoxesEl, function (box: HTMLElement) { box.style.display = 'none'; }); var boxWidth = getBoxPixelWidth($scope.selectedWidth || 'small') - spacing; var boxHeight = boxWidth; var hasBoxWidthChanged = false; _.forEach(boxesSorted, function (box: HTMLElement, i) { var prevIndex = box.hasAttribute('data-rendered-index') ? parseInt(box.getAttribute('data-rendered-index')) : -1; if ((x + boxWidth) >= availableWidth) { x = 0; y += currentRowHeight; totalHeight += currentRowHeight; currentRowHeight = 0; } var boxTransform = 'translateX(' + x + 'px) translateY(' + y + 'px) translateZ(0px)'; var isAdded = _.isUndefined(box.style.transform) || _.isNull(box.style.transform) || box.style.transform === ''; if (box.style.transform !== boxTransform) { transformAnimations.push({ box: box, transform: boxTransform, zIndex: isAdded ? motiv.length : Math.max(0, (i - prevIndex) * changeDirection), noAnimation: isAdded || noAnimation }); } if (box.style.zIndex !== '0') { box.style.zIndex = '0'; } box.setAttribute('data-rendered-index', String(i)); x += boxWidth + spacing; currentRowHeight = Math.max(currentRowHeight, boxHeight + spacing); hasBoxWidthChanged = hasBoxWidthChanged ? hasBoxWidthChanged : box.style.width !== (boxWidth + 'px'); }); totalHeight += currentRowHeight; if (transformAnimations.length > 0) { $timeout(function () { applyTransform(transformAnimations); }, 0); } if (hasBoxWidthChanged) { $timeout(function () { var size = boxWidth + 'px'; _.forEach(boxesSorted, function (box: HTMLElement) { box.style.width = size; box.style.height = size; }); gridContainer[0].style.height = totalHeight + 'px'; $scope.currentWidth = $scope.selectedWidth; }, 0); } if (!gridContainer[0].style.height) { gridContainer[0].style.height = totalHeight + 'px'; } if (gridContainer[0].style.visibility !== 'visible') { $timeout(function () { gridContainer[0].style.visibility = 'visible'; }, 0); } } function updateGridLayouts(noAnimation?: boolean) { var objektBilderContainerEl = $element.find('.container-images.fb-bildhantering-objektbilder'); var naeromraadeBilderContainerEl = $element.find('.container-images.fb-bildhantering-naeromraade'); if (objektBilderContainerEl.length > 0) { var objektBilder = $scope.onlyOmraade($scope.bilder.Objekten, false); updateGridLayout(objektBilderContainerEl, objektBilder, gridStateLastMoveStepDirection, noAnimation); } if (naeromraadeBilderContainerEl.length > 0) { var naeromraadeBilder = $scope.onlyOmraade($scope.bilder.Objekten, true); updateGridLayout(naeromraadeBilderContainerEl, naeromraadeBilder, gridStateLastMoveStepDirection, noAnimation); } } // Motivobjekten function reorderHemnetOrdning() { var temp = _.sortBy($scope.hemnetImages, function (obj) { return obj.SfdOrdning.value; }); for (var i = 0; i < temp.length; i++) { temp[i].HemnetOrdningsnummer.setValue(i + 1); } } function postReorder() { $scope.bilder.Objekten = _.sortBy($scope.bilder.Objekten, function (motiv: fb.MotivObjekt) { return 10 === motiv.KategoriId.value ? 1 : 0; }); if ($scope.maeklarObjektType) { if ($scope.hemnet1to5) { $scope.setHemnet1to5(); } reorderHemnetOrdning(); } } function moveImage(bildIndex: number, binIndex: number, left: boolean) { moveImageList([bildIndex], binIndex, left); } function moveImageList(bildIndexList: number[], binIndex: number, left: boolean) { if (bildIndexList.length < 1) { throw Error('Förväntar oss minst en bild som ska flyttas'); } const bilder: fb.Motiv = $scope.bilder; let antalObjektBilder = $scope.onlyOmraade(bilder.Objekten, false).length; if (!left) { antalObjektBilder += 1; //Hantering av släppa till vänster om första omrÃ¥desbilden och sista objektbilden har samma index } const tempList: fb.MotivObjekt[] = []; let kategoriIdOfFirstIsNaeromraade = bilder.Objekten[bildIndexList[0]].KategoriId.value === fb.FasITDomain.MotivKategoriId.NAEROMRAADE; bildIndexList.forEach((bildIndex) => { const bild = bilder.Objekten[bildIndex]; tempList.push(bild); if ((bild.KategoriId.value === fb.FasITDomain.MotivKategoriId.NAEROMRAADE) !== kategoriIdOfFirstIsNaeromraade) { throw Error('KategoriId skiljer sig'); } }); // Kräver att alla är av samma typ if (kategoriIdOfFirstIsNaeromraade) { if (binIndex < antalObjektBilder) { tempList.forEach((temp) => { temp.KategoriId.setValue(null); }); } } else { if (binIndex >= antalObjektBilder) { tempList.forEach((temp) => { temp.KategoriId.setValue(fb.FasITDomain.MotivKategoriId.NAEROMRAADE); }); } } const objekten: fb.MotivObjekt[] = bilder.Objekten; // Ta bort bilder som ska flyttas i array (måste börja bakifrån eftersom listan förändras av detta) for (let i = bildIndexList.length - 1; i >= 0; i--) { objekten.splice(bildIndexList[i], 1); } //Bin Indexet förändras för alla bilder som var till vänster om const numberOfBilderLeftOfBin = bildIndexList.filter(bildIndex => bildIndex < binIndex).length; binIndex -= numberOfBilderLeftOfBin; objekten.splice(binIndex, 0, ...tempList); for (let index: number = 0; index < bilder.Objekten.length; index++) { //setValue används inte här för att vi inte ska dirtytracka dessa på det sättet. //originalValue sätts så vi slipper få mergekonflikter här. objekten[index].SfdOrdning.value = index; objekten[index].SfdOrdning.originalValue = index; } } function getSelectedMotivMapById(isNaeromraadeMotiv: boolean) { return _.groupBy(_.filter($scope.bilder.Objekten, function (m: fb.MotivObjekt) { var isSelected = $scope.selectedMotiv[m.MotivId.value].value; return isSelected && (isNaeromraadeMotiv ? m.KategoriId.value === 10 : m.KategoriId.value !== 10); }), function (m: fb.MotivObjekt) { return m.MotivId.value; }); } function getSelectedMotivBinIndices(isNaeromraadeMotiv: boolean) { var selectedMotivById = getSelectedMotivMapById(isNaeromraadeMotiv); var ngRepeatMotivArray = $scope.onlyOmraade($scope.bilder.Objekten, isNaeromraadeMotiv); return _.reject(_.map(ngRepeatMotivArray, function (m, index) { return selectedMotivById[m.MotivId.value] ? index : null; }), _.isNull); } function moveMotivToTheLeft(binIndex: number, startIndex: number) { var moveToBinIndex = Math.max(0, binIndex - 1); if (moveToBinIndex === binIndex) { return binIndex; } moveImage(startIndex + binIndex, startIndex + moveToBinIndex, true); return moveToBinIndex; } function moveMotivToTheRight(binIndex: number, startIndex: number, nrOfMotiv: number) { var moveToBinIndex = Math.min(nrOfMotiv - 1, binIndex + 1); if (moveToBinIndex === binIndex) { return binIndex; } moveImage(startIndex + moveToBinIndex, startIndex + binIndex, true); return moveToBinIndex; } function moveMotivOneStep(binIndices: number[], startIndex: number, nrOfMotiv: number, leftStep: boolean) { var sorted = _.sortBy(binIndices, function (index) { return leftStep ? index : -index; }); _.forEach(sorted, function (binIndex, i) { var prevBinIndex = i === 0 ? binIndex : sorted[i - 1]; var indexDiff = Math.abs(binIndex - prevBinIndex); if (prevBinIndex === binIndex || indexDiff >= 2) { sorted[i] = leftStep ? moveMotivToTheLeft(binIndex, startIndex) : moveMotivToTheRight(binIndex, startIndex, nrOfMotiv); } }); } function moveMotivToTheEdges(binIndices: number[], startIndex: number, nrOfMotiv: number, front: boolean) { var sorted = _.sortBy(binIndices, function (index) { return front ? index : -index; }); _.forEach(sorted, function (binIndex, i) { if (front && binIndex > 0) { moveImage(startIndex + binIndex, startIndex + i, true); } else if (!front && binIndex < nrOfMotiv) { moveImage(startIndex + binIndex, startIndex + nrOfMotiv - i, false); } }); } function moveOneOrAllSelectedMotivOneStep(srcMotiv: fb.MotivObjekt, leftStep: boolean) { var isNaeromraadeMotiv = srcMotiv.KategoriId.value === 10; var motiv = $scope.onlyOmraade($scope.bilder.Objekten, isNaeromraadeMotiv); var nrOfMotiv = motiv.length; var isPartOfSelection = $scope.isSelected(srcMotiv); var binIndices = isPartOfSelection ? getSelectedMotivBinIndices(isNaeromraadeMotiv) : [motiv.indexOf(srcMotiv)]; var startIndex = isNaeromraadeMotiv ? $scope.onlyOmraade($scope.bilder.Objekten, false).length : 0; gridStateLastMoveStepDirection = leftStep ? -1 : 1; moveMotivOneStep(binIndices, startIndex, nrOfMotiv, leftStep); postReorder(); $scope.saveObjekten(); } function moveOneOrAllSelectedMotivToTheEdges(srcMotiv: fb.MotivObjekt, front: boolean) { var isNaeromraadeMotiv = srcMotiv.KategoriId.value === 10; var motiv = $scope.onlyOmraade($scope.bilder.Objekten, isNaeromraadeMotiv); var nrOfMotiv = motiv.length; var isPartOfSelection = $scope.isSelected(srcMotiv); var binIndices = isPartOfSelection ? getSelectedMotivBinIndices(isNaeromraadeMotiv) : [motiv.indexOf(srcMotiv)]; var startIndex = isNaeromraadeMotiv ? $scope.onlyOmraade($scope.bilder.Objekten, false).length : 0; gridStateLastMoveStepDirection = front ? -1 : 1; moveMotivToTheEdges(binIndices, startIndex, nrOfMotiv, front); postReorder(); $scope.saveObjekten(); } function getIndexFromId(id) { return parseInt(id.substring(id.indexOf('-') + 1, id.length)); } function getAllSelectedMotiv() { return _.filter($scope.bilder.Objekten, function (item: fb.MotivObjekt) { return $scope.selectedMotiv[item.MotivId.value].value; }); } function getAllSelectedMotivIds() { return _.map(getAllSelectedMotiv(), function (item: fb.MotivObjekt) { return item.MotivId.value; }); } // Upload function startUpload(obj) { var fildo: any = obj.fildo || { BildUrl: '', MotivText: '' }; switch ($scope.type) { case fb.BildHanteringEnum.MAEKLAROBJEKT: case fb.BildHanteringEnum.MAEKLAROBJEKT_OEVRIG: case fb.BildHanteringEnum.PROJEKT: fildo.MaeklarObjektId = $scope.changetrackId.value; break; case fb.BildHanteringEnum.NAEROMRAADEN: fildo.NaeromraadeInfoId = $scope.changetrackId.value; break; case fb.BildHanteringEnum.PERSON: fildo.PersonId = $scope.changetrackId.value; break; } var obstr = JSON.stringify(fildo); $upload.upload({ url: '/WebAPI/api/Motiv2/', method: 'POST', data: { FilDO: obstr }, 'file': obj.File, }).progress(function (evt) { obj.Progress = Math.round(100.0 * evt.loaded / evt.total); }).success(function (data, status, headers, config) { var item = new fb.MotivObjekt(data); $scope.bilder.Objekten.push(item); postReorder(); obj.Success = true; $timeout(function () { $scope.deleteUploadProgress(obj); }, 1000); }).error(function (data, status, headers, config) { obj.Success = false; if (data.Message) { obj.Message = data.Message; } else { obj.Message = $translate('BILDHANTERING.BILDUPPLADDNING_MISSLYCKADES'); } }); } // Hemnet function removeHemnetAll() { _.each($scope.hemnetImages, function (item) { if (item.HemnetOrdningsnummer.value !== null) { item.setValue(item.HemnetOrdningsnummer, null); } }); $scope.hemnetImages.length = 0; } function addHemnet(motivObjekt: fb.MotivObjekt) { if (motivObjekt.SkallVisasPaaObjektPresentationen.value) { $scope.hemnetImages.push(motivObjekt); motivObjekt.setValue(motivObjekt.SkallVisasPaaObjektPresentationen, true); motivObjekt.setValue(motivObjekt.HemnetOrdningsnummer, 1); reorderHemnetOrdning(); } } function removeHemnet(motivObjekt: fb.MotivObjekt) { motivObjekt.setValue(motivObjekt.HemnetOrdningsnummer, null); $scope.hemnetImages.splice($scope.hemnetImages.indexOf(motivObjekt), 1); if ($scope.hemnet1to5) { if ($scope.bilder.Objekten.length < 6) { $scope.hemnet1to5 = false; } else { var nextNonHidden; for (var i = 5; !nextNonHidden && i < $scope.bilder.Objekten.length; i++) { var bilden = $scope.bilder.Objekten[i]; if (bilden.SkallVisasPaaObjektPresentationen.value && bilden.KategoriId.value !== 10) { nextNonHidden = i; } } if (nextNonHidden) { moveImage(nextNonHidden, $scope.bilder.Objekten.indexOf(motivObjekt), true); moveImage($scope.bilder.Objekten.indexOf(motivObjekt), 6, true); $scope.setHemnet1to5(); } else { $scope.hemnet1to5 = false; } } } else { reorderHemnetOrdning(); } } // Scope $scope.options = { isTouchDevice: 'ontouchstart' in $document[0], }; $scope.uploadProgress = []; $scope.selectedMotiv = []; $scope.kategoris = [ { Namn: 'Ingen', KategoriId: null }, { Namn: 'Planritning', KategoriId: 2 }, { Namn: 'Tomtkarta', KategoriId: 4 }, { Namn: 'Närområde', KategoriId: fb.FasITDomain.MotivKategoriId.NAEROMRAADE }, ]; $scope.hemnet1to5 = false; $scope.hemnetImages = []; // Kopiering $scope.kopiera = { oeppna: function (type: fb.BildHanteringEnum) { switch (type) { case fb.BildHanteringEnum.MAEKLAROBJEKT: $scope.kopiera.entitetnamn = 'GLOBALS.OBJEKT'; $scope.kopiera.objekts = _.filter(navigationService.getNavigationObjects().OeppnaObjekt.OeppnaMaeklarObjekt, function (oeppetObjekt: fb.OeppnaMaeklarObjekt) { return oeppetObjekt.MaeklarObjektId !== $scope.changetrackId.value; }).reverse(); $scope.kopiera.getShowStr = function (oeppetObjekt: fb.OeppnaMaeklarObjekt) { return oeppetObjekt.Visningstext + ' (' + oeppetObjekt.Objektnummer + ')'; }; $scope.kopiera.kopieraTyp = 'MaeklarObjekt'; $scope.kopiera.getKopieraId = function () { return ($scope.kopiera.objekt).MaeklarObjektId; } break; case fb.BildHanteringEnum.PERSON: $scope.kopiera.def = motivService.kopiera('Brf', ($scope.$parent).foereningWrapper.foerening.PersonId.value, getAllSelectedMotivIds()); $scope.kopiera.def.$promise.then(function () { $scope.kopiera.showPopup = false; }); break; case fb.BildHanteringEnum.NAEROMRAADEN: $scope.kopiera.entitetnamn = 'GLOBALS.NAEROMRAADE'; $scope.kopiera.objekts = naeromraadeService.query(); $scope.kopiera.getShowStr = function (omraade: fb.NaeromrListItem) { return omraade.DelomraadeNamn; }; $scope.kopiera.kopieraTyp = 'Naeromraade'; $scope.kopiera.getKopieraId = function () { return ($scope.kopiera.objekt).NaeromraadeInfoId; } break; default: throw "Felaktiv parameter till bildkopiering"; } $scope.kopiera.showPopup = true; }, kopieraTyp: undefined, kopieraId: undefined, getKopieraId: undefined, entitetnamn: undefined, def: new fb.ResourceBase({}), showPopup: false, showSpinner: false, objekts: undefined, kopiera: function () { if ($scope.kopiera.objekt) { var motivIds = getAllSelectedMotivIds(); $scope.kopiera.def = motivService.kopiera($scope.kopiera.kopieraTyp, $scope.kopiera.getKopieraId(), motivIds); $scope.kopiera.def.$promise.then(function () { $scope.kopiera.showPopup = false; }); $scope.kopiera.objekt = undefined; } else { $scope.kopiera.showPopup = false; } }, getShowStr: undefined }; $scope.kopieraTillAllaObjekt = { showPopup: false, alternativ: [ $filter('translate')('BILDHANTERING.LAEGG_TILL_SIST'), $filter('translate')('BILDHANTERING.ERSAETT_ALLA_BEFINTLIGA'), ], valtAlternativ: null, kopiera: function () { var kopieringsobjekt: fb.IKopieraBilderObjektIProjektDO = { MaeklarObjektIdFoerProjektet: $scope.maeklarObjekt.MaeklarObjektId.value, Motiv: (function () { return getAllSelectedMotivIds(); })(), KopieringsaettBilder: -1 }; if ($scope.kopieraTillAllaObjekt.valtAlternativ === $scope.kopieraTillAllaObjekt.alternativ[0]) { // Lägg till sist kopieringsobjekt.KopieringsaettBilder = fb.FasITDomain.KopieringsaettBilder.TILLFOER_SIST; } else if ($scope.kopieraTillAllaObjekt.valtAlternativ === $scope.kopieraTillAllaObjekt.alternativ[1]) { // Ersätt alla befintliga kopieringsobjekt.KopieringsaettBilder = fb.FasITDomain.KopieringsaettBilder.ERSAETT_ALLA_BILDER; } motivService.kopieraTillObjektIProjekt(kopieringsobjekt); $scope.kopieraTillAllaObjekt.valtAlternativ = null; $scope.kopieraTillAllaObjekt.showPopup = false; $scope.kopieraTillAllaObjekt.showAlert = true; }, showAlert: false, dismissAlert: function () { $scope.kopieraTillAllaObjekt.showAlert = false; } }; // Motiv $scope.onlyOmraade = function (objekten, filterOnNaeromraade) { return _.filter(objekten, function (item: fb.MotivObjekt) { return filterOnNaeromraade ? item.KategoriId.value === 10 : item.KategoriId.value !== 10; }); }; // Ladda upp motivobjekt $scope.onFileSelect = function ($files) { // Rensa valda filer så vi får nytt event om användaren väljer samma fil(er) igen. angular.element('#fb-bild-hantering-input-file-container input').val(''); for (var i = 0; i < $files.length; i++) { var file = $files[i]; var obj = { File: file, Progress: 0, Message: null, Success: undefined, Done: false } $scope.uploadProgress.push(obj); startUpload(obj); } }; $scope.deleteUploadProgress = function (fil) { $scope.uploadProgress.splice($scope.uploadProgress.indexOf(fil), 1); }; // Ändra motivobjekt $scope.changeKategori = function (bild: fb.MotivObjekt) { bild.KategoriId.setValue(bild.KategoriId.value); // Om byter till närområde, flytta bilden längst ner i listan så den hamnar sist bland alla närområdesbilder /*if (bild.KategoriId.value === 10) { moveImage($scope.bilder.Objekten.indexOf(bild), $scope.bilder.Objekten.length, false); }*/ postReorder(); $scope.saveObjekten(); }; // Selected Funktioner $scope.selectMotiv = function (bild: fb.MotivObjekt) { $scope.selectedMotiv[bild.MotivId.value].value = !$scope.selectedMotiv[bild.MotivId.value].value; }; $scope.unSelectAll = function () { _.each(_.values($scope.selectedMotiv), function (isSelected) { isSelected.value = false; }); }; $scope.isSelected = function (bild: fb.MotivObjekt) { return $scope.selectedMotiv[bild.MotivId.value] && $scope.selectedMotiv[bild.MotivId.value].value; }; $scope.nbrOfSelectedItems = function () { return _.where(_.values($scope.selectedMotiv), { value: true }).length; }; // Menyval för markerade bilder $scope.openSkickaEpostSideDrawer = function () { // Motiven för område och objekt ligger i samma array och kan ha samma ordningsnummer. // Vi sorterar därför alla områdesbiler separat och lägger sedan ihop dem var vanligaMotivSortedBySfdOrdning = _.sortBy( _.filter(getAllSelectedMotiv(), function (item: fb.MotivObjekt) { return item.KategoriId.value !== 10; }), function (item: fb.MotivObjekt) { return item.SfdOrdning.value; }); var omraadenMotivSortedBySfdOrdning = _.sortBy( _.filter(getAllSelectedMotiv(), function (item: fb.MotivObjekt) { return item.KategoriId.value === 10; }), function (item: fb.MotivObjekt) { return item.SfdOrdning.value; }); sideDrawerService.setSideDrawer('EpostUtskick', { recipients: [], sender: null, body: null, maeklarObjektId: ($scope.maeklarObjekt && $scope.maeklarObjekt.MaeklarObjektId && $scope.maeklarObjekt.MaeklarObjektId.value) ? $scope.maeklarObjekt.MaeklarObjektId.value : null, subject: null, showAddButtons: true, attachedMotiv: vanligaMotivSortedBySfdOrdning.concat(omraadenMotivSortedBySfdOrdning), }); }; $scope.toggleSelectAll = function () { var finnsEjValdBild = _.find(_.values($scope.selectedMotiv), function (isSelected: fb.ChangeTrack) { return isSelected.value === false; }); var bools = !(!finnsEjValdBild || finnsEjValdBild.value); _.each(_.values($scope.selectedMotiv), function (isSelected) { isSelected.setValue(bools); }); } $scope.hideSelected = function () { _.each($scope.bilder.Objekten, function (motiv) { if ($scope.selectedMotiv[motiv.MotivId.value].value) { $scope.hideMotiv(motiv); } }); }; $scope.print = function (style: string) { // Motiven för område och objekt ligger i samma array och kan ha samma ordningsnummer. // Vi sorterar därför alla områdesbiler separat och lägger sedan ihop dem var vanligaMotivSortedBySfdOrdning = _.sortBy( _.filter(getAllSelectedMotiv(), function (item: fb.MotivObjekt) { return item.KategoriId.value !== 10; }), function (item: fb.MotivObjekt) { return item.SfdOrdning.value; }); var omraadenMotivSortedBySfdOrdning = _.sortBy( _.filter(getAllSelectedMotiv(), function (item: fb.MotivObjekt) { return item.KategoriId.value === 10; }), function (item: fb.MotivObjekt) { return item.SfdOrdning.value; }); var adress = $scope.maeklarObjekt.isUtland ? $scope.maeklarObjekt.Adress.GatuAdressUtland.value : $scope.maeklarObjekt.Adress.AdressText.value; utskriftService.skrivUtMotiv(vanligaMotivSortedBySfdOrdning.concat(omraadenMotivSortedBySfdOrdning), $scope.maeklarObjekt.Adress.AdressText.value, style); }; $scope.hasFoerening = function () { var foerening = ($scope.$parent).foereningWrapper.foerening return foerening.PersonId && !!foerening.PersonId.value; }; $scope.fattasKartMarkering = function () { var ret = !( $scope.maeklarObjekt.Latitud.originalValue && $scope.maeklarObjekt.Longitud.originalValue ); return ret; }; $scope.openImportGallery = function () { var maeklarObjektScope = (($scope).$parent); var foereningsId = maeklarObjektScope.foereningWrapper.foerening.PersonId ? maeklarObjektScope.foereningWrapper.foerening.PersonId.value : undefined; var naeromraadeInfoId = maeklarObjektScope.maeklarObjekt.NaeromraadeInfoId ? maeklarObjektScope.maeklarObjekt.NaeromraadeInfoId.value : undefined; var typeHasFoerning = !maeklarObjektScope.maeklarObjekt.isSmaahus && !maeklarObjektScope.maeklarObjekt.isGaard && !maeklarObjektScope.maeklarObjekt.isOevrig && !maeklarObjektScope.maeklarObjekt.isArrende; sideDrawerService.setSideDrawer('Bildgalleri', { bilder: $scope.bilder.Objekten, maeklarObjektId: $scope.changetrackId.value, foereningsId: foereningsId, naeromraadeInfoId: naeromraadeInfoId, typeHasFoerning: typeHasFoerning, ProjektId: $scope.maeklarObjekt && $scope.maeklarObjekt.ObjektIProjekt && $scope.maeklarObjekt.ObjektIProjekt.ProjektId ? $scope.maeklarObjekt.ObjektIProjekt.ProjektId.value : null }); }; // Zoom-meny $scope.getTextForWidth = function () { switch ($scope.selectedWidth) { case 'big': return $translate('BILDHANTERING.STOERST'); case 'medium': return $translate('BILDHANTERING.STOR'); case 'small': return $translate('BILDHANTERING.LITEN'); case 'xsmall': return $translate('BILDHANTERING.MINST'); default: return ''; } }; // Hemnet $scope.toggleHemnet1to5 = function (is1to5: boolean, event?: any) { if (event) { if ($scope.isDoldaBilderPos1To5()) { event.stopPropagation(); return; } } $scope.hemnet1to5 = is1to5; if ($scope.hemnet1to5) { $scope.setHemnet1to5(); } else { $scope.showSelectedOnHemnet(); } }; $scope.isHemnet = function (bild) { return _.contains($scope.hemnetImages, bild); }; $scope.isDoldaBilderPos1To5 = function () { if ($scope.bilder.$resolved) { for (var i = 0; i < 5 && i < $scope.bilder.Objekten.length; i++) { if (!$scope.bilder.Objekten[i].SkallVisasPaaObjektPresentationen.value) { return true; } } } return false; } $scope.showOnHemnet = function (motivObjekt: fb.MotivObjekt) { if (_.contains($scope.hemnetImages, motivObjekt)) { removeHemnet(motivObjekt); } else { if ($scope.hemnetImages.length === 5) { return; } addHemnet(motivObjekt); } } $scope.setHemnet1to5 = function () { removeHemnetAll(); for (var index = 0; index < $scope.bilder.Objekten.length; index++) { if ($scope.bilder.Objekten[index].SkallVisasPaaObjektPresentationen.value === false) { $scope.bilder.Objekten[index].setValue( $scope.bilder.Objekten[index].SkallVisasPaaObjektPresentationen, true ); } addHemnet($scope.bilder.Objekten[index]); if ($scope.hemnetImages.length === 5) { break; } } reorderHemnetOrdning(); $scope.saveObjekten(); }; $scope.showSelectedOnHemnet = function () { removeHemnetAll(); $scope.hemnet1to5 = false; _.each($scope.bilder.Objekten, function (motivobjekt) { if ($scope.selectedMotiv[motivobjekt.MotivId.value].value) { $scope.showOnHemnet(motivobjekt); } }); $scope.saveObjekten(); }; $scope.setWidth = function (width: string) { $scope.selectedWidth = width; updateGridLayouts(true); }; // Motivklick $scope.imageClick = function (bild, $event: JQueryInputEventObject) { if ($event.shiftKey) { $scope.selectMotiv(bild); } else { $scope.openImageEditor(bild); } }; $scope.openImageEditor = function (bild) { var headerText = ''; switch ($scope.type) { case fb.BildHanteringEnum.MAEKLAROBJEKT: case fb.BildHanteringEnum.MAEKLAROBJEKT_OEVRIG: headerText = $scope.maeklarObjekt.isUtland ? $scope.maeklarObjekt.Adress.GatuAdressUtland.value : $scope.maeklarObjekt.Adress.AdressText.value; break; case fb.BildHanteringEnum.NAEROMRAADEN: headerText = ''; break; case fb.BildHanteringEnum.PERSON: headerText = (($scope.$parent).kontakt).Personnamn.value; break; case fb.BildHanteringEnum.PROJEKT: headerText = $scope.maeklarObjekt.MaeklarObjektNamn.value; break; } sideDrawerService.setSideDrawer('Bildeditering', { kommentarer: $scope.kommentarTraadar, bilder: $scope.bilder.Objekten, kanKommentera: $scope.kanKommentera, aerKundportalenAktiv: $scope.visaKundportalenKommentarer, highlightedImage: bild, headerText: headerText, showKategorier: $scope.maeklarObjektType || $scope.maeklarObjektOevrigType, showToggleMotiv: $scope.maeklarObjektType || $scope.projektType || $scope.maeklarObjektOevrigType, showToggleHemnet: $scope.maeklarObjektType, toggleHemnet: $scope.showOnHemnet, toggleMotiv: $scope.hideMotiv, changeKategori: $scope.changeKategori, isHemnetMotiv: $scope.isHemnet, canAddHemnetMotiv: function () { return $scope.hemnetImages.length < 5; }, saveNewImage: function (fildo, file) { var obj = { File: file, Progress: 0, Message: null, Success: undefined, Done: false, fildo: fildo }; $scope.uploadProgress.push(obj); startUpload(obj); } }); }; function getIndexFromIdList(idList: string) : number[] { const subStr = idList.substring(idList.indexOf('-') + 1, idList.length); const numberList = subStr.split(',').map(val => parseInt(val)); return numberList; } // Flytta bild $scope.handleImageDragDrop = function (draggedMotivIndex: string, droppeddMotivIndex: string, left: boolean) { let binIndex: number = getIndexFromId(droppeddMotivIndex); if (draggedMotivIndex.indexOf(draggedMotivListTag) !== -1) { const bildIndexList: number[] = getIndexFromIdList(draggedMotivIndex); gridStateLastMoveStepDirection = _.sortBy(bildIndexList)[0] > binIndex ? -1 : 1; if (!left) { binIndex += 1; } moveImageList(bildIndexList, binIndex, left); } else { const bildIndex: number = getIndexFromId(draggedMotivIndex); gridStateLastMoveStepDirection = bildIndex > binIndex ? -1 : 1; if (!left) { binIndex += 1; } moveImage(bildIndex, binIndex, left); } postReorder(); $scope.saveObjekten(); }; $scope.getDraggedIdList = function (srcMotiv: fb.MotivObjekt): string { const isPartOfSelection = $scope.isSelected(srcMotiv); const isNaeromraade = srcMotiv.KategoriId.value === fb.FasITDomain.MotivKategoriId.NAEROMRAADE; // Ska inte kunna dra flera närområden eller när det inte är en ikryssad if (!isPartOfSelection || isNaeromraade) { return null; } const list = getSelectedMotivBinIndices(false); return draggedMotivListTag + '-' + list.join(); } $scope.moveMotivOneStepToTheLeft = function (srcMotiv: fb.MotivObjekt) { moveOneOrAllSelectedMotivOneStep(srcMotiv, true); }; $scope.moveMotivOneStepToTheRight = function (srcMotiv: fb.MotivObjekt) { moveOneOrAllSelectedMotivOneStep(srcMotiv, false); }; $scope.moveMotivToTheFront = function (srcMotiv: fb.MotivObjekt) { moveOneOrAllSelectedMotivToTheEdges(srcMotiv, true); }; $scope.moveMotivToTheEnd = function (srcMotiv: fb.MotivObjekt) { moveOneOrAllSelectedMotivToTheEdges(srcMotiv, false); }; // Arkivering $scope.haamtaBilderFraanArkivet = function () { var ret = motivService.getFraanArkivet($scope.changetrackId.value); ret.$promise.then(function (data) { if (!!data && data.data) { $scope.arkiverad = false; $scope.laeserFraanArkiv = false; //$scope.bilder = motivService.maeklarObjekt.get($scope.changetrackId.value); //$scope.nyligenAaterlaestFraanArkivet = true; $scope.laddaBilder(); } else { //Någonting gick fel $scope.arkiverad = true; $scope.laeserFraanArkiv = false; $scope.nyligenAaterlaestFraanArkivet = false; } }); $scope.arkiverad = false; $scope.laeserFraanArkiv = true; }; // Watchers / Listeners var windowResizeListener = _.throttle(function () { updateGridLayouts(true); }, 350); var uiBreakpointListenerUninstaller = $rootScope.$on('ui-breakpoint-changed', function () { $timeout(function () { updateGridLayouts(true); }, 500); }); const nyaKommentarTraadar = $rootScope.$on('nyaBildKommentarer', (event, nyaTraadar: fb.List) => { if (nyaTraadar .toArray() .every(kt => kt.MaeklarObjektId === $scope.maeklarObjekt.MaeklarObjektId.value && kt.KundportalKommentarTypId === fb.FasITDomain.KundportalKommentarTyp.BILDER ) ) { $scope.kommentarTraadar.splice(0, $scope.kommentarTraadar.length - 2); nyaTraadar.toArray().forEach(item => $scope.kommentarTraadar.push(item)); } }); $window.addEventListener('resize', windowResizeListener, false); $scope.$on('$destroy', function () { $window.removeEventListener('resize', windowResizeListener, false); uiBreakpointListenerUninstaller(); nyaKommentarTraadar(); }); // Tillåt inte första visade bild stående const calcPortraitWarning = images => { const first = images .find(bild => { return bild.SkallVisasPaaObjektPresentationen.value; }); if (first && first.MotivId.value) { const img = (document.getElementById(first.MotivId.value) as HTMLImageElement); if (img) { $scope.portraitWarning = img.naturalHeight > img.naturalWidth; } else { $scope.portraitWarning = false; } } else { $scope.portraitWarning = false; } }; $scope.$watchCollection("bilder.Objekten", function (newVal: any, oldVal: any) { if (!_.isArray(newVal) || !$scope.bilder.$resolved) { return; } newVal.forEach(item => { if (!$scope.selectedMotiv[item.MotivId.value]) { $scope.selectedMotiv[item.MotivId.value] = new fb.ChangeTrack(false); } }); // Vill ge tid att ladda in setTimeout(function () { calcPortraitWarning($scope.bilder.Objekten); }, 200); //calcPortraitWarning(newVal); $timeout(function () { updateGridLayouts(); }, 0); }); $scope.$watch('type', function (newV) { if (newV >= 0) { var resource; var motivArrayClass: fb.MotivIdArray; var removeImage = function (bilden: fb.MotivObjekt) { $scope.bilder.Objekten.splice($scope.bilder.Objekten.indexOf(bilden), 1); //Dequeuea bilden från sparning så att den inte sparas under/efter den blir borttagen bilden.dequeue(); //Ta bort bilnden från motivArrayobjektet if (angular.isDefined(motivArrayClass) && motivArrayClass.motivObjektId && motivArrayClass.motivObjektId.length > 0) { var taBort = _.find(motivArrayClass.motivObjektId, function (id: fb.ChangeTrack) { return id.value === bilden.MotivId.value; }); if (taBort) { motivArrayClass.motivObjektId.splice(motivArrayClass.motivObjektId.indexOf(taBort), 1); } } delete $scope.selectedMotiv[bilden.MotivId.value]; var hemnetIndex = $scope.hemnetImages.indexOf(bilden); if (hemnetIndex !== -1) { $scope.hemnetImages.splice(hemnetIndex, 1); } motivService.remove(bilden).$promise.then(function () { postReorder(); }); }; //FUNKTIONER $scope.saveObjekten = function () { motivArrayClass.motivObjektId = _.map($scope.bilder.Objekten, function (item: fb.MotivObjekt) { return new fb.ChangeTrack(item.MotivId.value); }); motivArrayClass.enqueue(); }; $scope.hideMotiv = function (bild: fb.MotivObjekt) { bild.setValue(bild.SkallVisasPaaObjektPresentationen, !bild.SkallVisasPaaObjektPresentationen.value); if ($scope.maeklarObjektType && bild.HemnetOrdningsnummer.value != null) { removeHemnet(bild); } calcPortraitWarning($scope.bilder.Objekten); }; $scope.removeSelected = function () { _.each(getAllSelectedMotiv(), function (item) { removeImage(item); }); calcPortraitWarning($scope.bilder.Objekten); }; //INIT $scope.maeklarObjektType = fb.BildHanteringEnum.MAEKLAROBJEKT === $scope.type; $scope.maeklarObjektOevrigType = fb.BildHanteringEnum.MAEKLAROBJEKT_OEVRIG === $scope.type; $scope.projektType = fb.BildHanteringEnum.PROJEKT === $scope.type; switch ($scope.type) { case fb.BildHanteringEnum.MAEKLAROBJEKT: case fb.BildHanteringEnum.MAEKLAROBJEKT_OEVRIG: case fb.BildHanteringEnum.PROJEKT: resource = motivService.maeklarObjekt; $scope.maeklarObjekt = ($scope.$parent).maeklarObjekt; break; case fb.BildHanteringEnum.NAEROMRAADEN: resource = motivService.naeromraade; break; case fb.BildHanteringEnum.PERSON: resource = motivService.person; break; } motivArrayClass = new fb.MotivIdArray([], $scope.changetrackId.value, $scope.type); $scope.laddaBilder = function () { $scope.bilder = resource.get($scope.changetrackId.value); $scope.bilder.$promise.then(function () { $scope.bilder.Objekten = _.sortBy($scope.bilder.Objekten, function (obj) { return obj.SfdOrdning.value; }); $scope.bilder.Objekten = _.sortBy($scope.bilder.Objekten, function (motiv: fb.MotivObjekt) { return motiv.KategoriId.value === 10 ? 1 : 0; }); $scope.nyligenAaterlaestFraanArkivet = ($scope.bilder.Objekten.length > 0 && $scope.bilder.Objekten[0].BildUrl.value && $scope.bilder.Objekten[0].BildUrl.value.indexOf('?Arkiv=true') !== -1); _.each($scope.bilder.Objekten, function (obj) { $scope.selectedMotiv[obj.MotivId.value] = new fb.ChangeTrack(false); }); // Ska köras när bilderna är inlästa, fullöses genom timeout setTimeout(function () { calcPortraitWarning($scope.bilder.Objekten); }, 200); }); }; $scope.laddaBilder(); $scope.setWidth('small'); //Arkivering if ($scope.type === fb.BildHanteringEnum.MAEKLAROBJEKT || $scope.type === fb.BildHanteringEnum.MAEKLAROBJEKT_OEVRIG) { $scope.arkiverad = (($scope).$parent).maeklarObjekt.BilderArkiverade.value; } $scope.laeserFraanArkiv = false; //Hemnet $scope.bilder.$promise.then(function () { var first5Hemnet = true; for (var y: number = 0; y < Math.min($scope.bilder.Objekten.length, 5); y++) { if ($scope.bilder.Objekten[y].HemnetOrdningsnummer && !angular.isNumber($scope.bilder.Objekten[y].HemnetOrdningsnummer.value)) { first5Hemnet = false; } } $scope.hemnet1to5 = first5Hemnet; _.each($scope.bilder.Objekten, function (item) { if (angular.isNumber(item.HemnetOrdningsnummer.value)) { $scope.hemnetImages.push(item); } }); }); // Anropar webAPI för att se ifall det finns några pågående bilduppladdningar var stilBilduppladdningPollTimeout; var stilBilduppladdningPoll = function () { if (!$scope.currentBilduppladdningStil || moment($scope.currentBilduppladdningStil.AendratDatum).diff(moment(), 'minutes') < -10) { // Stoppar pollingen om ingen statusändring hänt på 10 minuter delete $scope.currentBilduppladdningStil; return; } var bilduppladdning = bilduppladdningService.haemtaBilduppladdning($scope.currentBilduppladdningStil.BilduppladdningId); bilduppladdning.$promise.then(function () { $scope.currentBilduppladdningStil.Status = bilduppladdning.Status; $scope.currentBilduppladdningStil.AendratDatum = bilduppladdning.AendratDatum; switch (bilduppladdning.Status) { case null: case fb.FasITDomain.BilduppladdningStatus.UppladdningBestaelld: // Fortsätt polla case fb.FasITDomain.BilduppladdningStatus.UppladdningStartad:// Fortsätt polla case fb.FasITDomain.BilduppladdningStatus.InlaesningStartad:// Fortsätt polla stilBilduppladdningPollTimeout = $timeout(stilBilduppladdningPoll, 5000); break; case fb.FasITDomain.BilduppladdningStatus.InlaesningSlutfoerd:// Avbryt polling case fb.FasITDomain.BilduppladdningStatus.InlaesningMisslyckadesFoersoekIgen:// Avbryt polling stilBilduppladdningPollTimeout = $timeout(function () { delete $scope.currentBilduppladdningStil; }, 3000); return; } }); }; if ($scope.maeklarObjektType) { var bilduppladdningar = bilduppladdningService.haemtaBilduppladdningFoerMaeklarObjekt($scope.maeklarObjekt.MaeklarObjektId.value); bilduppladdningar.$promise.then(function () { for (var i = bilduppladdningar.length - 1; i > 0; i--) { // Om det finns en bilduppladdning som har ändrats de senaste 10 minuterna och inte är i en slutstatus, starta polling if (moment(bilduppladdningar[i].AendratDatum).diff(moment(), 'minutes') >= -10 && bilduppladdningar[i].Status !== fb.FasITDomain.BilduppladdningStatus.InlaesningMisslyckadesFoersoekIgen && bilduppladdningar[i].Status !== fb.FasITDomain.BilduppladdningStatus.InlaesningSlutfoerd) { $scope.currentBilduppladdningStil = bilduppladdningar[i]; if (stilBilduppladdningPollTimeout) { $timeout.cancel(stilBilduppladdningPollTimeout); } stilBilduppladdningPoll(); return; } } }); } $scope.$on('$destroy', function () { if (stilBilduppladdningPollTimeout) { $timeout.cancel(stilBilduppladdningPollTimeout); } }); $scope.openFastighetskarta = function () { if ($scope.fattasKartMarkering()) { return } sideDrawerService.setSideDrawer('Fastighetskarta', { maeklarObjekt: $scope.maeklarObjekt, callback: function () { $scope.laddaBilder(); } } ); }; } }); function harKommentarer(motivId: number): boolean { let result: boolean = false; if ($scope.kommentarTraadar && $scope.kommentarTraadar.$resolved) { result = $scope.kommentarTraadar .toArray() .some(kt => kt.MotivId === motivId && kt.Kommentarer && kt.Kommentarer.length > 0 ); } return result; } function harOloestaKommentarer(motivId: number): boolean { let result: boolean = false; if ($scope.kommentarTraadar && $scope.kommentarTraadar.$resolved) { result = $scope.kommentarTraadar .toArray() .some(kt => kt.MotivId === motivId && kt.Kommentarer && kt.Kommentarer.some(k => !k.AerLoest) ); } return result; } }]; return { restrict: 'E', scope: { changetrackId: '=', type: '=', kanKommentera: '=?', visaKundportalenKommentarer: '=?' }, controller: controller, templateUrl: 'app/Directives/fbBildHantering/fbBildHantering.html' } });