<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  watch,
  nextTick,
  unref,
  watchEffect,
} from 'vue';
import { getDictTypeList, getDeptList, getPageList } from '../../../api/common';
import { getLeftTreeJson } from '../../../api/permission/userManagement';
import { ElTable } from 'element-plus';
import { getCustomIp } from '../../../api/collection/infoCollection/collectionPlan';
interface props {
  type?: Number | string; // targetType 目标地址 port 目标端口
  isShow?: Number | string; // dept 部门 custom 自定义 3 常见端口 immediately 立即执行 custom_point 定时执行 daily 每天一次 weekly 每周一次 monthly_day 每月一次（按日期）monthly_week 每月一次（按星期）
  disabled?: boolean; // 是否可编辑
  dataValue?: Object; // 编辑对象
  showType?: Number | string; // 1 自定义输入框 2 自定义表格
  // value?: any[] | number | string | boolean, // 绑定值
}

const {
  isShow = 0,
  disabled = false,
  dataValue = {},
  showType = 1,
} = defineProps<props>();
const emit = defineEmits(['modelValue', 'dateValue']);
const value = ref([]);
const portValue = ref(1);
const dateObj = reactive({
  weekDay: '',
  time: '',
  month: '',
  allWeek: '',
  type: '',
  targetList: '',
});
const deptList = ref([]);
const resetDateObj = () => {
  dateObj.time = '';
  dateObj.weekDay = '';
  dateObj.month = '';
  dateObj.allWeek = '';
  dateObj.type = '';
};
const resetDateObj1 = () => {
  dateObj.targetList = '';
  scanAsset.value = [];
};
defineExpose({
  resetDateObj,
  resetDateObj1,
});
/**
 * @description: 日期数据
 */
const weekList = ref([
  {
    value: '2',
    label: '星期一',
  },
  {
    value: '3',
    label: '星期二',
  },
  {
    value: '4',
    label: '星期三',
  },
  {
    value: '5',
    label: '星期四',
  },
  {
    value: '6',
    label: '星期五',
  },
  {
    value: '7',
    label: '星期六',
  },
  {
    value: '1',
    label: '星期日',
  },
]);
/**
 * @description: 获取当前月份的天数
 */
const getCountDays = () => {
  var curDate = new Date();
  var curMonth = curDate.getMonth();
  curDate.setMonth(curMonth + 1);
  curDate.setDate(0);
  /* 返回当月的天数 */
  return curDate.getDate();
};
/**
 * @description: 获取当前月份的星期数
 */
const getWeekDays = () => {
  let d = new Date();
  let year = d.getFullYear();
  let month = d.getMonth() + 1;
  let time = year + `/` + month + `/` + `01`;
  let startDate = new Date(time);
  let day =
    parseInt(startDate.getDay()) == 0 ? 7 : parseInt(startDate.getDay());
  // 判断当月有几周
  let days = new Date(year, month, 0).getDate();
  let y = days % 7;
  if (7 - day >= y) {
    var zhou = parseInt(days / 7) + 1;
  } else {
    var zhou = parseInt(days / 7) + 2;
  }
  let endDate = new Date(year + `/` + month + `/` + days).getDay();
  if (endDate == 0) {
    zhou = zhou - 1;
  }
  return zhou;
};
const monthList = ref([]);
for (var i = 1; i < getCountDays() + 1; i++) {
  monthList.value.push({
    value: i.toString(),
    label: i + '日',
  });
}
const allWeekList = ref([]);
for (var i = 1; i < getWeekDays() + 1; i++) {
  allWeekList.value.push({
    value: i.toString(),
    label: i,
  });
}
const scanAsset = ref([]); // 目标地址参数 自定义资产列表
const target = ref(''); // 搜索条件
watch(target, () => {
  multipleTableRef.value.initData();
});
const choseDept = ref();
watch(
  dataValue,
  (newVal) => {
    if (newVal) {
      if (newVal.type == 'custom_point') {
        dateObj.time = newVal.startTime;
      } else {
        dateObj.time = newVal.executeTime;
      }
      if (newVal.targetType == 'custom' && showType == 2) {
        getCustomIp({ id: newVal.id }).then((res) => {
          scanAsset.value = [];
          if (res.code == 200) {
            if (res.data) {
              res.data.forEach((item) => {
                item.showIp = item.ipv4;
                scanAsset.value.push(item);
              });
            }
          }
        });
      } else if (newVal.targetType == 'dept') {
        choseDept.value = Number(newVal.targetList);
      } else {
        dateObj.targetList = newVal.targetList;
      }
      if (newVal.type == 'monthly_week') {
        let str = newVal.typeParam.split(',');
        dateObj.allWeek = str[0];
        dateObj.weekDay = str[1];
      } else if (newVal.type == 'monthly_multiple' || newVal.type == 'weekly_multiple') {
        let str = newVal.typeParam.split(',');
        dateObj.weekDay = str;
        // dateObj.time = str[1];
      } else {
        dateObj.weekDay = newVal.typeParam;
      }
    }
  },
  { immediate: true }
);
watchEffect(() => {
  emit('modelValue', unref(value) | unref(portValue));
  emit('dateValue', dateObj);
});
/**
 * @description: 页面渲染结束后执行
 */
onMounted(() => {
  getDept();
});

/**
 * @description: 获取资产清单
 */
const getPage = (type) => {
  let _data = JSON.parse(JSON.stringify(type))._value;
  tableDataList.value = [];
  getPageList({
    target: target.value,
    ..._data,
  }).then((res) => {
    console.log(res);
    if (res.code == 200) {
      tableDataList.value = res.data.records;
      total.value = res.data.total;
      setTableCheck();
    }
  });
};
// 分页参数
const page = ref(1);
const total = ref(0);
const size = ref(20);
const tableDataList = ref([]);
const tableColumn = ref([
  {
    type: 'selection',
    width: '65px',
    'reserve-selection': true,
  },
  {
    prop: 'showIp',
    label: 'IP',
    minWidth: '180px',
  },
  {
    prop: 'domain',
    label: '域名',
    minWidth: '180px',
  },
  {
    prop: 'urlLink',
    label: 'URL',
    minWidth: '180px',
  },
  {
    prop: 'networkAreaName',
    label: '网络域',
    minWidth: '180px',
  },
]);
const lastSelectedRow = ref([]);
const selectedRow = ref([]); // 选中行
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
/**
 * @description 漏洞新建任务-自定义-已选 ip tag 删除，同时需要将表格中的选中状态取消
 * @param index 当前删除索引
 * @param row 当前删除行数据 需要在表格中删除
 */
const deleteIpTag = (index, row) => {
  const { code } = row;
  tableDataList.value.forEach((item) => {
    if (item.code == code) {
      multipleTableRef.value.getTableMethods().toggleRowSelection(item, false);
    }
  });
  const findIndex = scanAsset.value.findIndex((item) => item.code === code);
  if (findIndex > -1) {
    scanAsset.value.splice(findIndex, 1);
  }
};
/**
 * @description: 表格选中事件
 * @param row 当前行
 * @author changjun
 */
const handleSelectionChange = (row) => {
  console.log('选择的行', row);
  selectedRow.value = row;
  scanAsset.value = row;
  console.log(lastSelectedRow.value);
};
watch(scanAsset, () => {
  dateObj.targetList = scanAsset.value
    .map((item) => {
      return item.code;
    })
    .toString();
});
const setTableCheck = () => {
  lastSelectedRow.value = JSON.parse(JSON.stringify(scanAsset.value));
  scanAsset.value.forEach((item) => {
    const { code } = item;
    const findItem = tableDataList.value.filter(
      (tableItem) => tableItem.code === code
    );
    if (findItem.length > 0) {
      const checkedIndex = selectedRow.value.findIndex(
        (selectedItem) => selectedItem.code === code
      );
      if (checkedIndex === -1) {
        nextTick(() => {
          multipleTableRef.value
            .getTableMethods()
            .toggleRowSelection(findItem[0], true);
        });
      }
    }
  });
};
const getRowKeys = (row) => {
  return row.code;
};
watch(choseDept, () => {
  dateObj.targetList = choseDept.value.toString();
});
/**
 * @description: 获取部门
 */
const getDept = () => {
  // 部门
  getLeftTreeJson().then((res) => {
    const { code, data } = res || {};
    if (code === 200) {
      deptList.value = data.treeData || [];
    }
  });
};
</script>
<template>
  <div class="add-form">
    <div v-if="type == 'targetType'">
      <el-cascader
        v-if="isShow == 'dept'"
        style="width: 100%"
        ref="cascader"
        placeholder="请选择部门"
        :props="{
          checkStrictly: true,
          value: 'id',
          emitPath: false,
        }"
        :disabled="disabled"
        v-model="choseDept"
        :options="deptList"
        :show-all-levels="false"
      >
      </el-cascader>
      <el-input
        v-if="isShow == 'custom' && showType == 1"
        v-model="dateObj.targetList"
        :rows="4"
        :disabled="disabled"
        type="textarea"
        show-word-limit
        maxlength="20000"
        :placeholder="'输入IP标准格式提示为：单个IP：192.168.1.0，198.168.1.1，FF01:0:0:0:0:0:0:1101, FF01::1101\nIP段：192.168.1.0-192.168.1.255\nIP/掩码：192.168.1.1/24'"
      ></el-input>
      <div v-if="isShow == 'custom' && showType == 2">
        <el-input
          v-model="target"
          v-if="!dataValue.id"
          placeholder="请输入IP"
          clearable
        ></el-input>
        <YaPageContent
          v-show="target"
          ref="multipleTableRef"
          layout="prev, pager, next"
          @selection-change="handleSelectionChange"
          @init="getPage"
          :row-key="getRowKeys"
          :tableData="tableDataList"
          :tableColumns="tableColumn"
          :total="total"
        ></YaPageContent>
        <div class="custom-label" v-if="target || dataValue.id">已选择</div>
        <div
          class="custom-content"
          :class="dataValue.id ? 'custom-content-disabled' : ''"
          v-if="target || dataValue.id"
        >
          <el-tag
            type="info"
            v-for="(asset, index) in scanAsset"
            :key="asset.code"
            class="custom-tag"
            :closable="dataValue.id ? false : true"
            @close="deleteIpTag(index, asset)"
            >{{ asset.showIp }}</el-tag
          >
        </div>
      </div>
    </div>
    <div v-if="type == 'port'">
      <el-radio-group v-model="portValue" v-if="isShow == 'top'">
        <el-radio :label="1">0-1023</el-radio>
        <el-radio :label="2">1024-49151</el-radio>
        <el-radio :label="3">49152-65535</el-radio>
      </el-radio-group>
      <el-input
        v-if="isShow == 'custom'"
        v-model="dateObj.time"
        :disabled="disabled"
        :rows="4"
        type="textarea"
        show-word-limit
        maxlength="20000"
        placeholder="请输入内容"
      ></el-input>
    </div>
    <div v-if="isShow == 'custom_point'">
      <el-date-picker
        v-model="dateObj.time"
        type="datetime"
        placeholder="请选择"
        value-format="YYYY-MM-DD HH:mm:ss"
      />
    </div>
    <div v-if="isShow == 'daily'">
      <el-time-picker
        style="width: 100%"
        v-model="dateObj.time"
        format="HH:mm"
        value-format="HH:mm"
        placeholder="请选择"
      />
    </div>
    <div v-if="isShow == 'weekly'" class="flex-st">
      <div class="flex-one">
        <el-select placeholder="请选择" v-model="dateObj.weekDay">
          <el-option
            v-for="item in weekList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="margin-left5">
        <el-time-picker
          style="width: 100%"
          v-model="dateObj.time"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="请选择"
        />
      </div>
    </div>
    <div v-if="isShow == 'monthly_day'" class="flex-st">
      <div class="flex-one">
        <el-select placeholder="请选择" v-model="dateObj.weekDay">
          <el-option
            v-for="item in monthList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="margin-left5">
        <el-time-picker
          v-model="dateObj.time"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="请选择"
        />
      </div>
    </div>
    <div v-if="isShow == 'monthly_week'" class="flex-st">
      <div class="flex-st">
        <span class="color-span">第</span>
        <el-select
          class="margin-left5"
          style="min-width: 100px"
          placeholder="请选择"
          v-model="dateObj.allWeek"
        >
          <el-option
            v-for="item in allWeekList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <span class="margin-left5 color-span">个</span>
      </div>
      <div class="margin-left5">
        <el-select placeholder="请选择" v-model="dateObj.weekDay">
          <el-option
            v-for="item in weekList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="margin-left5">
        <el-time-picker
          style="width: 100%"
          v-model="dateObj.time"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="请选择"
        />
      </div>
    </div>
    <!-- 每周多次 -->
    <div v-if="isShow == 'weekly_multiple'" class="flex-st">
      <div>
        <el-select placeholder="请选择" multiple collapse-tags  v-model="dateObj.weekDay">
          <el-option
            v-for="item in weekList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="margin-left5 flex-one">
        <el-time-picker
          v-model="dateObj.time"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="请选择"
        />
      </div>
    </div>
    <!-- 每月多次 -->
    <div v-if="isShow == 'monthly_multiple'" class="flex-st">
      <div>
        <el-select
          placeholder="请选择"
          multiple
          collapse-tags
          v-model="dateObj.weekDay"
        >
          <el-option
            v-for="item in monthList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div class="margin-left5 flex-one">
        <el-time-picker
          v-model="dateObj.time"
          format="HH:mm"
          value-format="HH:mm"
          placeholder="请选择"
        />
      </div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.add-form {
  width: 100%;
  // margin-top: 10px;
}
.flex-st {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.flex-one {
  flex: 1;
}
.width40 {
  margin-left: 20px;
}
.margin-left5 {
  margin-left: 5px;
}
.color-span {
  color: rgba(0, 0, 0, 0.65);
}
.ya-tableList {
  margin-top: 10px;
}
.custom-label {
  font-size: var(--el-form-label-font-size);
  color: var(--el-text-color-primary);
}
.custom-content {
  height: 91px;
  background: #ffffff;
  border-radius: 2px;
  border: 1px solid #e4e4e4;
  padding: 10px;
  padding-bottom: 0;
  padding-right: 0;
  overflow-y: auto;
  .custom-tag {
    margin-right: 10px;
    border: 1px solid rgba(0, 0, 0, 0.16);
    background: #fff;
    border-radius: 2px;
    margin-bottom: 10px;
  }
}
.custom-content-disabled {
  background: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.12);
  cursor: not-allowed;
  .custom-tag {
    background: rgba(0, 0, 0, 0.05);
    color: rgba(0, 0, 0, 0.6);
  }
}
::v-deep .ya-layout-content-table {
  padding: 0 !important;
}
</style>
