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

import { Router, ActivatedRoute } from "@angular/router";
import { switchMap, merge, tap } from "rxjs/operators";
import { Modal, Picker, Toast, PickerService, ToastService, ModalService } from "ng-zorro-antd-mobile";

import {
  FormGroup,
  FormControl,
  Validators,
  FormBuilder
} from "@angular/forms";
import { APIService } from "src/app/service/layout/service/api.service";
import {
  GaoDeLocation,
  PositionOptions
} from "@ionic-native/gao-de-location/ngx";
import { b64toBlob } from 'src/app/layout/service/util.service';
import { isFulfilled } from 'q';
import { defer, Observable, of } from 'rxjs';
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,
    private route: Router,
    private gaoDeLocation: GaoDeLocation,
     private _toast: ToastService,
     private router2: Router
  ) {
    this.getCurrentPosition();
  }
  //调用定位
  getCurrentPosition() {
    this.gaoDeLocation
      .getCurrentPosition()
      .then((res: PositionOptions) => {
        console.log(res);// res.address  为位置信息
      })
      .catch(error => console.error(error));
  }
  registerForm: FormGroup;
  submit: any = { checkPlanAssetList: [] };
  inventoryType = ["资产明细盘点", "资产范围盘点"];
  checkStaType = ["未开始", "待审核", "清查中", "已完成","其他"];
  fileStrs:[]=[];
  detail: any = { asset: {}, belongUnit: {}, projectTeam: {},  };
  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: {}
  };
  param = null;
  ngOnInit() {
    const accessPlan = (param)=>{
      this.api
      .getCheckTaskText(param.id, param.planId)
      .subscribe(data => (this.detail = data.body.checkPlanAsset))
    }
    const planDialog= (data)=>{
      if (data.success) {
        Modal.operation(
          [{text:"请选择盘点计划："}].concat(
          data.body.checkList.map(c => ({
            text: c.name,
            onPress: () =>
            accessPlan({...this.param,planId:c.id})
          }))
          )
        );
      }
    }
    this.buildForm();
    this.router.params
      .pipe(
       tap(param=>{this.param=param;console.log(param)}),
       switchMap(param=>param.planId?of(param):this.api.getCheckTask(param.id))
      )
      .subscribe(data => {
        if(data.planId){
          accessPlan(data);
        }else{
          planDialog(data);
        }
      });
  }

  oninventoryType() {}
  onCheck() {
    this.route.navigateByUrl("../checkResult");
  }
  buildForm(): void {
    this.registerForm = this.fb.group({
      mode: "add",
      id:[],
      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.registerForm.controls['checkSta'].valueChanges.subscribe(value => {
      if(value=="其他"){
        this.showPromptPromise();
      }
    });
    this.onValueChanged();
  }
  showPromptPromise() {
    ModalService.prompt(
      '自定义盘点状态',
      '',
      [
        {
          text: '关闭',
          onPress: value =>
            new Promise(resolve => {
            

                resolve();

            })
        },
        {
          text: '确定',
          onPress: value =>
            new Promise((resolve, reject) => {
              
              this.detail.checkSta=value;
              this.registerForm.controls["checkSta"].setValue(value);
                resolve();

            })
        }
      ],
      'default',
      null
    );
  }

  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];
    console.log(this.registerForm.value);

    var result = {id:this.registerForm.value.id,remarks:this.registerForm.value.remarks,checkSta:this.registerForm.value.checkSta,checkAnnex:""}
    result.checkAnnex =  this.fileStrs.join(',');
    this.api.addCheckPlan(result).subscribe(data => {
      if (!data.success) {
        this.msg = data.msg.replace(/\w+:/g, "*");
      }else{
        this.router2.navigate(["/"]);
      }
    });
  }
  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 ,operationType} = params;

   if(operationType=="remove"){
     this.fileStrs.splice(index);
     return;
   }

    this.files = files;
    var data = new FormData();
    var block = files[0].url.split(";");
    // Get the content type of the image
    var contentType = block[0].split(":")[1];// In this case "image/gif"
    // get the real base64 content of the file
   var realData = block[1].split(",")[1];// In this case "R0lGODlhPQBEAPeoAJosM...."
   data.append("type", contentType);
   data.append("name", "WU_FILE_0.jpg");
   data.append("id", "WU_FILE_0");
   data.append("file", b64toBlob( realData, contentType),"upload.jpg");
   var query = {assetNum:this.detail.asset.num,modeName:"盘点",uploadPath:"/asset/checkPlan"};

   var xhr = new XMLHttpRequest();
   xhr.open("POST",`asset/a/sys/file/webupload/upload?assetNum=${this.detail.asset.num}&modelName=盘点&uploadPath=/asset/checkPlan`);
   xhr.send(data);
   const _this =this;
   xhr.onreadystatechange= function(data){
    if ( xhr.readyState !== 4 ) {
      return;
  }
    _this.fileStrs.push((JSON.parse(xhr.responseText).body.url) as never);
   }
  }

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