form.component.ts 11.7 KB
Newer Older
liujiaxin's avatar
1  
liujiaxin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnChanges,
  OnInit,
  Output,
  ApplicationRef,
  ChangeDetectorRef,
  ViewChildren, QueryList, ElementRef, ViewChild, AfterViewInit
} from '@angular/core';
import { CropperComponent } from 'angular-cropperjs';
import { NzMessageService } from 'ng-zorro-antd';
import * as _ from 'lodash';
limingzhe's avatar
limingzhe committed
16

liujiangnan's avatar
liujiangnan committed
17 18 19 20

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
liujiaxin's avatar
1  
liujiaxin committed
21
  styleUrls: ['./form.component.scss']
liujiangnan's avatar
liujiangnan committed
22
})
liujiaxin's avatar
1  
liujiaxin committed
23
export class FormComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy {
liujiangnan's avatar
liujiangnan committed
24

limingzhe's avatar
limingzhe committed
25
  // 储存数据用
liujiaxin's avatar
1  
liujiaxin committed
26
  saveKey = 'ww_reading';
limingzhe's avatar
limingzhe committed
27 28
  // 储存对象
  item;
liujiaxin's avatar
1  
liujiaxin committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
  _tmpEditWord: string;
  _tmpEditData: any;
  imageUploader: any;

  uploading = false;

  progress = 0;
  // enableChangeImage = true;
  picId = '';
  @Output()
  imageUploaded = new EventEmitter();
  @Output()
  update = new EventEmitter();
  respipe: any;
  cropperParts: Array<{
    word: string,
    data: any,
    // imgData: any,
    previewCss: any,
    imgCss: any,

    // color: string
  }> = [];
  currentEditPartIndex = -1;
  colorIndex = 0;
  @ViewChildren('partConfigBoxes')
  partConfigBoxes: QueryList<ElementRef>;

  @ViewChild('angularCropper')
  angularCropper: CropperComponent;


  @ViewChild('partConfigBox')
  partConfigBox: ElementRef;
  @ViewChild('uploadImage')
  uploadImage: ElementRef;
  @ViewChild('img')
  img: ElementRef;


  colors = [
    '#4FC200',
    '#00C0FF',
    '#FFDC00',
    '#FF8F00',
    '#CF0000',
    '#8E33D4',
    '#FF0075'
  ];

  cropperConfig = {
    dragMode: 'move',
    movable: true,
    viewMode: 3,
    autoCrop: true,
    autoCropArea: .5,
    rotatable: false,
    zoomOnWheel: false,
    zoomable: false,
    toggleDragModeOnDblclick: false,
    ready: this.initCropper.bind(this),

    preview: '.crop-preview'
  };


  constructor(private appRef: ApplicationRef,
              private nzMessageService: NzMessageService,
              private changeDetectorRef: ChangeDetectorRef) {
limingzhe's avatar
limingzhe committed
98 99 100 101

  }


liujiangnan's avatar
liujiangnan committed
102 103
  ngOnInit() {

liujiaxin's avatar
1  
liujiaxin committed
104 105 106
    this.item = {
      contentObj: {}
    };
limingzhe's avatar
limingzhe committed
107

limingzhe's avatar
limingzhe committed
108
    // 获取存储的数据
liujiaxin's avatar
1  
liujiaxin committed
109
    (window as any).courseware.getData((data) => {
limingzhe's avatar
limingzhe committed
110 111 112

      if (data) {
        this.item = data;
liujiaxin's avatar
1  
liujiaxin committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
        if (this.angularCropper) {
          this.angularCropper.cropper.reset();
          this.angularCropper.cropper.destroy();
        }
        this.picId = this.item.contentObj.pic_id;
        this.currentEditPartIndex = -1;
        this.cropperParts.length = 0;
        setTimeout(() => {
          // console.log(this.item.id , this.item.contentObj.parts)
          const parts = _.get(this.item.contentObj, 'parts', []);
          this.cropperParts = parts.map(item => {
            const nitem = Object.assign({}, item);
            nitem.previewCss = {};
            nitem.imgCss = {};
            return nitem;
          });
liujiaxin's avatar
liujiaxin committed
129
          this.initWithDataAfterData();
liujiaxin's avatar
1  
liujiaxin committed
130
        });
limingzhe's avatar
limingzhe committed
131 132 133
      }

      this.init();
liujiangnan's avatar
liujiangnan committed
134 135
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
limingzhe's avatar
limingzhe committed
136 137
      this.refresh();

limingzhe's avatar
limingzhe committed
138
    }, this.saveKey);
limingzhe's avatar
limingzhe committed
139 140 141 142

  }


limingzhe's avatar
limingzhe committed
143
  ngOnChanges() {
limingzhe's avatar
limingzhe committed
144 145
  }

limingzhe's avatar
limingzhe committed
146
  ngOnDestroy() {
limingzhe's avatar
limingzhe committed
147 148 149 150
  }



limingzhe's avatar
limingzhe committed
151
  init() {
limingzhe's avatar
limingzhe committed
152

liujiangnan's avatar
liujiangnan committed
153 154
  }

limingzhe's avatar
limingzhe committed
155 156 157 158 159





limingzhe's avatar
limingzhe committed
160 161 162
  /**
   * 储存数据
   */
limingzhe's avatar
limingzhe committed
163
  save() {
liujiaxin's avatar
1  
liujiaxin committed
164 165 166 167 168 169 170 171 172
    const data = this.cropperParts.map(item => {
      const nitem = Object.assign({}, item);
      delete nitem.previewCss;
      delete nitem.imgCss;
      return nitem;
    });
    this.item.contentObj.parts = data;
    // this.item.contentObj['imgData'] = imgData;
    (window as any).courseware.setData(this.item, null, this.saveKey);
limingzhe's avatar
limingzhe committed
173 174 175
    this.refresh();
  }

limingzhe's avatar
limingzhe committed
176 177 178
  /**
   * 刷新 渲染页面
   */
limingzhe's avatar
limingzhe committed
179 180 181 182
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
liujiangnan's avatar
liujiangnan committed
183
  }
liujiaxin's avatar
1  
liujiaxin committed
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  changeImage() {
    // console.log(this.imageUploader);
    this.imageUploader = this.uploadImage.nativeElement.querySelector('input[type="file"]');
    // if (!this.imageUploader) {
    //   this.imageUploader = this.uploadImage.nativeElement.querySelector('input[type="file"]')
    //   if (!this.imageUploader.onclick) {
    //     const self = this;
    //     this.imageUploader.onclick = () => {
    //       document.body.addEventListener('focus', self.afterChangeImage.bind(self), true);
    //     };
    //   }
    // }

    this.imageUploader.click();
    // const self = this;

    // this.picId = 0;
  }


  onImageUploadSuccess(e) {
    this.item.contentObj.pic_id = e.url;
    this.picId = e.url;
    this.update.emit(this.item);
    if (this.angularCropper ) {
      this.item.contentObj.pic_id = this.picId = e.url;
      this.cropperParts.length = 0;
      if (this.angularCropper && this.angularCropper.cropper) {
        this.angularCropper.cropper.reset();
        this.angularCropper.cropper.destroy();
        this.colorIndex = 0;
      }
    }
  }



  getCss(data, target) {
    const imgData = this.item.contentObj.imgData;
    // const w = this.partConfigBox.nativeElement.offsetWidth;
    // const w = this.partBoxTpl.nativeElement.offsetWidth;
    // const part = this.partConfigBoxes.toArray()[this.currentEditPartIndex]

    const w = target.clientWidth;
    const h = target.clientHeight;
    // let scale = w / data.width;
    // if (data.height >= data.width) {
    //   scale = h / data.height;
    // }


    let scale = 1;
    const c_w = w / data.width;
    const c_h = h / data.height;
    scale = Math.min(c_w, c_h);


    const iw = scale * imgData.naturalWidth;
    const ih = scale * imgData.naturalHeight;
    const ix = scale * data.x;
    const iy = scale * data.y;

    const pw = scale * data.width;
    const ph = scale * data.height;

    return {iw, ih, ix, iy, pw, ph };
  }




  addPart() {
    // console.log('addPart');
    // const inv_idx = this.cropperParts.findIndex(item => {
    //   return !item.word || !item.word.trim();
    // });
    // if (inv_idx !== -1) {
    //   this.currentEditPartIndex = inv_idx;
    //   const el = this.partConfigBoxes.toArray()[inv_idx].nativeElement.querySelector('.part-word');
    //   if (!el.classList.contains('err')) {
    //     el.classList.add('err');
    //   }
    //   return;
    // }
    if (this.cropperParts.length === this.colors.length ) {
      this.nzMessageService.info('you can only add seven parts.');
      return;
    }
    // const last_color = this.cropperParts[this.cropperParts.length - 1].color;
    // this.colorIndex = this.colors.findIndex((c) => {
    //   return last_color === c;
    // });
    // this.colorIndex++;
    // const color = this.colors[this.colorIndex % this.colors.length];

    this.cropperParts.push({
      word: '',
      data: this.angularCropper.cropper.getData(),
      // imgData: imgData,
      previewCss: { },
      // `width:${pw}px;height:${ph}px;`,
      imgCss: {},
      // playerPmgCss: {},
      // color: color
    });
    this.currentEditPartIndex = this.cropperParts.length - 1;
    // this.angularCropper.cropper.reset();
    this.focusUserInput();
    this.save();
  }
  focusUserInput() {
    setTimeout(() => {
liujiaxin's avatar
liujiaxin committed
296 297 298 299
      const ipt = this.partConfigBoxes.toArray()[this.currentEditPartIndex].nativeElement.querySelector('input')
        if (ipt) {
          ipt.focus();
        }
liujiaxin's avatar
1  
liujiaxin committed
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    }, 10);
  }
  editPart(idx) {
    this.currentEditPartIndex = idx;
    const obj = this.cropperParts[idx];
    this.angularCropper.cropper.setData(obj.data);
    obj.previewCss = { };
    obj.imgCss = { };
    this._tmpEditWord = obj.word;
    this._tmpEditData = Object.assign({}, obj.data);
    this.focusUserInput();
  }
  confirmRemovePart(idx, evt) {
    this.removePart(idx, evt);
  }
  removePart(idx, evt) {
    this.cropperParts.splice(idx, 1);
    this.save();
    this.colorIndex -= 1;
    if (this.colorIndex < 0 ) {
      this.colorIndex = 0;
    }
  }
  exitEditPart(evt, idx) {
    // if( !this.cropperParts[idx].word) {
    //   const el = this.partConfigBoxes.toArray()[idx].nativeElement.querySelector('.part-word');
    //   if (!el.classList.contains('err')) {
    //     el.classList.add('err');
    //   }
    //   return;
    // }
    // if (!this._tmpEditWord) {
    //   this._tmpEditWord = this.cropperParts[idx].word;
    // }

    this.currentEditPartIndex = -1;
    this.cropperParts[idx].word = this._tmpEditWord;
    if (this._tmpEditData) {
      this.cropperParts[idx].data = this._tmpEditData;
      this.angularCropper.cropper.setData(this._tmpEditData);
    }
    this._tmpEditWord = '';
    this._tmpEditData = {};

    const cropper: any = this.angularCropper.cropper;
    cropper.previews = [];
  }
  savePart(evt, idx) {

    // const el = this.partConfigBoxes.toArray()[idx].nativeElement.querySelector('.part-word');
    // if (!el.value) {
    //   if (!el.classList.contains('err')) {
    //     el.classList.add('err');
    //   }
    //   return;
    // }
    // if (el && el.classList.contains('err')) {
    //   return;
    // }

    this.currentEditPartIndex = this.cropperParts.length - 1;
    this.currentEditPartIndex = -1;
    // const origin = this.cropperParts[idx];
    const data = this.angularCropper.cropper.getData();
    this.cropperParts[idx].data = data;

    const cropper: any = this.angularCropper.cropper;
    cropper.previews = [];

    this.save();
  }
  previewUserSelectPart(idx) {
    const part = this.cropperParts[idx];
    this.angularCropper.cropper.setData(part.data);
  }
  initPart(evt, idx) {
    // console.log('initPart', evt);
    const part = this.cropperParts[idx];
    const img = evt.target;
    const preview = img.parentNode;
    if (!preview) {
      return;
    }
    const {iw, ih, ix, iy, pw, ph } = this.getCss(part.data, preview);
    part.previewCss = {
      'width.px': pw,
      'height.px': ph,
      'padding-bottom': 0
    };
    part.imgCss = {
      'width.px': iw,
      'height.px': ih,
      transform: `translateX(-${ix}px) translateY(-${iy}px)`
    };
  }
  onChangePartWord(val, idx ) {
    // const part = this.cropperParts[idx];
    const el: any  = this.partConfigBoxes.toArray()[idx].nativeElement.querySelector('.part-word');

    if (!val) {
      if (el && el.classList.contains('err')) {}
      el.classList.add('err');
    } else {
      if (el) {
        el.classList.remove('err');
      }
    }
  }


liujiaxin's avatar
liujiaxin committed
410
  ngAfterViewInit(){
liujiaxin's avatar
1  
liujiaxin committed
411

liujiaxin's avatar
liujiaxin committed
412 413
  }
  initWithDataAfterData() {
liujiaxin's avatar
1  
liujiaxin committed
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
    // console.log('ngAfterViewInit');

    this.partConfigBoxes.changes.subscribe(t => {
      const part = this.partConfigBoxes.toArray()[this.currentEditPartIndex];
      if (part) {
        const p = part.nativeElement.querySelector('.part-view');
        p.innerHTML = '';
        // debugger
        /*
        const img = <HTMLElement>this.angularCropper.imageElement.cloneNode();
        img.className = 'crop-part-preview';
        img.style.cssText = (
          `display: block;
          position: absolute;
          width: 100%;
          min-width: 0;
          min-height: 0;
          max-width: none;
          max-height: none;`
        );

        p.appendChild(img);
        */
        // const cfg = Object.assign({}, this.cropperConfig);
        // cfg['preview'] = p;
        const  cropper: any = this.angularCropper.cropper;
        if (!cropper.viewBox) {
          return;
        }
        cropper.viewBox.innerHTML = '';
        cropper.options.preview = p;
        cropper.initPreview();
        cropper.preview();
        p.style.padding = '0';

        // this.setPreviewImage();
      }
    });
    // this.enableChangeImage = true;



  }

  initCropper(evt) {

    // this.enableChangeImage = true;
    // this.angularCropper.cropper.setDragMode('move');
    // console.log('initCropper save imgData');
    this.item.contentObj.imgData = this.angularCropper.cropper.getImageData();
    // console.log(this.item.contentObj['imgData']);
    // this.item.contentObj['parts'] = [];
    // this.previewPart.nativeElement.style.padding = '0';

    // console.log('initCropper', pic, this.item.contentObj.pic_id);
    if (evt.target.src === this.item.contentObj.pic_id) {

    } else {
      // Ken 2018-09-29 14:54 不同时说明是重新上传的, 需要保存
      this.save();
    }
  }
liujiangnan's avatar
liujiangnan committed
476 477

}
limingzhe's avatar
limingzhe committed
478