<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <div class="content_process">
        <div>
          <el-steps :active="step">
            <el-step title="" :class="{ process_complete: step > 1 }">
              <template #icon>
                <span class="process_desc">
                  <span class="icon_box" v-if="step > 0"><bg-icon class="step_icon" icon="#bg-ic-file"></bg-icon></span>
                  <span class="circle" v-else></span>
                  基本信息
                </span>
              </template>
            </el-step>
            <el-step title="" :class="{ process_complete: step > 2 }">
              <template #icon>
                <span class="process_desc">
                  <span class="icon_box" v-if="step > 1"
                    ><bg-icon class="step_icon" icon="#bg-ic-instruction"></bg-icon
                  ></span>
                  <span class="circle" v-else></span>
                  执行内容
                </span>
              </template>
            </el-step>
            <el-step title="">
              <template #icon>
                <span class="process_desc">
                  <span class="icon_box" v-if="step > 2"
                    ><bg-icon class="step_icon" icon="#bg-ic-file-success"></bg-icon
                  ></span>
                  <span class="circle" v-else></span>
                  完成
                </span>
              </template>
            </el-step>
          </el-steps>
        </div>
      </div>
      <div
        class="content_main log_content_nor"
        :style="step == 3 && state.isSave ? { height: 'calc(100vh - 234px)' } : {}">
        <base-info
          v-show="step == 1"
          v-if="state.loadComponents"
          :isEdit="state.pageType == 1"
          :data="state.data"
          ref="baseInfoRef"></base-info>
        <use-content
          v-show="step == 2"
          v-if="state.loadComponents"
          :data="state.data"
          ref="useContentRef"></use-content>
        <finish
          v-show="step == 3 && state.isSave"
          :state="state.status"
          :finishType="state.pageType"
          v-if="state.loadComponents"
          @clear="clearData"></finish>
        <finish-use
          v-show="step == 3 && !state.isSave"
          v-if="state.loadComponents"
          :state="state.useStatus"
          :codes="state.finishUseData.logArr"
          :time="state.finishUseData.time"></finish-use>
      </div>
      <div class="content_foot apaas_button" v-if="step == 1 || step == 2 || (step == 3 && !state.isSave)">
        <el-button type="default" v-if="step == 1 || step == 2" @click="cancel"> 取消 </el-button>
        <el-button type="default" v-if="step == 2" @click="confirm(-1)"> 上一步 </el-button>
        <el-button type="primary" v-if="step == 1" @click="confirm(1)"> 下一步 </el-button>
        <el-button type="primary" v-if="step == 2" @click="saveTask()"> 保存 </el-button>
        <el-button type="success" v-if="step == 2" @click="useScript"> 立即执行 </el-button>
        <el-button type="default" v-if="step == 3" @click="cancel"> 返回列表 </el-button>
        <el-button type="primary" v-if="step == 3" @click="reUseScript"> 重新执行 </el-button>
      </div>
    </div>

    <el-dialog class="dialog_box" title="立即执行" 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 } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import baseInfo from "./base-info.vue";
import useContent from "./use-content.vue";
import finish from "./finish.vue";
import finishUse from "./finish-use.vue";
import { secondeToHour } from "@/services/helper.js";
const router = useRouter();
const route = useRoute();

const step = ref(1);
const baseInfoRef = ref(null);
const useContentRef = ref(null);

const state = reactive({
  data: {},
  useScriptShow: false,
  useType: 0,
  useData: ["yaml", "json"],
  useText: "",
  isSave: true,
  isReuse: false,
  status: true,
  useStatus: -1,
  pageType: 0, //0新增，1编辑，2复制
  loadComponents: false, //控制子组件的加载
  taskId: "",
  finishUseData: {
    time: "",
    logArr: [],
  },
});

const cancel = () => {
  router.back();
};

const confirm = async (val) => {
  let flag = true;
  if (val == 1) {
    await baseInfoRef.value
      .save()
      .then()
      .catch(() => {
        flag = false;
      });
  }
  if (flag) {
    step.value = step.value + val;
  }
};

//保存
const saveTask = async () => {
  await useContentRef.value
    .save()
    .then(() => {
      step.value = 3;
      if (state.pageType == 0 || state.pageType == 2) {
        postTask().then((res) => {
          if (res.data.code == 200) {
            state.status = true;
            ElMessage.success("保存成功");
          } else {
            state.status = false;
            ElMessage.error(res.data.msg);
          }
        });
      } else if (state.pageType == 1) {
        editTask();
      }
    })
    .catch(() => {});
};

const editTask = () => {
  axios
    .put(`/v1/api/automated_mainten/task_manage/edit`, {
      task_name: state.data.name,
      task_desc: state.data.desc,
      yaml_desc: state.data.useText,
      yaml_url: JSON.stringify(state.data.doc_file),
      host_group_id: state.data.pcName,
    })
    .then((res) => {
      if (res.data.code == 200) {
        state.status = true;
        ElMessage.success("保存成功");
      } else {
        state.status = false;
        ElMessage.error(res.data.msg);
      }
    });
};

const postTask = () => {
  return axios.post(`/v1/api/automated_mainten/task_manage/add`, {
    task_name: state.data.name,
    task_desc: state.data.desc,
    yaml_desc: state.data.useText,
    yaml_url: JSON.stringify(state.data.doc_file),
    host_group_id: state.data.pcName,
  });
};

const useScript = async () => {
  //填写完成才可以进行执行
  await useContentRef.value
    .save()
    .then(() => {
      state.useScriptShow = true;
    })
    .catch(() => {
      ElMessage.error("请先完善表单再执行");
    });
};

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

//重新执行
const reUseScript = () => {
  state.useScriptShow = true;
  state.isReuse = true;
};

const confirmUse = () => {
  state.useScriptShow = false;
  state.isSave = false;
  step.value = 3;
  if (state.isReuse) {
    postScript(state.taskId);
  } else {
    postTask().then((res) => {
      if (res.data.code == 200) {
        state.taskId = res.data.data;
        postScript(res.data.data);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
  }
};

const getLog = (id) => {
  axios.get(`/v1/api/automated_mainten/task_history/task_exec_log?id=${id}`).then((res) => {
    if (res.data.code == 200) {
      let data = res.data.data;
      state.finishUseData.time = secondeToHour(data.exec_time);
      state.finishUseData.logArr = data.exec_log.split("\n");
      state.useStatus = data.state;

      if (data.state == 0) {
        setTimeout(() => {
          getLog(id);
        }, 2000);
      }
    }
  });
};

const postScript = (task_id) => {
  let params = new FormData();
  params.append("task_id", task_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) {
        getLog(res.data.data);
      } else {
        state.useStatus = 2;
        ElMessage.error(res.data.msg);
      }
    })
    .finally(() => {
      state.useType = 0;
      state.useText = "";
    });
};

const clearData = () => {
  baseInfoRef.value.clear();
  useContentRef.value.clear();
  state.data = {};
  step.value = 1;
  state.loadComponents = false;
  state.isReuse = false
  state.useStatus = -1
  state.taskId = ''
  init();
};

const getDetails = () => {
  axios
    .get(`/v1/api/automated_mainten/task_manage/details`, {
      params: {
        id: route.query.id,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        let data = res.data.data;
        state.data = {
          name: data.task_name,
          desc: data.task_desc,
          useText: data.yaml_desc,
          doc_file: data.yaml_url ? JSON.parse(data.yaml_url) : [],
          pcName: data.host_group_id,
        };
        //复制，名字置空
        if (state.pageType == 2) {
          state.data.name = "";
        }
        state.loadComponents = true;
      }
    });
};

const init = () => {
  if (route.path.indexOf("edit") > -1) {
    state.pageType = 1;
  } else if (route.path.indexOf("copy") > -1) {
    state.pageType = 2;
  }
  if (state.pageType !== 0) {
    getDetails();
  } else {
    state.loadComponents = true;
  }
};

onBeforeMount(() => {
  state.loadComponents = false;
  init();
});
</script>

<style scoped>
.content_process {
  border-bottom: 1px solid #e6e9ef;
  padding: 38px 16%;
}
.content_main {
  height: calc(100vh - 287px);
  padding: 30px;
  overflow-x: hidden;
  overflow-y: scroll;
  box-sizing: border-box;
}
.content_foot {
  border-top: 1px solid #e6e9ef;
  padding: 16px 16px 0 16px;
  display: flex;
  justify-content: flex-end;
}

.process_desc {
  background-color: #fff;
  display: inline-block;
  position: absolute;
  padding: 0 5px;
  font-size: 18px;
  color: #202531;
  font-weight: bold;
}
.process_desc img {
  height: 25px;
  width: 25px;
  vertical-align: middle;
}
.process_end {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
.process_end div {
  text-align: center;
}
.step_icon {
  color: #fff;
  font-weight: 600;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.icon_box {
  display: inline-block;
  background-color: #2b4695;
  width: 48px;
  height: 48px;
  border-radius: 99px;
  position: relative;
  border: 3px solid #b0bee8;
  vertical-align: middle;
}
.circle {
  display: inline-block;
  background-color: #a9b1c7;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  position: relative;
  border: 6px solid #e6e9ef;
  vertical-align: middle;
}
.content_process :deep(.el-step.is-horizontal .el-step__line) {
  height: 4px;
}
.content_process :deep(.el-step__head.is-finish .el-step__line) {
  background: linear-gradient(to right, #2b4695 50%, #e6e9ef 50%);
}
.process_complete :deep(.el-step__head.is-finish .el-step__line) {
  background: linear-gradient(to right, #2b4695 100%, #e6e9ef 0%);
}

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