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';
import { ConfigFormDataService } from 'src/app/service/configFormData.service';
import { SendFileComponent } from './send-file/send-file.component';
import { ImageLabel2Component } from '../image-label2/image-label2.component';
import { ImageLabelComponent } from '../image-label/image-label.component';
import { HuangHaiConfigComponent } from './huang-hai-config/huang-hai-config.component';
interface Camera {
  name: string;
  user: string;
  password: string;
  uri: string;
  type: number;
  order: number;
  dimensionedPoints: string;
  dimensionedPointsHuanghai: string;
  dimensionedPointsHuanghaiObj: any;
  isEnabled: boolean;
}

import yaml from 'js-yaml';
import * as YAML from 'yaml';

@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,
    public configFormData: ConfigFormDataService
  ) { }

  hostId; //主机id
  orId; //加油站id
  hostType; //黄海还是交大的盒子

  hostData;
  ngOnInit(): void {
    this.hostId = this.route.snapshot.queryParams.hostId;
    this.orId = this.route.snapshot.queryParams.orId;

    this.hostType = this.route.snapshot.queryParams.type;
    this.getCamera();

    this.http.get(`/api/EdgeDevices/${this.hostId}`).subscribe({
      next: (data: any) => {
        console.log(data);
        this.hostData = data;
        // let isExist = data.configFiles.find((item, index, arr) => {
        //   if (item.name == 'source.yaml') {
        //     console.log("存在", index)
        //     return item
        //   }
        // })
        if (data.configFiles && data.configFiles.length != 0) {
          this.isSourceYaml = true;
        } else {
          this.isSourceYaml = false;
        }
      },
      error: (err) => {
        // this.message.create('error', '请先下发source.yaml配置');
      },
    });
  }
  listOfData: Camera[] = [];
  goback() {
    history.go(-1);
  }
  //摄像头
  isLoading = false;
  getCamera() {
    let params = {
      ContainsChildren: true,
      EdgeDeviceId: this.hostId,
      pageNumber: 1,
      pageSize: 99,
    };
    this.isLoading = true;
    this.http.get('/api/Cameras', { params: params }).subscribe((data: any) => {
      data.items.forEach((element) => {
        element.dimensionedPointsObj = JSON.parse(element.dimensionedPoints);
        element.dimensionedPointsHuanghaiObj = JSON.parse(
          element.dimensionedPointsHuanghai
        );
      });
      this.listOfData = data.items;
      this.isLoading = false;
      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, rejects) => {
            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,
              edgeDeviceId: this.hostId,
              // order: instance.validateForm.value.order,
            };
            this.http.post('/api/Cameras', body).subscribe({
              next: (data: any) => {
                resolve(data);
                if (this.hostType === '黄海') {
                  this.anewgetImg(data.id);
                }
                this.message.create('success', '创建成功!');
                this.getCamera();
                this.isSourceYaml = false;
                return true;
              },
              error: (err) => {
                rejects(err);
                return false;
              },
            });
          });
        } 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,
              edgeDeviceId: this.hostId,
              order: instance.validateForm.value.order,
            };
            this.http.put(`/api/Cameras/${data.id}`, body).subscribe((mes) => {
              if (this.hostType === '黄海') {
                this.anewgetImg(data.id);
              }
              resolve(mes);
              this.message.create('success', '编辑成功!');
              this.getCamera();
              this.isSourceYaml = false;
              return true;
            });
          });
        } else {
          this.message.create('warning', '请填写完整!');
          return false;
        }
      },
    });
    const instance = modal.getContentComponent();
  }

  anewgetImg(id) {
    let params = {
      cameraId: id,
      provider: 1,
    };
    this.http
      .put('/api/Cameras/Commands/CaptureImages', '', { params: params })
      .subscribe({
        next: (value: Object) => {
          // this.message.create(
          //   'success',
          //   '向边缘设备发送请求成功,请过一段时间手动刷新页面!'
          // );
          console.log('向边缘设备发送拉取图片请求成功');
        },
        error: (error: HttpErrorResponse) => { },
        complete: () => { },
      });
  }

  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();
          this.isSourceYaml = false;
        });
      },
      nzCancelText: '取消',
    });
  }

  isSourceYaml: boolean;

  label(item) {
    this.http.get(`/api/EdgeDevices/${this.hostId}`).subscribe({
      next: (data: any) => {
        if (this.hostType == '交大') {
          if (data.configFiles) {
            this.isSourceYaml = true;
            const element = document.documentElement;
            if (element.requestFullscreen) {
              //进入全屏
              element.requestFullscreen();
            }
            const modal = this.modal.create({
              nzContent: ImageLabel2Component,
              nzViewContainerRef: this.viewContainerRef,
              nzWidth: 1920,
              nzClosable: false,
              nzFooter: null,
              nzWrapClassName: 'canvasContentBox',
              nzBodyStyle: {
                'border-radius': '0px',
                padding: '0px',
                margin: '0px',
              },
              nzComponentParams: {
                data: item.id,
              },
              nzOnOk: async () => { },
            });
            modal.afterClose.subscribe((result) => {
              this.ngOnInit();
            });
          } else {
            this.isSourceYaml = false;
            this.message.create('error', '请先下发source.yaml配置');
          }
        } else if (this.hostType == '黄海') {
          const element = document.documentElement;
          if (element.requestFullscreen) {
            //进入全屏
            element.requestFullscreen();
          }
          const modal = this.modal.create({
            nzContent: ImageLabelComponent,
            nzViewContainerRef: this.viewContainerRef,
            nzWidth: 1920,
            nzClosable: false,
            nzFooter: null,
            nzWrapClassName: 'canvasContentBox',
            nzBodyStyle: {
              'border-radius': '0px',
              padding: '0px',
              margin: '0px',
            },
            nzComponentParams: {
              cameraId: item.id,
            },
          });
          modal.afterClose.subscribe((result) => {
            this.ngOnInit();
          });
        }
      },
      error: (err) => { },
    });
  }

  connect() {
    // let isAllLabel = this.listOfData.find((item: any) => {
    //   if (item.type != 1 && !item.dimensionedPoints) {
    //     console.log('存在摄像头未标注的情况')
    //     return item
    //   }
    // })
    // if (isAllLabel) {
    //   this.message.create('error', '存在摄像头未标注的情况');
    //   return
    // }
    // 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)

    //   },
    //   error: (err) => {
    //     console.log('连接失败', err)
    //   }
    // })
    this.disposalData();
    this.router.navigate(['/system/host/camera/configForm'], {
      queryParams: { hostId: this.hostId, orId: this.orId },
    });
  }

  forbidden(item) {
    console.log(item);
    let body = {
      isEnabled: !item.isEnabled,
    };
    this.http.put(`/api/Cameras/${item.id}`, body).subscribe((data) => {
      this.message.create('success', '修改成功!');
      this.getCamera();
    });
  }
  sourceYaml() {
    let copyListOfData = JSON.parse(JSON.stringify(this.listOfData));
    copyListOfData = copyListOfData.filter((item, i) => {
      return item.isEnabled;
    });
    let config4 = `video_rate: 5
inference_buffer_second: 10
sources:`;
    copyListOfData.forEach((item: any, index) => {
      if (
        item.type == 3 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.arrow.length != 0
      ) {
        let arrowArr = item.dimensionedPointsObj.arrow;
        let str =
          arrowArr[1].startX +
          ',' +
          arrowArr[1].startY +
          ',' +
          arrowArr[1].endX +
          ',' +
          arrowArr[1].endY +
          ',' +
          arrowArr[0].startX +
          ',' +
          arrowArr[0].startY +
          ',' +
          arrowArr[0].endX +
          ',' +
          arrowArr[0].endY;
        let customArea = [];
        if (
          item.dimensionedPointsObj &&
          item.dimensionedPointsObj.polygonOfmonitor &&
          item.dimensionedPointsObj.polygonOfmonitor.length !== 0
        ) {
          item.dimensionedPointsObj.polygonOfmonitor.forEach((element) => {
            customArea.push(element.x);
            customArea.push(element.y);
          });
        }
        config4 += `
  - name: '${item.name}'
    user: '${item.user}'
    password: '${item.password}'
    uri: '${item.uri}'
    type: ${item.type}
    line-crossing-Entry: [${str}]
    custom-area: [${customArea}]
    `;
      } else if (
        item.type == 2 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.arrow.length != 0 &&
        item.dimensionedPointsObj.arrowOfWest &&
        item.dimensionedPointsObj.arrowOfWest.length == 0
      ) {
        let arrowArr = item.dimensionedPointsObj.arrow;
        let str =
          arrowArr[1].startX +
          ',' +
          arrowArr[1].startY +
          ',' +
          arrowArr[1].endX +
          ',' +
          arrowArr[1].endY +
          ',' +
          arrowArr[0].startX +
          ',' +
          arrowArr[0].startY +
          ',' +
          arrowArr[0].endX +
          ',' +
          arrowArr[0].endY;
        let customArea = [];
        if (
          item.dimensionedPointsObj &&
          item.dimensionedPointsObj.polygonOfmonitor &&
          item.dimensionedPointsObj.polygonOfmonitor.length !== 0
        ) {
          item.dimensionedPointsObj.polygonOfmonitor.forEach((element) => {
            customArea.push(element.x);
            customArea.push(element.y);
          });
        }
        config4 += `
  - name: '${item.name}'
    user: '${item.user}'
    password: '${item.password}'
    uri: '${item.uri}'
    type: ${item.type}
    line-crossing-Entry: [${str}]
    custom-area: [${customArea}]
    `;
      } else if (
        item.type == 2 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.arrow.length != 0 &&
        item.dimensionedPointsObj.arrowOfWest &&
        item.dimensionedPointsObj.arrowOfWest.length != 0
      ) {
        let arrowArr = item.dimensionedPointsObj.arrow;
        let str =
          arrowArr[1].startX +
          ',' +
          arrowArr[1].startY +
          ',' +
          arrowArr[1].endX +
          ',' +
          arrowArr[1].endY +
          ',' +
          arrowArr[0].startX +
          ',' +
          arrowArr[0].startY +
          ',' +
          arrowArr[0].endX +
          ',' +
          arrowArr[0].endY;
        let arrowArr2 = item.dimensionedPointsObj.arrowOfWest;
        let str2 =
          arrowArr2[1].startX +
          ',' +
          arrowArr2[1].startY +
          ',' +
          arrowArr2[1].endX +
          ',' +
          arrowArr2[1].endY +
          ',' +
          arrowArr2[0].startX +
          ',' +
          arrowArr2[0].startY +
          ',' +
          arrowArr2[0].endX +
          ',' +
          arrowArr2[0].endY;
        let str3 = '[' + str + ',' + str2 + ']';
        let customArea = [];
        if (
          item.dimensionedPointsObj &&
          item.dimensionedPointsObj.polygonOfmonitor &&
          item.dimensionedPointsObj.polygonOfmonitor.length !== 0
        ) {
          item.dimensionedPointsObj.polygonOfmonitor.forEach((element) => {
            customArea.push(element.x);
            customArea.push(element.y);
          });
        }
        config4 += `
  - name: '${item.name}'
    user: '${item.user}'
    password: '${item.password}'
    uri: '${item.uri}'
    type: ${item.type}
    line-crossing-Entry: ${str3}
    custom-area: [${customArea}]
    `;
      } else {
        let customArea = [];
        if (item.type == 0) {
          item.dimensionedPointsObj
            ? item.dimensionedPointsObj.polygon.forEach((element) => {
              customArea.push(element.x);
              customArea.push(element.y);
            })
            : null;
        } else {
          console.log(item.dimensionedPointsObj);
          if (
            item.dimensionedPointsObj &&
            item.dimensionedPointsObj.polygonOfmonitor &&
            item.dimensionedPointsObj.polygonOfmonitor.length !== 0
          ) {
            item.dimensionedPointsObj.polygonOfmonitor.forEach((element) => {
              customArea.push(element.x);
              customArea.push(element.y);
            });
          }
        }
        config4 += `
  - name: '${item.name}'
    user: '${item.user}'
    password: '${item.password}'
    uri: '${item.uri}'
    type: ${item.type}
    line-crossing-Entry: []
    custom-area: [${customArea}]
    `;
      }
    });
    const modal = this.modal.create({
      nzTitle: '下发source.yaml配置',
      nzContent: SendFileComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzWidth: 1000,
      nzBodyStyle: {
        'border-radius': '0px',
        padding: '7px',
      },
      nzComponentParams: {
        data: config4,
      },
      nzOnOk: async () => {
        await new Promise((resolve) => {
          console.log('表单信息', instance.validateForm);
          let body = {
            configFiles: [{ name: 'source.yaml', content: instance.datacopy }],
          };
          this.http.put(`/api/EdgeDevices/${this.hostId}`, body).subscribe({
            next: (data) => {
              this.message.create('success', `文件保存成功`);
              resolve('成功了');
              this.isSourceYaml = true;
              let params = {
                edgeDeviceId: this.hostId,
                fileName: 'source.yaml',
              };
              this.http
                .put('/api/EdgeDevices/Commands/PushFile', '', {
                  params: params,
                })
                .subscribe({
                  next: (data) => {
                    this.message.create('success', `发送文件名成功`);
                  },
                  error: (err) => {
                    // this.message.create('error', `发送文件名失败`);
                    // reject('失败了')
                  },
                });
            },
            error: (err) => {
              // this.message.create('error', `文件保存失败`);
            },
          });
        });
      },
    });
    const instance = modal.getContentComponent();
  }
  //整理配置文件数据
  async disposalData() {
    let copyListOfData = JSON.parse(JSON.stringify(this.listOfData));
    copyListOfData = copyListOfData.filter((item, i) => {
      return item.isEnabled;
    });

    console.log('摄像头列表', copyListOfData);

    // return

    let config1 = `[property]
enable=1
#Width height used for configuration to which below configs are configured
config-width=1980
config-height=1080
#osd-mode 0: Dont display any lines, rois and text
#         1: Display only lines, rois and static text i.e. labels
#         2: Display all info from 1 plus information about counts
osd-mode=2
#Set OSD font size that has to be displayed
display-font-size=12
    `;
    let config2 = '';
    let config3 = '';
    let config4 = `test_action: true
logging_interval : 600
oil_truck_threshold: 0.8
oil_other_threshold: 0.5
    `;
    let xieyouqu = [];
    let oilDischargeOrder;
    copyListOfData.forEach((item: any, index) => {
      if (item.type == 2) {
        xieyouqu.push(item);
        oilDischargeOrder = item.order;
      }

      if (
        item.type == 0 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.polygon.length != 0
      ) {
        let str = '';
        item.dimensionedPointsObj
          ? item.dimensionedPointsObj.polygon.forEach((element) => {
            str += element.x + ';';
            str += element.y + ';';
          })
          : 0;
        str = str.substring(0, str.lastIndexOf(';'));
        console.log('进出口多边形', str);
        config1 += `
## Per stream configuration
[roi-filtering-stream-${item.order}]
#enable or disable following feature
enable=1
#ROI to filter select objects, and remove from meta data
roi-RF=${str}
#remove objects in the ROI
inverse-roi=0
class-id=-1
      `;
      }
      if (
        item.type == 3 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.arrow.length != 0
      ) {
        let arrowArr = item.dimensionedPointsObj.arrow;
        let str =
          arrowArr[1].startX +
          ';' +
          arrowArr[1].startY +
          ';' +
          arrowArr[1].endX +
          ';' +
          arrowArr[1].endY +
          ';' +
          arrowArr[0].startX +
          ';' +
          arrowArr[0].startY +
          ';' +
          arrowArr[0].endX +
          ';' +
          arrowArr[0].endY;
        config1 += `
[line-crossing-stream-${item.order}]
enable=1
#Label;direction;lc
line-crossing-Entry=${str}
class-id=0
extended=0
mode=strict
      `;
      }
      if (
        item.type == 2 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.arrow.length != 0 &&
        item.dimensionedPointsObj.arrowOfWest &&
        item.dimensionedPointsObj.arrowOfWest.length == 0
      ) {
        let arrowArr = item.dimensionedPointsObj.arrow;
        let str =
          arrowArr[1].startX +
          ';' +
          arrowArr[1].startY +
          ';' +
          arrowArr[1].endX +
          ';' +
          arrowArr[1].endY +
          ';' +
          arrowArr[0].startX +
          ';' +
          arrowArr[0].startY +
          ';' +
          arrowArr[0].endX +
          ';' +
          arrowArr[0].endY;
        config1 += `
[line-crossing-stream-${item.order}]
enable=1
#Label;direction;lc
line-crossing-Entry=${str}
class-id=0
extended=0
mode=strict
      `;
      }
      if (
        item.type == 2 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.arrow.length != 0 &&
        item.dimensionedPointsObj.arrowOfWest &&
        item.dimensionedPointsObj.arrowOfWest.length != 0
      ) {
        let arrowArr = item.dimensionedPointsObj.arrow;
        let str =
          arrowArr[1].startX +
          ';' +
          arrowArr[1].startY +
          ';' +
          arrowArr[1].endX +
          ';' +
          arrowArr[1].endY +
          ';' +
          arrowArr[0].startX +
          ';' +
          arrowArr[0].startY +
          ';' +
          arrowArr[0].endX +
          ';' +
          arrowArr[0].endY;
        let arrowArr2 = item.dimensionedPointsObj.arrowOfWest;
        let str2 =
          arrowArr2[1].startX +
          ';' +
          arrowArr2[1].startY +
          ';' +
          arrowArr2[1].endX +
          ';' +
          arrowArr2[1].endY +
          ';' +
          arrowArr2[0].startX +
          ';' +
          arrowArr2[0].startY +
          ';' +
          arrowArr2[0].endX +
          ';' +
          arrowArr2[0].endY;

        config1 += `
[line-crossing-stream-${item.order}]
enable=1
#Label;direction;lc
line-crossing-Entry1=${str}
class-id=0
extended=0
mode=strict
line-crossing-Entry2=${str2}
class-id=0
extended=0
mode=strict
      `;
      }
      if (
        item.type !== 0 &&
        item.dimensionedPointsObj &&
        item.dimensionedPointsObj.polygonOfmonitor &&
        item.dimensionedPointsObj.polygonOfmonitor.length != 0
      ) {
        let str = '';
        item.dimensionedPointsObj.polygonOfmonitor.forEach((element) => {
          str += element.x + ';';
          str += element.y + ';';
        });
        str = str.substring(0, str.lastIndexOf(';'));
        console.log('全局限制多边形', str);
        config1 += `
## Per stream configuration
[roi-filtering-stream-${item.order}]
#enable or disable following feature
enable=1
#ROI to filter select objects, and remove from meta data
roi-RF=${str}
#remove objects in the ROI
inverse-roi=0
class-id=-1
      `;
      }
    });
    //新增东南西北参数
    copyListOfData.forEach((element) => {
      if (element.type == 2 || element.type == 3) {
        //卸油区
        let obj = element.dimensionedPointsObj;
        let str1 = '';
        if (obj && obj.arrow && obj.arrow.length == 2) {
          str1 = `${obj.arrow[1].startX};${obj.arrow[1].startY};${obj.arrow[1].endX};${obj.arrow[1].endY}`;
        }
        let str2 = '';
        if (obj && obj.arrowOfWest && obj.arrowOfWest.length == 2) {
          str2 = `${obj.arrowOfWest[1].startX};${obj.arrowOfWest[1].startY};${obj.arrowOfWest[1].endX};${obj.arrowOfWest[1].endY}`;
        }
        if (str1 || str2) {
          let arr = [
            { name: 'South', value: str1 },
            { name: 'West', value: str2 },
          ];
          let newstr = '';
          arr.forEach((item) => {
            if (item.value) {
              newstr += `direction-${item.name}=${item.value}
`;
            }
          });
          config1 += `
[direction-detection-stream-${element.order}]
enable=1
#Label;direction;
${newstr}class-id=0
  `;
        }
      }
    });
    let xieyouguan = '';
    let jingdian = '';
    if (
      xieyouqu.length != 0 &&
      xieyouqu[0].dimensionedPointsObj &&
      xieyouqu[0].dimensionedPointsObj.rectangle.length != 0
    ) {
      xieyouqu[0].dimensionedPointsObj.rectangle.forEach((element) => {
        if (element.oilUnloadingArea) {
          xieyouguan =
            element.x +
            ',' +
            element.y +
            ',' +
            element.width +
            ',' +
            element.height;
        } else {
          jingdian =
            element.x +
            ',' +
            element.y +
            ',' +
            element.width +
            ',' +
            element.height;
        }
      });
    } else {
      xieyouguan = '0,0,0,0';
      jingdian = '0,0,0,0';
    }

    oilDischargeOrder != undefined
      ? null
      : (oilDischargeOrder =
        copyListOfData[copyListOfData.length - 1].order + 1);
    console.log('泄油管区域', xieyouguan);
    console.log('静电接地', jingdian);

    console.log(this.hostData);
    //如果之前保存过文件
    if (this.hostData.configFiles && this.hostData.configFiles.length !== 0) {
      console.log('走这里了吗')
      let config_arm = this.hostData.configFiles.find(
        (item) => item.name == 'config_arm.yaml'
      ).content;
      let config_x86 = this.hostData.configFiles.find(
        (item) => item.name == 'config_x86.yaml'
      ).content;
      // console.log(111, config_arm);
      // console.log(222, config_x86);
      //修改config_arm.yaml文件
      //更改connet_oil
      let config_armObj = yaml.load(config_arm);
      // let config_armObj = YAML.parse(config_arm);

      // for (const key in config_armObj.connet_oil.roi[0]) {
      //   delete config_armObj.connet_oil.roi[0][key];
      // }
      // let key1 = `oil_tube-${oilDischargeOrder}`;
      // let arr1 = [];
      // xieyouguan.split(',').forEach((item) => {
      //   arr1.push(Number(item));
      // });
      // config_armObj.connet_oil.roi[0][key1] = [arr1];
      //更改connet_grounder
      // for (const key in config_armObj.connet_grounder.roi[0]) {
      //   delete config_armObj.connet_grounder.roi[0][key];
      // }
      // let key2 = `grounder-${oilDischargeOrder}`;
      // let arr2 = [];
      // jingdian.split(',').forEach((item) => {
      //   arr2.push(Number(99));
      // });
      // config_armObj.connet_grounder.roi[0][key2] = [arr2];
      // let yyy = JSON.parse(JSON.stringify(config_armObj, null, 2))
      config2 = yaml.dump(config_armObj, { lineWidth: -1, indent: 3, noArrayIndent: true });
      // config2 =JSON.parse(JSON.stringify(YAML.stringify(config_armObj)) ) 
      console.log(888, config2)
    } else {
      //使用模板
      config2 = `# The all in one config file.

      debug: false #when the debug is on, osd.
      video_record: 10 #time to record into the .ts video
      
      sources:
        config: 'config/source.yaml'
      
      tracker:
        config: 'config/dstest_tracker_config.txt'
      
      analytics:
        config: 'config/config_nvdsanalytics.txt'
      
      ## 通用模型 ##
      
      # 1:人物检测
      peoplenet:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 16
        topk: 5
        roi-top-offset: 0
        roi-bottom-offset: 0
        detected-min-w: 20 
        detected-min-h: 200
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/peoplenet/weights/yolov4_cspdarknet_tiny_fp16.etlt_b16_gpu0_fp16.engine'
        threshold: 0.3
      
      # 2:车辆检测
      trafficcam:
        enable: true
        apply_on: 0
        interval: 1
        batch_size: 16
        topk: 5
        roi-top-offset: 0
        roi-bottom-offset: 0
        detected-min-w: 100 
        detected-min-h: 100
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/trafficcam/weights/resnet18_trafficcamnet_pruned.etlt_b16_gpu0_int8.engine'
      
      # 3:人物倚靠行为
      actionnet:
        enable: false
        apply_on: 1
        # roi:
        #   - 'fuel_island-4':
        #     - [200, 0, 450, 500]
        #   - 'fuel_island-5':
        #     - [930, 93, 940, 987]
        #   - 'fuel_island-6':
        #     - [1174, 151, 746, 929]
        #   - 'fuel_island-7':
        #     - [1450, 300, 460, 650]
        interval: 1
        batch_size: 32
      
      # 4:烟火检测
      fire_smoke_net:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 16
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/fire_smoke_net/weights/yolov4_cspdarknet_tiny_fp16.etlt_b16_gpu0_fp16.engine'
        threshold: 0.95
      
      # 5:抽烟打电话检测
      smoking_calling_net:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/smoking_calling_net/weights/resnet50_smoking_calling_net_fp16.etlt_b2_gpu0_fp16.engine'
      
      ## 油站专用模型 ##
      
      # 1:身份判别:工装、反光衣、便衣
      idnet:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/idnet/weights/resnet50_idnet_fp16.etlt_b2_gpu0_fp16.engine'
      
      # 2:卸油区物体识别:油罐车、灭火器、手推车、三角木、取样桶、隔离锥、卸油管
      oilnet:
        enable: true
        apply_on: 2
        interval: 1
        batch_size: 2 
        roi-top-offset: 0
        roi-bottom-offset: 0
        detected-min-w: 20 
        detected-min-h: 20
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/oilnet/weights/yolov4_cspdarknet_tiny_fp16.etlt_b2_gpu0_fp16.engine'
        threshold: 0.5
      
      # 3:卸油管是否连接判定
      connet_oil:
        enable: true
        apply_on: 2
        roi:
          - 'oil_tube-${oilDischargeOrder}':
            - [${xieyouguan}]   
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/connet_oil/weights/resnet50_connet_oil_fp16.etlt_b2_gpu0_fp16.engine'
      
      # 4:静电接地仪器是否连接判定
      connet_grounder:
        enable: true
        apply_on: 2
        roi:
          - 'grounder-${oilDischargeOrder}':
            - [${jingdian}]
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/connet_grounder/weights/resnet50_connet_grounder_fp16.etlt_b2_gpu0_fp16.engine'
      
      # 5:散装桶加油
      bulk_oil_net:
        enable: False
        apply_on: 2
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/bulk_oil_net/weights/yolov4_cspdarknet_tiny_fp16.etlt_b2_gpu0_fp16.engine'
        threshold: 0.2
      
      # 模型阈值通用设定
      rule_threshold:
        object_occurence_interval_second: 3
        object_disappear_interval_second: 10
        on_car_parking_interval_second: 1800
        on_fire_smoke_interval_second: 5
        on_helmet_interval_second: 5
        threshold_relying_sitting: 0.4 #rolling mean confidence
        threshold_smoking_calling: 0.3 #rolling mean confidence
        threshold_connecting: 0.667 #rolling mean confidence
        threshold_identity: 0.1 #only to filter out people net error
        threshold_helmet: 0 #num of helmet detected on a person
        enable_seconday_model: False      # secondary model (双模型)
        threshold_secondary_model: 0.5    
        secondary_model_window: 50
        secondary_model_path: '/opt/app/xgboost'
      `;
      config3 = `# The all in one config file.
      
      debug: false #when the debug is on, osd.
      video_record: 10 #time to record into the .ts video
      
      sources:
        config: 'config/source.yaml'
      
      tracker:
        config: 'config/dstest_tracker_config.txt'
      
      analytics:
        config: 'config/config_nvdsanalytics.txt'
      
      ## 通用模型 ##
      
      # 1:人物检测
      peoplenet:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 16
        topk: 5
        roi-top-offset: 0
        roi-bottom-offset: 0
        detected-min-w: 20 
        detected-min-h: 200
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/peoplenet/weights/yolov4_cspdarknet_tiny_fp16.etlt_b16_gpu0_fp32.engine'
        threshold: 0.3
      
      # 2:车辆检测
      trafficcam:
        enable: true
        apply_on: 0
        interval: 1
        batch_size: 16
        topk: 5
        roi-top-offset: 0
        roi-bottom-offset: 0
        detected-min-w: 100 
        detected-min-h: 100
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/trafficcam/weights/resnet18_trafficcamnet_pruned.etlt_b16_gpu0_int8.engine'
      
      # 3:人物倚靠行为
      actionnet:
        enable: false
        apply_on: 1
        # roi:
        #   - 'fuel_island-4':
        #     - [200, 0, 450, 500]
        #   - 'fuel_island-5':
        #     - [930, 93, 940, 987]
        #   - 'fuel_island-6':
        #     - [1174, 151, 746, 929]
        #   - 'fuel_island-7':
        #     - [1450, 300, 460, 650]
        interval: 1
        batch_size: 32
      
      # 4:烟火检测
      fire_smoke_net:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 16
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/fire_smoke_net/weights/yolov4_cspdarknet_tiny_fp16.etlt_b16_gpu0_fp32.engine'
        threshold: 0.95
      
      # 5:抽烟打电话检测
      smoking_calling_net:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/smoking_calling_net/weights/resnet50_smoking_calling_net_fp16.etlt_b2_gpu0_fp32.engine'
      
      ## 油站专用模型 ##
      
      # 1:身份判别:工装、反光衣、便衣
      idnet:
        enable: true
        apply_on: -1
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/idnet/weights/resnet50_idnet_fp16.etlt_b2_gpu0_fp32.engine'
      
      # 2:卸油区物体识别:油罐车、灭火器、手推车、三角木、取样桶、隔离锥、卸油管
      oilnet:
        enable: true
        apply_on: 2
        interval: 1
        batch_size: 2 
        roi-top-offset: 0
        roi-bottom-offset: 0
        detected-min-w: 20 
        detected-min-h: 20
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/oilnet/weights/yolov4_cspdarknet_tiny_fp16.etlt_b2_gpu0_fp32.engine'
        threshold: 0.5
      
      # 3:卸油管是否连接判定
      connet_oil:
        enable: true
        apply_on: 2
        roi:
          - 'oil_tube-${oilDischargeOrder}':
            - [${xieyouguan}]   
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/connet_oil/weights/resnet50_connet_oil_fp16.etlt_b2_gpu0_fp32.engine'
      
      # 4:静电接地仪器是否连接判定
      connet_grounder:
        enable: true
        apply_on: 2
        roi:
          - 'grounder-${oilDischargeOrder}':
            - [${jingdian}]
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/connet_grounder/weights/resnet50_connet_grounder_fp16.etlt_b2_gpu0_fp32.engine'
      
      # 5:散装桶加油
      bulk_oil_net:
        enable: False
        apply_on: 2
        interval: 1
        batch_size: 2
        model_engine_file: '/opt/nvidia/deepstream/deepstream-6.0/sources/project/models/bulk_oil_net/weights/yolov4_cspdarknet_tiny_fp16.etlt_b2_gpu0_fp32.engine'
        threshold: 0.3
      
      #模型阈值通用设定
      rule_threshold:
        object_occurence_interval_second: 3
        object_disappear_interval_second: 10
        on_car_parking_interval_second: 1800
        on_fire_smoke_interval_second: 5
        on_helmet_interval_second: 5
        threshold_relying_sitting: 0.4 #rolling mean confidence
        threshold_smoking_calling: 0.3 #rolling mean confidence
        threshold_connecting: 0.667 #rolling mean confidence
        threshold_identity: 0.1 #only to filter out people net error
        threshold_helmet: 0 #num of helmet detected on a person
        enable_seconday_model: False      # secondary model (双模型)
        threshold_secondary_model: 0.5    
        secondary_model_window: 50
        secondary_model_path: '/opt/app/xgboost'
      `;
    }

    sessionStorage.setItem('config1', config1);
    sessionStorage.setItem('config2', config2);
    sessionStorage.setItem('config3', config3);
    sessionStorage.setItem('config4', config4);
  }
  // 读取文本文件内容
  async readFile(file) {
    const reader = new FileReader()
    const promise = new Promise((resolve, reject) => {
      reader.onload = function () {
        resolve(reader.result)
      }
      reader.onerror = function (e) {
        reader.abort()
        reject(e)
      }
    })
    reader.readAsText(file, 'UTF-8') // 将文件读取为文本

    return promise
  }

  //黄海配置文件
  config() {
    let invalid = this.listOfData.find((item) => {
      return item.type !== 1 && !item.dimensionedPointsHuanghai;
    });
    if (invalid) {
      this.message.info(`${invalid.name}未标注`);
      return;
    }

    let data = this.configJson();
    const modal = this.modal.create({
      nzTitle: '下发黄海config.json配置',
      nzContent: HuangHaiConfigComponent,
      nzViewContainerRef: this.viewContainerRef,
      nzWidth: 1000,
      nzBodyStyle: {
        'border-radius': '0px',
        padding: '7px',
      },
      nzComponentParams: {
        data: data,
      },
      nzOnOk: () => {
        new Promise((resolve, reject) => {
          console.log('表单信息', instance.validateForm);
          let body = {
            configFiles: [{ name: 'config.json', content: instance.datacopy }],
          };
          this.http.put(`/api/EdgeDevices/${this.hostId}`, body).subscribe({
            next: (data) => {
              resolve(data);
              this.message.success('文件保存成功');
              let params = {
                edgeDeviceId: this.hostId,
                fileName: 'config.json',
              };
              this.http
                .put('/api/EdgeDevices/Commands/PushFile', '', {
                  params: params,
                })
                .subscribe({
                  next: (data) => {
                    this.message.create('success', `发送文件名成功`);
                  },
                });
            },
            error: (err) => {
              this.message.error('文件保存失败');
              reject(err);
            },
          });
        });
      },
    });
    const instance = modal.getContentComponent();
  }

  configJson() {
    let obj = {
      sources: [],
      freq: 5,
      minPersonWidth: 40,
      minPersonHeight: 70,
      personAttMaxCount: [8, 8, 10, 10],
      carStopMaxCount: 9000,
      fireMaxCount: 5,
      smokeMaxCount: 5,
      saveVideoSize: [800, 640],
      delayWarning: 0,
      smoke_th: 0.8,
      phone_th: 0.8,
      bulkoil_th: 0.8,
      fileUpload: 'https://gas.anxincloud.cn/api/Objects/gas/violations',
      alarmUpload: 'https://gas.anxincloud.cn/api/Data/ViolationRecordPush',
      unloadingProUpload:
        'https://gas.anxincloud.cn/api/Data/OilUnloadingProcessPush',
      prefix: '/api/Objects/gas',
    };
    this.listOfData.forEach((item: any) => {
      if (item.type === 0) {
        let objitem: any = {
          nickName: '进出口',
          rtsp: item.uri,
          areaName: item.name,
        };
        if (
          item.dimensionedPointsHuanghaiObj &&
          item.dimensionedPointsHuanghaiObj.carStopROI.length !== 0
        ) {
          objitem.carStopROI = pointsArrTransition(
            item.dimensionedPointsHuanghaiObj.carStopROI
          );
        }
        obj.sources.push(objitem);
      }
      if (item.type === 1) {
        let objitem: any = {
          nickName: '加油区',
          rtsp: item.uri,
          areaName: item.name,
        };
        if (
          item.dimensionedPointsHuanghaiObj &&
          item.dimensionedPointsHuanghaiObj.bulkoilROI.length !== 0
        ) {
          objitem.bulkoilROI = pointsArrTransition(
            item.dimensionedPointsHuanghaiObj.bulkoilROI
          );
        }
        obj.sources.push(objitem);
      }
      if (item.type === 2) {
        let objitem: any = {
          nickName: '卸油区',
          rtsp: item.uri,
          areaName: item.name,
        };
        if (
          item.dimensionedPointsHuanghaiObj &&
          item.dimensionedPointsHuanghaiObj.intrusionROI
        ) {
          objitem.intrusionROI = pointsArrTransition(
            item.dimensionedPointsHuanghaiObj.intrusionROI
          );
        }
        if (
          item.dimensionedPointsHuanghaiObj &&
          item.dimensionedPointsHuanghaiObj.unloadingROI
        ) {
          objitem.unloadingROI = [
            item.dimensionedPointsHuanghaiObj.unloadingROI[0].x,
            item.dimensionedPointsHuanghaiObj.unloadingROI[0].y,
            item.dimensionedPointsHuanghaiObj.unloadingROI[0].x +
            item.dimensionedPointsHuanghaiObj.unloadingROI[0].width,
            item.dimensionedPointsHuanghaiObj.unloadingROI[0].y +
            item.dimensionedPointsHuanghaiObj.unloadingROI[0].height,
          ];
        }
        if (
          item.dimensionedPointsHuanghaiObj &&
          item.dimensionedPointsHuanghaiObj.carStopROI
        ) {
          objitem.carStopROI = pointsArrTransition(
            item.dimensionedPointsHuanghaiObj.carStopROI
          );
        }
        obj.sources.push(objitem);
      }
      if (item.type === 3) {
        let objitem: any = {
          nickName: '便利店',
          rtsp: item.uri,
          areaName: item.name,
        };
        if (
          item.dimensionedPointsHuanghaiObj &&
          item.dimensionedPointsHuanghaiObj.cashierROI.length !== 0
        ) {
          objitem.cashierROI = pointsArrTransition(
            item.dimensionedPointsHuanghaiObj.cashierROI
          );
        }
        obj.sources.push(objitem);
      }
    });
    console.log(obj);
    return JSON.stringify(obj);

    function pointsArrTransition(data) {
      let arr = [];
      data.forEach((item) => {
        arr.push([item.x, item.y]);
      });
      arr.push([data[0].x, data[0].y]);
      return arr;
    }
  }
}