<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <bg-filter-group @search="changeSearch" v-model="filter.search" placeholder="请输入关键字">
        <template v-slot:left_action>
          <div class="apaas_button">
            <el-button type="primary" @click="gotoPage(`/auto-maintenance/task-manage/add`)">
              <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
              新增
            </el-button>
            <el-button type="default" @click="deleteAllTips"> 批量删除 </el-button>
            <span class="header_info"
              >已选择 <span style="color: #202531; font-weight: bold"> {{ state.selectedNum }} </span> 项
            </span>
            <span class="header_info can_click_text" @click="clearSelected">清空</span>
          </div>
        </template>
        <template v-slot:filter_group>
          <div class="left-filter filter_list">
            <div class="filter_item">
              <span class="filter_title">创建时间</span>
              <el-date-picker
                v-model="filter.time"
                type="daterange"
                value-format="YYYY-MM-DD"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </div>
          </div>
          <div class="right-action apaas_button">
            <el-button type="primary" @click="filterAction"> 查询 </el-button>
            <el-button type="default" @click="filterClear"> 重置 </el-button>
          </div>
        </template>
      </bg-filter-group>
      <div class="table_container">
        <div class="table bg-scroll">
          <bg-table
            ref="dataTable"
            :headers="headers"
            :rows="tableRows"
            @selectAc="selectRows"
            :isIndex="true"
            :select="true"
            :stripe="true">
            <template v-slot:task_name="{ row }">
              <span class="can_click_text" @click="gotoPage(`/auto-maintenance/task-manage/detail?id=${row.id}`)">
                {{ row.task_name }}
              </span>
            </template>
            <template v-slot:create_time="{ row }">
              {{ row.create_time.split("+")[0].replace("T", " ").replace("Z", " ") }}
            </template>
            <template v-slot:action="{ row }">
              <bg-table-btns2 :limit="3" :tableData="tableRows">
                <bg-table-btn @click="useRow(row)">执行任务</bg-table-btn>
                <bg-table-btn @click="gotoPage(`/auto-maintenance/task-manage/edit?id=${row.id}`)">编辑</bg-table-btn>
                <bg-table-btn @click="gotoPage(`/auto-maintenance/task-manage/copy?id=${row.id}`)">复制</bg-table-btn>
                <bg-table-btn @click="deleteRow(row)">删除</bg-table-btn>
              </bg-table-btns2>
            </template>
          </bg-table>
        </div>
        <bg-pagination
          :page="filter.page"
          :size="filter.page_size"
          :total="tableTotal"
          @change-page="changePage"
          @change-size="changeSize">
        </bg-pagination>
      </div>
    </div>
    <!-- 删除弹窗 -->
    <el-dialog
      class="dialog_box"
      title="提示"
      v-model="state.dialogDelete"
      width="400px"
      :before-close="
        () => {
          state.dialogDelete = false;
        }
      ">
      <div>确定要删除任务吗？</div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="state.dialogDelete = false">取 消</el-button>
          <el-button type="primary" @click="deleteData">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      class="dialog_box"
      title="立即执行"
      :close-on-click-modal="false"
      v-model="state.useScriptShow"
      width="1024px">
      <div>
        <div class="dialog-tips">
          <bg-icon icon="#bg-ic-s-circle-warning" style="color: #a9b1c7"></bg-icon> 向执行脚本传递额外的命令行变量。这是
          ansible-playbook 的 -e 或 --extra-vars 命令行参数。使用 YAML 或 JSON 提供键/值对，此项为非必填项。
        </div>
        <bg-inner-tabs v-model="state.useType" :data="state.useData" style="float: left"></bg-inner-tabs>
        <div style="clear: both"></div>
        <div style="height: 370px">
          <bg-code-editor v-model="state.useText"></bg-code-editor>
        </div>
      </div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="cancelUse">取消</el-button>
          <el-button type="primary" @click="confirmUse">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, onBeforeMount, toRefs, computed, watch, nextTick, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { Search } from "@element-plus/icons-vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import { useRouter, useRoute } from "vue-router";
const router = useRouter();
const route = useRoute();

const dataTable = ref(null);
const headers = [
  {
    label: "任务名称",
    prop: "task_name",
    width: 200,
  },
  {
    label: "执行次数",
    prop: "exec_cnt",
  },
  {
    label: "描述",
    prop: "task_desc",
    minWidth: 300,
  },
  {
    label: "创建人",
    prop: "create_user",
  },
  {
    label: "创建时间",
    prop: "create_time",
    width: 180,
  },
  {
    label: "操作",
    prop: "action",
    width: 200,
    fixed: "right",
  },
];

const state = reactive({
  tableRows: [], // 表格数据
  selected: [], //选择数据
  selectedNum: 0, //选择数据数量
  tableTotal: 0, // 表格数据条数
  filter: {
    time: "",
    search: "",
    page: 1,
    page_size: 10,
  }, // 表格筛选项
  actionRow: null, // 当前操作的数据
  dialogDelete: false, // 删除弹窗
  useScriptShow: false,
  useType: 0,
  useText: "",
  useData: ["yaml", "json"],
  deleteType: 0, //0单个删除，1批量删除
});

const useRow = (row) => {
  state.actionRow = row;
  state.useScriptShow = true;
};

const cancelUse = () => {
  state.useScriptShow = false;
};

const confirmUse = () => {
  state.useScriptShow = false;
  let params = new FormData();
  params.append("task_id", state.actionRow.id);
  params.append("type", state.useType + 1);
  params.append("value", state.useText);
  axios
    .post(`/v1/api/automated_mainten/task_manage/exec/script`, params)
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("执行成功");
        router.push(`/auto-maintenance/task-history/list/record?id=${res.data.data}`);
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .finally(() => {
      state.useType = 0;
      state.useText = "";
      state.actionRow = null;
    });
};

const deleteRow = (row) => {
  state.actionRow = row;
  state.dialogDelete = true;
  state.deleteType = 0;
};

const deleteData = () => {
  state.dialogDelete = false;
  let ids = [];
  if (state.deleteType == 0) {
    ids = [state.actionRow.id];
  } else {
    let dealData = dataTable.value.dealSelectData();
    for (const key in dealData) {
      ids.push(dealData[key].id);
    }
  }
  axios
    .delete(`/v1/api/automated_mainten/task_manage/del`, {
      data: {
        id: ids,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("删除成功");
        changePage(1);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
};

const selectRows = (data) => {
  state.selectedNum = data.allLength;
  state.selected = data.selection;
};

const clearSelected = () => {
  dataTable.value.clearTable();
};

const deleteAllTips = () => {
  if (state.selected.length > 0) {
    state.dialogDelete = true;
    state.deleteType = 1;
  } else {
    ElMessage.error("请先选择要删除任务");
  }
};

const gotoPage = (url) => {
  router.push(url);
};

const changeSearch = (val) => {
  state.filter.search = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const filterClear = () => {
  state.filter = {
    time: "",
    search: "",
    page: 1,
    page_size: 10,
  };
  changePage(1);
}; // 重置筛选项

const getTableRows = () => {
  let params = { ...state.filter };
  if (params.time) {
    params.create_date_from = params.time[0];
    params.create_date_to = params.time[1];
  } else {
    params.create_date_from = "";
    params.create_date_to = "";
  }
  axios
    .get(`/v1/api/automated_mainten/task_manage/list`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        let data = res.data.data || [];
        state.tableRows = data;
        state.tableTotal = res.data.total;
      } else {
        ElMessage.error(res.data.data);
      }
    });
}; // 获取表格数据

const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
}; // 改变页码

const changeSize = (size) => {
  state.filter.page_size = size;
  changePage(1);
}; // 改变每页条数

onBeforeMount(() => {
  getTableRows();
});

const { tableRows, tableTotal, filter } = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  padding: 0 24px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    height: 100%;
    .filter-group {
      .left-filter {
        flex: 1;
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
      }
      .right-action {
        width: 144px;
        padding-bottom: 16px;
        .el-button {
          width: 64px;
        }
      }
    }

    .table_container {
      height: calc(100% - 70px);
      width: 100%;
      padding: 0 16px;
    }
  }

  .bg_form {
    width: 100%;
    box-sizing: border-box;
    .el-form-item {
      margin-bottom: 24px;
      :deep().el-form-item__label {
        line-height: 36px;
        height: 36px;
      }
      .el-form-item__content {
        width: 100%;
        .el-textarea {
          :deep().el-input__count {
            bottom: -16px;
            right: 4px;
            font-family: Roboto-Regular;
            color: #a9b1c7;
          }
        }
        .bg-switch-ele {
          width: 52px;
          height: 24px;
          :deep().el-switch__core {
            width: 100%;
            height: 24px;
            .el-switch__inner,
            .el-switch__action {
              top: 3px;
            }
          }
        }
      }
    }
  }
}

.dialog-tips {
  height: 38px;
  line-height: 38px;
  background-color: #f7f7f9;
  border-radius: 4px;
  font-size: 14px;
  color: #404a62;
  margin-bottom: 16px;
}
</style>
