import { ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { get, log } from '@bixi/core/utils';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { EStatus, IStatusCol } from '../table.type';
import { hasKey } from '../utils';
import { ColStatusService } from './col-status.service';
import { ColBase } from './col.base';

@Component({
  selector: 'bixi-table-col-status',
  host: { '[class.bixi-table-col-status]': 'true' },
  template: `
    <div nz-tooltip [nzTooltipTitle]="statusTooltip" [class]="_class" [ngStyle]="_style">
      <span>{{_text}}</span>
    </div>
  `,
  styleUrls: ['../style/index.less'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class BixiTableColStatusComponent extends ColBase implements OnChanges {
  @Input() col: IStatusCol;

  _class = this.colStatusService.defaultStatus.default.class;
  _text = this.colStatusService.defaultStatus.default.text;
  _style = this.colStatusService.defaultStatus.default.style;

  get options() {
    return get(this.col, 'options', []);
  }

  constructor(private colStatusService: ColStatusService) {
    super();
  }

  get statusTooltip() {
    if (hasKey(this.col, 'tooltip')) {
      return this.tooltip;
    }
    return false;
  }

  ngOnChanges(changes: SimpleChanges) {
    if (get(changes, 'col')) {
      const statusMap: NzSafeAny = {};
      this.options.forEach(e => {
        statusMap[e.value] = { text: e.text, type: e.type };
      });
      this.colStatusService.mergeTableConfig();
      let type = get(statusMap, `${this.value}.type`);
      if (!this.colStatusService.defaultStatus[type] && !this.colStatusService.defaultStatus[this.value]) {
        log('bixi-table', `The status ${type} was not found, please check if the provider is set for BIXI_TABLE_CONFIG`);
        type = EStatus.default;
      } else if (!this.colStatusService.defaultStatus[type]) {
        type = this.value;
      }
      this._class = this.colStatusService.defaultStatus[type].class;
      this._style = this.colStatusService.defaultStatus[type].style;
      // 先获取 options 中配置的 text
      // 如果没有，则获取 defaultStatus 中的 text
      // 如果没有，则设置为 default
      this._text = get(statusMap, `${this.value}.text`, get(this.colStatusService.defaultStatus[type], 'text'));
    }
  }


}
