import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import Parse from 'parse';
import { CompUploadComponent } from '../../../../app/comp-upload/comp-upload.component';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { CommonCompModule } from '../../../../services/common.modules';
import { NzMessageService } from 'ng-zorro-antd/message';
import { textbookServer } from '../../../../services/textbook';
import { ProvierOssAli } from '../../../../app/comp-upload/provider-oss-aliyun';
import { NzModalService } from 'ng-zorro-antd/modal';
interface link {
  url: string;
  username?: string;
  password?: string;
}
@Component({
  selector: 'app-upload-collect',
  templateUrl: './upload-collect.component.html',
  styleUrls: ['./upload-collect.component.scss'],
  standalone: true,
  imports: [CommonCompModule, CommonModule, CompUploadComponent, NzRadioModule],
})
export class UploadCollectComponent implements OnInit {
  @Input('review') review: boolean = false; //只读
  @Input('eduTextbookVolume') eduTextbookVolume: Parse.Object | undefined;
  @Output() save: EventEmitter<any> = new EventEmitter<any>();

  collectFiles: Array<any> = []; //纸质教材PDF文件列表
  collectDigitFiles: Array<any> = []; //数字资源PDF文件列表
  collectLink: link = {
    url: '',
    username: '',
    password: '',
  }; //链接、账号密码

  radioValue: string = '上传文件';
  carrierShape: string = ''; //类型
  ossProvider: { signatureUrl: any } | undefined;

  constructor(
    private modal: NzModalService,
    public tbookSer: textbookServer,
    private msg: NzMessageService
  ) {
    this.ossProvider = new ProvierOssAli();
  }

  ngOnInit() {
    this.collectFiles = this.eduTextbookVolume?.get('collectFiles') || [];
    this.collectDigitFiles =
      this.eduTextbookVolume?.get('collectDigitFiles') || [];
    this.collectLink = this.eduTextbookVolume?.get('collectLink') || {
      url: '',
      username: '',
      password: '',
    };
    this.radioValue = this.eduTextbookVolume?.get('collectCheck') || '上传文件';
    this.carrierShape = this.eduTextbookVolume?.get('carrierShape')?.trim();
  }
  upload(e: any, type: string) {
    console.log('上传材料发生改变');
    console.log(e);
    if (type == 'collectFiles' || type == 'collectDigitFiles') {
      this[type] = e;
    }
  }
  async submitForm(type: string) {
    if (
      this.carrierShape == '纸质教材' ||
      this.carrierShape == '纸质教材附带数字资源'
    ) {
      let upload = this.collectFiles?.some((item) => item.url);
      // console.log(upload);
      if (!upload && type == 'sbmit') {
        // this.msg.warning('请上传纸质教材PDF文件');
        return;
      }
      this.eduTextbookVolume?.set('collectFiles', this.collectFiles);
    }
    if (
      this.carrierShape == '数字教材' ||
      this.carrierShape == '纸质教材附带数字资源'
    ) {
      let upload = this.collectDigitFiles?.some((item) => item.url);
      // console.log(upload);
      if (this.radioValue == '上传文件' && !upload && type == 'sbmit') {
        // this.msg.warning('请上传数字文件PDF');
        return;
      }
      this.eduTextbookVolume?.set('collectDigitFiles', this.collectDigitFiles);
      this.eduTextbookVolume?.set('collectCheck', this.radioValue);
      if (
        type == 'sbmit' &&
        ((this.radioValue == '链接' && !this.collectLink?.url) ||
          (this.radioValue == '链接和账号密码' &&
            (!this.collectLink?.url ||
              !this.collectLink?.username ||
              !this.collectLink?.password)))
      ) {
        // this.msg.warning('请填写完整信息');
        return;
      }
      this.eduTextbookVolume?.set('collectLink', this.collectLink);
    }
    /* 100：已上传 200：已提交*/
    this.eduTextbookVolume?.set(
      'collectStatus',
      type == 'sbmit' ? '200' : '100'
    );
    await this.eduTextbookVolume?.save();
    return true;
  }

  async openUrl(url: string, isFile?: boolean) {
    let path = window.location;
    if (
      isFile &&
      (this.eduTextbookVolume?.get('editionUnit') ===
        this.tbookSer.profile?.user?.department?.name ||
        (path.pathname.indexOf(
          `/external/review/detail/${
            this.eduTextbookVolume?.get('eduTextbook')?.id
          }`
        ) != -1 &&
          Parse.User.current()?.get('username') === '145review' &&
          (await this.authVerifly())))
    ) {
      url = await this.ossProvider?.signatureUrl(url, { expires: 180 });
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '教材文件临时链接已打开，请勿外泄。',
      });
    }
    window.open(url);
  }
  authVerifly(): Promise<boolean> {
    const currentUrl = window.location.href;
    return new Promise((resolve) => {
      fetch(
        'https://audit.hep.com.cn/common-shenhe-api/api/public/index/search/bookPath_cache_check',
        {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ path: currentUrl }),
        }
      )
        .then((response) => response.json())
        .then((data) => {
          console.log(data.data);
          if (data.data.rs == 0) {
            resolve(false);
            window.location.href =
              'https://audit.hep.com.cn/admin/401?noGoBack=0';
          } else {
            resolve(true);
          }
        })
        .catch((error) => {
          resolve(false);
          console.error('Error:', error);
          window.location.href =
            'https://audit.hep.com.cn/admin/401?noGoBack=0';
        });
    });
  }
}
