import { Component, OnInit, ViewContainerRef } from '@angular/core';
import { ActivatedRoute, Route, Router } from '@angular/router';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzFormTooltipIcon } from 'ng-zorro-antd/form';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AddcameraComponent } from './addcamera/addcamera.component';
import { NzMessageService } from 'ng-zorro-antd/message';
import { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { EditcameraComponent } from './editcamera/editcamera.component';
import { catchError, tap } from 'rxjs/operators';
interface Camera {
  name: string;
  user: string;
  password: string;
  uri: string;
  type: number
}

@Component({
  selector: 'app-host-config',
  templateUrl: './host-config.component.html',
  styleUrls: ['./host-config.component.scss']
})

export class HostConfigComponent implements OnInit {


  constructor(private router: Router, private route: ActivatedRoute, private fb: FormBuilder, private modal: NzModalService, private message: NzMessageService, private viewContainerRef: ViewContainerRef, private http: HttpClient) { }

  hostId//主机id
  orId//加油站id
  ngOnInit(): void {
    this.hostId = this.route.snapshot.queryParams.hostId
    this.orId = this.route.snapshot.queryParams.orId
    this.getCamera()
  }
  listOfData: Camera[] = [];
  goback() {
    history.go(-1)
  }
  //摄像头
  getCamera() {
    this.http.get('/api/Cameras').subscribe((data: any) => {
      this.listOfData = data.items
      console.log('摄像头列表', data.items)
    })
  }
  addCamera() {
    const modal = this.modal.create({
      nzTitle: '新增加油站摄像头',
      nzContent: AddcameraComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzWidth: 388,
      nzComponentParams: {},
      nzOnOk: async () => {
        if (instance.validateForm.valid) {
          await new Promise(resolve => {
            console.log('表单信息', instance.validateForm)
            let body = {
              name: instance.validateForm.value.name,
              user: instance.validateForm.value.user,
              password: instance.validateForm.value.password,
              uri: instance.validateForm.value.uri,
              type: instance.validateForm.value.type,
              organizationId: this.orId
            }
            this.http.post('/api/Cameras', body).subscribe(data => {
              resolve(data)
              this.message.create('success', '创建成功!');
              this.getCamera()
              return true
            })
          })
        } else {
          this.message.create('warning', '请填写完整!');
          return false
        }
      }
    });
    const instance = modal.getContentComponent();
  }
  editCamera(data) {
    console.log(data)
    const modal = this.modal.create({
      nzTitle: '编辑加油站摄像头',
      nzContent: EditcameraComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzWidth: 388,
      nzComponentParams: {
        data: data
      },
      nzOnOk: async () => {
        if (instance.validateForm.valid) {
          await new Promise(resolve => {
            console.log('表单信息', instance.validateForm)
            let body = {
              name: instance.validateForm.value.name,
              user: instance.validateForm.value.user,
              password: instance.validateForm.value.password,
              uri: instance.validateForm.value.uri,
              type: instance.validateForm.value.type,
              organizationId: this.orId
            }
            this.http.put(`/api/Cameras/${data.id}`, body).subscribe(data => {
              resolve(data)
              this.message.create('success', '创建成功!');
              this.getCamera()
              return true
            })
          })
        } else {
          this.message.create('warning', '请填写完整!');
          return false
        }
      }
    });
    const instance = modal.getContentComponent();
  }
  deleteCamera(item) {
    console.log(item)
    this.modal.confirm({
      nzTitle: `确定要删除${item.name}这个摄像头吗?`,
      nzOkText: '确定',
      nzOkType: 'default',
      nzOnOk: () => {
        this.http.delete(`/api/Cameras/${item.id}`).subscribe(data => {
          this.message.create('success', '删除成功!');
          this.getCamera()
        })
      },
      nzCancelText: '取消'
    });
  }

  label(item){
    this.router.navigate(['/system/host/camera/imageLabel'])
  }


  connect() {
    let ids = []
    this.listOfData.forEach((item: any) => {
      ids.push(item.id)
    })
    this.http.get('/api/Cameras/Statuses', {
      params: { ids: ids }
    }).subscribe({
      next: (data) => {
        console.log('连接状态', data)
        this.router.navigate(['/system/host/camera/imageList'])
      },
      error: (err) => {
        console.log('连接失败', err)
      },

      // complete: () => console.log('complete!'), // not called
    })

  }
}