import { Component, Input, OnInit } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { CommonCompModule } from '../../../services/common.modules';
import { Router, ActivatedRoute } from '@angular/router';
import { NzSelectModule } from 'ng-zorro-antd/select';
import Parse from 'parse';
import {
  FormControl,
  FormGroup,
  NonNullableFormBuilder,
  Validators,
} from '@angular/forms';
import { textbookServer } from '../../../services/textbook';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { SubmittedComponent } from '../components/submitted/submitted.component';
import { ProfileComponent } from '../components/profile/profile.component';
import { MatButtonModule } from '@angular/material/button';
import { differenceInCalendarDays, setHours } from 'date-fns';
@Component({
  selector: 'app-process-create',
  templateUrl: './process-create.component.html',
  styleUrls: ['./process-create.component.scss'],
  imports: [
    CommonCompModule,
    FormsModule,
    ReactiveFormsModule,
    NzSelectModule,
    SubmittedComponent,
    ProfileComponent,
    MatButtonModule,
  ],
  standalone: true,
})
export class ProcessCreateComponent implements OnInit {
  eduCollectionId:string|undefined //指向的合集

  eduProcess: Parse.Object | undefined;
  showProfileFrom: boolean = false;
  @Input('isEdit') isEdit: boolean = false; //当前是否作为编辑子组件
  profileIds: Array<string> = []; //报送人

  timeDefaultValue = setHours(new Date(), 0);
  
  validateForm: FormGroup<{
    name: FormControl<Array<string> | any>; //流程名称
    desc: FormControl<Array<string> | any>; //流程描述
    code: FormControl<string | any>; //流程唯一标识
    num: FormControl<number | any>; //报送配额
    startDate: FormControl<Date>; //开始时间
    deadline: FormControl<Date>; //结束时间
  }> = this.fb.group({
    name: ['', [Validators.required]],
    desc: ['', [Validators.required]],
    code: ['', [Validators.required]],
    num: ['', [Validators.required]],
    startDate: [new Date(), [Validators.required]],
    deadline: [new Date(), [Validators.required]],
  });
  getNumlength(): number {
    return this.validateForm.value.num.toString().length;
  }
  constructor(
    private activeRoute: ActivatedRoute,
    private router: Router,
    public tbookSer: textbookServer,
    private fb: NonNullableFormBuilder,
    private msg: NzMessageService,
    private modal: NzModalService
  ) {}

  ngOnInit() {
    this.activeRoute.paramMap.subscribe(async (params) => {
      let id = params.get('id');
      this.eduCollectionId = params.get('cid')!;
      console.log(id);
      if (id) {
        this.isEdit = true;
        let query = new Parse.Query('EduProcess');
        query.equalTo('eduProcess', id);
        this.eduProcess = await query.first();
        this.validateForm = this.fb.group({
          name: [this.eduProcess?.get('name') || '', [Validators.required]],
          desc: [this.eduProcess?.get('desc') || '', [Validators.required]],
          code: [this.eduProcess?.get('code') || '', [Validators.required]],
          num: [this.eduProcess?.get('num') || '', [Validators.required]],
          startDate: [
            this.eduProcess?.get('startDate') || new Date(),
            new Date(),
            [Validators.required],
          ],
          deadline: [
            this.eduProcess?.get('deadline') || new Date(),
            ,
            [Validators.required],
          ],
        });
        this.profileIds = this.eduProcess?.get('profileSubmitteds')?.map((item:any)=> item.objectId)
        // let querySubmitted = new Parse.Query('Submitted')
        // querySubmitted.equalTo('eduProcess',this.eduProcess?.id)
        // let submitteds = await querySubmitted.find()
        // if(submitteds?.length > 0){
        //   this.profileIds = submitteds.map(item=> item.id)
        // }
      }
    });
  }
  onShowCheck() {
    if (!this.eduProcess?.id) {
      this.msg.warning('请先创建报送流程');
      return;
    }
    this.showProfileFrom = true;
  }
  async submitForm(type: string): Promise<void> {
    if (type == 'close') {
      this.modal.confirm({
        nzTitle: '你确定取消吗?',
        nzContent: '',
        nzOkText: '是',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => history.back(),
        nzCancelText: '否',
        nzOnCancel: () => console.log('Cancel'),
      });
      return;
    }
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
      let params = this.validateForm.value;
      this.saveEduCollection(params);
    } else {
      this.msg.warning('请填写完整信息');
      Object.values(this.validateForm.controls).forEach((control) => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  async saveEduCollection(params: any) {
    if (!this.eduProcess?.id) {
      let obj = Parse.Object.extend('EduProcess');
      this.eduProcess = new obj();
    }
    this.eduProcess?.set('user', Parse.User.current()?.toPointer());
    this.eduProcess?.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.tbookSer.company,
    });
    this.eduProcess?.set('eduCollection', {
      __type: 'Pointer',
      className: 'EduCollection',
      objectId: this.eduCollectionId,
    });
    this.eduProcess?.set('name', params.name);
    this.eduProcess?.set('desc', params.desc);
    this.eduProcess?.set('code', params.code);
    this.eduProcess?.set('num', params.num);
    this.eduProcess?.set('startDate', params.startDate);
    this.eduProcess?.set('deadline', params.deadline);
    let profileSubmitteds = this.profileIds?.map(id=>{
      let pointer = {
        __type: 'Pointer',
        className: 'Profile',
        objectId: id,
      }
      return pointer
    })|| []
    this.eduProcess?.set('profileSubmitteds',profileSubmitteds)
    this.eduProcess = await this.eduProcess?.save();
    this.msg.success(this.isEdit ? '已保存' : '已创建');
    this.showProfileFrom = false;
  }
  // async setSubmitted(){
  //   for (let index = 0; index < this.profileIds.length; index++) {
  //     const id = this.profileIds[index];
  //     let obj = Parse.Object.extend('Submitted');
  //     let submitted = new obj();
  //     this.eduProcess?.set('company', {
  //       __type: 'Pointer',
  //       className: 'Company',
  //       objectId: this.tbookSer.company,
  //     });
  //     this.eduProcess?.set('profileSubmitted', {
  //       __type: 'Pointer',
  //       className: 'Profile',
  //       objectId: id,
  //     })
  //     this.eduProcess?.set('profileSubmitted', {
  //       __type: 'Pointer',
  //       className: 'Profile',
  //       objectId: id,
  //     })
  //   }
  // }
  async changeSubmitted(e: Array<string>) {
    console.log(e);
    if (e[0]) this.profileIds = e;
  }
}
