import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { SFComponent, SFRadioWidgetSchema, SFSchema, SFSelectWidgetSchema, SFUISchema } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { EAEnvironmentService } from '@shared';
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays';
import format from 'date-fns/format';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Observable, Observer, of } from 'rxjs';
import { apiConf } from '@conf/api.conf';
import { ScrollImgService } from '../../services/scrollimg.service';

@Component({
  selector: 'app-ad-components-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.less']
})
export class ScrollimgComponentsAddComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  record: any = {};
  i: any;
  schema: SFSchema = {};
  contentListData = [];
  queryParams: any = {};
  oldTakeEffectTime = '';
  maxSort = 0;
  isVisible = false;
  validFalg = true;
  detailData: any = {
    advertisementContentDTOList: []
  };
  changeTimeFlag = false;
  currentIndex = 0;
  addFlag = true;
  addId = 1;
  inputPoint: any = {
    lng: 0,
    lat: 0
  };
  today = new Date();
  navData: any = [];
  navigationName = '';
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 200,
      grid: { span: 24 },
    },
  };
  constructor(
    public msgSrv: NzMessageService,
    public http: _HttpClient,
    public service: ScrollImgService,
    private route: ActivatedRoute,
    private router: Router,
    private envSrv: EAEnvironmentService,
  ) { }


  ngOnInit(): void {
    this.queryParams = this.route.snapshot.queryParams;
    if (this.queryParams.type !== 'add') {
      this.initDetailData();
    }
    this.initSF();
  }
  initDetailData() {

  }
  initSF() {
    this.schema = {
      properties: {
        name: {
          type: 'string',
          title: '轮播图名称',
          maxLength: 10,
          ui: {
            showRequired: true,
            placeholder: '请不要超过10个字',
          }
        },
        licensePhotoWatermark: {
          type: 'string',
          title: '轮播图',
          ui: {
            action: apiConf.fileUpload,
            accept: 'image/png,image/jpeg,image/jpg,image/gif',
            limit: 1,
            limitFileCount: 1,
            resReName: 'data.fullFileWatermarkPath',
            urlReName: 'data.fullFileWatermarkPath',
            widget: 'upload',
            descriptionI18n: '图片支持JPG、PNG格式，文件小于2M（建议尺寸 702px * 280px）',
            data: {
              appId: this.envSrv.env.appId,
            },
            name: 'multipartFile',
            multiple: false,
            listType: 'picture-card',
            change: (args: any) => {
              if (args.type === 'success') {
                this.detailData.enterpriseBaseDTO.licensePhoto = args.file.response.data.fullFilePath
              }
            },
            beforeUpload: (file: any, _fileList: any) => {
              return new Observable((observer: Observer<boolean>) => {
                const isLt4M = file.size / 1024 / 1024 < 2;
                if (!isLt4M) {
                  this.service.msgSrv.warning('图片大小超过2M!');
                  observer.complete();
                  return;
                }
                observer.next(isLt4M);
                observer.complete();
              });
            },
            previewFile: (file: NzUploadFile) => of(file.url),
          },
        },
        linkType: {
          type: 'string',
          title: '可见范围',
          ui: {
            widget: 'radio',
            showRequired: true,
          } as SFRadioWidgetSchema,
          enum: [
            { label: '全部可见', value: 1 },
            { label: '合伙人可见', value: 2 },
            { label: '销售渠道可见', value: 3 },
          ],
        },
        sortId: {
          type: 'string',
          title: '顺序',
          ui: {
            showRequired: true,
            widget: '=',
            placeholder: '请输入0~99，数字越大，排序越靠前',
            serverSearch: true,
          } as SFSelectWidgetSchema,
        },
        content: {
          type: 'string',
          title: '内容',
          ui: {
            widget: 'tinymce',
            loadingTip: 'loading...',
            config: {
              height: 450
            },
            visibleIf: { name5: (value: string) => value === '1' }
          },
        },
      },
      required: [],
    };
    if (this.queryParams.type === 'add') {
      setTimeout(() => {
        this.sf.setValue('/takeEffectType', 1);
        this.sf.setValue('/style', 1);
      }, 500);
    }
  }
  get reqParams() {
    return {};
  }
  disabledDate = (current: Date): boolean => {
    // Can not select days before today and today
    return differenceInCalendarDays(current, this.today) < 0;
  }
  changeTime() {
    this.changeTimeFlag = true;
  }


  checkSort() {
    const params: any = {
      navigationId: this.sf?.value.navigationId,
      sortId: this.sf?.value.sortId,
      takeEffectType: this.sf?.value.takeEffectType,
    };
    if (this.queryParams.id !== '0') {
      params.advertisementId = this.queryParams.id;
    }
    if (this.sf.value.takeEffectType === 2) {
      if (this.changeTimeFlag) {
        params.takeEffectTime = format(this.detailData.takeEffectTime, 'yyyy-MM-dd HH:mm');
      } else {
        params.takeEffectTime = this.detailData.takeEffectTime;
      }
    }

  }
  save() {
    const params: any = {
      ...this.sf?.value,
      latitude: this.inputPoint.lat,
      longitude: this.inputPoint.lng,
      id: this.queryParams.id
    };
    this.detailData.advertisementContentDTOList.forEach((item: any) => {
      delete item.addId;
    });
    if (this.queryParams.type === 'add') {
      delete params.id;
    }
    if (this.sf.value.takeEffectType === 2) {
      if (this.changeTimeFlag) {
        params.takeEffectTime = format(this.detailData.takeEffectTime, 'yyyy-MM-dd HH:mm');
      } else {
        params.takeEffectTime = this.detailData.takeEffectTime;
      }
    } else {
      delete params.takeEffectTime;
    }
    this.service.request(this.service.$api_add_one, params).subscribe(res => {
      if (res) {
        this.service.msgSrv.success('保存成功');
        this.router.navigate(['../list'], { relativeTo: this.route });
      }
    });
  }

  goBack() {
    window.history.go(-1);
  }
  gotoMap() {
    this.isVisible = true;
  }

  handleOk(): void {
    this.isVisible = false;
  }

  handleCancel(): void {
    this.isVisible = false;
  }
  outputPointAddress(data: any) {
    this.sf.setValue('/companyAddress', data.address);
    this.inputPoint = data.inputPoint;
  }
}
