<!-- 
  相机管理

  目录位置：设备管理 -> 视频监控设备信息 -> 相机管理
  功能概述：管理所有区域下的相机，rtsp地址，安装位置等
 -->
<template>
  <div style="background: #fff">
    <p style="margin: 0; padding: 5px 20px; font-size: 20px">
      相机列表
      <a-icon type="sync" @click="reNew" ref="reNewBtn" />
    </p>
    <div class="cameraBox">
      <!--    树形控件界面-->
      <div class="treeBox">
        <a-input-search style="margin-bottom: 8px" placeholder="搜索" @change="onChange" />
        <a-tree
          :defaultExpandAll="true"
          v-if="gData.length != 0"
          :expanded-keys="expandedKeys"
          :auto-expand-parent="autoExpandParent"
          :tree-data="treeData"
          :fieldNames="replaceFields"
          @select="onSelect"
          @expand="onExpand"
          ref="dataTree"
          style="display: inline-block"
        >
        </a-tree>
      </div>
      <!--    菜单界面-->
      <div class="menuBox">
        <div class="menuTop">
          <a-button type="primary" @click="add"> 新增 </a-button>
          <a-button style="margin-left: 10px" @click="edit" :disabled="!getTag"> 修改 </a-button>
          <a-button style="margin-left: 10px" type="danger" @click="del" :disabled="!getTag"> 删除 </a-button>
          <a-button style="margin-left: 10px" type="danger" @click="cancel" v-show="cancelFlag"> 取消 </a-button>
        </div>
        <div class="menuFrom">
          <a-form
            style="flex: 1"
            class="antd-modal-form"
            :label-col="{ span: 6, offset: 1 }"
            :wrapper-col="{ span: 14 }"
            ref="ruleForm"
            :model="cameraForm"
          >
            <a-form-item label="监控点位" class="mustInput" name="siteName">
              <a-col :span="11">
                <a-select name="lineNameTemp" v-model:value="lineNameTemp" @change="handleLineChange" :disabled="!changeTag">
                  <a-select-option v-for="(line, i) in lineArr" :key="line.id">
                    {{ line.name }}
                  </a-select-option>
                </a-select>
              </a-col>

              <a-col :offset="1" :span="12">
                <a-form-item style="margin-bottom: 0px">
                  <a-select name="siteNameTemp" v-model:value="siteNameTemp" @change="handleSiteChange" :disabled="!changeTag">
                    <a-select-option v-for="(site, i) in siteArr" :key="site.id">
                      {{ site.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-form-item>
            <a-form-item label="相机名称" class="mustInput" name="cameraName">
              <a-input v-model:value="cameraForm.cameraName" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="相机IP" class="mustInput" name="ip">
              <a-input v-model:value="cameraForm.ip" :disabled="!changeTag" />
            </a-form-item>

            <a-form-item label="相机备用IP" class="mustInput" name="ip2">
              <a-input v-model:value="cameraForm.ip2" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="相机端口" class="mustInput" name="port">
              <!-- <a-input v-model="cameraForm.port" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.port" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="相机认证用户名" class="mustInput" name="user">
              <a-input v-model:value="cameraForm.user" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="相机认证密码" class="mustInput" name="password">
              <a-input-password v-model:value="cameraForm.password" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="厂家" class="mustInput" name="factory" v-if="cameraFactorys.length > 0">
              <!-- <j-dict-select-tag v-model:value="cameraForm.factory" placeholder="选择"
                                dictCode="ms_camera_factory" :disabled="!changeTag" /> -->
              <!-- 使用antd原生下拉框 -->
              <a-select v-model:value="cameraForm.factory" :disabled="!changeTag">
                <template :key="Number(cameraFactory.value)" v-for="cameraFactory in cameraFactorys">
                  <a-select-option :value="Number(cameraFactory.value)">{{ cameraFactory.text }}</a-select-option>
                </template>
              </a-select>
            </a-form-item>
            <a-form-item label="类型" class="mustInput" name="type">
              <a-col :span="11">
                <!-- <j-dict-select-tag name="type" v-model:value="cameraForm.type" placeholder="选择"
                                    dictCode="ms_camera_type" @change="typeChange" :disabled="!changeTag" /> -->
                <!-- 使用antd原生下拉框 -->
                <a-select name="type" v-model:value="cameraForm.type" :disabled="!changeTag" @change="typeChange">
                  <template :key="Number(cameraType.value)" v-for="cameraType in cameraTypes">
                    <a-select-option :value="Number(cameraType.value)">{{ cameraType.text }}</a-select-option>
                  </template>
                </a-select>
              </a-col>
              <a-col :offset="1" :span="12">
                <!-- <a-form-item style="margin-bottom: 0px;">
                                    <j-dict-select-tag name="style" v-model:value="cameraForm.style" placeholder="选择"
                                        dictCode="ms_camera_style" :disabled="!flag || !changeTag" />
                                </a-form-item> -->
                <!-- 使用antd原生下拉框 -->
                <a-select name="style" v-model:value="cameraForm.style" :disabled="!flag || !changeTag">
                  <template :key="Number(cameraStyle.value)" v-for="cameraStyle in cameraStyles">
                    <a-select-option :value="Number(cameraStyle.value)">{{ cameraStyle.text }}</a-select-option>
                  </template>
                </a-select>
              </a-col>
            </a-form-item>

            <a-form-item label="安装高度" class="mustInput" name="height">
              <!-- <a-input v-model="cameraForm.height" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.height" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="录像机" name="videoRecorder">
              <a-select v-model:value="cameraForm.videoRecorderId" :disabled="!changeTag">
                <a-select-option v-for="(vr, i) in videoRecorderArr" :value="vr.id" :key="vr.id">
                  {{ vr.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="相机认证通道号" name="channel">
              <a-input v-model:value="cameraForm.channel" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="视频预览RTSP地址" name="preRtsp">
              <a-input v-model:value="cameraForm.preRtsp" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="视频分析RTSP地址" name="analysisRtsp">
              <a-input v-model:value="cameraForm.analysisRtsp" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="视频录像RTSP地址" name="recordRtsp">
              <a-input v-model:value="cameraForm.recordRtsp" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="Web播放地址" name="webcastAddress">
              <a-input v-model:value="cameraForm.webcastAddress" :disabled="!changeTag" />
            </a-form-item>
          </a-form>
          <a-form
            style="flex: 1"
            class="antd-modal-form"
            :label-col="{ span: 6, offset: 0 }"
            :wrapper-col="{ span: 14 }"
            ref="ruleForm"
            :model="cameraForm"
          >
            <a-form-item label="地理经度" name="longitude">
              <a-input v-model:value="cameraForm.longitude" disabled />
            </a-form-item>
            <a-form-item label="地理纬度" name="latitude">
              <a-input v-model:value="cameraForm.latitude" disabled />
            </a-form-item>
            <!-- <a-form-model-item :wrapper-col="{offset:8,span:14}" name="style">
                                                                                                                                  <j-dict-select-tag v-model="cameraForm.style" placeholder="选择" dictCode="ms_camera_style"/>
                                                                                                                                </a-form-model-item>-->
            <a-form-item label="视线水平左夹角" name="leftAngle">
              <!-- <a-input v-model="cameraForm.leftAngle" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.leftAngle" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="视线水平右夹角" name="rightAngle">
              <!-- <a-input v-model="cameraForm.rightAngle" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.rightAngle" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="视野中央有效视距" name="viewDistance">
              <!-- <a-input v-model="cameraForm.viewDistance" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.viewDistance" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="采样帧率" name="frameRate">
              <!-- <a-input v-model="cameraForm.frameRate" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.frameRate" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="最大跟踪范围" name="maxRange">
              <!-- <a-input v-model="cameraForm.maxRange" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.maxRange" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="云台控制IP" name="cloudCtrlIp">
              <a-input v-model:value="cameraForm.cloudCtrlIp" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="云台控制端口" name="cloudCtrlPort">
              <a-input v-model:value="cameraForm.cloudCtrlPort" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="零方位角" name="zeroAzimuth">
              <!-- <a-input v-model="cameraForm.zeroAzimuth" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.zeroAzimuth" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="最大仰角" name="maxElevation">
              <!-- <a-input v-model="cameraForm.maxElevation" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.maxElevation" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="安装垂直角" name="fixedAngle">
              <!-- <a-input v-model="cameraForm.fixedAngle" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.fixedAngle" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="最大可视距离" name="maxVisibleDistance">
              <!-- <a-input v-model="cameraForm.maxVisibleDistance" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.maxVisibleDistance" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="变倍因子" name="zoomFactor">
              <!-- <a-input v-model="cameraForm.zoomFactor" type="number" :disabled="!changeTag" /> -->
              <a-input-number v-model:value="cameraForm.zoomFactor" :disabled="!changeTag" style="width: 100%" />
            </a-form-item>
            <a-form-item label="报警持续时间（秒）" name="alarmNum">
              <a-input-number placeholder="" style="width: 100%" v-model:value="cameraForm.alarmNum" :disabled="!changeTag" />
            </a-form-item>
            <a-form-item label="白光时间段" name="dayBeginTime">
              <a-col :span="11">
                <a-time-picker
                  name="dayBeginTime"
                  valueFormat="HH:mm:ss"
                  placeholder=""
                  v-model:value="cameraForm.dayBeginTime"
                  style="width: 100%"
                  format="HH:mm:ss"
                  :disabled="!changeTag"
                />
              </a-col>
              <a-col class="timePeriodDelimiter" span="2"> - </a-col>
              <a-col :span="11">
                <a-form-item name="dayEndTime">
                  <a-time-picker
                    name="dayEndTime"
                    valueFormat="HH:mm:ss"
                    placeholder=""
                    v-model:value="cameraForm.dayEndTime"
                    style="width: 100%"
                    :disabled="!changeTag"
                    format="HH:mm:ss"
                /></a-form-item>
              </a-col>
            </a-form-item>
          </a-form>
        </div>
        <div class="menuBottom">
          <a-button @click="submitForm" type="primary" :disabled="!addOrEdit"> 提交 </a-button>
          <a-button style="margin-left: 10px" @click="fromReset()"> 重置 </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import axios from 'axios';
  import { defHttp } from '/@/utils/http/axios';
  import { Modal } from 'ant-design-vue';

  // 厂家
  const cameraFactorys: any = ref([]);
  // 类型
  const cameraTypes: any = ref([]);
  const cameraStyles: any = ref([]);

  // 获取场景类型字典
  const getCameraFactory = () => {
    return defHttp.get({ url: '/sys/dict/getDictItems/ms_camera_factory' }, { isTransformResponse: false });
  };
  //获取场景类型字典
  const getCameraType = () => {
    return defHttp.get({ url: '/sys/dict/getDictItems/ms_camera_type' }, { isTransformResponse: false });
  };
  //获取场景类型字典
  const getCameraStyle = () => {
    return defHttp.get({ url: '/sys/dict/getDictItems/ms_camera_style' }, { isTransformResponse: false });
  };
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 6 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 18 } });

  const reNewBtn = ref();
  const userStore = useUserStore();
  const { createMessage } = useMessage();
  const x = 3;
  const y = 2;
  const z = 1;
  // const gData = []
  // const dataList = []

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.id === key)) {
          parentKey = node.id;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  const expandedKeys: any = ref([]);
  const searchValue = ref('');
  const autoExpandParent = ref(true);
  const gData: any = ref([]);
  const treeData: any = ref([]);
  const dataList: any = ref([]);
  const replaceFields = ref({
    key: 'id',
    title: 'name',
    children: 'children',
  });
  const url = ref({
    getSiteCameraInfo: '/military/camera/site/getSiteCameraInfo',
    getCameraInfoById: '/military/camera/setting/queryById',
    add: '/military/camera/setting/add',
    edit: '/military/camera/setting/edit',
    delete: '/military/camera/setting/delete',
    getVideoRecorderInfo: '/military/videoRecorder/qryCameraList',
    getVMCameraInfo: '/third/api/getVMCameraInfo',
  });
  const lineNameTemp = ref('');
  const siteNameTemp = ref('');
  const vrNameTemp = ref('');
  const dataId = ref('');
  const cancelFlag = ref(false);
  const flag = ref(false);
  const changeTag = ref(false);
  const getTag = ref(false);
  const addOrEdit = ref(false);
  const cameraForm: any = ref({
    id: '',
    ip: '',
    ip2: '',
    port: '',
    factory: '',
    style: '',
    type: '',
    user: '',
    siteId: '',
    password: '',
    channel: '',
    preRtsp: '',
    analysisRtsp: '',
    recordRtsp: '',
    lineName: '',
    siteName: '',
    cloudCtrlIp: '',
    cloudCtrlPort: '',
    cameraName: '',
    latitude: '',
    longitude: '',
    height: '',
    videoRecorder: '',
    cameraType: '',
    cameraColor: '',
    leftAngle: '',
    rightAngle: '',
    viewDistance: '',
    frameRate: '',
    maxRange: '',
    zeroAzimuth: '',
    maxElevation: '',
    fixedAngle: '',
    maxVisibleDistance: '',
    zoomFactor: '',
    videoRecorderId: '',
    dayBeginTime: '',
    dayEndTime: '',
    alarmNum: undefined,
    webcastAddress: '',
  });
  const lineArr: any = ref([]); //线路数据
  const siteData: any = ref({}); //线路站点对应关系
  const siteArr: any = ref([]); //站点数据
  const videoRecorderArr: any = ref([]); //录像机数据

  onMounted(() => {
    dataList.value.length = 0;
    getTreeInfo();
    // 厂家
    getCameraFactory().then((response) => {
      if (response.success) {
        cameraFactorys.value = response.result;
      }
    });
    // 类型
    getCameraType().then((response) => {
      if (response.success) {
        cameraTypes.value = response.result;
      }
    }),
      getCameraStyle().then((response) => {
        if (response.success) {
          cameraStyles.value = response.result;
        }
      });
    getVideoRecorderArr();
  });

  function handleLineChange(id) {
    changeSiteArr(id);
  }

  function handleSiteChange(id) {
    cameraForm.value.siteId = id;
  }

  function changeSiteArr(id) {
    let lineLen = gData.value.length;
    siteArr.value = [];
    for (let i = 0; i < lineLen; i++) {
      let lineData: any = gData.value[i];
      if (gData.value[i].id === id) {
        if (lineData.children !== null && lineData.children.length > 0) {
          let siteTempArr = lineData.children;
          for (let j = 0; j < siteTempArr.length; j++) {
            let siteData = siteTempArr[j];
            siteArr.value.push({ id: siteData.id, name: siteData.name });
          }
        } else {
          siteArr.value.push({ id: '', name: '' });
        }
      }
    }
    cameraForm.value.siteId = siteArr.value[0].id;
    cameraForm.value.siteName = siteArr.value[0].name;
    siteNameTemp.value = cameraForm.value.siteName; //改变线路，默认回显该线路的第一个站点
  }

  function add() {
    addOrEdit.value = true;
    cancelFlag.value = true;
    changeTag.value = true;
    getTag.value = false;
    dataId.value = '';
    fromClear();
  }

  function edit() {
    if (cameraForm.value.type == '1' || cameraForm.value.type == '3') {
      flag.value = true;
    } else {
      cameraForm.value.style = '';
      flag.value = false;
    }

    if (cameraForm.value.id == '') {
      // this.$message.info("请先选择需要修改的数据!");
      createMessage.info('请先选择需要修改的数据!');
      return false;
    }
    cancelFlag.value = true;
    addOrEdit.value = true;
    changeTag.value = true;
  }

  function del() {
    Modal.confirm({
      title: '确认删除',
      content: '是否删除选中数据?',
      onOk: function () {
        defHttp
          .delete(
            {
              url: url.value.delete,
              params: { id: cameraForm.value.id },
            },
            { joinParamsToUrl: true, isTransformResponse: false }
          )
          //   deleteAction(that.url.delete, {id: that.cameraForm.id})
          .then((res) => {
            if (res.success) {
              createMessage.success(res.message);
              fromClear();
              getTreeInfo();
              getTag.value = false;
            } else {
              createMessage.warning(res.message);
            }
          });
        changeTag.value = false;
        cancelFlag.value = false;
        addOrEdit.value = false;
      },
    });
  }

  function submitForm() {
    const pattern =
      /(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)\.(25[0-5]|2[0-4]\d|[0-1]\d{2}|[1-9]?\d)/;
    let settingId = cameraForm.value.id;
    let cloudCtrlIp = cameraForm.value.cloudCtrlIp;
    let cloudCtrlPort = cameraForm.value.cloudCtrlPort;
    let cameraName = cameraForm.value.cameraName;
    let siteName = cameraForm.value.siteName;
    let ip = cameraForm.value.ip;
    let ip2 = cameraForm.value.ip2;
    let port = cameraForm.value.port;
    let user = cameraForm.value.user;
    let password = cameraForm.value.password;
    let height = cameraForm.value.height;
    let videoRecorderId = cameraForm.value.videoRecorderId;
    let type = cameraForm.value.type;
    let factory = cameraForm.value.factory;
    let leftAngle = cameraForm.value.leftAngle;
    let rightAngle = cameraForm.value.rightAngle;
    let frameRate = cameraForm.value.frameRate;
    let viewDistance = cameraForm.value.viewDistance;
    let maxRange = cameraForm.value.maxRange;
    let zeroAzimuth = cameraForm.value.zeroAzimuth;
    let maxElevation = cameraForm.value.maxElevation;
    let fixedAngle = cameraForm.value.fixedAngle;
    let maxVisibleDistance = cameraForm.value.maxVisibleDistance;
    let zoomFactor = cameraForm.value.zoomFactor;
    let channel = cameraForm.value.channel;
    let style = cameraForm.value.style;
    cameraForm.value.cloudCtrlIp = cloudCtrlIp ? cloudCtrlIp : ip;
    let flagList = [
      {
        code: siteName,
        name: '站点名称',
      },
      {
        code: cameraName,
        name: '相机名',
      },
      {
        code: port,
        name: '相机端口',
      },
      {
        code: user,
        name: '相机认证用户名',
      },
      {
        code: password,
        name: '相机认证密码',
      },
      {
        code: factory,
        name: '厂家',
      },
      {
        code: type,
        name: '类型',
      },
      {
        code: ip,
        name: '相机IP',
      },
      {
        code: ip2,
        name: '相机备用IP',
      },
      {
        code: height,
        name: '安装高度',
      },
    ];
    let errorMessage = '';
    if (!cameraName || !siteName || !port || !user || !password || !height || !type || !factory || !ip || !ip2) {
      for (const flag of flagList) {
        if (!flag.code) {
          errorMessage += flag.name + '、';
        }
      }
      errorMessage = errorMessage.slice(0, errorMessage.length - 1);
      createMessage.warning(errorMessage + '未填写！');
      return;
    } else if (!pattern.test(ip) || !pattern.test(cameraForm.value.cloudCtrlIp) || !pattern.test(ip2)) {
      createMessage.warning('请检查IP格式并正确填写！');
      return;
    }
    // else if (!pattern.test(this.cameraForm.cloudCtrlIp)){
    //   this.$message.warning("请正确填写云台IP！");
    //   return
    // }
    cameraForm.value.channel = channel ? channel : '0';
    cameraForm.value.leftAngle = leftAngle ? leftAngle : '0';
    cameraForm.value.rightAngle = rightAngle ? rightAngle : '0';
    cameraForm.value.frameRate = frameRate ? frameRate : '0';
    cameraForm.value.viewDistance = viewDistance ? viewDistance : '0';
    cameraForm.value.zeroAzimuth = zeroAzimuth ? zeroAzimuth : '0';
    cameraForm.value.maxRange = maxRange ? maxRange : '0';
    cameraForm.value.maxElevation = maxElevation ? maxElevation : '0';
    cameraForm.value.fixedAngle = fixedAngle ? fixedAngle : '0';
    cameraForm.value.maxVisibleDistance = maxVisibleDistance ? maxVisibleDistance : '0';
    cameraForm.value.zoomFactor = zoomFactor ? zoomFactor : '0';
    cameraForm.value.cloudCtrlIp = cloudCtrlIp ? cloudCtrlIp : ip;
    cameraForm.value.cloudCtrlPort = cloudCtrlPort ? cloudCtrlPort : port;
    console.log(cameraForm.value.style);
    cameraForm.value.style = style ? style : '';
    console.log(cameraForm.value.style);
    let http;
    if (addOrEdit.value) {
      let httpurl = '';
      let method = '';
      if (!cameraForm.value.id) {
        httpurl += url.value.add;
        method = 'post';
        console.log(cameraForm.value.style);
        http = defHttp.post(
          {
            url: httpurl,
            params: cameraForm.value,
          },
          { isTransformResponse: false }
        );
      } else {
        httpurl += url.value.edit;
        method = 'put';
        console.log(cameraForm.value.style);
        http = defHttp.put(
          {
            url: httpurl,
            params: cameraForm.value,
          },
          { isTransformResponse: false }
        );
      }
      http
        // httpAction(httpurl, cameraForm.value, method)
        .then((res) => {
          let success_message = cameraForm.value.id ? '修改成功' : '添加成功';
          let error_message = cameraForm.value.id ? '修改失败' : '添加失败';
          if (res.success) {
            createMessage.success(success_message);
            cameraForm.value = res.result;
            getTreeInfo();
            // fromClear();
          } else {
            console.log(res);
            createMessage.warning(error_message);
          }
        });
      cancelFlag.value = false;
      addOrEdit.value = false;
      changeTag.value = false;
      getTag.value = true;
      flag.value = false;
    }
  }

  function selectSite(item, option) {
    let siteId = option.key;
    cameraForm.value.siteId = siteId;
  }

  function typeChange(item) {
    console.log(item);
    if (item == '1' || item == '3') {
      flag.value = true;
    } else {
      cameraForm.value.style = '';
      flag.value = false;
    }
  }

  function onSelect(selectedKeys, info) {
    console.log(selectedKeys);
    fromClear();
    addOrEdit.value = false;
    cancelFlag.value = false;
    changeTag.value = false;
    dataId.value = selectedKeys[0];
    // console.log(selectedKeys,info);

    selectedKeys = selectedKeys;
    let gDataLen = gData.value.length;
    getTag.value = false;
    for (let i = 0; i < gDataLen; i++) {
      if (gData.value[i].id == dataId.value) {
        return;
      }
    }
    //请求相机数据
    console.log('dataId.value', dataId.value);

    defHttp
      .get(
        {
          url: url.value.getCameraInfoById,
          params: { id: dataId.value },
        },
        { isTransformResponse: false }
      )
      //   getAction(this.url.getCameraInfoById + "?id=" + this.dataId)
      .then((res) => {
        console.log(res);
        if (res.success) {
          getTag.value = true;
          cameraForm.value = res.result;
          lineNameTemp.value = cameraForm.value.lineName;
          siteNameTemp.value = cameraForm.value.siteName;
          vrNameTemp.value = cameraForm.value.videoRecorderName;
        }
      });
  }

  function getTreeInfo() {
    defHttp
      .get(
        {
          url: url.value.getSiteCameraInfo,
          // params: model.value
        },
        { isTransformResponse: false }
      )
      //   httpAction(this.url.getSiteCameraInfo, this.model, 'get')
      .then((res) => {
        if (res.success) {
          gData.value = res.result;
          treeData.value = gData.value;
          // console.log("treeData",treeData.value);

          generateList(gData.value);
          lineArr.value = [];
          initLineArr();
        }
      });
  }

  function onExpand(onExpandedKeys) {
    expandedKeys.value = onExpandedKeys;
    autoExpandParent.value = false;
  }

  function onChange(e) {
    let time = null;
    const value = e.target.value;
    treeData.value = [];
    // console.log(time)
    const expandedKeys = dataList.value.map((item) => {
      if (value) {
        if (item.title.indexOf(value) > -1) {
          console.log(item);

          treeData.value.push({
            children: [],
            id: item.key,
            name: item.title,
          });
          // treeData.value = gData.value
        }
      } else {
        treeData.value = gData.value;
      }
    });

    // Object.assign(this, {
    //   expandedKeys,
    //   searchValue: value,
    //   autoExpandParent: true
    // })
  }

  function generateList(data) {
    // dataList.length=0
    // console.log(dataList)
    for (let i = 0; i < data.length; i++) {
      const node: any = data[i];
      const key = node.name;
      dataList.value.push({ key: node.id, title: node.name });
      if (node.children) {
        generateList(node.children);
      }
    }
  }

  function initLineArr() {
    let lineLen = gData.value.length;
    for (let i = 0; i < lineLen; i++) {
      let lineData = gData.value[i];
      lineArr.value.push({ id: lineData.id, name: lineData.name });
    }
  }
  function cancel() {
    // fromClear()

    let mycameraForm = cameraForm.value;
    if (!getTag.value) {
      // this.getTag = false;
      cameraForm.value.id = '';
      cameraForm.value.ip = '';
      cameraForm.value.ip2 = '';
      cameraForm.value.channel = '';
      cameraForm.value.analysisRtsp = '';
      cameraForm.value.cameraName = '';
      cameraForm.value.cameraType = '';
      cameraForm.value.cameraColor = '';
      cameraForm.value.cloudCtrlIp = '';
      cameraForm.value.cloudCtrlPort = '';
      cameraForm.value.latitude = '';
      cameraForm.value.height = '';
      cameraForm.value.videoRecorderId = '';
      cameraForm.value.viewDistance = '';
      cameraForm.value.frameRate = '';
      cameraForm.value.leftAngle = '';
      cameraForm.value.rightAngle = '';
      cameraForm.value.longitude = '';
      cameraForm.value.password = '';
      cameraForm.value.port = '';
      cameraForm.value.preRtsp = '';
      cameraForm.value.maxRange = '';
      cameraForm.value.lineName = '';
      cameraForm.value.siteName = '';
      cameraForm.value.user = '';
      cameraForm.value.type = '';
      cameraForm.value.factory = '';
      cameraForm.value.style = '';
      cameraForm.value.recordRtsp = '';
      cameraForm.value.siteId = '';
      cameraForm.value.zeroAzimuth = '';
      cameraForm.value.maxElevation = '';
      cameraForm.value.fixedAngle = '';
      cameraForm.value.maxVisibleDistance = '';
      cameraForm.value.zoomFactor = '';
      cameraForm.value.createBy = '';
      cameraForm.value.createTime = '';
      cameraForm.value.updateBy = '';
      cameraForm.value.updateTime = '';
      cameraForm.value.dayBeginTime = '';
      cameraForm.value.dayEndTime = '';
      cameraForm.value.alarmNum = '';
      lineNameTemp.value = '';
      siteNameTemp.value = '';
      vrNameTemp.value = '';
    } else {
      defHttp
        .get(
          {
            url: url.value.getCameraInfoById,
            params: { id: dataId.value },
          },
          { isTransformResponse: false }
        )
        // getAction(this.url.getCameraInfoById + "?id=" + that.dataId)
        .then((res) => {
          if (res.success) {
            getTag.value = true;
            cameraForm.value = res.result;
            lineNameTemp.value = cameraForm.value.lineName;
            siteNameTemp.value = cameraForm.value.siteName;
            vrNameTemp.value = cameraForm.value.videoRecorderName;
          }
        });
    }
    changeTag.value = false;
    cancelFlag.value = false;
    addOrEdit.value = false;
  }
  function fromReset() {
    if (dataId.value) {
      defHttp
        .get(
          {
            url: url.value.getCameraInfoById,
            params: { id: dataId.value },
          },
          { isTransformResponse: false }
        )
        // getAction(this.url.getCameraInfoById + "?id=" + that.dataId)
        .then((res) => {
          if (res.success) {
            getTag.value = true;
            cameraForm.value = res.result;
            lineNameTemp.value = cameraForm.value.lineName;
            siteNameTemp.value = cameraForm.value.siteName;
            vrNameTemp.value = cameraForm.value.videoRecorderName;
          }
        });
    } else {
      fromClear();
    }
  }
  function fromClear() {
    // let cameraForm = cameraForm.value;
    dataId.value = '';
    cameraForm.value.id = '';
    cameraForm.value.ip = '';
    cameraForm.value.ip2 = '';
    cameraForm.value.channel = '';
    cameraForm.value.analysisRtsp = '';
    cameraForm.value.cameraName = '';
    cameraForm.value.cameraType = '';
    cameraForm.value.cameraColor = '';
    cameraForm.value.cloudCtrlIp = '';
    cameraForm.value.cloudCtrlPort = '';
    cameraForm.value.latitude = '';
    cameraForm.value.height = '';
    cameraForm.value.videoRecorderId = '';
    cameraForm.value.viewDistance = '';
    cameraForm.value.frameRate = '';
    cameraForm.value.leftAngle = '';
    cameraForm.value.rightAngle = '';
    cameraForm.value.longitude = '';
    cameraForm.value.password = '';
    cameraForm.value.port = '';
    cameraForm.value.preRtsp = '';
    cameraForm.value.maxRange = '';
    cameraForm.value.lineName = '';
    cameraForm.value.siteName = '';
    cameraForm.value.user = '';
    cameraForm.value.type = '';
    cameraForm.value.factory = '';
    cameraForm.value.style = '';
    cameraForm.value.recordRtsp = '';
    cameraForm.value.siteId = '';
    cameraForm.value.zeroAzimuth = '';
    cameraForm.value.maxElevation = '';
    cameraForm.value.fixedAngle = '';
    cameraForm.value.maxVisibleDistance = '';
    cameraForm.value.zoomFactor = '';
    cameraForm.value.createBy = '';
    cameraForm.value.createTime = '';
    cameraForm.value.updateBy = '';
    cameraForm.value.updateTime = '';
    cameraForm.value.dayBeginTime = '';
    cameraForm.value.dayEndTime = '';
    cameraForm.value.alarmNum = '';
    lineNameTemp.value = '';
    siteNameTemp.value = '';
    vrNameTemp.value = '';
  }
  function getVideoRecorderArr() {
    defHttp
      .get(
        {
          url: url.value.getVideoRecorderInfo,
        },
        { isTransformResponse: false }
      )
      //   getAction(this.url.getVideoRecorderInfo)
      .then((res) => {
        if (res.success) {
          res.result.forEach((data, index) => {
            videoRecorderArr.value.push({ id: data.id, name: data.deviceName });
          });
        }
      });
  }
  function videoRecorderChange(id) {
    cameraForm.value.videoRecorderId = id;
  }
  function reNew() {
    reNewBtn.value.spin = true;
    defHttp
      .get(
        {
          url: url.value.getVMCameraInfo,
        },
        { isTransformResponse: false }
      )
      //   getAction(this.url.getVMCameraInfo)
      .then((res) => {
        if (res.success) {
          createMessage.success('相机列表更新成功!');
        } else {
          createMessage.error(res.message);
        }
        getTreeInfo();
        getVideoRecorderArr();
        reNewBtn.value.spin = false;
      });
  }

  defineExpose({
    reNewBtn,
    gData,
  });
</script>

<style scoped lang="less">
  ::-webkit-scrollbar {
    display: inline-block;
  }

  ::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0);
    border-radius: 2px;
  }

  .ant-form-vertical .ant-form-item {
    padding-bottom: 0 !important;
  }

  .cameraBox {
    width: 100%;
    height: 100%;
    display: flex;
    padding: 5px 15px;
  }

  .treeBox {
    flex: 1;
    padding: 15px 20px;
    border: #88887770 1px solid;
    overflow: scroll;
    max-height: 863px;
  }

  .menuBox {
    flex: 4;
    padding: 0 20px;
  }

  .menuFrom {
    display: flex;
    padding: 15px 0 0 0;
  }

  .menuBottom {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .mustInput {
    display: flex;
    position: relative;
  }

  .mustInput::before {
    content: '*';
    color: red;
    position: absolute;
    top: 6px;
    left: -8px;
  }

  .timePeriodDelimiter {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    height: 2em;
  }

  :deep(.ant-form-item-control-input-content) {
    display: flex;
  }

  :deep(.ant-form-item-label) {
    display: flex;
    justify-content: flex-start;
  }
</style>
