import {Component, OnInit} from '@angular/core';
import {ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {NzModalModule, NzModalService} from "ng-zorro-antd/modal";
import {AgentService} from "../../../services/agent.service";
import {ActivatedRoute, Router} from "@angular/router";
import {ValidatorsService} from "../../../services/validators.service";
import {NzBreadCrumbComponent, NzBreadCrumbItemComponent} from "ng-zorro-antd/breadcrumb";
import {NzFormDirective, NzFormLabelComponent} from "ng-zorro-antd/form";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzButtonComponent} from "ng-zorro-antd/button";

@Component({
  selector: 'app-agent-add',
  standalone: true,
  imports: [
    NzBreadCrumbComponent,
    NzFormDirective,
    NzRowDirective,
    NzColDirective,
    NzInputDirective,
    NzFormLabelComponent,
    NzButtonComponent,
    NzBreadCrumbItemComponent,
    ReactiveFormsModule,
    NzModalModule
  ],
  templateUrl: './agent-add.component.html',
  styleUrl: './agent-add.component.less'
})
export class AgentAddComponent implements OnInit {

  agentForm: UntypedFormGroup;
  btnLoading = false;

  constructor(private form: UntypedFormBuilder,
              private modal: NzModalService,
              private agentService: AgentService,
              private activatedRoute: ActivatedRoute,
              private router: Router) { }

  ngOnInit(): void {
    this.agentForm = this.form.group({
      loginName: [null, [Validators.required, ValidatorsService.minLength(6), ValidatorsService.maxLength(20)]],
      password: [null, [Validators.required, ValidatorsService.minLength(6), ValidatorsService.maxLength(20)]],
      name: [null, [Validators.required]],
      contactPerson: [null, [Validators.required]],
      contactPersonPhone: [null, [Validators.required]],
      address: [null],
    });
  }

  submitFrom() {
    this.btnLoading = true;
    for (const i in this.agentForm.controls) {
      this.agentForm.controls[i].markAsDirty();
      this.agentForm.controls[i].updateValueAndValidity();
    }
    if (this.agentForm.status == null || this.agentForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请规范填写所有的必填项信息',
      });
      return;
    }

    this.agentService.insertAgent(this.agentForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '添加成功',
          nzOnOk: () => this.router.navigateByUrl('admin/agent/list')
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
      this.btnLoading = false;
    });
  }
}
