<template>
  <div class="yaBox">
    <yaEditForm
      ref="editForm"
      v-model="formData"
      :formColumns="formColumns"
      @submit="handlerToSubmit"
      :loading="isLoading"
    >
    <!-- 目标地址的导入 -->
     <!-- 目标地址的导入 -->
     <template #yaTargetAddress>
        <yaInputUpload
          :pass="['txt']"
          @handleChangeUpload="handleImport"
          @handleDeleteFile="handleDelete"
        ></yaInputUpload>
        <span class="ya-config" @click="handleDownloadTemplate">模板下载</span>
      </template>
        <!-- 执行方式 -->
        <template #carryOutType="{ data }">
        <div style="width: 100%">
          <AddPopUp
            v-if="data.type && data.type != 'manual'"
            ref="refAddPopUp"
            :showType="1"
            :isShow="data.type"
            @dateValue="getModelValue"
            :dataValue="timeObj"
          />
        </div>
      </template>
      <!-- 口令猜测 -->
      <template #weakGuess="{ data }">
        <el-checkbox v-model="data.weakPassEnable">启用</el-checkbox>
        <span
          class="ya-config"
          v-if="data.weakPassEnable"
          @click="handlerToOtherPage('detailConfig', route.query)"
          >详细配置</span
        >
      </template>
      <!-- 仅生成扫描报告 -->
      <template #generateReport="{ data }">
        <el-checkbox v-model="data.generateReportEnable">启用</el-checkbox>
      </template>
      <!-- 登录检查 -->
      <template #loginCheck="{ data }">
        <el-checkbox v-model="data.loginCheckEnable">启用</el-checkbox>
      </template>
        <!-- 登陆配置 -->
        <template #loginCheckTable="{ data }">
        <template v-if="data.loginCheckEnable">
          <div class="ya-buttons">
            <ya-button @click="handleToExport">导出</ya-button>
            <div class="ya-right-buttons">
              <ya-button @click="uploadProps.showDrawer = true">导入</ya-button>
              <ya-button type="primary"  @click="handlerToOtherPage('sshLogin')"
                >添加</ya-button
              >
            </div>
          </div>
          <ya-table
            @btnClick="handleTableBtnClick"
            :data="data.loginCheckConfigConfigList"
            :column="column"
          ></ya-table>
        </template>
      </template>
    </yaEditForm>
    <yaDrawerUpload
      v-if="uploadProps.showDrawer"
      templateUrl="xxx.xlsx"
      :http="http"
      :drawerProps="uploadProps"
      @submit="uploadSubmit"
      @handleChangeUpload="handleChangeUpload"
    ></yaDrawerUpload>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, defineProps } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { yaMessage, yaConfirmMessage } from 'yuan-plus';
import { downLoadFile } from '../../../../utils/utils';
import {hostScanColumn, column } from './hostScan';
import { FormRules } from 'element-plus';
import {
  sshLoginFileExport,
  targetAnalysis,
  sshLoginFileAnalysis,
  createHostVulTask,
  modifyHostVulTask,
} from '../../../../api/riskDetect/riskIdentify/addTask/hostScan';
import AddPopUp from './components/addPopUp.vue';
import { getModifyVo } from '../../../../api/riskDetect/riskIdentify/taskList';
import { handleGetIndex } from '../../../../utils/tools';
import { getDownloadFile } from '../../../../api/common';
import { http } from '@/utils/https';
const { whichSystem } = defineProps({
  whichSystem: String,
});
const editForm = ref(null);
const router = useRouter();
const route = useRoute();
const formColumns: any = ref([]);
const formData=ref({
  weakPassEnable: false,
  loginCheckEnable: true,
  scanDepth: 3,
  plugTimeout: 30,
  socketTimeout: 5,
  opensshRemoteEnable: false,
  ntpRemoteEnable: false,
})
//保存按钮的转圈效果
const isLoading = ref(false);
const refAddPopUp = ref(null);
const detailConfigData = ref({
  weakPassConfigList: [],
  guessFrequency: null,
  guessNum: null,
  guessTime: null,
  maxThread: null,
});
//执行方式的时间选择
const timeObj = ref({
  type: '',
  startTime: '',
  executeTime: '',
  typeParam: '',
});

//目标地址上传按钮
const handleImport = (file) => {
  let fd = new FormData();
  fd.append('file', file.raw);
  targetAnalysis(fd).then((res) => {
    const { code, data } = res || {};
    code == 200&& (formData.value.targetList=data || '');
  });
};
//目标地址删除按钮
const handleDelete = () => {
  formData.value.targetList = ' ';
};
//目标地址的导入的模板下载
const handleDownloadTemplate=()=>{
  getDownloadFile('/template/loginCheckTemplate.xlsx');
}
//保存按钮的事件
const handlerToSubmit = (data) => {
  isLoading.value = true;
  //接口需要
  let demo = {
    hazardPlugScanEnable: false,
    scanHintEnable: false,
    oracleVulDeepScanEnable: false,
    targetEncoding: 'gbkZhCn',
  };
  let params = {
    params: { ...detailConfigData.value, ...data, ...demo },
    ...timeObj.value,
    ...data,
  };
  let query = route.query?.taskId ? modifyHostVulTask : createHostVulTask;
  route.query?.taskId && (params.id = route.query?.taskId);
  query(params)
    .then((res) => {
      const { code, message } = res || {};
      if (code == 200) {
        yaMessage(message, 'success');
        debugger
        router.push('/taskManagement/taskList');
      }
    })
    .finally(() => {
      isLoading.value = false;
    });
};

//跳转页面 --path为detailConfig跳转到详情页，path为sshLogin且params存在，则到ssh页面进行编辑，params不存在进入ssh登录页面进行新增
const handlerToOtherPage = (path, params?) => {
  console.log('/riskDetect/riskIdentify/addTask/' + path);
  debugger
  let obj = {
    ...editForm.value?.formData,
    ...detailConfigData.value,
    ...timeObj.value,
  };
  sessionStorage.setItem('YA-HOSTSCANDATA', JSON.stringify(obj));
  router.push({
    path: '/riskDetect/riskIdentify/addTask/' + path,
    query: params,
  });
};

//登陆检查的导出的事件
const handleToExport = () => {
  const i = handleGetIndex(
    formColumns.value,
    'key',
    'loginCheckConfigConfigList'
  );
  sshLoginFileExport(formColumns.value[i].value).then((res) => {
    downLoadFile(res, '登录检查IP信息导出');
  });
};

//ssh的删除
const handlerToDel = (index) => {
  yaConfirmMessage(`删除该数据后无法恢复, 是否继续删除？`, `删除`)
    .then(() => {
      const i = handleGetIndex(
        formColumns.value,
        'key',
        'loginCheckConfigConfigList'
      );
      formColumns.value[i].value?.find((item) => {
        if (item.id == index) {
          formColumns.value[i].value.splice(index, 1);
        }
      });
    })
    .catch(() => {
      yaMessage('操作已取消', 'info');
    });
};

/**
 * 登录检查table点击事件
 */
const handleTableBtnClick = (btn, row) => {
  let { eventName } = btn || {};
  if (eventName == 'editEvent') {
    handlerToOtherPage('sshLogin', { id: row.id });
  }
  if (eventName == 'deleteEvent') {
    handlerToDel(row.id);
  }
};
// 登陆配置--start
//导入抽屉
const uploadProps = reactive({
  title: '导入',
  showDrawer: false,
});
//导入的校验
const handleChangeUpload = (uploadFile, resolve) => {
  let fd = new FormData();
  fd.append('file', uploadFile.raw);
  resolve({
    importStatus: true, // importStatus: Boolean; true: 导入成功, 为true时failInfoList为空; false: 导入失败;
    message: '成功', // 文件校验是否通过 param --> message: 提示信息
    failInfoList: [],
  });
};
//导入抽屉的确定按钮事件
const uploadSubmit = (file) => {
  let fd = new FormData();
  fd.append('file', file.raw);
  console.log('重新刷新列表数据');
};

//登陆配置--end
/**
 * @description: 获取组件传参
 */
const getModelValue = (e) => {
  if (timeObj.value.type == 'custom_point') {
    timeObj.value.startTime = e.time;
  } else {
    timeObj.value.executeTime = e.time;
  }
  if (e.allWeek) {
    timeObj.value.typeParam = e.allWeek + ',' + e.weekDay;
  } else {
    timeObj.value.typeParam = e.weekDay;
  }
};

onMounted(() => {
  formColumns.value = hostScanColumn;
  const i = handleGetIndex(formColumns.value, 'key', 'type');
  formColumns.value[i].onChange = (data) => {
    timeObj.value.type = data;
    refAddPopUp.value?.resetDateObj();
  };
  //从详情配置和登录检查的添加进入
  if (sessionStorage.getItem('YA-HOSTSCANDATA')) {
    const hostScanData = JSON.parse(sessionStorage.getItem('YA-HOSTSCANDATA'));
    hostScanData.loginCheckConfigConfigList?.forEach((item, index) => {
      item.id = index;
      item.hidePwd = '***';
    });
    for (let key in timeObj.value) {
      timeObj.value[key] = hostScanData[key];
    }
    for (let key in hostScanData) {
      formColumns.value.find((item) => {
        if (item.key == key) {
          item.value = hostScanData[key];
        }
      });
      for (let child in detailConfigData.value) {
        child == key && (detailConfigData.value[key] = hostScanData[key]);
      }
    }
  
  }
  // 获取字典项
  // getDict(formColumns.value);
  //从编辑入口进入
  if (
    route.query.title == '编辑' &&
    !sessionStorage.getItem('YA-HOSTSCANDATA')
  ) {
    getModifyVo({ taskId: route.query?.taskId }).then((res) => {
      const { code, data = {} } = res || {};
      if (code == 200 && data) {
        data.params.loginCheckConfigConfigList?.forEach((item, index) => {
          item.id = index;
          item.hidePwd = '***';
        });
        for (let key in timeObj.value) {
          timeObj.value[key] = data[key];
        }
        for (let key in data) {
          formColumns.value.find((item) => {
            item.key == key && (item.value = data[key]);
          });
        }
        for (let key in data.params) {
          formColumns.value.find((item) => {
            if(key=='scanDepth'||key=='plugTimeout'||key=='socketTimeout'){
              data.params[key]=data.params[key]+''
            }
            item.key == key && (item.value = data.params[key]);
           
          });
          for (let child in detailConfigData.value) {
            child == key && (detailConfigData.value[key] = data.params[key]);
          }
        }
      }
    });
  }

  sessionStorage.removeItem('YA-HOSTSCANDATA');
});
</script>
<style lang="scss" scoped>
.yaBox {
  ::v-deep .ya-form-title {
    width: calc(100% + 75px);
    font-weight: 500;
    color: rgba(0, 0, 0, 0.8);
    position: relative;
    padding-left: 8px;
    padding-bottom: 16px;
    padding-top: 0px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.12);
    &::before {
      content: '';
      display: block;
      width: 3px;
      height: 14px;
      background: var(--el-color-primary);
      position: absolute;
      left: 0;
      top: -1px;
    }
  }

  ::v-deep .add-form {
    max-width: calc((100% - 56px) / 2);
    .el-input {
      width: 100%;
    }
  }
  ::v-deep .yaInputUp {
    max-width: calc((100% - 196px) / 2);
  }
  .ya-config {
    color: #0095ff;
    text-decoration: underline;
    cursor: pointer;
    margin-left: 16px;
  }
  .ya-buttons {
    width: 100%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
  }
  ::v-deep .ya-table-content {
    width: 100%;
  }
}
</style>
