<script lang="ts" setup>
import { ref, reactive, onMounted, watch, nextTick, unref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue'
import { getDictTypeList, getDeptList } from '../../../api/common'
import { 
  targetList,
  executeMode,
  weekList,
  rocordTableData,
  rocordTableColumn,
  collectionTableColumn,
  portList
} from '../components/config.ts'
const init = (title, e) => {
  switch (title) {
    case '新增':
      addData()
      break;
    case '编辑':
      edit(e)
      break;
    case '删除':
      deletedata(e)
      break;
    case '执行记录':
      rocordBtn(e, title)
      break;
    case '采集对象':
      rocordBtn(e, title)
      break;
    case '目标地址':
      rocordBtn(e, title)
      break;
  }
}
const emit = defineEmits(['onInit','getNetwork']);
const props = defineProps({
  obj:Object
})
console.log(props.obj, 'objobjobj')
defineExpose({ init })
// 新增
const addData = () => {
  drawerFormDisabled.value = false;
  drawerProps.title = "新增";
  drawerProps.showDrawer = true;
  drawerProps.size = 'small';
  formData.name =  "";
  formData.type = 'manual';
  formData.target = 'all';
  formData.port = '';
  formData.portList = '';
  formData.targetList = '';
  formData.networkAreaIds = []; // 网络域id
  formData.startTime = '';  // 执行时间
  formData.typeParam = ''; 
  formData.rate = null;  // 发包率
}
const isClear = ref(false)
// 编辑
const edit = (row) => {
  isClear.value = true
  let title = props.obj.type;
  drawerProps.title = "编辑";
  drawerProps.size = 'small'
  formData.id =  row.id;
  formData.name =  row.name;
  formData.type = row.type;
  formData.target = row.target;
  formData.port = row.port;
  formData.portList = row.portList;
  if (row.target == 'custom') {
    if (row.networkArea) {
      formData.networkAreaIds = row.networkArea.split(',').map((item)=>{
        return Number(item)
      }); // 网络域id
    }
    formData.targetList = row.targetList;
  } else if (row.target == 'dept') {
    if (row.targetList) {
      targetListOne.value = row.targetList.split(',').map((item) => {
        return Number(item)
      })
    }
  }
  if (row.type == 'weekly') {
    if(row.typeParam) {
      typeParam.value = row.typeParam.split(',').map((item)=>{
        return Number(item)
      }); 
    }
  } else {
    formData.typeParam = row.typeParam
  }
  console.log(typeParam.value)
  formData.startTime = row.startTime;  // 执行时间

  if (title == '探测任务') {
    formData.rate = row.rate;  // 发包率
  }
  nextTick(() => {
    drawerProps.showDrawer = true;
  })
}
// 删除
const deletedata = (row) => {
  ElMessageBox.confirm("此操作不可逆，是否要确认删除？", "提示", {
    customClass: "message-warning",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then(() => {
    let idValue = {
      id:row.id
    };
    let { delSercer } = props.obj;

    delSercer(idValue).then((res) => {
      if (res.code == 200) {
        emit('onInit')
        ElMessage.success("删除成功");
      }
    });
  });
};
// 执行记录
const rocordBtn = (row,e) => {
  drawerFormDisabled.value = true;
  let title = '';
  if(e == '执行记录') {
    drawerProps.size = 'big'
    if (props.obj.type == '拨测计划') {
      title = "执行记录:拨测任务";
    } else if (props.obj.type == '采集计划') {
      title =  "执行记录:采集任务";
    } else if (props.obj.type == '资产清单') {
      title =  "执行记录:资产清单";
    } else {
      title =  "执行记录:探测任务";
    }
  } else {
    if (props.obj.type == '拨测计划') {
      title = "拨测目标地址";
      collectionTableColumn.value[1].label = '拨测目标地址'
    } else if (props.obj.type == '采集计划') {
      title = "采集对象";
      collectionTableColumn.value[1].label = '采集对象'
    } else {
      title = "IP信息";
      collectionTableColumn.value[1].label = 'IP'
    }
    drawerProps.size = 'small'
  } 
  drawerProps.title = title
  taskId.value = e.id;
  getAdress()
}
const collectionTableData = ref([])
const recordSearch = ref('')
const taskId = ref('')
// 获取地址详情
const getAdress = async () => {
  drawerProps.showDrawer = true;
  return
  let { detailTargetServe } = props.obj;
  let parms = {
    taskId:taskId.value,
    pageIndex:page.value,
    pageSize:size.value,
    ip:recordSearch.value
  }
  let res = await detailTargetServe(parms)
  if (res.code == 200) {
    collectionTableData.value = res.data.rows.map((item,index) => {
      return {
        index: index +1,
        time: item
      }
    })
    total.value = res.data.total
    drawerProps.showDrawer = true;
  }
}
 // 分页参数
const page = ref(1);
const total = ref(0);
const size = ref(10);
  
/**
 * @description: 页面容量切换
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const sizeChange = function (val: number) {
  size.value = val;
  page.value = 1;
  getAdress();
};

/**
 * @description: 分页切换
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const currentChange = function (val: number) {
  page.value = val;
  getTableData('page');
};
const formData = reactive({
  name: "",
  type: 'manual',
  target: 'all',
  port:'',
  portList: '',
  targetList:'',
  networkAreaIds:[], // 网络域id
  startTime:'',  // 执行时间
  typeParam:'', 
  rate:''  // 发包率
});
watch(
  () => formData.target,
  (val) => {
    if (val == 'all') {
      formColumns.value[2].show = false
    } else {
      formColumns.value[2].show = true
    }
    if (isClear.value) return setTimeout(()=>{
      isClear.value = false
    },50)
    targetListOne.value = []
    formData.targetList = ''
  }
)
watch(
  () => formData.port,
  () => {
    if (isClear.value) return setTimeout(()=>{
      isClear.value = false
    },50)
    formData.portList = ''
  }
)
watch(
  () => formData.type,
  (val) => {
    if (val == 'manual') {
      formColumns.value[5].show = false
    } else {
      formColumns.value[5].show = true
    }
    if (isClear.value) return setTimeout(()=>{
      isClear.value = false
    },50)
    typeParam.value = [];
    formData.startTime = ''
    formData.typeParam = ''
  }
)
onMounted(() => {
  let type = props.obj.type;
  if (type == '拨测计划') {
    formColumns.value[0].label = '任务名称'
    formColumns.value[0].placeholder = "请输入任务名称";
    formColumns.value[1].label = '拨测目标地址';
    formColumns.value.push({
      key: "comment",
      type: "textarea",
      label: "任务描述",
      col: 24,
      placeholder: "请输入任务描述",
      clearable: true,
      rows: 4,
      showWordLimit: true,
      maxlength: "200",
    })
  } else if (type == '探测任务') {
    formColumns.value[0].label = '任务名称'
    formColumns.value[0].placeholder = "请输入任务名称";
    formColumns.value[1].label = '目标地址';
    formColumns.value.forEach((item) =>{
      if (item.slotName == 'point') {
        item.show = true
      }
    })
    formColumns.value.push({
      key: "rate",
      type: "input",
      label: "发包速率",
      col: 24,
      placeholder: "请输入发包速率",
      disabled: false,
      clearable: true,
    })
  }
  getNetwork()
  getdDept()
})
const formColumns = ref([
  {
    key: "name",
    type: "input",
    label: "计划名称",
    col: 24,
    placeholder: "请输入计划名称",
    disabled: false,
    clearable: true,
  },
  {
    key: "target",
    type: "select",
    label: "采集对象",
    col: 24,
    placeholder: "请选择",
    options: targetList,
    clearable: false,
  },
  {
    show:false,
    col: 24,
    slotName: "dep"
  },
  {
    show:false,
    col: 24,
    slotName: "point"
  },
  {
    key: "type",
    type: "select",
    label: "执行方式",
    col: 24,
    placeholder: "请选择",
    options: executeMode,
    clearable: false,
  },
  {
    show:false,
    col: 24,
    slotName: "mode"
  }
]);
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入", trigger: "change" }],
  target: [{ required: true, message: "请选择采集对象", trigger: "change" }],
  type: [{ required: true, message: "请选择采集对象", trigger: "change" }],
});
const dialogForm = ref({});
const drawerProps = reactive({
  showDrawer: false,
  title: "新增",
  size: "small",
});
const drawerFormDisabled = ref(false);
const handleDrawerEvent = (data) => {
  const { eventName = "" } = data;
    // 抽屉点击确定按钮
    console.log(eventName);
    if (eventName === "success") {
        handleConfirm();
    }
};
const handleConfirm = () => {
  dialogForm.value.submitForm(dialogForm.value.ruleFormRef);
};
const handleCloseDrawer = async (done) => {
  done();
};
const handleEvent = (data) => {
  if (data.eventName == "errorSubmit") {
    return;
  }
  if (data.eventName === "successSubmit") {
    handleFormSuccess();
    return;
  }
};
const typeParam = ref([])
const targetListOne = ref([])
const handleFormSuccess = async () => {
  let type = props.obj.type;
  let requir = "";
  let { addServer, upDateServe } = props.obj;
  if (type == '探测任务' || type=='采集计划') {
    if (drawerProps.title == "新增") {
      if (formData.id) {
        delete formData.id;
      }
      requir = addServer
    } else {
      requir = upDateServe
    }
  }
  if (formData.target == 'dept') {
    formData.targetList = targetListOne.value.toString()
  }
  if (formData.type == 'weekly') {
    formData.typeParam = typeParam.value.toString()
  } 
  if (type == '探测任务') {
    if (formData.rate) {
      formData.rate = Number(formData.rate)
    }
  } else if (type == '采集计划') {}
  let parms = {
    ...formData,
  };
  let res = await requir(parms);
  if (res.code == 200) {
    if (drawerProps.title == "新增") {
      ElMessage.success("新增成功");
    } else {
      ElMessage.success("编辑成功");
    }
    drawerProps.showDrawer = false;
    emit('onInit')
  }
};
const internetList = ref([])
const getNetwork = async() => {
  let res = await getDictTypeList({dictType:'networkArea'})
  if (res) {
    internetList.value = res.map((item) => {
      return {
        value:item.id,
        label:item.dictName
      }
    })
    emit('getNetwork', internetList.value)
  }
}
const deptList = ref([])
const getdDept = async() => {
  let res = await getDeptList();
  if (res.code == 200) {
    deptList.value = res.data
  }
  console.log(res)
}
</script>
<template>
   <!-- 新增/编辑 -->
   <ya-drawer
    :drawerProps="drawerProps"
    :showConfirm="!drawerFormDisabled"
    @handleEvent="handleDrawerEvent"
    destroy-on-close
    :before-close="handleCloseDrawer"
  >
    <template #content>
      <ya-form
        v-if="drawerProps.size == 'small'"
        label-position="top"
        @handleEvent="handleEvent"
        :formColumns="formColumns"
        labelWidth="100px"
        :formData="formData"
        :rules="rules"
        :ref="
          (el) => {
            if (el) dialogForm = el;
          }
        "
      >
        <template #dep="item">
          <div v-if="item.data.show" class="select-form">
            <el-select multiple v-model="targetListOne" placeholder="请选择部门" v-if="formData.target == 'dept'">
              <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.deptName"
                :value="item.id"
              />
            </el-select>
            <el-input v-if="formData.target == 'custom'" v-model="formData.targetList" :rows="4" type="textarea" show-word-limit maxlength="200" placeholder="请输入内容"></el-input>
            <div v-if="formData.target == 'custom' && props.obj.type == '探测任务'">
              <div class="slect-label margin-top-10">网络域</div>
              <el-select multiple v-model="formData.networkAreaIds" placeholder="请选择">
                <el-option
                  v-for="item in internetList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
          </div>
        </template>  
        <template #point="item">
          <div v-if="item.data.show" class="select-form">
            <div class="slect-label">目标端口</div>
            <el-select placeholder="请选择目标端口" v-model="formData.port">
              <el-option
                v-for="item in portList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <div class="select-form" v-if="formData.port == 'top'">
                <div class="slect-label">TCP</div>
                <div>
                  <el-input v-model="formData.portList" placeholder="请输入TCP"></el-input>
                </div>
              </div>
              <el-input class="custom" v-model="formData.portList" v-if="formData.port == 'custom'" :rows="4" type="textarea" show-word-limit maxlength="20000" placeholder="请输入内容"></el-input>
            </div>
        </template>
       
        <template #mode="item">
          <div v-if="item.data.show" class="select-form">
              <div class="weekList" v-if="formData.type == 'weekly'">
                <el-checkbox-group v-model="typeParam">
                  <el-checkbox v-for="item in weekList" :label="item.value">
                    {{item.label}}
                  </el-checkbox>
                </el-checkbox-group>
              </div>
              <div v-if="formData.type == 'monthly'">
                <el-date-picker
                  v-model="formData.typeParam"
                  type="date"
                  placeholder="请选择日期"
                />
              </div>
              <div v-if="formData.type == 'custom'">
                <el-input placeholder="请手动输入周期（范围1-90天）" v-model="formData.typeParam">
                  <template #prefix>
                    <div class="select-item">每</div>
                  </template>
                  <template #suffix>
                    <div class="select-item">天</div>
                  </template>
                </el-input>
              </div>
              <div v-if="props.obj.type != '探测任务'">
                <div class="slect-label">次数</div>
                <div>
                  <el-input placeholder="请输入次数"></el-input>
                </div>
              </div>
              <div v-if="props.obj.type != '探测任务'">
                <div class="slect-label">执行时间</div>
                <el-date-picker v-model="formData.startTime"
                  type="datetime"
                  placeholder="请选择执行时间"
                  format="YYYY/MM/DD hh:mm:ss"
                  value-format="YYYY-MM-DDThh:mm:ss"
                />
              </div>
          </div>
        </template>  
      </ya-form>
    </template>
  </ya-drawer>
</template>
<style scoped lang="scss">
  @import '../../../style/popUp.scss';
  .record-table {
    ::v-deep .ya-layout-content-table {
      padding: 0;
    }
  }
  .weekList {
    border-radius: 2px;
    border: 1px solid rgba(0,0,0,0.2);
    padding: 8px;
  }
  .custom {
    margin-top: 8px;
  }
  .margin-top-10 {
    margin-top: 10px;
  }
</style>