<template>
  <div>
    <YaEditForm
      v-model="formData"
      :formColumns="formColumns"
      :rules="rules"
      :loading="btnLoading"
      labelWidth="120px"
      @submit="submit"
    >
      <template #ip>
        <div class="custom">
          <div class="mb-16">
            <el-input
              :disabled="Route.query.ipv4 ? true : false"
              @change="inputValue"
              v-model="formData.ipv4"
              placeholder="请输入IPV4"
              clearable
            />
          </div>
          <el-input
            :disabled="Route.query.ipv6 ? true : false"
            @change="inputValue"
            v-model="formData.ipv6"
            placeholder="请输入IPV6"
            clearable
          />
        </div>
      </template>
      <template #assetTagCodeSet>
        <YaTag
          ref="yaTagChild"
          :canAdd="!disabledStatus"
          :tag="tagValue"
          @tabChange="tabChange"
        ></YaTag>
      </template>
      <template #test="{ item }">
        <div class="custom">
          <div>
            <el-checkbox label="remote" v-model="formData.gatherTypeSet"
              >远程扫描</el-checkbox
            >
          </div>
          <div class="content" v-if="formData.gatherTypeSet.includes('remote')">
            <el-form-item
              label="探测引擎"
              prop="gatherConfig.remoteScan.engineId"
            >
              <el-select
                v-model="formData['gatherConfig.remoteScan.engineId']"
                clearable
                placeholder="请选择探测引擎"
              >
                <el-option
                  v-for="item in remoteListBy"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="探测模式"
              prop="gatherConfig.remoteScan.modeConfig.mode"
            >
              <el-select
                v-model="formData['gatherConfig.remoteScan.modeConfig.mode']"
                clearable
                placeholder="请选择探测模式"
              >
                <el-option
                  v-for="item in detectModeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <div
              v-if="formData['gatherConfig.remoteScan.modeConfig.mode'] == 3"
            >
              <el-form-item prop="gatherConfig.remoteScan.modeConfig.rate">
                <template #label>
                  发包速率
                  <Tooltip
                    title="存活探测每秒的发包数，快速模式默认值为10000，标准模式为8000，慢速模式为5000，自定义范围500-200000。"
                  ></Tooltip>
                </template>
                <el-input
                  @input="
                    formData['gatherConfig.remoteScan.modeConfig.rate'] =
                      formData[
                        'gatherConfig.remoteScan.modeConfig.rate'
                      ].replace(/^(0+)|[^\d]+/g, '')
                  "
                  v-model="formData['gatherConfig.remoteScan.modeConfig.rate']"
                  placeholder="请输入发包速率"
                  clearable
                />
              </el-form-item>
              <el-form-item prop="gatherConfig.remoteScan.modeConfig.retry">
                <template #label>
                  重试次数
                  <Tooltip
                    title="代表探测的过程中重新尝试的次数，快速模式默认值0，标准模式为2，慢速模式为3，自定义范围为0-8次。"
                  ></Tooltip>
                </template>
                <el-input
                  class="flex-one m-l-12"
                  v-model="formData['gatherConfig.remoteScan.modeConfig.retry']"
                  @input="
                    formData['gatherConfig.remoteScan.modeConfig.retry'] =
                      formData[
                        'gatherConfig.remoteScan.modeConfig.retry'
                      ].replace(/[^\d]+/g, '')
                  "
                  placeholder="请输入重试次数"
                  clearable
                />
              </el-form-item>
              <el-form-item prop="gatherConfig.remoteScan.modeConfig.interval">
                <template #label>
                  间隔时间
                  <Tooltip
                    title="针对单个IP的发包间隔时间，单位为毫秒（ms），快速模式默认值为100毫秒，标准模式为300毫秒，慢速模式默认值为500毫秒，自定义范围为100-1000毫秒。"
                  ></Tooltip>
                </template>
                <el-input
                  class="flex-one m-l-12"
                  v-model="
                    formData['gatherConfig.remoteScan.modeConfig.interval']
                  "
                  @input="
                    formData['gatherConfig.remoteScan.modeConfig.interval'] =
                      formData[
                        'gatherConfig.remoteScan.modeConfig.interval'
                      ].replace(/^(0+)|[^\d]+/g, '')
                  "
                  placeholder="请输入间隔时间"
                  clearable
                />
              </el-form-item>
              <el-form-item prop="gatherConfig.remoteScan.modeConfig.timeout">
                <template #label>
                  超时时间
                  <Tooltip
                    title="代表响应的最大等待时间，单位为秒（s）,快速模式默认值为3秒，标准模式为4秒，慢速默认值为5秒，自定义范围为1-30秒。"
                  ></Tooltip>
                </template>
                <el-input
                  class="flex-one m-l-12"
                  v-model="
                    formData['gatherConfig.remoteScan.modeConfig.timeout']
                  "
                  @input="
                    formData['gatherConfig.remoteScan.modeConfig.timeout'] =
                      formData[
                        'gatherConfig.remoteScan.modeConfig.timeout'
                      ].replace(/^(0+)|[^\d]+/g, '')
                  "
                  placeholder="请输入超时时间"
                  clearable
                />
              </el-form-item>
              <el-form-item class="custom-label">
                <template #label>
                  TCP端口扫描
                  <Tooltip
                    title="标准端口扫描：标准端口扫描测策略扫描目标的已知各种应用、木马等使用的端口；快速端口扫描：扫描1-1024；指定端口范围：端口范围：1-65535，多个端口以英文“,”隔开；建议输入十个端口以内！"
                  ></Tooltip>
                </template>
                <div v-for="item in tcpPortList">
                  <div class="flex-st">
                    <el-radio
                      v-model="
                        formData[
                          'gatherConfig.remoteScan.detectScanConfig.tcpPortScanRange'
                        ]
                      "
                      :label="item.value"
                    >
                      <span>{{ item.label }}</span>
                    </el-radio>
                    <div
                      v-if="item.value == 'standard'"
                      class="port-list"
                      @click="toPort"
                    >
                      编辑端口服务列表
                    </div>
                    <div v-if="item.value == 'customize'" class="port-range">
                      <el-input
                        v-model="
                          formData[
                            'gatherConfig.remoteScan.detectScanConfig.tcpScanPort'
                          ]
                        "
                        placeholder="请输入1-65535"
                      ></el-input>
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item>
                <template #label>
                  TCP端口扫描方式
                  <Tooltip
                    title="SYN：推荐选项，通过直接建立完整的TCP连接来判断端口开放情况，此方法快而准确；CONNECT：向目标端口发送SYN包，依据对方是否回复ACK报文来判断端口开放情况；"
                  ></Tooltip>
                </template>
                <el-radio-group
                  v-model="
                    formData[
                      'gatherConfig.remoteScan.detectScanConfig.tcpPortScanType'
                    ]
                  "
                >
                  <el-radio v-for="item in tcpPortScanType" :label="item.value">
                    <span>{{ item.label }}</span>
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="UDP扫描端口">
                <template #label>
                  UDP扫描端口
                  <Tooltip
                    title="端口范围：1-65535；多个端口以英文“,”隔开；建议输入十个端口以内！"
                  ></Tooltip>
                </template>
                <span>
                  <el-switch
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectScanConfig.udpScanEnable'
                      ]
                    "
                /></span>
                <el-input
                  class="ml-8"
                  v-if="
                    formData[
                      'gatherConfig.remoteScan.detectScanConfig.udpScanEnable'
                    ]
                  "
                  v-model="
                    formData[
                      'gatherConfig.remoteScan.detectScanConfig.udpScanPort'
                    ]
                  "
                  placeholder="请输入1-65535"
                >
                </el-input>
              </el-form-item>
              <el-form-item>
                <template #label>
                  探活方式
                  <Tooltip
                    title="UDP PING端口：向目标主机发送UDP数据报文，根据目标主机的反应以判断其是否存活；TCP PING端口：向目标主机TCP SYN/ACK/FIN等数据报文，根据目标主机的反应以判断其是否存活；"
                  ></Tooltip>
                </template>
                <div>
                  <el-checkbox
                    disabled
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.icmpPing'
                      ]
                    "
                    label="true"
                    >ICMP PING</el-checkbox
                  >
                </div>
                <div class="flex-bt mt-8">
                  <el-checkbox
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.udpPing'
                      ]
                    "
                    label="true"
                  >
                    UDP PING端口
                  </el-checkbox>
                  <el-input
                    class="ml-8"
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.udpPort'
                      ]
                    "
                    placeholder="请输入1-65535"
                  ></el-input>
                </div>
                <div class="flex-bt mt-8">
                  <el-checkbox
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.tcpPing'
                      ]
                    "
                    label="true"
                    :disabled="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.tcpPingAllPort'
                      ]
                        ? true
                        : false
                    "
                  >
                    TCP PING端口
                  </el-checkbox>
                  <el-input
                    class="ml-8"
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.tcpPort'
                      ]
                    "
                    placeholder="请输入1-65535"
                  ></el-input>
                </div>
                <div class="mt-8">
                  <el-checkbox
                    v-model="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.tcpPingAllPort'
                      ]
                    "
                    :disabled="
                      formData[
                        'gatherConfig.remoteScan.detectSurviveConfig.tcpPing'
                      ]
                        ? true
                        : false
                    "
                    label="true"
                    >TCP PING全端口</el-checkbox
                  >
                </div>
              </el-form-item>
            </div>
          </div>
          <div>
            <el-checkbox label="login" v-model="formData.gatherTypeSet"
              >登录采集</el-checkbox
            >
            <ya-button
              class="btn-one"
              type="success"
              :loading="isSubLoading"
              @click="handlerDialTest()"
              >一键拨测
            </ya-button>
          </div>
          <div class="content" v-if="formData.gatherTypeSet.includes('login')">
            <el-form-item
              label="探测引擎"
              prop="gatherConfig.loginGatherConfig.engineId"
            >
              <el-select
                v-model="formData['gatherConfig.loginGatherConfig.engineId']"
                clearable
                placeholder="请选择探测引擎"
              >
                <el-option
                  v-for="item in loginListBy"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="登录协议"
              prop="gatherConfig.loginGatherConfig.protocol"
            >
              <el-select
                v-model="formData['gatherConfig.loginGatherConfig.protocol']"
                clearable
                placeholder="请选择登录协议"
              >
                <el-option
                  v-for="item in loginProtocolList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="登录端口"
              prop="gatherConfig.loginGatherConfig.port"
            >
              <el-input
                v-model="formData['gatherConfig.loginGatherConfig.port']"
                placeholder="请输入登录端口"
                clearable
              />
            </el-form-item>
            <el-form-item
              label="登录账户"
              prop="gatherConfig.loginGatherConfig.account"
            >
              <el-input
                v-model="formData['gatherConfig.loginGatherConfig.account']"
                placeholder="请输入登录账户"
                clearable
              />
            </el-form-item>
            <el-form-item
              label="登录密码"
              prop="gatherConfig.loginGatherConfig.pwd"
            >
              <el-input
                show-password
                type="password"
                autocomplete="new-password"
                v-model="formData['gatherConfig.loginGatherConfig.pwd']"
                placeholder="请输入登录密码"
                clearable
              />
            </el-form-item>
          </div>
        </div>
      </template>
    </YaEditForm>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  unref,
  watchEffect,
  watch,
  nextTick,
} from 'vue';
import { getDictTypeList, getDeptList, firstLevelList, getSubDeptTreeById } from '../../../api/common';
import { getLeftTreeJson } from '../../../api/permission/userManagement';
import { detectMode } from '../../../api/collection/assetsFound/detectTask';
import YaTag from '../../../components/tag/index.vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox, FormRules, ElTable } from 'element-plus';
import Tooltip from '../../../components/tooltip/tooltip.vue';
import {
  listByType
} from '../../../api/collection/assetsFound/detectTask';
import {
  confirmSingle,
  getRemoteScan,
  queryGatherConfig
} from '../../../api/collection/assetsFound/propertyAudit';
import { getDeptInfo } from '../../../api/collection/infoCollection/inventory';
import {
  getDialTestData,
  getDialTestResult
} from "../../../api/collection/infoCollection/inventory";
const router = useRouter();
const Route = useRoute();

const formData = ref({
  ipv4: '',
  ipv6: '',
  networkAreaCode: '',
  name: '',
  assetType: [],
  position: '',
  domain: '',
  feature: {
    importanceLevel: '',
    internetAccess: '0',
    networkLocation: '1'
  },
  assetTagCodeSet: [],

  gatherTypeSet: ['remote'],
  input7: 2,
  input8: 2,
  gatherConfig: {
    remoteScan: {
      engineId: '',
      // 远程扫描
      detectScanConfig: {
        tcpPortScanRange: 'standard',
        tcpPortScanType: 1,
        tcpScanPort: '1-100,443,445',
        udpScanEnable: false,
        udpScanPort: '25,53',
      },
      detectSurviveConfig: {
        icmpPing: true,
        tcpPing: true,
        tcpPingAllPort: false,
        tcpPort: '21,22,23,25,80,443,445,139,3389,6000',
        udpPing: false,
        udpPort: '25,53',
      },
      modeConfig: {
        mode: 0,
        interval: 0,
        rate: 100,
        retry: 100,
        timeout: 3,
      },
    },
    loginGatherConfig: {
      engineId: '', // 引擎id
      account: '', // 登录账户
      pwd: '', //登录密码
      protocol: null, // 登录协议
      port: null, //登录端口
    },
    gatherStatus: '',
  },
});
//发包速率的校验
var checkRate = (rule, value, callback) => {
  console.log(value);
  if (value < 500) {
    callback(new Error('范围在500-200000'));
  } else if (value > 200000) {
    callback(new Error('范围在500-200000'));
  } else {
    callback();
  }
};
//重试次数的校验
var checkRetry = (rule, value, callback) => {
  if (value < 0) {
    callback(new Error('范围在0-8'));
  } else if (value > 8) {
    callback(new Error('范围在0-8'));
  } else {
    callback();
  }
};
//间隔时间的校验
var checkInterval = (rule, value, callback) => {
  if (value < 100) {
    callback(new Error('范围在100-1000'));
  } else if (value > 1000) {
    callback(new Error('范围在100-1000'));
  } else {
    callback();
  }
};
//超时时间的校验
var checkTimeout = (rule, value, callback) => {
  if (value < 1) {
    callback(new Error('范围在1-30'));
  } else if (value > 30) {
    callback(new Error('范围在1-30'));
  } else {
    callback();
  }
};
const rules = ref({
  'gatherConfig.remoteScan.engineId': [{ required: true, message: '请选择探测引擎', trigger: 'change' }],
  'gatherConfig.loginGatherConfig.engineId': [{ required: true, message: '请选择探测引擎', trigger: 'change' }],
  'gatherConfig.remoteScan.modeConfig.mode': [{ required: true, message: '请选择探测模式', trigger: 'change' }],
  'gatherConfig.loginGatherConfig.protocol': [
    { required: true, message: '请选择登录协议', trigger: 'change' },
  ],
  'gatherConfig.loginGatherConfig.port': [
    { required: true, message: '请输入登录端口', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (/^(?:[0-9]\d*)$/.test(value) == false) {
          callback(new Error('请输入正整数'));
        } else if (value < 1) {
          callback(new Error('范围在1-65535'));
        } else if (value > 65535) {
          callback(new Error('范围在1-65535'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  'gatherConfig.loginGatherConfig.account': [
    { required: true, message: '请输入登录账号', trigger: 'change' },
    { min: 1, message: '登录账号至少1位' },
    { max: 16, message: '登录账号最多20位' },
  ],
  'gatherConfig.loginGatherConfig.pwd': [
    { required: true, message: '请输入登录密码', trigger: 'change' },
  ],
  'gatherConfig.remoteScan.modeConfig.rate': [
    { required: true, message: '发包速率不能为空', trigger: 'change' },
    { validator: checkRate, trigger: 'change' },
  ],
  'gatherConfig.remoteScan.modeConfig.retry': [
    { required: true, message: '重试次数不能为空', trigger: 'change' },
    { validator: checkRetry, trigger: 'change' },
  ],
  'gatherConfig.remoteScan.modeConfig.interval': [
    { required: true, message: '间隔时间不能为空', trigger: 'change' },
    { validator: checkInterval, trigger: 'change' },
  ],
  'gatherConfig.remoteScan.modeConfig.timeout': [
    { required: true, message: '超时时间不能为空', trigger: 'change' },
    { validator: checkTimeout, trigger: 'change' },
  ],
});
const formColumns = reactive([
  {
    title: '基础属性',
    formItemClassName: 'line',
  },
  {
    key: 'ip',
    slotName: 'ip',
    label: '资产IP',
    type: 'define',
    rules: true,
  },
  {
    key: 'networkAreaCode',
    type: 'select',
    label: '网络域',
    disabled: true,
    options: [],
    rules: true,
  },
  {
    key: 'name',
    type: 'input',
    label: '资产名称',
  },
  {
    key: 'assetType',
    type: 'select',
    label: '资产类型',
    options: [
      {
        label: '选项一',
        value: '1',
      },
      {
        label: '选项二',
        value: '2',
      },
    ],
    rules: true,
  },
  {
    key: 'position',
    type: 'cascader',
    label: '资产所在区域',
    props: {
      checkStrictly: true,
      value: 'dictValue',
      label: 'dictName',
      emitPath: false,
    },
    showAllLevels: false,
  },
  {
    key: 'domain',
    type: 'input',
    label: '域名',
  },
  {
    key: 'feature.importanceLevel',
    type: 'select',
    label: '资产重要级别',
  },
  {
    key: 'assetTagCodeSet',
    label: '资产标签',
    slotName: 'assetTagCodeSet',
  },
  {
    key: 'feature.internetAccess',
    type: 'radio',
    label: '可从互联网访问',
    options: [
      {
        key: '是',
        value: '1',
      },
      {
        key: '否',
        value: '0',
      },
    ],
  },
  {
    key: 'feature.networkLocation',
    type: 'select',
    label: '网络位置',
    options: [
      {
        label: '内网',
        value: '1',
      },
      {
        label: '外网',
        value: '2',
      },
    ],
  },
  {
    key: 'gatherTypeSet',
    type: 'checkbox',
    label: '采集方式',
    slotName: 'test',
    rules: true,
  },
  {
    title: '资产归属',
    formItemClassName: 'line',
  },
  {
    key: 'feature.companyId',
    type: 'select',
    label: '所属单位',
    onChange(e) {
      getOneDept(e)
    }
  },
  {
    key: 'deptId',
    label: '所属部门',
    type: 'cascader',
    props: {
      checkStrictly: true,
      value: 'id',
      emitPath: false,
    },
    showAllLevels: false,
    rules: true,
    onChange(e) {
      getPeopel(e);
    },
  },
  {
    key: 'feature.contact',
    type: 'input',
    label: '负责人',
  },
  {
    key: 'feature.contactMobile',
    type: 'input',
    label: '联系方式',
  },
  {
    key: 'feature.contactEmail',
    type: 'input',
    label: '邮箱',
  },
  {
    key: 'feature.cabinet',
    type: 'input',
    label: '机柜位置',
  },
  {
    key: 'feature.securityDomain',
    type: 'input',
    label: '安全域',
  },
  {
    key: 'feature.isOwn',
    type: 'radio',
    label: '是否自有资产',
    options: [
      {
        key: '是',
        value: '1',
      },
      {
        key: '否',
        value: '2',
      },
    ],
  },
  {
    key: 'feature.businessSystem',
    type: 'input',
    label: '所属业务系统',
  },
  {
    title: '设备型号',
    formItemClassName: 'line',
  },
  {
    key: 'feature.cpuManufacturer',
    type: 'input',
    label: 'CPU厂商与型号',
  },
  {
    key: 'feature.memoryManufacturer',
    type: 'input',
    label: '内存厂商与型号',
  },
  {
    key: 'feature.switchingChipManufacturer',
    type: 'input',
    label: '交换芯片厂商与型号',
  },
  {
    key: 'feature.hardwareManufacturer',
    type: 'input',
    label: '硬件厂商与型号',
  },
  {
    key: 'feature.operatingSystem',
    type: 'input',
    label: '操作系统与版本',
  },
  {
    title: '合规信息',
    formItemClassName: 'line',
  },
  {
    key: 'feature.networkUnitType',
    type: 'select',
    label: '网络单元类型',
  },
  {
    key: 'feature.ratingObjectName',
    type: 'input',
    label: '定级对象名称',
  },
  {
    key: 'feature.ratingLevel',
    type: 'select',
    label: '定级级别',
  },
  {
    key: 'feature.protectionLevel',
    type: 'select',
    label: '等保级别',
  },
]);
/**
 * @description 监听输入
 */
const inputValue = (e) => {
  formData.value.ip = e
}
/**
 * @description 提交
 */
const btnLoading = ref(false)
const submit = (e) => {
  e.code = Route.query.code;
  btnLoading.value = true;
  confirmSingle(e).then(res=>{
    btnLoading.value = false
    if(res.code == 200) {
      ElMessage.success(res.message);
      router.go(-1);
    }
  }).catch(()=>{
    btnLoading.value = false
  })
};
/**
 * @description: 字典数据初始化
 */
const resetDictData = (e) => {
  let list = e.map((item) => {
    return {
      label: item.dictName,
      value: item.dictValue,
    };
  });
  return list;
};
const restDataOne = (data) => {
  data = data.map(item=>{
    return {
      ...item,
      label: item.dictName,
      children: item.childList ? restDataOne(item.childList) : item.childList
    }
  })
  return data
}
const detectModeList = ref([]); // 扫描模式
const tcpPortList = ref([]); // TCP端口扫描
const tcpPortScanType = ref([]); // TCP 端口扫描方式
const loginProtocolList = ref([]); // 登录协议
const detectModeData = ref({}); // 获取远程配置默认数据
const remoteListBy = ref([]); // 远程-引擎数据
const loginListBy = ref([]); // 远程-引擎数据
const getDictList = () => {
  // 网络域
  getDictTypeList({ dictType: 'networkArea' }).then((res) => {
    if (res.code == 200) {
      if(res.data && res.data.length > 0) {
        formData.value.networkAreaCode = Route.query.networkAreaCode;
      }
      formColumns.forEach((item) => {
        if (item.key == 'networkAreaCode') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
   // 资产类型
   getDictTypeList({ dictType: 'assetType' }).then((res) => {
    if (res.code == 200) {
      if(res.data && res.data.length > 0) {
        formData.value.assetType = resetDictData(res.data)[0].value;
      }
      formColumns.forEach((item) => {
        if (item.key == 'assetType') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
   // 资产重要级别
   getDictTypeList({ dictType: 'importanceLevel' }).then((res) => {
    if (res.code == 200) {
      if(res.data && res.data.length > 0) {
        formData.value['feature.importanceLevel'] = resetDictData(res.data)[0].value;
      }
      formColumns.forEach((item) => {
        if (item.key == 'feature.importanceLevel') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
   // 定级级别
   getDictTypeList({ dictType: 'ratingLevel' }).then((res) => {
    if (res.code == 200) {
      if(res.data && res.data.length > 0) {
        formData.value['feature.ratingLevel'] = resetDictData(res.data)[0].value;
      }
      formColumns.forEach((item) => {
        if (item.key == 'feature.ratingLevel') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
   // 等保级别
   getDictTypeList({ dictType: 'protectionLevel' }).then((res) => {
    if (res.code == 200) {
      if(res.data && res.data.length > 0) {
        formData.value['feature.protectionLevel'] = resetDictData(res.data)[0].value;
      }
      formColumns.forEach((item) => {
        if (item.key == 'feature.protectionLevel') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
  // 扫描模式
  getDictTypeList({ dictType: 'detectMode' }).then((res) => {
    if (res.code == 200) {
      detectModeList.value = resetDictData(res.data)
    }
  });
  // TCP端口扫描
  getDictTypeList({ dictType: 'portScanRange' }).then((res) => {
    if (res.code == 200) {
      tcpPortList.value = resetDictData(res.data);
    }
  });
  // tcp 端口扫描方式
  getDictTypeList({ dictType: 'tcpPortScanType' }).then((res) => {
    if (res.code == 200) {
      tcpPortScanType.value = resetDictData(res.data).map((item) => {
        return item;
      });
    }
  });
  // 登录协议
  getDictTypeList({ dictType: 'loginProtocol' }).then((res) => {
    if (res.code == 200) {
      loginProtocolList.value = resetDictData(res.data);
    }
  });
  // 所属单位
  firstLevelList({}).then((res)=>{
    if(res.code == 200) {
      formColumns.forEach((item) => {
        if (item.key == 'feature.companyId') {
          item.options = res.data ? res.data.map((item)=>{
            item.label = item.deptName;
            item.value = item.id;
            return item
          }) : []
        }
      });
    }
  })
  // 资产所在区域
  getDictTypeList({
    dictType: 'position',
    needChild: true,
    needChildTree: true,
    dictKey: 'position',
    needRoot: true,
  }).then((res) => {
    if (res.code == 200) {
      formColumns.forEach((item) => {
        if (item.key == 'position') {
          item.options = restDataOne(res.data)
        }
      });
    }
  });
  // 远程扫描探测引擎
  getDetectionEngine('detectEngine');
  // 登录探测引擎
  getDetectionEngine('loginCheckEngine');
};
/**
 * @descripiton 探测引擎
 */
 const getDetectionEngine = (e) => {
  listByType({ engineType: e }).then((res) => {
    const { code, data } = res;
    if (code == 200) {
      let list = data.map((item) => {
          item.label = item.engineName;
          item.value = item.id;
          return item;
        }) || [];
        if(e == 'detectEngine') {
          remoteListBy.value = list
        } else {
          loginListBy.value = list
        }
    }
  });
}
const restData = (data) => {
  data = data.map(item=>{
    return {
      ...item.data,
      label: item.data.deptName,
      children: item.children ? restData(item.children) : item.children
    }
  })
  return data
}
const getOneDept = (id) => {
    // 获取部门层级
    getSubDeptTreeById({deptId: id}).then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      formColumns.forEach((item) => {
        if (item.key == 'deptId') {
          item.options = data?restData(data):[]
        }
      });
      if(data.length == 0) {
        formData.value.deptId = '';
        formData.value['feature.contact'] = '';
        formData.value['feature.contactMobile'] = '';
      }
    }
  })
}
/**
 * @description 获取部门联系人
 */
 const getPeopel = (e) => {
  getDeptInfo({ id: e }).then((res) => {
    if (res.code == 200) {
      if ( res.data && res.data.owner ) {
        formData.value['feature.contact'] = res.data.owner.realityName;
        formData.value['feature.contactMobile'] = res.data.owner.mobile;
      } else {
        formData.value['feature.contact'] = '';
        formData.value['feature.contactMobile'] = '';
      }

    }
  });
};
/**
 * @description: 端口策略列表
 */
const toPort = () => {
  router.push({
    path: '/system/systemConfig/portStrategy',
  });
};
/**
 * @description 获取标签值
 */
const disabledStatus = ref(false);
const tagValue = ref([]); // 标签值
const tabChange = (params) => {
  formData.value.assetTagCodeSet = params || null;
};
/** *
 *
 * 获取请求的UUID，指定长度和进制,如
 * getUUID(8, 2)   //"01001010" 8 character (base=2)
 * getUUID(8, 10) // "47473046" 8 character ID (base=10)
 * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
 *
 */
 const getUUID = (len, radix) => {
  var chars =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");
  var uuid = [];
  var i;
  radix = radix || chars.length;
  if (len) {
    for (i = 0; i < len; i++) uuid[i] = chars[0 | (Math.random() * radix)];
  } else {
    var r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = "-";
    uuid[14] = "4";
    for (i = 0; i < 36; i++) {
      if (!uuid[i]) {
        r = 0 | (Math.random() * 16);
        uuid[i] = chars[i === 19 ? (r & 0x3) | 0x8 : r];
      }
    }
  }
  return uuid.join("");
};
/**
 * @description 一键拨测
 */
const uuid = ref("");
const isSubLoading = ref(false);
const handlerDialTest = () => {
  let loginGatherConfig = formData.value.gatherConfig.loginGatherConfig
  for(var key in loginGatherConfig) {
    loginGatherConfig[key] = formData.value['gatherConfig.loginGatherConfig.' + key];
  }
  const params = {
    uuid: uuid.value,
    ip: formData.value.ipv4 ? formData.value.ipv4 : formData.value.ipv6,
    networkAreaCode: formData.value.networkAreaCode,
    loginGather: loginGatherConfig,
  };
  isSubLoading.value = true;
  getDialTestData(params).then((res) => {
    if (res.code == 200) {
      let timer = "";
      timer = setInterval(() => {
        getDialTestResult({ uuid: uuid.value }).then((res) => {
          if (
            res.data == "timeout" ||
            res.data == "success" ||
            res.data == "fail"
          ) {
            isSubLoading.value = false;
            clearInterval(timer);
            if (res.data == "success") {
              ElMessage.success("拨测成功！");
            } else if (res.data == "timeout") {
              ElMessage.success("拨测超时！");
            } else {
              ElMessage.error("拨测失败！");
            }
          }
        });
      }, 1000);
    } else {
      isSubLoading.value = false;
    }
  });
};
/**
 * @description 获取默认配置信息
 */
const getDeatil = () => {
  if(Route.query.companyId) {
    formData.value['feature.companyId'] = Number(Route.query.companyId);
    formData.value.deptId = Number(Route.query.deptId);
    formData.value.ipv4 = Route.query.ipv4;
    formData.value.ipv6 = Route.query.ipv6;
    inputValue(Route.query.ipv4?Route.query.ipv4:Route.query.ipv6)
    getOneDept(Route.query.companyId);
    getPeopel(Route.query.deptId)
  }
  queryGatherConfig({assetCode: Route.query.code}).then((res)=>{
    if(res.code == 200) {
     let { remoteScan,loginGatherConfig } = res.data;
     let { detectScanConfig, detectSurviveConfig, modeConfig } = remoteScan;
     formData.value['gatherConfig.remoteScan.engineId'] = remoteScan.engineId;
      for( var key in modeConfig) {
        formData.value['gatherConfig.remoteScan.modeConfig.' + key] =modeConfig[key];
      }
      for( var key in detectScanConfig) {
        formData.value['gatherConfig.remoteScan.detectScanConfig.' + key] =detectScanConfig[key];
      }
      for( var key in detectSurviveConfig) {
        formData.value['gatherConfig.remoteScan.detectSurviveConfig.' + key] =detectSurviveConfig[key];
      }
      for( var key in loginGatherConfig) {
        formData.value['gatherConfig.loginGatherConfig.' + key] = loginGatherConfig[key];
      }
    }
  })

}
onMounted(() => {
  getDictList();
  // getProvinceAndCity(provinceData);
  getDeatil();
  uuid.value = getUUID(32, 16) + "-";
});
</script>

<style lang="scss" scoped>
::v-deep .ya-form .el-cascader {
  width: calc((100% - 54px) / 2);
}
.custom {
  width: calc((100% - 54px) / 2);
  .content {
    width: 100%;
    .el-input,
    .el-select {
      max-width: 100% !important;
    }
  }
}
.custom-label {
  ::v-deep .el-form-item__content {
    display: block;
  }
  .flex-st {
    display: flex;
  }
  .port-list {
    color: var(--el-color-primary);
    text-decoration: underline;
  }
  .port-range {
    flex: 1;
  }
  ::v-deep .el-radio {
    margin-right: 12px;
  }
}
.ml-8 {
  margin-left: 8px;
}
.flex-bt {
  display: flex;
  width: 100%;
}
.mt-8 {
  margin-top: 8px;
}
.btn-one {
  color: #fff;
  margin-left: 58px;
  height: 30px;
  margin-bottom: 12px;
}
.mb-16 {
  margin-bottom: 16px;
}
</style>
