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';
import { NzRadioModule } from 'ng-zorro-antd/radio';
@Component({
  selector: 'app-process-create',
  templateUrl: './process-create.component.html',
  styleUrls: ['./process-create.component.scss'],
  imports: [
    CommonCompModule,
    FormsModule,
    ReactiveFormsModule,
    NzSelectModule,
    SubmittedComponent,
    MatButtonModule,
    ProfileComponent,
    NzRadioModule,
  ],
  standalone: true,
})
export class ProcessCreateComponent implements OnInit {
  timeDefaultValue = setHours(new Date(), 0);

  eduProcess: Parse.Object | undefined;
  showProfileFrom: boolean = false;
  @Input('isEdit') isEdit: boolean = false; //当前是否作为编辑子组件
  profileId: string = '';
  isVisible: boolean = false;
  searchValue: string = ''; //搜索部门内容

  validateForm: FormGroup<{
    name: FormControl<Array<string> | any>; //流程名称
    desc: FormControl<Array<string> | any>; //流程描述
    code: FormControl<string | any>; //流程唯一标识
    num: FormControl<number | any>; //报送配额
    branch: FormControl<Array<string> | any>; //所属分类
    startDate: FormControl<Date>; //开始时间
    deadline: FormControl<Date>; //结束时间
  }> = this.fb.group({
    name: ['', [Validators.required]],
    desc: ['',],
    code: ['', [Validators.required]],
    num: ['',],
    branch: ['', [Validators.required]],
    startDate: [new Date('2024/07/20'), [Validators.required]],
    deadline: [new Date('2024-09-20'), [Validators.required]],
  });
  department: string = ''; //所属单位
  unitTypes: Array<any> = []; //单位类型

  getNumlength(): number {
    return this.validateForm.value.num.toString().length;
  }
  parentMap: Array<any> = [];
  parentList: Array<any> = []; //单位列表

  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');
      await this.getUnitTypes();
      if (id) {
        this.isEdit = true;
        let query = new Parse.Query('EduProcess');
        query.include('branch', 'department','profileSubmitted');
        query.equalTo('objectId', id);
        this.eduProcess = await query.first();
        this.validateForm = this.fb.group({
          name: [this.eduProcess?.get('name') || '', [Validators.required]],
          desc: [this.eduProcess?.get('desc') || '',],
          code: [this.eduProcess?.get('code') || '', [Validators.required]],
          num: [this.eduProcess?.get('num') || ''],
          branch: [
            this.eduProcess?.get('branch')?.id || '',
            [Validators.required],
          ],
          startDate: [
            this.eduProcess?.get('startDate')
              ? this.eduProcess?.get('startDate')
              : new Date('2024/07/20'),
            [Validators.required],
          ],
          deadline: [
            this.eduProcess?.get('deadline')
              ? this.eduProcess?.get('deadline')
              : new Date('2024-09-20'),
            [Validators.required],
          ],
        });
      }
      this.profileId = this.eduProcess?.get('profileSubmitted')?.id || '';
      this.department = this.eduProcess?.get('department')?.id || '';
    });
  }
  async getUnitTypes() {
    let query = new Parse.Query('Department');
    query.equalTo('branch', undefined);
    query.equalTo('parent', undefined);
    query.notEqualTo('isDeleted', true);
    query.select('name');
    query.descending('createdAt')
    let r = await query.find();
    r.forEach((item) => {
      this.unitTypes.push({ id: item.id, name: item.get('name') });
    });
  }
  //根据所选单位类型获取对应单位
  async provinceChange(id?: string, val?: string) {
    let query = new Parse.Query('Department');
    id && query.equalTo('parent', id);
    query.select('name', 'branch');
    query.limit(100);
    val && query.contains('name', val);
    let r = await query.find();
    this.parentList = r;
  }
  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;
    }
    console.log('submit', this.validateForm.value);
    if (this.validateForm.valid) {
      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('branch', {
      __type: 'Pointer',
      className: 'Department',
      objectId: params.branch,
    });
    this.department &&
      this.eduProcess?.set('department', {
        __type: 'Pointer',
        className: 'Department',
        objectId: this.department,
      });
    this.eduProcess?.set('name', params.name);
    this.eduProcess?.set('desc', params.desc);
    this.eduProcess?.set('code', params.code);
    params.num && this.eduProcess?.set('num', params.num);
    this.eduProcess?.set('startDate', params.startDate);
    this.eduProcess?.set('deadline', params.deadline);
    if (!this.eduProcess?.get('profileSubmitted')) {
      let pid = await this.getProfile();
      this.eduProcess?.set('profileSubmitted', {
        __type: 'Pointer',
        className: 'Profile',
        objectId: pid,
      });
    }
    !this.eduProcess?.get('status') && this.eduProcess?.set('status', '200');
    this.eduProcess = await this.eduProcess?.save();
    this.msg.success(this.isEdit ? '已保存' : '已创建');
    this.showProfileFrom = false;
    this.router.navigate([
      '/nav-admin/manage/process/page',
      { id: this.eduProcess?.id },
    ]);
  }
  //选择部门
  async showModalDepart() {
    if (this.eduProcess?.get('department')) {
      this.parentMap = await this.formatNode(
        this.eduProcess?.get('department').id
      );
    } else {
      let dp = this.unitTypes.find(
        (item) => item.id == this.validateForm.value.branch
      );
      this.parentMap = [
        {
          title: dp?.name,
          id: dp?.id,
        },
      ];
    }
    this.provinceChange(this.validateForm.value.branch);
    this.isVisible = true;
  }
  async formatNode(id: string): Promise<Array<any>> {
    let arr = [];
    if (id) {
      let query = new Parse.Query('Department');
      query.equalTo('objectId', id);
      query.select('parent', 'name');
      let r = await query.first();
      if(!r?.get('parent')){
        arr.push({
          title: r?.get('name'),
          id: r?.id,
        });
      }
      arr.unshift(...(await this.formatNode(r?.get('parent')?.id)));
    }
    return arr;
  }
  //选择联系人
  onShowCheck() {
    if(!this.eduProcess?.get('department')?.id){
      this.msg.error('请先选择申报单位')
      return
    }
    if(this.profileId)return
    this.showProfileFrom = true;
  }
  //获取联系人
  async getProfile(): Promise<string | any> {
    let queryParams = {
      where: {
        $or: [
          {
            user: {
              $inQuery: {
                where: {
                  $or: [
                    {
                      department: { $eq: this.department },
                    },
                  ],
                },
                className: '_User',
              },
            },
          },
        ],
      },
    };
    let query = Parse.Query.fromJSON('Profile', queryParams);
    query.equalTo('identity', '工作联系人');
    query.notEqualTo('isDeleted', true);
    query.select('user');
    let r = await query.first();
    if (r?.id) {
      return r.id;
    }
    return;
  }
  async changeSubmitted(e: Array<string>) {
    console.log(e);
    this.profileId = e[0];
    this.eduProcess?.set(
      'profileSubmitted',
      this.profileId
        ? {
            __type: 'Pointer',
            className: 'Profile',
            objectId: this.profileId,
          }
        : null
    );
    await this.eduProcess?.save();
    if(this.profileId){
      this.msg.success('成功设置联系人')
    }else{
      this.msg.success('已删除联系人，请重新选择')
    }
    this.ngOnInit();
    this.showProfileFrom = false
  }
  onCheck(e: any) {
    console.log(e);
  }
  //选择部门
  async onCheckedDepart(e: any, checked?: boolean) {
    console.log(e);
    this.department = e.id;
  }
  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }
  async handleOk(): Promise<void> {
    this.eduProcess?.set('branch', {
      __type: 'Pointer',
      className: 'Department',
      objectId: this.validateForm.value.branch,
    });
    this.department &&
      this.eduProcess?.set('department', {
        __type: 'Pointer',
        className: 'Department',
        objectId: this.department,
      });
    await this.eduProcess?.save();
    this.ngOnInit();
    this.msg.success('申报单位设置成功')
    this.isVisible = false;
  }
}
