본문 바로가기
Angular.ts

typescript 사용해보기 3

by improve 2024. 8. 7.

.ts 부분이다.

import { AfterViewInit, ChangeDetectorRef, Component, ElementRef, Injectable, OnInit, ViewChild } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { ActivatedRoute, ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import * as wjcCore from '@grapecity/wijmo';
import { closest, contains, createElement, getElement, hasClass, hidePopup, removeChild, showPopup } from '@grapecity/wijmo';
import { WjFlexGrid } from '@grapecity/wijmo.angular2.grid';
import * as wjcGrid from '@grapecity/wijmo.grid';
import { FlexGrid, FormatItemEventArgs } from '@grapecity/wijmo.grid';
import * as wjGridFilter from '@grapecity/wijmo.grid.filter';
import * as wjcGridPdf from '@grapecity/wijmo.grid.pdf';
import { ListBox } from '@grapecity/wijmo.input';
import * as wjcPdf from '@grapecity/wijmo.pdf';
import { ArrayUtil, CmmBase, CmmCodeService, CmmExcelExportComponent, CmmFileService, CmmLocaleService, CmmPagingComponent, CmmWjFlexGridComponent, ColumnGroupProvider, ColumnProvider, DateUtil, FormUtil, ObjectUtil, PageHeaderVo, PaginationInfoVo, PipeUtil } from 'cmm-lib';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
 import { ToastrService } from 'ngx-toastr';

// import { LoginUserInfoVo } from '../../../cmm/model/login-user-info-vo';
// import { CmmLoginService } from '../../../cmm/services/cmm-login.service';
// import { PotPtmtPartsOutService } from '../../ptmt/part/service/pot-ptmt-parts-out.service';
// import { PotPtmtPartsInService } from '../../ptmt/part/service/pot-ptmt-parts-in.service';
// import { PotPtmtPartsInVo } from '../../ptmt/part/model/pot-ptmt-part-in-vo';
// import { PotMyptNtarScmiVo } from '../../mypt/cmmn/model/pot-mypt-ntar-scmi-vo';
// import { PotPtmtPartsOutVo } from '../../ptmt/part/model/pot-ptmt-part-out-vo';
import { RadioVo } from 'projects/sample/model/radio-vo';
// import { StatRentalStateService } from './service/stat-rental-state.service';
import { StatRentalStateVo } from './model/stat-rental-state-vo';
import { LoginUserInfoVo } from 'projects/amr-client/src/app/cmm/model/login-user-info-vo';
import { CmmLoginService } from 'projects/amr-client/src/app/cmm/services/cmm-login.service';
import { PotMyptNtarScmiVo } from '../../../mypt/cmmn/model/pot-mypt-ntar-scmi-vo';
import { PotPtmtPartsInVo } from '../../../ptmt/part/model/pot-ptmt-part-in-vo';
import { PotPtmtPartsInService } from '../../../ptmt/part/service/pot-ptmt-parts-in.service';
import { PotPtmtPartsOutService } from '../../../ptmt/part/service/pot-ptmt-parts-out.service';
import { PotPtmtPartsOutVo } from '../../../ptmt/part/model/pot-ptmt-part-out-vo';
import { StatrentMgrService } from './service/stat-rent-mgr.service';
import { palette } from 'projects/amr-client/src/app/com/main-view/app.palette';
import { HitTestInfo } from '@grapecity/wijmo.chart';
// import { StatTestStateVo } from '../../test/test-mgr/model/stat-Test-state-vo';
import { StatTestStateVo } from './model/stat-test-state-vo';

@Injectable()
export class StatrentMgrResolveService {
  constructor(
    private comCodeService?: CmmCodeService
  ) { }
  // RTM_0001 교육상태
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    return Promise.all([
      this.comCodeService.setComCodeList('PTM_0001, POT_0070, COM_0111, COM_0113')
    ]);
  }
 
}

@Component({
  selector: 'rent-mgr',
  templateUrl: './rent-mgr.component.html',
  styleUrls: ['./rent-mgr.component.css']
})
export class RentMgrComponent extends CmmBase implements OnInit, AfterViewInit {
 
이안에서 Vo값, searchVo값, gridList 값을 적어준다.

  public allListCount: any;
  public dataList: wjcCore.CollectionView = new wjcCore.CollectionView([]);
  [x: string]: any;
  public pageHeader: PageHeaderVo = new PageHeaderVo();
  private formUtil: FormUtil;

  public radioVo: RadioVo = new RadioVo();
  public radioForm!: FormGroup;

  public searchVo: StatRentalStateVo = new StatRentalStateVo();
  public searchVo2: PotPtmtPartsOutVo = new PotPtmtPartsOutVo();
  public searchVo3: StatTestStateVo = new StatTestStateVo();
  public searchForm: FormGroup;
  public searchRange: Array<string>;

  public detlVo: PotPtmtPartsInVo = new PotPtmtPartsInVo();
  public detlForm: FormGroup;

  public scmiVo: PotMyptNtarScmiVo = new PotMyptNtarScmiVo();
  public scmiForm: FormGroup;

  public twoScmiVo: PotMyptNtarScmiVo = new PotMyptNtarScmiVo();
  public twoScmiForm: FormGroup;

  public gridList: wjcCore.CollectionView;

  gridFilter: wjGridFilter.FlexGridFilter;
  public gridLayout;

  gridFilter2: wjGridFilter.FlexGridFilter;
  public gridLayout2;

  public groupList: wjcCore.CollectionView = new wjcCore.CollectionView([]);
 
  private _isDragEnabled: boolean = false;
  private _dragSrc: HTMLElement = null;
  private _dragDst: HTMLElement = null;

  public loginUserInfoVo: LoginUserInfoVo;
  public isRegist = false; // 등록준비상태
  public detlEdit = false; // 상세영역 수정상태
  public isIn = true;
  private setBackCn = '';
  public popupRef: BsModalRef;
  public minDate = '2024-01-01';

  @ViewChild('flexGrid') public flexGrid: CmmWjFlexGridComponent;
  @ViewChild('paging') private paging: CmmPagingComponent;
  @ViewChild('paging2') private paging2: CmmPagingComponent;
  @ViewChild('columnPicker', { static: true }) columnPicker: ListBox;
  @ViewChild('columnPicker2', { static: true }) columnPicker2: ListBox;

  constructor(
    private toastr: ToastrService,
    private localeService: CmmLocaleService,
    private modalService: BsModalService,
    private cmmLoginService: CmmLoginService,
    private cmmFileService: CmmFileService,
    private router: Router,
    private route: ActivatedRoute,
    private StatrentMgrService: StatrentMgrService,
    private cdr: ChangeDetectorRef,
    public elRef: ElementRef
  ) {
    super(elRef);
    this.loginUserInfoVo = this.cmmLoginService.loginUserInfoVo;
    this.formUtil = new FormUtil(toastr, localeService, modalService);
  }
해당 페이지의 타이틀을 적어준다.
  ngOnInit() {
    this.pageHeader.title = '임대 농기계 통계';
    this.pageHeader.scrnId = this.scrnId;

    // this.radioForm = this.formUtil.getFormGroup(this.radioVo, this.radioVo.inputValid);

    // this.radioVo = new RadioVo();

    // this.radioVo.readOnly = 'IN';
    // this.radioVo.typeCode = 'IN';
   
    // this.detlVo = new PotPtmtPartsInVo();

    this.searchForm = this.formUtil.getFormGroup(this.searchVo, this.searchVo.searchValid);
    this.scmiForm = this.formUtil.getFormGroup(this.scmiVo, this.scmiVo.inputValid);
    this.twoScmiForm = this.formUtil.getFormGroup(this.twoScmiVo, this.twoScmiVo.inputValid);
 
    // this.searchVo = new StatRentalStateVo();
    // this.searchVo.selectDt = 'D';
    this.getData();
    this.allListCount = setInterval(() => {
      this.getData();
    }, 60000)
  } get palette() {
    return palette;
  }
  override ngOnDestroy(): void {
      clearInterval(this.allListCount);
  }
해당하는 데이터의 그래프를 나타내기 위해 적어줫다.
  tooltipContent(hti: HitTestInfo) {
    try {
      let item = hti.item;
      return `<b>${item.date}</b></br>보유갯수: ${PipeUtil.number(item.total_count)}`;
    } catch(error) {
      console.log(error);
      return '';
    }
  }

  public changed_getData(event: any) {
    this.getData();
  }
switch 문을 사용하여, case에 따른 값을 만들어 준다. 여기서 case는 해당하는 프로그램안에서 만들 수 있다.
  public getData() {
    switch(this.searchVo3.dateType) {
      case "TOT0001":
        this.StatrentMgrService.callRentGridList(this.searchVo3).subscribe(res => {
          if (ArrayUtil.isNotEmpty(res.resultList)) {
            const data: Array<any> = [];
            for (let index = 0; index < res.resultList.length; index++) {
              const element = res.resultList[index];
              data.push({
                id: index,
                date: element.key,
                total_count: element.total_count
              });
            }
            console.log(data);
            this.dataList = new wjcCore.CollectionView(data);
          } else {

          }
        });
        break;
    }
  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this.click_Reset();
    });
  }

  /**
   * 다중 폼 유효성 검사를 위한 폼 데이터 배열
   */
  get formData(): FormArray {
    const formArr: FormArray = <FormArray>this.detlForm.get('scmiList');
    return formArr;
  }
여기서는 표를 나타내고 있다. 표의 이름과 바인딩의 값을 적어준다.
  /**
   *그리드 초기화
   */
  public event_initGrid(flexGrid: WjFlexGrid) {
    flexGrid.columnFooters.rows.push(new wjcGrid.GroupRow());
    // var s = 'trnStrYmd'.concat('trnEndYmd');
    const gridLayout = [
      { header: '기간', binding: 'year', width: '*', align: 'center'},
      { header: '동력기', binding: 'mov_mac', width: '*', align: 'center' },
      { header: '작업기', binding: 'work_mac', width: '*', align: 'center'},
      { header: '농기계 그룹', binding: 'noung_group', width: '*', align: 'center' },
      { header: '총금액', binding: 'total_price', width: '*', align: 'center', aggregate:'Sum'},
      { header: '보유갯수', binding: 'total_count', width: '*', align: 'center', aggregate:'Sum'}
    ];
    const grid = new ColumnProvider(flexGrid, gridLayout);
    this.gridLayout = gridLayout;
    this.gridFilter = new wjGridFilter.FlexGridFilter(this.flexGrid);
이표에대해 칼럼을 삭제하거나 해당하는 값만을 보여주기 위해 작성햇다.
    //그리드 상세조건 수정
    flexGrid.itemFormatter = this.flexGrid_itemFormatter;
    if (this.flexGrid) {
      console.log("visible");
      this.columnPicker.itemsSource = this.flexGrid.columns;
      this.columnPicker.checkedMemberPath = 'visible';
      this.columnPicker.displayMemberPath = 'header';
      this.columnPicker.lostFocus.addHandler(() => {
        hidePopup(this.columnPicker.hostElement);
      });
      this.columnPicker.formatItem.addHandler((s, e) => {
        this._enableDragItem(e.item, this._isDragEnabled);
      });
    }

    if (this.flexGrid) {
      this.flexGrid.formatItem.addHandler((s: FlexGrid, e: FormatItemEventArgs) => {
        if (e.panel == s.topLeftCells) {
          e.cell.innerHTML = '<span class="column-picker-icon fa fa-gear"></span>';
        }
      });

      // show the column picker when the user clicks the top-left cell
      let ref = this.flexGrid.hostElement.querySelector('.wj-topleft');
      ref.addEventListener('mousedown', (e) => {
        if (hasClass(<Element>e.target, 'column-picker-icon')) {
          let host = this.columnPicker.hostElement;
          // console.log(this.columnPicker);
          // this.columnPicker._items.forEach(element => {
          //   element._hdr = this.localeService.translate(element._hdr);
          //   console.log(element);
          // });
          if (!host.offsetHeight) {
            showPopup(host, ref, false, true, false);
            this.columnPicker.focus();
          } else {
            hidePopup(host, true, true);
            this.flexGrid.focus();
          }
          e.preventDefault();
          this.onSaveStateClick();
        }
      });


    // this.PotRtmtReceService_selectBupaList(0);
  }

}
 



  private flexGrid_itemFormatter(p: wjcGrid.GridPanel, r: number, c: number, cell: HTMLElement) {
    if (p.cellType === wjcGrid.CellType.Cell) { // regular cells
      const cellValue = p.getCellData(r, c, false);
      const binding = p.columns[c].binding;
      var formatValue = p.getCellData(r, c, true);
      let html = '';

      switch (c) { // Position de la colonne !==컬럼위치==!
        default:
          html = '<div>' + formatValue + '</div>';
          // cell.onclick = () => this.event_selectGrid(c);
          break;
      }
    }
  }

  private flexGrid2_itemFormatter2(p: wjcGrid.GridPanel, r: number, c: number, cell: HTMLElement) {
    if (p.cellType === wjcGrid.CellType.Cell) { // regular cells
      const cellValue = p.getCellData(r, c, false);
      const binding = p.columns[c].binding;
      var formatValue = p.getCellData(r, c, true);
      let html = '';

      switch (c) { // Position de la colonne !==컬럼위치==!
        default:
          html = '<div>' + formatValue + '</div>';
          // cell.onclick = () => this.event_selectGrid(c);
          break;
      }
    }
  }

  /**
 * 버튼 클릭시 수행
 */
  public click_linkButton(value: string) {
    this.toastr.success(`value : ${value}`, '[click_linkButton]');
  }


  /**
   * 조회영역 초기화
   */
  public click_Reset() {
    this.searchVo = new StatRentalStateVo();
    this.searchVo.searchKeywordFrom = DateUtil.getToday(-30);
    this.searchVo.searchKeywordTo = DateUtil.getToday();
    this.searchVo.selectDt = '0';
    this.searchRange = [this.searchVo.searchKeywordFrom, this.searchVo.searchKeywordTo];

    this.gridList = new wjcCore.CollectionView([]);
    this.paging.init();
    this.detlVo = new PotPtmtPartsInVo();
    this.scmiVo = new PotMyptNtarScmiVo();
    //    this.uploader.setDownloader([])
    this.isIn = true;
    this.click_Search();

    // this.radioVo.readOnly = 'IN';
    // this.radioVo.typeCode = 'IN';
  }

  /**
   * 목록 조회
   */
  public click_Search() {
    const validResult = this.formUtil.formValidMessage(this.searchForm, this.searchVo);
    if (validResult === 'true') {
      this.isIn = true;
      this.potPtmtPartsInService_selectPartInList(0);
    } else {
      this.formUtil.modalMessage('warning', validResult, 'T_CFRM_RSLT');
    }


  }

  /**
   * 조회 리스트
   */
  public potPtmtPartsInService_selectPartInList(pageIndex: number) {
    this.searchVo.pageIndex = pageIndex;
    this.StatrentMgrService.callPcStatTest(this.searchVo).subscribe(res => {
      if (ArrayUtil.isNotEmpty(res.resultList)) {
        for (let index = 0; index < res.resultList.length; index++) {
          const element = res.resultList[index];
          element.rnum = index + 1;
          element.year = element.year.toString();

        }
        this.gridList = new wjcCore.CollectionView(res.resultList);
        console.log(res.resultList, this.gridList);
        this.paging.pagingInfo.totalRecordCount = res.resultList.length;
      } else {
        this.formUtil.toastrMessage('info', 'msg.00001', 'T_INFO');
        this.gridList = new wjcCore.CollectionView([]);
        this.paging.init();
      }
      this.gridList.currentPosition = -1; // 목록 select 해제
      this.detlVo = new PotPtmtPartsInVo(); // Detail 초기화
      //      this.uploader.setDownloader([]);

      this.isRegist = false;
      this.detlEdit = false;

      setTimeout(() => {
        this.onRestoreClick();
      });
    });
  }


  /**
   * PagingInfo Change Event
   */
  public event_changedPagingInfo(pagingInfo: PaginationInfoVo) {
    this.formUtil.pagingToVo(this.searchVo, pagingInfo);
    if (pagingInfo.totalRecordCount > 0) {
      this.potPtmtPartsInService_selectPartInList(this.searchVo.pageIndex);
    }
  }


  public event_clickGrid(e: MouseEvent) {
    const ht: wjcGrid.HitTestInfo = this.flexGrid.hitTest(e);
    //console.log('ht='+ht);
    console.log('wjcGrid.CellType[ht.cellType]=' + wjcGrid.CellType[ht.cellType]);
    if (wjcGrid.CellType.Cell === ht.cellType) {
      try {
        this.detlVo = ObjectUtil.copy(this.gridList.currentItem);
        this.router.navigate(['./d', this.detlVo.partRecvId], { relativeTo: this.route });
      } catch (error) {
       
      }
    }
  }

  /**
   * 신규 버튼
   */
  public click_New() {
    this.router.navigate(['./d/_new'], { relativeTo: this.route });
  }

  /**
   * 등록일자 조회
   */
  public event_changedRange(value: Array<string>) {
    this.searchVo.searchKeywordFrom = value[0];
    this.searchVo.searchKeywordTo = value[1];
  }

  ////////////////////////////////// 그리드 레이아웃 저장 ///////////////////////////////////

  onResetStateClick() {
    window.localStorage.removeItem('rental-state-gridState');
    history.go(0);
  }

  onSaveStateClick() {
    // var state = {
    //   columns: this.flexGrid.columnLayout,
    //   filterDefinition: this.gridFilter.filterDefinition,
    //   sortDescriptions: this.flexGrid.collectionView.sortDescriptions.map(function (sortDesc) {
    //     return { property: sortDesc.property, ascending: sortDesc.ascending };
    //   })
    // }

    // var mapCols = [];
    // this.flexGrid.columns.forEach(col => {
    //   if (col.dataMap) {
    //     mapCols.push({
    //       binding: col.binding,
    //       valuePath: col.dataMap.selectedValuePath,
    //       displayPath: col.dataMap.displayMemberPath,
    //       mapData: col.dataMap.collectionView.items
    //     });
    //   }
    // });

    // state['mapCols'] = mapCols;

    // localStorage['rental-state-gridState'] = JSON.stringify(state);
  }


  ////////////////////////////////// 그리드 레이아웃 불러오기 ///////////////////////////////////

  onRestoreClick() {
    // var json = localStorage['rental-state-gridState'];
    // if (json) {
    //   var state = JSON.parse(json);
    //   //
    //   // restore column layout (order/width)
    //   this.flexGrid.columnLayout = state.columns;
    //   // restore filter definitions
    //   this.gridFilter.filterDefinition = state.filterDefinition;
    //   //
    //   // restore sort state
    //   var view = this.flexGrid.collectionView;
    //   console.log(this.flexGrid.collectionView);
    //   if (view) {
    //     view.deferUpdate(function () {
    //       view.sortDescriptions.clear();
    //       for (var i = 0; i < state.sortDescriptions.length; i++) {
    //         var sortDesc = state.sortDescriptions[i];
    //         view.sortDescriptions.push(
    //           new wjcCore.SortDescription(sortDesc.property, sortDesc.ascending)
    //         );
    //       }
    //     });

    //   }
    //   //restore dataMap
    //   state.mapCols.forEach(map => {
    //     var col = this.flexGrid.columns.getColumn(map.binding);
    //     if (col) {
    //       col.dataMap = new wjcGrid.DataMap(map.mapData, map.valuePath, map.displayPath);
    //     }
    //   });
    // }
  }

  _updateColumnMap(col) {
    if (col.dataMap) {
      col.dataMap.getDisplayValues = this.getMapUpdateFunction(col.dataMap);
    }
  }

  getMapUpdateFunction(dMap) {
    let fun = (item => {
      if (!item) {
        return dMap.collectionView.items.map(item => item[dMap.selectedValuePath]);
      }

      let curDisplay = dMap.collectionView.items.filter((cml) => {
        if (cml.key < item.id) {
          return true;
        }
        return false;
      }).map(pz => pz.name);

      return curDisplay;
    });
    return fun;
  }

  ////////////////////////////////// 열 선택 시작 ///////////////////////////////////

  handleDragStart(e: DragEvent) {
    this._dragSrc = <HTMLElement>closest(e.target, '.wj-listbox-item');
    if (this._dragSrc) {
      e.dataTransfer.setData('text', this._dragSrc.innerHTML);
      e.dataTransfer.effectAllowed = 'move';
    }
  }

  handleDragOver(e: DragEvent) {
    const dragOver = <HTMLElement>closest(e.target, '.wj-listbox-item');
    if (this._dragDst && this._dragDst !== dragOver) {
      this._removeDropMarker();
    }
    if (dragOver && dragOver !== this._dragSrc) {
      e.preventDefault();
      e.dataTransfer.dropEffect = 'move';

      this._dragDst = dragOver;

      const src = this._getElementIndex(this._dragSrc);
      const dst = this._getElementIndex(this._dragDst);
      this._removeDropMarker();
      this._addDropMarker(dst > src);
    } else {
      this._dragDst = null;
    }
  }

  handleDrop(e: DragEvent) {
    if (this._dragSrc && this._dragDst) {
      e.preventDefault();
      const src = this._getElementIndex(this._dragSrc);
      const dst = this._getElementIndex(this._dragDst);
      this.flexGrid.columns.moveElement(src, dst);
    }
  }

  handleDragEnd(e: DragEvent) {
    this._dragSrc = null;
    this._dragDst = null;
    this._removeDropMarker();
  }

  enableDrag(e: Event) {
    const element = <HTMLInputElement>e.target;
    this._isDragEnabled = element.checked;
    const host = this.columnPicker.hostElement;
    const items = host.getElementsByClassName('wj-listbox-item');
    for (let i = 0; i < items.length; i++) {
      this._enableDragItem(items[i], this._isDragEnabled);
    }
  }

  private _enableDragItem(item: Element, enabled: boolean) {
    item.setAttribute('draggable', enabled.toString());
  }

  private _getElementIndex(element: Element): number {
    const parent = element.parentElement;
    const siblings = Array.prototype.slice.call(parent.children);
    return siblings.indexOf(element);
  }

  private _removeDropMarker() {
    removeChild(getElement('.drop-marker'));
  }

  private _addDropMarker(isAfterPos: boolean) {
    const itemsGap = 10;
    const width = 6;
    const margin = itemsGap / width;
    const height = this._dragDst.clientHeight;
    const topPos = this._dragDst.offsetTop;
    const leftPos = isAfterPos
      ? (this._dragDst.offsetLeft + this._dragDst.clientWidth + margin)
      : (this._dragDst.offsetLeft - itemsGap + margin);
    const css = `top:${topPos}px;left:${leftPos}px;height:${height}px;width:${width}px`;
    const html = `<div class="drop-marker" style="${css}">&nbsp</div>`;
    createElement(html, this.columnPicker.hostElement);
  }

  ////////////////////////////////// 열 선택 끝 ///////////////////////////////////



}

'Angular.ts' 카테고리의 다른 글

grid 에 select 된 값을 back 으로 보내기  (0) 2024.08.19
typescript 사용해보기2  (0) 2024.08.07
typescript 사용해보기  (0) 2024.08.07