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 { provinces } from '../../../../services/provinces';
import { SubmittedComponent } from '../../components/submitted/submitted.component';
import { ProfileComponent } from '../../components/profile/profile.component';
import { MatButtonModule } from '@angular/material/button';
@Component({
  selector: 'app-create-collection',
  imports: [
    CommonCompModule,
    FormsModule,
    ReactiveFormsModule,
    NzSelectModule,
    SubmittedComponent,
    ProfileComponent,
    MatButtonModule
  ],
  standalone: true,
  templateUrl: './create-collection.component.html',
  styleUrls: ['./create-collection.component.scss'],
})
export class CreateCollectionComponent implements OnInit {
  eduCollection: Parse.Object | undefined;
  provinces: Array<string> = provinces.options;
  showProfileFrom: boolean = false;
  @Input('isEdit')isEdit:boolean = false //当前是否作为编辑子组件
  profileId:string = '' //报送人
  validateForm: FormGroup<{
    name: FormControl<Array<string> | any>; //合集名称
    desc: FormControl<Array<string> | any>; //合集描述
    code: FormControl<string | any>; //合集code
    area: FormControl<string>; //关联省级行政区
    num: FormControl<number|any>; //流程数量
  }> = this.fb.group({
    name: ['', [Validators.required]],
    desc: ['', [Validators.required]],
    code: ['', [Validators.required]],
    area: ['', [Validators.required]],
    num: [''],
  });
  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');
      console.log(id);
      if (id) {
        this.isEdit = true
        let query = new Parse.Query('EduCollection');
        query.equalTo('objectId', id);
        this.eduCollection = await query.first();
        this.validateForm = this.fb.group({
          name: [
            this.eduCollection?.get('name') || '',
            [Validators.required],
          ],
          desc: [
            this.eduCollection?.get('desc') || '',
            [Validators.required],
          ],
          code: [
            this.eduCollection?.get('code') || '',
            [Validators.required],
          ],
          area: [
            this.eduCollection?.get('area') || '',
            [Validators.required],
          ],
          num: [
            this.eduCollection?.get('num') || '',
            [Validators.required],
          ],
        });
        this.profileId = this.eduCollection?.get('profileSubmitted')?.id
      }
    });
  }
  onShowCheck(){
    if(!this.eduCollection?.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.eduCollection?.id){
      let obj = Parse.Object.extend('EduCollection');
      this.eduCollection = new obj();
    }
    this.eduCollection?.set('user', Parse.User.current()?.toPointer());
    this.eduCollection?.set('company', {
      __type: 'Pointer',
      className: 'Company',
      objectId: this.tbookSer.company,
    });
    this.eduCollection?.set('name', params.name);
    this.eduCollection?.set('desc', params.desc);
    this.eduCollection?.set('code', params.code);
    if(this.isEdit){
      this.eduCollection?.set('num', params.num);
    }else{
      this.eduCollection?.set('area', params.area);
    }
    this.profileId ? this.eduCollection?.set('profileSubmitted',{
      __type: 'Pointer',
      className: 'Profile',
      objectId: this.profileId,
    }) :
    this.eduCollection?.set('profileSubmitted',undefined)
    this.eduCollection = await this.eduCollection?.save()
    this.msg.success(this.isEdit ? '已保存' : '已创建')
    this.showProfileFrom = false
  }

  async changeSubmitted(e:Array<string>){
    console.log(e);
    if(e[0]) this.profileId = e[0]
  }
}
