<!--
* @Description: 异常特征样本
* @Author: tqh
* @Date: 2022-08-31 17:00
-->

<script lang="ts" setup>
import {
  ref,
  reactive,
  onMounted,
  watch,
  nextTick,
  getCurrentInstance,
} from 'vue';
import { openSocket, registerSockets } from '@/utils/socket/useSocket';
import { ElMessage, ElMessageBox, ElTable } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { downLoadFile, deepCopy } from '../../../utils/utils';
import { usePermissions } from '../../../composables/usePermissions';
import {
  getList,
  delAll,
  add,
  delOne,
  update,
  queryTargetDetail,
  execute,
  executeByIds,
  pauseDetect,
  cancelDetect,
} from '../../../api/collection/infoCollection/collectionPlan';
import { getDownloadFile,postDownloadFile } from '../../../api/common';
import {
  getDictTypeList,
  getDeptList,
  getRecordAssetsList,
} from '../../../api/common';
import {
  collectionTableColumn,
  taskRocordTableColumn,
} from "../components/config.ts";
import RecordDialog from '../components/recordDialog.vue';
import AddPopUp from '../components/addPopUp.vue';
import { yaConfirmMessage } from 'yuan-plus';
import stop from '@/assets/image/collection/stop.png';
import loading from '@/assets/image/collection/loading.gif';
import end from '@/assets/image/collection/end.png';
import cancel from '@/assets/image/collection/cancel.png';

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
// 清空选择的值
const clearSelect = () => {
  multipleTableRef.value.getTableMethods().clearSelection();
};
const { proxy } = getCurrentInstance();
/**
 * @description: 列表socket
 */
const sockets = {
  message(res) {
    if (res.type == 'ws_gather') {
      const { data, code } = res.data;
      if (code == 200) {
        tableData.value = data.records;
        total.value = data.total;
      }
    }
  },
};
const { permissionsButtons } = usePermissions();
const bottomData = new Map();
const rightButtons = ref([]);

onMounted(() => {
  // registerSockets(sockets, proxy);
  init();
});
/**
 * 按钮权限
 */
const buttons = ref([]) as any;
const btnPower = () => {
  permissionsButtons.map((item) => {
    bottomData.set(item.menuId, item);
  });
  if (bottomData.has(400221)) {
    buttons.value.push({
      eventName: 'add',
    });
  }
  if (bottomData.has(400223)) {
    buttons.value.push({
      eventName: 'delete',
    });
  }
};
// 分页参数
const total = ref(0);
/**
 * @description: 初始化方法
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const init = () => {
  btnPower();
  getDictList();
};
// 表格数据
const tableData = ref([]) as any;
const tableColumn: any[] = reactive([
  {
    type: 'selection',
    width: '65px',
    fixed: 'left',
    reserveSelection: true,
  },
  {
    prop: 'name',
    label: '计划名称',
    type: 'input',
    search: true,
    minWidth: '180px',
    drawer: true,
    rules: true,
  },
  {
    label: '采集范围',
    slotName: 'colection',
    minWidth: '180px',
  },
  {
    prop: 'targetType',
    label: '采集范围',
    type: 'select',
    drawerSlotName: 'targetType',
    tableHide: true,
    drawer: true,
    rules: true,
    onChange(e) {
      formData.value.targetType = e;
    },
  },
  {
    prop: 'typeName',
    label: '执行方式',
    minWidth: '180px',
  },
  {
    prop: 'type',
    label: '执行方式',
    type: 'select',
    drawerSlotName: 'type',
    tableHide: true,
    drawer: true,
    rules: true,
    onChange(e) {
      formData.value.type = e;
    },
  },
  {
    prop: 'taskDescription',
    label: '任务描述',
    tableHide: true,
    type: 'textarea',
    drawer: true,
    rows: 6,
  },
  {
    prop: 'fingerprint',
    label: '信息远程采集设置',
    tableHide: true,
    type: 'radio',
    drawer: true,
    drawValue: 1,
    options: [
      {
        key: '主机标准模式',
        value: 1,
      },
      {
        key: '主机精准模式',
        value: 2,
      },
    ],
  },
  {
    prop: 'schedule',
    label: '进度',
    align: 'center',
    minWidth: '180px',
    slotName: 'schedule',
  },
  {
    label: '执行状态',
    slotName: 'status',
    minWidth: '180px',
    search: true,
    type: 'select',
  },
  {
    prop: 'nextTime',
    label: '下次执行时间',
    minWidth: '200px',
  },
  {
    prop: 'gmtCreate',
    label: '添加时间',
    minWidth: '200px',
    type: 'daterange',
    search: true,
    valueFormat: 'YYYY-MM-DD',
    sortable: 'custom',
  },
  {
    prop: 'gmtCreate',
    label: '操作人',
    width: '180px',
  },
  {
    label: '操作',
    slotName: 'deal',
    fixed: 'right',
    width: '250px',
    buttons: [
      {
        title: '开始',
        icon: stop,
        eventName: 'state_stop',
        hide: function (row) {
          if (
            bottomData.has(400226) &&
            (row.status == 'none' ||
              row.status == 'finish' ||
              row.status == 'cancel')
          ) {
            return true;
          } else {
            return false;
          }
        },
      },
      {
        title: '暂停',
        icon: loading,
        eventName: 'state_loading',
        hide: function (row) {
          if (bottomData.has(400226) && row.status == 'running') {
            return true;
          } else {
            return false;
          }
        },
      },
      {
        title: '继续执行',
        icon: end,
        eventName: 'state_end',
        hide: function (row) {
          if (bottomData.has(400226) && row.status == 'pause') {
            return true;
          } else {
            return false;
          }
        },
      },
      {
        title: '取消',
        icon: cancel,
        eventName: 'state_cancel',
        hide: function (row) {
          if (
            bottomData.has(400226) &&
            row.status != 'none' &&
            row.status != 'finish' &&
            row.status != 'cancel'
          ) {
            return true;
          } else {
            return false;
          }
        },
      },
      {
        title: '编辑',
        disabled: function (row) {
          if (bottomData.has(400222)) {
            return false;
          } else {
            return true;
          }
        },
        eventName: 'edit',
      },
      {
        title: '删除',
        eventName: 'delete',
        disabled: function (row) {
          if (bottomData.has(400223)) {
            return false;
          } else {
            return true;
          }
        },
      },
      {
        title: '执行记录',
        eventName: 'record',
        disabled: function (row) {
          if (bottomData.has(400228)) {
            return false;
          } else {
            return true;
          }
        },
      },
    ],
  },
]);
/**
 * @description: 表格多选操作
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const selectData = ref([]);
const handleSelect = (data) => {
  selectData.value = data;
};

/**
 * @description: 获取表格数据
 * @param {*}
 * @return {*}
 * @author: xuch
 */
const getTableData = async (type) => {
  let _data = JSON.parse(JSON.stringify(type))._value;
  if (_data && _data.gmtCreate) {
    let begin = _data.gmtCreate[0] + ' 00:00:00';
    let End = _data.gmtCreate[1] + ' 23:59:59';
    _data.createTimeStart = begin;
    _data.createTimeEnd = End;
    delete _data.gmtCreate;
  }
  try {
    const params = {
      ..._data,
    };
    // openSocket('ws_gather', params, sockets);
    const res = await getList(params);
    if (res.code !== 200) return;
    tableData.value = res.data.records;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
  }
};
/**
 * @description: 批量删除
 * @return {*}
 * @author: tqh
 */
const handleDel = async (id, type) => {
  // @ts-ignore
  const data = selectData.value.map((item) => item.id);
  if (type == 'one') {
    delOne({
      id: id,
    }).then((res) => {
      if (res.code == 200) {
        ElMessage.success(res.message);
        clearSelect();
        multipleTableRef.value.initData();
      }
    });
  } else {
    delAll(id).then((res) => {
      if (res.code == 200) {
        ElMessage.success(res.message);
        clearSelect();
        multipleTableRef.value.initData();
      }
    });
  }
};
const tableBtnClick = (btn, row) => {
  const { eventName } = btn;
  switch (eventName) {
    case 'add': // 新增
      tableColumn.forEach((item) => {
        if (item.prop == 'name' || item.prop == 'targetType') {
          item.disabled = false;
        }
      });
      formData.value = {};
      disabled.value = false;
      formDataObj.value = {};
      break;
    case 'edit': // 编辑
      formDataObj.value = row;
      formData.value.targetType = row.targetType;
      formData.value.type = row.type;
      disabled.value = true;
      tableColumn.forEach((item) => {
        if (item.prop == 'name' || item.prop == 'targetType') {
          item.disabled = true;
        }
      });
      break;
    case 'state_stop':
      executeBtn(row);
      break;
    case 'state_loading':
      executeBtn(row);
      break;
    case 'state_end':
      executeBtn(row);
      break;
    case 'state_cancel':
      executeBtn({
        status: 'state_cancel',
        id: row.id,
      });
      break;
    case 'record':
      recordBtn('record', row);
      break;
  }
};
const formDataObj = ref({});
const disabled = ref(false);
/**
 * @description: 字典数据初始化
 */
const resetDictData = (e) => {
  let list = e.map((item) => {
    return {
      label: item.dictName,
      value: item.dictValue,
    };
  });
  return list;
};
const getDictList = () => {
  // 执行方式
  getDictTypeList({ dictType: 'executeType' }).then((res) => {
    if (res.code == 200) {
      tableColumn.forEach((item) => {
        if (item.prop == 'type') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
  // 目标类型
  getDictTypeList({ dictType: 'targetType' }).then((res) => {
    if (res.code == 200) {
      tableColumn.forEach((item) => {
        if (item.prop == 'targetType') {
          item.options = resetDictData(res.data);
        }
      });
    }
  });
};
/**
 * @description: 执行操作
 */
const executeBtn = (e) => {
  let send, title;
  if (e.status == 'none' || e.status == 'finish' || e.status == 'cancel') {
    send = execute;
    title = '任务开始执行!';
  } else if (e.status == 'running') {
    send = pauseDetect;
    title = '任务暂停！';
  } else if (e.status == 'pause') {
    send = pauseDetect;
    title = '任务继续执行！';
  } else if (e.status == 'state_cancel') {
    send = cancelDetect;
    title = '任务取消！';
  }
  send({ id: e.id }).then((res) => {
    if (res.code == 200) {
      ElMessage.success(title);
      multipleTableRef.value.initData();
    }
  });
};
const formData = ref({});
const refAddPopUp = ref(null);
watch(
  () => formData.value.type,
  () => {
    nextTick(() => {
      console.log(refAddPopUp.value);
      if (refAddPopUp.value) {
        refAddPopUp.value.resetDateObj();
      }
    });
  }
);
watch(
  () => formData.value.targetType,
  () => {
    nextTick(() => {
      if (refAddPopUp.value) {
        refAddPopUp.value.resetDateObj1();
      }
    });
  }
);
/**
 * @description: 获取组件传参
 */
const getTargetTypeValue = (e) => {
  formData.value.targetList = e.targetList;
};
const getTypeValue = (e) => {
  console.log(e, 'formData.type', formData.value.type);
  if (formData.value.type == 'custom_point') {
    formData.value.startTime = e.time;
  } else {
    formData.value.executeTime = e.time;
  }

  if (e.allWeek) {
    formData.value.typeParam = e.allWeek + ',' + e.weekDay;
  } else {
    formData.value.typeParam = e.weekDay;
  }
};
/**
 * @description 模板提交事件
 * @param eventName 事件名称 export: 批量导出
 * @param data 表单提交数据
 * @param cb  { Function } 组件回调  （ 新增，编辑，删除，上传需要参数: Boolean true(关闭loading,弹窗)/false(关闭loading) ）
 */
const btnSubmit = (eventName, data, cb) => {
  switch (eventName) {
    case 'batchDelete': // 批量删除
      let ids = selectData.value.map((item) => {
        return item.id;
      });
      handleDel(ids, 'some');
      break;
    case 'delete':
      handleDel(data.id, 'one');
      break;
    case 'edit': // 编辑
      handleSubmit(data, cb);
      break;
    case 'add': // 新增
      handleSubmit(data, cb);
      break;
  }
};
/**
 * @description: 新增，编辑提交确认
 */
const handleSubmit = (data, cb) => {
  let send;
  if (data.id) {
    send = update;
  } else {
    send = add;
  }
  let params = {
    ...data,
    ...formData.value,
  };
  send(params)
    .then((res) => {
      if (res.code == 200) {
        cb(true);
        ElMessage.success(data.id ? '新增成功！' : '编辑成功！');
        clearSelect();
      } else {
        cb(false);
      }
    })
    .catch(() => {
      cb(false);
    });
};

/**
 * @description 打开记录弹窗
 */
 const tableColumnList = ref([]);
const tableDataList = ref([]);
const childDialog = ref<any>();
const RecordDialogType = ref(2);
const sizeWidth = ref('380px');
const taskId = ref("");
const recordBtn = (type, e) => {
  taskId.value = e.id;
  tableTotal.value = 0;
  tablePage.value = 1;
  tableSize.value = 20;
  if (type == "targetName") {
    tableColumnList.value = collectionTableColumn;
    RecordDialogType.value = 2;
    sizeWidth.value = '580px';
    childDialog.value.dialogProps.title='采集对象'
    getTargetDetail("");
  } else {
    tableColumnList.value = taskRocordTableColumn;
    RecordDialogType.value = 1;
    childDialog.value.dialogProps.title='执行记录'
    sizeWidth.value = '580px';
    getRecordDetail();
  }
};
/**
 * @description: ip信息搜索条件
 */
const getSearch = (e) => {
  getTargetDetail(e);
};
const tableTotal = ref(0);
const tablePage = ref(1);
const tableSize = ref(20);
/**
 * @description: 页面容量切换
 */
const tableSizeChange = function (val: number) {
  tableSize.value = val;
  tablePage.value = 1;
  if (RecordDialogType.value ==2) {
    getTargetDetail("");
  } else {
    getRecordDetail();
  }
};
/**
 * @description: 分页切换
 */
const tableCurrentChange = function (val: number) {
  tablePage.value = val;
  if (RecordDialogType.value ==2) {
    getTargetDetail("");
  } else {
    getRecordDetail();
  }
};
/**
 * @description: 获取ip信息
 */
const getTargetDetail = (e) => {
  queryTargetDetail({
    taskId: taskId.value,
    ip: e,
    pageIndex: tablePage.value,
    pageSize: tableSize.value,
  }).then((res) => {
    if (res.code == 200) {
      tableDataList.value = res.data.records.map((item, index) => {
        let obj = {
          number: Number(
            (tablePage.value - 1) * tableSize.value + index + 1 > 9
              ? (tablePage.value - 1) * tableSize.value + index + 1
              : `${(tablePage.value - 1) * tableSize.value + index + 1}`
          ),
          ip: item,
        };
        return obj;
      });
      tableTotal.value = res.data.total;
      childDialog.value.openDialog();
    }
  });
};
/**
 * @description: 任务记录
 */
const getRecordDetail = () => {
  getRecordAssetsList({
    taskId: taskId.value,
    pageIndex: tablePage.value,
    pageSize: tableSize.value,
  }).then((res) => {
    if (res.code == 200) {
      tableDataList.value = res.data.records.map((item, index) => {
        item.number = Number(
          (tablePage.value - 1) * tableSize.value + index + 1 > 9
            ? (tablePage.value - 1) * tableSize.value + index + 1
            : `${(tablePage.value - 1) * tableSize.value + index + 1}`
        );
        return item;
      });
      tableTotal.value = res.data.total;
      childDialog.value.openDialog();
    }
  });
};
</script>

<template>
  <div>
    <YaPageContent
      ref="multipleTableRef"
      :total="total"
      :tableData="tableData"
      :tableColumns="tableColumn"
      :buttons="buttons"
      :rightButtons="rightButtons"
      @submit="btnSubmit"
      @init="getTableData"
      @tableBtnClick="tableBtnClick"
      @selectionChange="handleSelect"
      drawerSize="460px"
    >
      <template #schedule="{ item }">
        <div class="schedule">
          <div class="schedule-item"></div>
          <div class="schedule-text">10%</div>
        </div>
      </template>
      <!-- 执行状态 -->
      <template #status="item">
        <div
          class="status-flex"
          v-if="item.item.status != 'running' && item.item.status != 'pause'"
        >
          <div
            class="circle"
            :class="[
              item.item.status == 'none'
                ? 'circle-start'
                : item.item.status == 'running'
                ? 'circle-begin'
                : item.item.status == 'pause'
                ? 'circle-stop'
                : 'circle-end',
            ]"
          ></div>
          <div>
            {{ item.item.statusName }}
          </div>
        </div>
        <div class="percentage" v-else>
          <el-progress :percentage="item.item.percentage" />
        </div>
      </template>
      <!-- 采集对象 -->
      <template #colection="item">
        <div
          v-if="item.item.feature.targetName"
          class="targetName text-hover"
          @click="recordBtn('targetName', item.item)"
        >
          {{ item.item.feature.targetName }}
          <span v-if="item.item.feature.targetNum != '0'"
            >+{{ item.item.feature.targetNum }}</span
          >
        </div>
        <div v-else>-</div>
      </template>
      <template #targetType="{ item }">
        <AddPopUp
          ref="refAddPopUp"
          :disabled="disabled"
          :isShow="formData.targetType"
          type="targetType"
          :showType="2"
          @dateValue="getTargetTypeValue"
          :dataValue="formDataObj"
        />
      </template>
      <template #type="{ item }">
        <AddPopUp
          ref="refAddPopUp"
          :isShow="formData.type"
          :dataValue="formDataObj"
          @dateValue="getTypeValue"
        />
      </template>
    </YaPageContent>
    <RecordDialog
      ref="childDialog"
      :sizeWidth="sizeWidth"
      :type="RecordDialogType"
      :title="RecordDialogTitle"
      :tableTotal="tableTotal"
      :tablePage="tablePage"
      :tableSize="tableSize"
      :tableDataList="tableDataList"
      :tableColumn="tableColumnList"
      @sizeChangeOne="tableSizeChange"
      @currentChangeOne="tableCurrentChange"
      @onSearch="getSearch"
    />
  </div>
</template>

<style scoped lang="scss">
@import '../../../style/popUp.scss';
.status-flex {
  display: flex;
  align-items: center;
  .circle {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 6px;
  }
  .circle-start {
    background: var(--el-color-info-light-7);
  }
  .circle-begin {
    background: var(--el-color-primary);
  }
  .circle-stop {
    background: rgba(0, 149, 255, 0.2);
  }
  .circle-end {
    background: var(--el-color-warning);
  }
}
.cursor:hover {
  cursor: pointer;
}
.record {
  font-weight: 400;
  color: var(--el-color-primary);
  font-size: 14px;
}
.img2 {
  width: 20px;
  height: 20px;
  position: relative;
  top: 5px;
  margin-right: 18px;
}
.targetName {
  font-weight: 400;
  color: var(--el-color-primary);
  font-size: 14px;
  cursor: pointer;
  span {
    display: inline-block;
    background: #fff;
    border: 1px solid var(--el-color-primary);
    border-radius: 4px;
    padding: 0px 10px;
    height: 24px;
    line-height: 24px;
  }
}
.percentage {
  position: relative;
  top: 0px;
}
::v-deep .add-form {
  .el-input {
    margin-top: 12px;
  }
}
.schedule {
  width: 100%;
  height: 16px;
  background: rgba(229, 229, 229, 0.6);
  border-radius: 2px;
  position: relative;
  .schedule-item {
    position: absolute;
    background: var(--el-color-primary);
    left: 0;
    height: 16px;
    width: 100%;
    border-radius: 2px;
  }
  .schedule-text {
    height: 16px;
    line-height: 16px;
    position: relative;
    z-index: 2;
  }
}
</style>
