import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { languages } from '../../../../../services/languages.map';
import { CommonCompModule } from '../../../../../services/common.modules';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { ReactiveFormsModule } from '@angular/forms';
import { NzRadioModule } from 'ng-zorro-antd/radio';
import { NzUploadModule } from 'ng-zorro-antd/upload';
import { NzTagModule } from 'ng-zorro-antd/tag';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { textbookServer } from '../../../../../services/textbook'
import Parse from 'parse';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
import { CompUploadComponent } from '../../../../../app/comp-upload/comp-upload.component';
import { NzInputModule } from 'ng-zorro-antd/input';
import * as major from '../../../../../services/majors4.map'
import { NzCheckboxModule } from 'ng-zorro-antd/checkbox';
import { NzInputNumberModule } from 'ng-zorro-antd/input-number';
import { NzPopoverModule } from 'ng-zorro-antd/popover';

@Component({
  selector: 'app-one',
  templateUrl: './basic.component.html',
  styleUrls: ['./basic.component.scss'],
  standalone: true,
  imports: [
    CommonCompModule,
    ReactiveFormsModule,
    NzSelectModule,
    NzRadioModule,
    NzUploadModule,
    NzInputModule,
    NzTagModule,
    CompUploadComponent,
    NzCheckboxModule,NzInputNumberModule,NzPopoverModule
  ],
})
export class BasicComponent implements OnInit {
  /**传递的分册记录id */
  @Input('eduTextbookVolumeId') eduTextbookVolumeId: string | any
  /** 所属教材id*/
  @Input('eduTextbookId') eduTextbookId: string | any

  validateForm: FormGroup<{
    ISBN: FormControl<number>; //国际标准书号
    author: FormControl<string>; //第一主编（作者）
    unit: FormControl<string>; //第一主编（作者）单位
    unitType: FormControl<string>//第一主编（作者）单位类型
    lang: FormControl<string>; //教材主要语种类型
    authors: FormControl<string>; //其他主编姓名
    editor: FormControl<string>; //其他编者姓名
    editionUnit: FormControl<string>; //出版单位
    editionFirst: FormControl<Date>; //初版时间
    carrierShape: FormControl<string>; //载体形式
    editionDate: FormControl<Date>; //出版时间
    editionNumber: FormControl<number>; //出版版次
    printDate: FormControl<Date>; //最新印次时间
    printNumber: FormControl<number>; //最新印次
    printSum: FormControl<number>; //初版以来合计印数
    importantProjectOther: FormControl<string>; //其他省部级及以上项目
  }> = this.fb.group({
    ISBN: [0, [Validators.required]],
    author: ['', [Validators.required]],
    unit: ['', [Validators.required]],
    lang: ['', [Validators.required]],
    authors: [''],
    editor: [''],
    editionUnit: ['', [Validators.required]],
    editionFirst: [new Date(), [Validators.required]],
    carrierShape: ['', [Validators.required]],
    editionDate: [new Date(), [Validators.required]],
    editionNumber: [1, [Validators.required]],
    printDate: [new Date(), [Validators.required]],
    printNumber: [1, [Validators.required]],
    printSum: [1, [Validators.required]],
    importantProjectOther: [''],
    unitType: ['', [Validators.required]],
  });



  /**分册记录Parse */
  eduTextbookVolume: Parse.Object | any



  ngAfterViewInit(): void {
  }
  ngOnInit() { 
    this.refersh()
  }
  /**获取扩展分册记录 */
  async getEduTextbookVolume() {
    console.log('传递的分册id: '+this.eduTextbookVolumeId)
    if (this.eduTextbookVolumeId) {
      let query = new Parse.Query('EduTextbookVolume')
      this.eduTextbookVolume = await query.get(this.eduTextbookVolumeId)
      // console.log(this.eduTextbookVolume);
    } else {
      console.log("分册id未传递")
    }
  }
  async refersh() {
    await this.getEduTextbookVolume()
    if (this.eduTextbookVolume?.get('editionUnit')) {
      this.isShowChooseEU = false
    }
    this.importantProject = this.eduTextbookVolume?.get('importantProject') || []
    if (this.importantProject?.length > 0) {
      for (let i in this.importantProjectList) {
        if (this.importantProject.indexOf(this.importantProjectList[i].value) != -1) {
          this.importantProjectList[i].checked = true
        }
      }
    }
    // this.validateForm = this.fb.group({
    //   ISBN: [parseInt(this.eduTextbookVolume?.get('ISBN')) || null, [Validators.required]],
    //   author: [this.eduTextbookVolume?.get('author') || '', [Validators.required]],
    //   unit: [this.eduTextbookVolume?.get('unit') || '', [Validators.required]],
    //   lang: [this.eduTextbookVolume?.get('lang') || '', [Validators.required]],
    //   authors: [this.eduTextbookVolume?.get('authors') || ''],
    //   editor: [this.eduTextbookVolume?.get('editor') || '',],
    //   editionUnit: [this.eduTextbookVolume?.get('editionUnit') || '', [Validators.required]],
    //   editionFirst: [this.eduTextbookVolume?.get('editionFirst') || new Date(), [Validators.required]],
    //   carrierShape: [this.eduTextbookVolume?.get('carrierShape') || '', [Validators.required]],
    //   editionDate: [this.eduTextbookVolume?.get('editionDate') || new Date(), [Validators.required]],
    //   editionNumber: [this.eduTextbookVolume?.get('editionNumber') || 1, [Validators.required]],
    //   printDate: [this.eduTextbookVolume?.get('printDate') || new Date(), [Validators.required]],
    //   printNumber: [this.eduTextbookVolume?.get('printNumber') || 1, [Validators.required]],
    //   printSum: [this.eduTextbookVolume?.get('printSum') || 1, [Validators.required]],
    //   importantProjectOther: [this.eduTextbookVolume?.get('importantProjectOther') || ''],
    //   unitType: [this.eduTextbookVolume?.get('unitType') || '', [Validators.required]],
    // });
    if(this.eduTextbookVolume?.id){
      this.validateForm.get("ISBN")?.setValue(Number(this.eduTextbookVolume?.get('ISBN')))
      this.validateForm.get("author")?.setValue(this.eduTextbookVolume?.get('author'))
      this.validateForm.get("unit")?.setValue(this.eduTextbookVolume?.get('unit'))
      this.validateForm.get("lang")?.setValue(this.eduTextbookVolume?.get('lang'))
      this.validateForm.get("authors")?.setValue(this.eduTextbookVolume?.get('authors'))
      this.validateForm.get("editor")?.setValue(this.eduTextbookVolume?.get('editor'))
      this.validateForm.get("editionUnit")?.setValue(this.eduTextbookVolume?.get('editionUnit'))
      this.validateForm.get("editionFirst")?.setValue(this.eduTextbookVolume?.get('editionFirst'))
      this.validateForm.get("carrierShape")?.setValue(this.eduTextbookVolume?.get('carrierShape'))
      this.validateForm.get("editionDate")?.setValue(this.eduTextbookVolume?.get('editionDate'))
      this.validateForm.get("editionNumber")?.setValue(this.eduTextbookVolume?.get('editionNumber'))
      this.validateForm.get("printDate")?.setValue(this.eduTextbookVolume?.get('printDate'))
      this.validateForm.get("printNumber")?.setValue(this.eduTextbookVolume?.get('printNumber'))
      this.validateForm.get("printSum")?.setValue(this.eduTextbookVolume?.get('printSum'))
      this.validateForm.get("importantProjectOther")?.setValue(this.eduTextbookVolume?.get('importantProjectOther'))
      this.validateForm.get("unitType")?.setValue(this.eduTextbookVolume?.get('unitType'))
    }
  }
  public isComlpete:boolean = false //填写是否完整
  async submitForm(eduTextbookId?:any):Promise<string|undefined> {
    // console.log('执行了分册组件的save方法',eduTextbookId)
    if((!this.eduTextbookId)&&(!eduTextbookId)){
      this.msg.create('error','出错了，教材id未获取')
      return
    }
    let params = this.validateForm.value
    this.changeImportantProject()
    console.log('ISBN:',params.ISBN );
    if (!this.eduTextbookVolume) {
      if (this.eduTextbookVolumeId) {
        let query = new Parse.Query('EduTextbookVolume')
        this.eduTextbookVolume = await query.get(this.eduTextbookVolumeId)
      }else{
        let obj = Parse.Object.extend('EduTextbookVolume');
        this.eduTextbookVolume = new obj();
      }
    }
    this.eduTextbookVolume?.set('eduTextbook',{
      __type: 'Pointer',
      className: 'EduTextbook',
      objectId: this.eduTextbookId||eduTextbookId,
    })
    this.eduTextbookVolume?.set('user', Parse.User.current()?.toPointer());
    this.eduTextbookVolume?.set('ISBN', (params.ISBN || '').toString());
    this.eduTextbookVolume?.set('author', params.author);
    this.eduTextbookVolume?.set('unit', params.unit);
    this.eduTextbookVolume?.set('lang', params.lang);
    this.eduTextbookVolume?.set('authors', params.authors);
    this.eduTextbookVolume?.set('editor', params.editor);
    this.eduTextbookVolume?.set('editionUnit', params.editionUnit);
    this.eduTextbookVolume?.set('editionFirst', params.editionFirst);
    this.eduTextbookVolume?.set('carrierShape', params.carrierShape);
    this.eduTextbookVolume?.set('editionDate', params.editionDate);
    this.eduTextbookVolume?.set('editionNumber', params.editionNumber);
    this.eduTextbookVolume?.set('printDate', params.printDate);
    this.eduTextbookVolume?.set('printNumber', params.printNumber);
    this.eduTextbookVolume?.set('printSum', params.printSum);
    this.eduTextbookVolume?.set('importantProject', this.importantProject);
    this.eduTextbookVolume?.set('importantProjectOther', params.importantProjectOther);
    this.eduTextbookVolume?.set('unitType', params.unitType)
    let save = await this.eduTextbookVolume?.save();
    this.isComlpete = this.validateForm.valid
    return save.id
  }

  changeCode() { }
  getCode(e: any) { }

  /**教材获批截图 */
  approvedImgList: Array<any> = [{
    name: '获批截图',
    status: 'done',
    url: ''
  }]
  /**
   * 书号自动补全函数
   * @param isbn 书号
   */
  async autoCompleteByISBN() {
    let isbn = this.validateForm.value?.ISBN;
    let result = await Parse.Cloud.run("tbookISBN", {
      isbn: String(isbn)
    })
    if (!result?.isbn) {
      this.msg.warning('未找到该书号的图书信息，请手动填写')
    }
    console.log(result)
    // 其他字段，需补充接口与数据库对应关系
    this.validateForm.get("author")?.setValue(result?.author_name)
    this.validateForm.get("authors")?.setValue(result?.author)
    this.validateForm.get("lang")?.setValue(languages.options?.[result?.languages]?.name)
    this.validateForm.get("editionUnit")?.setValue(result?.publisher)
    this.validateForm.get("editionDate")?.setValue(new Date(result?.publish_time))
    this.validateForm.get("carrierShape")?.setValue(result?.publication_class)
  }
  /**出版时间及版次不可选择时间 */
  disabledEditionDate = (current: Date): boolean => {
    return current < new Date(2022, 11, 1)
  }

  //语言选择
  selectLang: Array<any> = languages.options;
  //可选单位类型
  unitSelects: Array<any> = [
    {
      name: '部属高校',
      code: '部属高校',
    },
    {
      name: '部省合建高校',
      code: '部省合建高校',
    },
    {
      name: '省部共建高校',
      code: '省部共建高校',
    },
    {
      name: '其他',
      code: '其他',
    },
  ];
  //载体形式
  carrierOptions: Array<any> = [
    {
      name: '纸质教材',
      code: 'Z001',
    },
    {
      name: '数字教材',
      code: 'Z002',
    },
    {
      name: '纸质教材附带数字资源',
      code: 'Z003',
    },
  ];
  /**可选的重点项目 */
  importantProjectList: Array<any> = [
    {
      label: '首届全国教材建设奖全国优秀教材（高等教育类）',
      value: '首届全国教材建设奖全国优秀教材（高等教育类）',
      checked: false
    },
    {
      label: '“十二五”普通高等教育本科国家级规划教材',
      value: '“十二五”普通高等教育本科国家级规划教材',
      checked: false
    },
    {
      label: '“十二五”以来省级优秀教材',
      value: '“十二五”以来省级优秀教材',
      checked: false
    },
    {
      label: '“十二五”以来省级规划教材',
      value: '“十二五”以来省级规划教材',
      checked: false
    },
    {
      label: '其他省部级及以上项目',
      value: '其他省部级及以上项目',
      checked: false
    },
  ];
  /**选中的重点项目 */
  importantProject: Array<any> = []
  /**多选框改变/获取选中的重点项目 */
  changeImportantProject() {
    let checkedList = this.importantProjectList.filter(item => item.checked) || []
    this.importantProject = checkedList.map(item => item.value)
    // console.log(this.importantProject)
  }


  constructor(
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private modal: NzModalService,
    private msg: NzMessageService,
  ) { }

  isShowChooseEU: boolean = true


  upload(e: any, type: string) {
    console.log(e);
    let file = e[0];
    // if (type == 'approvedImgUrl') {
    //   this.validateForm.value[type] = file?.url
    // }
    console.log(this.validateForm.value)
  }



  nzFilterOption = (): boolean => true;
  /** 搜索出版单位防抖定时器*/
  eduTimeout: any
  /**出版单位列表 */
  eduList: Array<Parse.Object> = []
  /**搜索出版单位 */
  async search(value: string) {
    clearTimeout(this.eduTimeout)
    this.eduTimeout = setTimeout(async () => {
      let query = new Parse.Query('Department')
      query.notEqualTo('isDeleted', true)
      query.equalTo('parent', '66865d66ad23a23355b12aa7')
      query.contains('name', value)
      query.limit(50)
      this.eduList = await query.find()
    }, 500);
  }
  openFile(url: any) {
    window.open(url)
  }
}
