<script>
import axios from "axios";
import { inject } from "vue";
import { getCIDLogListService } from "@/api/cid.js";
import { runCIDService } from "@/api/cid.js";
import { addCIDService } from "@/api/cid.js";
import { deleteCIDService } from "@/api/cid.js";
import { updateCIDService } from "@/api/cid.js";
import router from "@/router/index.js";
import Menu from "@/views/Menu.vue";

export default {
  data() {
    return {
      ip: "",
      tableData: [],
      currentPageData: [],
      ConfigFileCurrentPageData: [],
      loading: false,
      pageSize: 10,
      currentPage: 1,
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        id:localStorage.getItem("cid_id"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
      },
      addDialogVisible: false,
      updateDialogVisible: false,
      updateForm: {
        create_time: "",
        script: "",
        end: "",
        error: "",
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    currentPageData() {
      const { tableData, currentPage, pageSize } = this;
      this.ConfigFileCurrentPageData = tableData.slice(
        (currentPage - 1) * pageSize,
        currentPage * pageSize
      );
    },
    roundNumber(number, decimals) {
      let num = 3.14159;
      let result = Math.round(number * 100) / 100;
      return result;
    },
    async getCIDLogList() {
      let result = {};
      this.loading = true;
      try {
        this.tokenData.id = parseInt(this.tokenData.id);
        result = await getCIDLogListService(this.tokenData);
        this.loading = false;
      } catch (e) {
        console.log(e);
        this.loading = false;
      }
      let data = result.data;
      for(var i=0;i<data.length;i++){
        data[i].RunTime =  Math.round(data[i].RunTime * 100) / 100;
      }
      this.tableData = data;
      for(let i = 0;i<this.tableData.length;i++) {
        this.tableData[i].UpdatedAt = this.formattedTime(this.tableData[i].UpdatedAt);
        this.tableData[i].CreatedAt = this.formattedTime(this.tableData[i].CreatedAt)
      //console.log('this.ConfigFileList:',this.ConfigFileList);
      }
      this.handleCurrentChange(1);
    },
    formattedTime(isoTime) {
      const date = new Date(isoTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    onSubmit() {
      getDeviceList({ token: token });
    },
    handleSizeChange(val) {
      this.pageSize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.currentPageData = this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },

    //设置项目执行构建部署
    async runCID(index) {
      var id = this.tableData[index].ID;
      var run_data = {
        id: id,
        ip: this.ip,
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await runCIDService(run_data);
        if (d_re.code == 0) {
          alert("操作成功");
        } else {
          alert("操作失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async deleteCID(index) {
      var id = this.tableData[index].ID;
      var delete_data = {
        id: id,
        userId: this.tokenData.userId,
        token: this.tokenData.token,
      };
      try {
        var d_re = await deleteCIDService(delete_data);
        if (d_re.code == 0) {
          alert("删除成功");
          //刷新页面
          this.getDeviceList();
        } else {
          alert("操作失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async updateButtonLogCID(index) {
      this.updateDialogVisible = true;
      // var id = this.tableData[index].ID;
      // this.updateForm.create_time = this.tableData[index].CreatedAt;
      // this.updateForm.script = this.tableData[index].Script;
      // this.updateForm.end = this.tableData[index].Log;
      // this.updateForm.error = this.tableData[index].Error;
      // this.updateForm.RunTime = this.tableData[index].RunTime;
      var id = this.currentPageData[index].ID;
      this.updateForm.create_time = this.currentPageData[index].CreatedAt;
      this.updateForm.script = this.currentPageData[index].Script;
      this.updateForm.end = this.currentPageData[index].Log;
      this.updateForm.error = this.currentPageData[index].Error;
      this.updateForm.RunTime = this.currentPageData[index].RunTime;
    },
    async getIpClient() {
      try {
        const response = await axios.get("https://ipinfo.io/json");
        this.ip = response.data.ip;
        localStorage.setItem("ip", this.ip);
        //console.log(response);
      } catch (error) {
        console.error(error);
      }
    },
    handleMenuSelect(val) {
      router.push(val);
    },
    toVideoList() {
      router.push("/videoList");
    },
    // 修改条纹颜色
    tableRowClassName({ row, rowIndex }) {
      if (row.human === 1) {
        return {
          background: "#488aff",
        };
      } else {
        return "";
      }
    },
  },

  // 生命周期钩子会在组件生命周期的各个不同阶段被调用
  // 例如这个函数就会在组件挂载完成后被调用
  async mounted() {
    let now = new Date();
    if (localStorage.getItem("token") === null) {
      router.push("/login");
    }
    // console.log("mounted");
    this.getIpClient();
    this.getCIDLogList();
  },
};
</script>

<template>
  <div>
    <Menu></Menu>
    <el-container style="height: 700px; border: 1px solid #eee">
      <el-header style="font-size: 40px; background-color: rgb(238, 241, 246)"
        >集成部署项目日志{{ tokenData.id }}</el-header
      >
      <el-container>
        <el-main>
          <!-- 表单 -->
          <el-form :inline="true" :model="tokenData" class="demo-form-inline">
            <el-form-item>
              <el-button
                class="el-button--danger"
                type="primary"
                @click="getCIDLogList()"
                :disabled="loading"
                >刷新</el-button
              >
            </el-form-item>

            <el-form-item>
              <el-dialog
                v-model="updateDialogVisible"
                title="查看集成项目日志"
                width="50%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="addFormRef"
                  :model="updateForm"
                  :rules="updateFormRules"
                  label-width="70px"
                >
                  <el-form-item label="创建时间" prop="create_time">
                    <el-input
                      v-model="updateForm.create_time"
                      autocomplete="on"
                      style="width: 600px" 
                    ></el-input>
                    
                  </el-form-item>
                  <el-col>
                    <el-form-item label="执行时间" prop="run_time">
                      <el-input
                        v-model="updateForm.RunTime"
                        autocomplete="on"
                        style="width: 100px" 
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-form-item label="脚本内容" prop="script">
                    <el-input type="textarea" v-model="updateForm.script" style="width: 700px" :autosize="{ minRows: 4, maxRows: 8 }" />
                  </el-form-item>
                  <el-form-item label="执行结果" prop="end">
                    <el-input type="textarea" v-model="updateForm.end" style="width: 700px" :autosize="{ minRows: 4, maxRows: 8 }" />
                  </el-form-item>
                  <el-col>
                    <el-form-item label="错误内容" prop="error">
                    <el-input type="textarea" v-model="updateForm.error" style="width: 700px" :autosize="{ minRows: 4, maxRows: 8 }" />
                  </el-form-item>
                  </el-col>
                  
                </el-form>
                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false"
                      >关闭</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>
          </el-form>

          <!-- 表格  :row-style="this.tableRowClassName"-->
          <el-table
            :data="currentPageData"
            width="100%" 
            v-loading="loading"
            element-loading-text="数据加载中..."
          >
            :row-style="this.tableRowClassName"
            <el-table-column prop="ID" label="id" width="80"></el-table-column>
            <el-table-column
              prop="CreatedAt"
              label="创建时间"
              show-overflow-tooltip
              width="200"
            ></el-table-column>
            <el-table-column
              prop="Script"
              label="执行脚本"
              width="180"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="Log"
              label="运行日志"
              width="180"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="Error"
              label="错误信息"
              width="250"
            ></el-table-column>
            <el-table-column
              prop="RunTime"
              label="运行时间(s)"
              width="80"
            ></el-table-column>
            <el-table-column label="操作" width="350">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="updateButtonLogCID(scope.$index)"
                  >详情</el-button
                >
                <!-- <el-button type="danger" size="mini">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <br />

          <!-- 分页条 -->
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.length">
          </el-pagination>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<style>
.blueRowbg {
  background: "#488aff";
}
</style>