<template>
  <div class="yaBox">
    <!-- 搜索栏 -->
    <YaSearch
      :formData="formData"
      :formColumns="formColumns"
      @search="initData"
      @reset="resetForm"
    ></YaSearch>
    <!-- 按钮 -->
    <div class="ya-table-btn">
      <div class="ya-left">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
          >全选</el-checkbox
        >
        <ya-button
          v-if="bottomData.has('删除')"
          class="ya-delBtn"
          title="批量删除"
          :disabled="deleteState"
          plain="true"
          @click="handlerToDel"
        ></ya-button>
      </div>
    <div class="ya-right">
      <ya-button
        v-if="bottomData.has('默认采集参数')"
        title="默认采集参数"
        type="primary"
        @click="handlerGoConfig()"
      ></ya-button>
      <ya-button
        v-if="bottomData.has('新增')"
        title="新增"
        type="primary"
        @click="handlerToOpenDrawer()"
      ></ya-button>
    </div>
    </div>
    <!-- table块 -->
    <div class="ya-table-blocks">
      <yaEngineBlock
        v-if="tableData.length > 0"
        ref="engineBlock"
        :data="tableData"
        :buttons="bottomData"
        @handlerToEdit="handlerToOpenDrawer"
        @handleChangeCheck="handleChangeCheck"
        @handlerChangeStates="handlerChangeStates"
        @handlerLookDetail="handlerLookDetail"
        @handlerToDelBlock="handlerToDelBlock"
        @handlerToUpgrade="handlerToUpgrade"
      ></yaEngineBlock>
      <ya-empty v-else></ya-empty>
    </div>
    <!-- 新增编辑的弹窗 -->
    <YaDrawerForm
      v-if="drawerProps.showDrawer"
      :modelValue="drawFormData"
      :drawerProps="drawerProps"
      :formColumns="drawerColumns"
      @submit="handleSubmit"
    ></YaDrawerForm>
    <!-- 引擎信息 -->
    <engineDialog
      ref="engineDialogRef"
      :dialogProps="dialogProps"
    ></engineDialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, defineProps, watch,getCurrentInstance } from 'vue';
import yaEngineBlock from '../collection/components/engineBlock.vue';
import { yaConfirmMessage, yaMessage } from 'yuan-plus';
import engineDialog from '../collection/components/engineDialog.vue';
import {
  getTableList,
  postDelEngine,
  postAddEngine,
  postEditEngine,
  postSwitchEnable,
  postSwitchDisable,
  postUpgradeTableData,
  postLookDetail,
} from '../../api/engine';
import { getDictList } from '../../utils/utils';
import { useRouter } from 'vue-router';
import { openSocket, registerSockets } from '@/utils/socket/useSocket';
const { proxy } = getCurrentInstance();
const router=useRouter()
const { bottomData, type } = defineProps({
  bottomData: Array,
  type: String,
});
const formData = ref({});
let isIndeterminate: any = ref(null);
//全选按钮的选中状态
let checkAll = ref(false);
const deleteState = ref(true)
//引擎状态下拉框
const engineStates = ref([]);
//搜索栏
const formColumns = reactive([
  {
    key: 'engineId',
    type: 'input',
    label: '引擎ID',
    clearable: true,
  },
  {
    key: 'engineName',
    type: 'input',
    label: '引擎名称',
    clearable: true,
  },
  {
    key: 'hostIp',
    type: 'input',
    label: 'IP',
    clearable: true,
  },
  {
    key: 'engineStatus',
    type: 'select',
    options: engineStates,
    label: '引擎状态',
    clearable: true,
  },
  {
    key: 'crateTime',
    type: 'daterange',
    label: '添加时间',
    valueFormat: 'YYYY-MM-DD',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间',
    clearable: true,
  },
]);
//table--start
const engineBlock = ref();
const tableData = ref([]);
//全选按钮的事件
const handleCheckAllChange = (val: boolean) => {
  deleteState.value=!val
  isIndeterminate.value = false;
  engineBlock.value?.childEvent(val);
};
// 子组件传递来的事件，根据data判断全选按钮是否勾选
const handleChangeCheck = (data) => {
  deleteState.value = !data
  checkAll.value = data === tableData.value.length;
  isIndeterminate.value = data > 0 && data < tableData.value.length;
};
//开关的事件
const handlerChangeStates = async (data) => {
  let interfaceName = data.switch ? postSwitchEnable : postSwitchDisable;
  const res = await interfaceName({
    engineId: data.engineId,
    engineType: type,
  });
  const { code, message } = res || {};
  code == 200 && yaMessage(message, 'success');
  initData();
};
//单个删除按钮
const handlerToDelBlock = (data) => {
  yaConfirmMessage().then(() => {
    postDelEngine([data.id]).then((res) => {
      const { code, message } = res || {};
      if (code == 200) {
        initData();
        yaMessage(message, 'success');
      }
    });
  });
};
//删除按钮的事件
const handlerToDel = () => {
  if (engineBlock.value?.checkedCount?.length == 0) {
    yaMessage('请选择需要删除的数据', 'warning');
  } else {
    yaConfirmMessage().then(() => {
      postDelEngine(engineBlock.value?.checkedCount).then((res) => {
        const { code, message } = res || {};
        if (code == 200) {
          initData();
          yaMessage(message, 'success');
        }
      });
    });
  }
};
//
const handlerGoConfig=()=>{
  router.push('/collection/collectConfig/scanEngine/config')
}
//升级按钮的事件
const handlerToUpgrade = async (data) => {
  const res = await postUpgradeTableData(data.id);
  const { code, message } = res || {};
  code == 200 && yaMessage(message, 'success');
};
const engineDialogRef = ref();
//引擎信息的弹窗
const dialogProps = reactive({
  showDialog: false,  
  title: '引擎详情',
});

//详情按钮的事件
const handlerLookDetail = async (params) => {
  dialogProps.showDialog = true;
  const res = await postLookDetail({ id: params.id });
  const { code, data } = res || {};
  if (code == 200) {
    engineDialogRef.value.engineInfo.map((item) => {
      item.value = data ? data[item.key] : '';
    });
    let info = data?.extraInfo || {};
    engineDialogRef.value.engineInfo.find((item) => {
      item.key == 'version' && (item.value = info.version || '');
      item.key == 'hostStatus' &&
        (item.value = {
          description: data ? data.engineStatusDesc : '',
          ...info?.hostStatus,
        });
      item.key == 'taskProgress' && (item.value = info?.taskProgress || []);
    });
  }
};
//table--end

//新增编辑--start
//访问网络域下拉框
const visitedNetWork = ref([]);
//新增编辑内容
const drawerColumns = reactive([
  {
    key: 'engineId',
    type: 'input',
    label: '引擎ID',
    rules: true,
    clearable: true,
  },
  {
    key: 'engineName',
    type: 'input',
    label: '引擎名称',
    rules: true,
    clearable: true,
    maxLength:20,
  },
  {
    key: 'hostIp',
    type: 'input',
    label: 'IP',
    rules: true,
    clearable: true,
  },
  {
    key: 'authCode',
    type: 'input',
    label: '授权码',
    rules: true,
    clearable: true,
  },
  {
    key: 'networkArea',
    label: '访问网络域',
    type: 'select',
    options: visitedNetWork,
    rules: true,
    clearable: true,
  },
  {
    key: 'engineDesc',
    type: 'textarea',
    label: '描述',
    clearable: true,
    showWordLimit: true,
    maxlength: '150',
    rows: 2,
  },
]);
//新增和编辑的数据
const drawFormData = ref({});
const drawerProps = reactive(<any>{
  showDrawer: false,
  title: '新增引擎',
  labelWidth: '80px',
});
//新增和编辑按钮的事件
const handlerToOpenDrawer = (data?) => {
  initDict(false);
  drawerProps.title = data ? '编辑引擎' : '新增引擎';
  drawFormData.value = data || {};
  drawerProps.showDrawer = true;
};
//确定按钮提交
const handleSubmit = async (data, resolve) => {
  let interfaceName = data.id ? postEditEngine : postAddEngine;
  data.engineType = type;
  const res = await interfaceName(data);
  const { code, message } = res || {};
  if (code == 200) {
    yaMessage(message, 'success');
    initData();
    drawerProps.showDrawer = false;
  }
  resolve(code == 200);
};
//新增编辑--end
const sockets = {
  message(res) {
    if (res.type == 'ws_engineManage') {
      const { data, code } = res.data;
      if (code == 200 && data) {
        data.records?.map((item) => {
        let hostStatus = item.extraInfo?.hostStatus || {};
        item.switch = item.engineStatus != 'close';
        item.version = item.extraInfo?.version;
        item.cpu = hostStatus.cpu?.substr(0, hostStatus.cpu.length - 1) || 0;
        item.disk = hostStatus.disk?.substr(0, hostStatus.disk.length - 1) || 0;
        item.memory =
          hostStatus.memory?.substr(0, hostStatus.memory.length - 1) || 0;
      });
      tableData.value = data.records || [];
      }
    }
  },
};
//数据初始化
const initData = () => {
  let params = {
    engineType: type,
    ...formData.value,
  };
  if (params.crateTime) {
    params.startTime = params.crateTime[0];
    params.endTime = params.crateTime[1];
  }
  getTableList(params).then((res) => {
    const { code, data } = res || {};
    if (code == 200 && data) {
      data.records?.map((item) => {
        let hostStatus = item.extraInfo?.hostStatus || {};
        item.switch = item.engineStatus != 'close';
        item.version = item.extraInfo?.version;
        item.cpu = hostStatus.cpu?.substr(0, hostStatus.cpu.length - 1) || 0;
        item.disk = hostStatus.disk?.substr(0, hostStatus.disk.length - 1) || 0;
        item.memory =
          hostStatus.memory?.substr(0, hostStatus.memory.length - 1) || 0;
      });
      tableData.value = data.records || [];
    }
  });
  openSocket('ws_engineManage', params, sockets);
};

//重置
const resetForm = () => {
  formData.value = {};
  initData();
};


//字典
const initDict = (state) => {
  state &&
    getDictList('engineStatus').then((res) => {
      engineStates.value = res || [];
    });
  !state &&
    getDictList('networkArea').then((res) => {
      visitedNetWork.value = res || [];
    });
};
onMounted(() => {
  registerSockets(sockets, proxy);
  initData();
  initDict(true);
});
</script>
<style lang="scss" scoped>
.yaBox {
  padding: 16px;
  .ya-table-btn {
    display: flex;
    justify-content: space-between;
    .ya-left {
      display: flex;
      align-items: center;
      ::v-deep .el-checkbox__label {
        color: rgba(0, 0, 0, 0.6);
        margin-right: 12px;
      }
      ::v-deep .el-checkbox__input.is-indeterminate .el-checkbox__inner {
        background: #eff8ff;
        border-radius: 1px;
        border: 1px solid #0095ff;
        &::before {
          background-color: #0095ff;
        }
      }
      .ya-delBtn {
        margin-right: 16px;
      }
    }
  }
  .ya-table-blocks {
    margin-top: 16px;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
