import { Component, OnInit } from "@angular/core";

import { Router, ActivatedRoute } from "@angular/router";
import { switchMap } from "rxjs/operators";
import { Modal, Picker, Toast } from "ng-zorro-antd-mobile";
import {
  FormGroup,
  FormControl,
  Validators,
  FormBuilder
} from "@angular/forms";
import { APIService } from "src/app/service/layout/service/api.service";
const data = [];

@Component({
  selector: "app-check-add",
  templateUrl: "./check-add.component.html",
  styleUrls: ["./check-add.component.css"],
  providers: [Picker, Toast]
})
export class CheckAddComponent implements OnInit {
  constructor(
    private router: ActivatedRoute,
    private _modal: Modal,
    private api: APIService,
    private fb: FormBuilder
  ) {}

  registerForm: FormGroup;
  submit: any = { checkPlanAssetList: [] };
  inventoryType = ["资产明细盘点", "资产范围盘点"];
  checkStaType = ["未开始", "待审核", "清查中", "已完成"];
  detail: any = { asset: {}, belongUnit: {}, projectTeam: {}, assetClass: {} };
  msg: any = "";
  formErrors: any = {
    invoicesNum: "",
    name: ""
  };
  validationMessage: any = {
    invoicesNum: {
      minlength: "At least four characters for account",
      maxlength: "At most ten characters for account",
      required: "username requied"
    },
    name: {}
  };
  id = null;
  ngOnInit() {
    this.buildForm();
    this.router.params
      .pipe(
        switchMap(param => {
          this.id = param.id;
          return this.api.getCheckTask(this.id);
        })
      )
      .subscribe(data => {
        if (data.success) {
          Modal.operation(
            data.body.checkList.map(c => ({
              text: c.name,
              onPress: () =>
                this.api
                  .getCheckTaskText(this.id, c.id)
                  .subscribe(data => (this.detail = data.body.checkPlanAsset))
            }))
          );
        }
      });
  }
  oninventoryType() {}
  buildForm(): void {
    this.registerForm = this.fb.group({
      mode: "add",
      invoicesNum: ["", Validators.required],
      name: ["", Validators.required],
      inventoryType: [],
      beginDate: [],
      checkUser: this.fb.group({
        id: ["1"]
      }),
      endDate: [],
      checkSta: [],
      remarks: []
    });
    this.registerForm.valueChanges.subscribe(data => this.onValueChanged(data));

    this.onValueChanged();
  }
  onValueChanged(data?: any) {
    if (!this.registerForm) {
      return;
    }
    const form = this.registerForm;

    for (const field in this.formErrors) {
      this.formErrors[field] = "";
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessage[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + "\n";
        }
      }
    }
  }
  renderHeader2() {
    return "资产扫描数据";
  }
  renderHeader() {
    return "盘点";
  }

  beforeSubmit() {
    const form = this.registerForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = "";
      const control = form.get(field);

      if (control && !control.valid) {
        const messages = this.validationMessage[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + "\n";
        }
        return false;
      } else {
        return true;
      }
    }
  }

  onSubmit() {
    var result = this.registerForm.value;
    console.log(result);
    result.checkPlanAssetList = [this.detail];
    this.api.addCheckPlan(result).subscribe(data => {
      if (!data.success) {
        this.msg = data.msg.replace(/\w+:/g, "*");
      }
    });
  }
  onReset() {
    this.registerForm.reset();
  }

  files = data.slice(0);
  multiple = false;
  multipleTab = 0;

  changeMultiple(value: number) {
    this.multipleTab = value;
  }

  fileChange(params) {
    console.log(params);
    const { files, type, index } = params;
    this.files = files;
    var data = new FormData();
    data.append("file", files[0]);
    this.api.upload(data, "/asset/checkPlan");
  }

  imageClick(params) {
    console.log(params);
  }
}
