<script>
import axios from "axios";
import router from "@/router/index.js";
import Cookies from "js-cookie";
import { ElMessage } from "element-plus";
import CryptoJS from "crypto-js";
import Menu from "@/views/Menu.vue";

import { getConfigShellListService } from "@/api/shell.js";
import { addConfigShellService } from "@/api/shell.js";
import { deleteConfigShellService } from "@/api/shell.js";
import { updateConfigShellService } from "@/api/shell.js";

export default {
  data() {
    return {
      ip: "",
      tableData: [],
      search_id: 2002,
      ConfigShellUpdateForm: {},
      keyword: "",
      updateDialogVisible: false,
      addConfigFileVisible: false,
      ConfigFileCurrentPageData: [],
      pageSize: 10,
      currentPage: 1,
      upload_file: null, //文件上传
      file_md5: "", //文件上传的md5
      addForm: {
        shell_name: "",
        shel_content: "",
        server:""
      },

      role: "",
      tokenData: {
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
        id: 2002,
        server: "gep.ljsea.top",
        keyword: "",
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    async getConfigFileList() {
      let result = {};
      try {
        //判断search_id是字符串还是数字
        let req = {
          token: this.tokenData.token,
          type: "all",
        };
        result = await getConfigShellListService(req);
      } catch (e) {
        console.log(e);
      }
      let data = result.data;
      if (data !== undefined && data !== null) {
        this.tableData = data;
      }
      this.currentPageData();
    },
    addConfigFileV() {
      this.addConfigFileVisible = true;
    },
    handleServerChange() {
      localStorage.setItem("config_file_server", this.tokenData.server);
      this.getConfigFileList();
    },
    async addConfigFile() {
      this.addDialogVisible = false;
      let result = {};
      try {
        let req = {
          token: this.tokenData.token,
          shell_name: this.addForm.shell_name,
          shell_content: this.addForm.shell_content,
          server: this.addForm.server
        };
        result = await addConfigShellService(req);
        if (result.code == 0) {
          ElMessage.success("添加成功");
          this.getConfigFileList();
          this.addConfigFileVisible = false;
        } else {
          //alert("添加失败");
          ElMessage.error("添加失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async updateConfigShellInfo() {
      let result = {};
      try {
        let d={}
        // for (var key in this.ConfigShellUpdateForm) {
        //   d[key] = this.ConfigShellUpdateForm[key];
        // }
        let req = {
          token: this.tokenData.token,
          shells: [{"id":this.ConfigShellUpdateForm.ID,"shell_result":this.ConfigShellUpdateForm.ShellResult,"status":this.ConfigShellUpdateForm.Status}],
        };
        result = await updateConfigShellService(req);
        if (result.code === 0) {
          ElMessage.success("更新成功");
          this.updateDialogVisible = false;
        } else {
          ElMessage.error("更新失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async deleteConfigFile(index) {
      // 是否删除
      let isDelete = confirm("是否删除?");
      if (!isDelete) {
        return;
      }
      // alert("删除 index: " + index);
      // return ;
      let is_delete_file = confirm("是否删除文件?");

      let result = {};
      try {
        let req = {
          token: this.tokenData.token,
          id: this.ConfigFileCurrentPageData[index].ID,
          del_file: is_delete_file,
        };
        result = await deleteConfigFileService(req);
        if (result.code == 0) {
          ElMessage.success("删除成功");
          this.getConfigFileList();
        } else {
          ElMessage.error("删除失败");
        }
      } catch (e) {
        console.log(e);
      }
    },
    async updateConfigShell(index) {
      //console.log("index:", index);
      let cf = this.ConfigFileCurrentPageData[index];
    //   console.log("cf:", cf);
    //   let req = {
    //     token: this.tokenData.token,
    //     id: cf.ID,
    //     type: "one",
    //   };
    //   let result = await getConfigShellListService(req);
    //   let data = result.data;
      this.ConfigShellUpdateForm = cf;
      this.updateDialogVisible = true;
    },
    async createAgain(index) {
      let cf = this.ConfigFileCurrentPageData[index];
      this.addForm.shell_name = cf.ShellName;
      this.addForm.shell_content = cf.ShellContent;
      this.addForm.server = cf.Server;

      await this.addConfigFile();

    },

    onSubmit() {
      getConfigFileList();
    },
    currentPageData() {
      this.ConfigFileCurrentPageData = this.tableData.slice(
        (this.currentPage - 1) * this.pageSize,
        this.currentPage * this.pageSize
      );
    },
    handleSizeChange(val) {
      //console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPageData();
    },
    handleCurrentChange(val) {
      //console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.currentPageData();
    },

    async displayMyInfo() {
      await this.getMyUserInfo(this.tokenData.user_id);
      this.updateDialogVisible = true;
    },
    async displayUserInfo(id) {
      await this.getMyUserInfo(id);
      this.updateDialogVisible = true;
    },

    handleMenuSelect(val) {
      router.push(val);
    },
    toVideoList() {
      router.push("/videoList");
    },
    // 修改条纹颜色
    tableRowClassName({ row, rowIndex }) {
      switch (row.Status) {
            case 0:
            return 'rgba(243, 243, 248, 0.1)'; // 浅蓝色
            case 1:
            return 'rgba(0, 0, 255, 0.5)'; // 中等深度蓝色
            case 2:
            return 'rgba(0, 0, 255, 0.9)'; // 深蓝色
            default:
            return 'transparent'; // 默认透明
        }
    },
  },

  // 生命周期钩子会在组件生命周期的各个不同阶段被调用
  // 例如这个函数就会在组件挂载完成后被调用
  async mounted() {
    let now = new Date();
    if (localStorage.getItem("token") === null) {
      router.push("/login");
    }
    await this.getConfigFileList();
    //await this.getMyUserInfo(localStorage.getItem("userId"));
  },
};
</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)"
        >命令分发</el-header
      >
      <el-container>
        <el-main>
          <el-form :inline="true" :model="tokenData" class="demo-form-inline">
            <el-form-item>
              <el-dialog
                v-model="updateDialogVisible"
                title="编辑配置"
                width="60%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="updateFormRef"
                  :model="ConfigShellUpdateForm"
                  :rules="UserUpdateFormRules"
                  label-width="70px"
                >
                  <!-- row -->
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="ID">
                        <el-input
                          v-model="ConfigShellUpdateForm.ID"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="名称">
                        <el-input
                          v-model="ConfigShellUpdateForm.ShellName"
                          disabled
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="32">
                      <el-form-item label="内容">
                        <el-input
                          v-model="ConfigShellUpdateForm.ShellContent"
                          disabled
                          type="textarea"
                          style="width: 512px"
                        ></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col>
                      <el-form-item label="运行结果" prop="shell_result">
                        <el-input
                          type="textarea"
                          v-model="ConfigShellUpdateForm.ShellResult"
                          style="width: 600px"
                          :autosize="{ minRows: 4, maxRows: 8 }"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="updateConfigShellInfo()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>

            <!-- 表单 -->
            <el-form :inline="true" :model="tokenData" class="demo-form-inline">
              <el-form-item>
                <el-button
                  class="el-button--danger"
                  type="primary"
                  @click="getConfigFileList()"
                  >查询</el-button
                >
              </el-form-item>
              <el-form-item>
                <el-button
                  class="el-button--danger"
                  type="primary"
                  @click="addConfigFileV()"
                  >创建命令</el-button
                >
              </el-form-item>
            </el-form>
          </el-form>

          <el-dialog
            v-model="addConfigFileVisible"
            title="创建命令"
            width="50%"
            :before-close="handleClose"
          >
            <!-- 内容主体区域 -->
            <el-form
              ref="addFormRef"
              :model="addForm"
              :rules="addFormRules"
              label-width="70px"
            >
              <el-row>
                <el-form-item label="名称" prop="shell_name">
                  <el-input
                    v-model="addForm.shell_name"
                    autocomplete="on"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="内容" prop="file_path">
                  <el-input
                    type="textarea"
                    v-model="addForm.shell_content"
                    autocomplete="on"
                    style="width: 600px"
                    :autosize="{ minRows: 4, maxRows: 8 }"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label="服务器" prop="server">
                  <el-select v-model="addForm.server">
                      <el-option label="家里服务器" value="home_server">家里服务器</el-option>
                      <el-option label="腾讯服务器" value="tx_vp_server">腾讯服务器</el-option>
                    </el-select>
                </el-form-item>
              </el-row>
            </el-form>
            <!-- 底部区域 -->
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="addConfigFileVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click="addConfigFile()"
                  >确定</el-button
                >
              </span>
            </template>
          </el-dialog>

          <!-- 表格  :row-style="this.tableRowClassName"-->
          <el-table :data="ConfigFileCurrentPageData" width="100%" border>
            :row-style="tableRowClassName"
            <el-table-column prop="ID" label="id" width="80"></el-table-column>
            <el-table-column
              prop="ShellName"
              label="命令名称"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="ShellContent"
              label="命令内容"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="Status"
              label="状态"
              width="40"
            ></el-table-column>
            <el-table-column
              prop="Server"
              label="服务器"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="CreatedAt"
              label="创建时间"
              width="160"
            ></el-table-column>
            <el-table-column
              prop="UpdatedAt"
              label="上次更新"
              width="160"
            ></el-table-column>
            <el-table-column
              prop="AuthID"
              label="创建用户ID"
              width="40"
            ></el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="updateConfigShell(scope.$index)"
                  >编辑</el-button
                >
                <!-- <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="deleteConfigFile(scope.$index)"
                  >删除</el-button
                > -->
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="createAgain(scope.$index)"
                  >再次执行</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页条 -->
          <!-- Pagination 分页 -->
          <el-pagination
            background
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="tableData.length"
          ></el-pagination>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<style>
.blueRowbg {
  background: "#488aff";
}
</style>