<script>
import axios from "axios";
import { inject } from "vue";
import { getCIDListService } 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";

import {ElMessage, ElLoading} from "element-plus";

export default {
  data() {
    return {
      ip: "",
      tableData: [],
      tokenData: {
        server:"gep.ljsea.xyz",
        token: localStorage.getItem("token"),
        ip: localStorage.getItem("ip"),
        userId: localStorage.getItem("userId"),
        username: localStorage.getItem("username"),
      },
      addDialogVisible: false,
      updateDialogVisible: false,
      searchForm: {
        hour: 0,
        entrydate: [],
      },
      addForm: {
        name: "",
        time: 0,
        url: "",
        script: "",
        token: localStorage.getItem("token"),
      },
      updateForm: {
        id:0,
        cidtoken:"",
        name: "",
        time:0,
        url: "",
        script: "",
        auth_id: -1,
        token: localStorage.getItem("token"),
      },
    };
  },

  // methods 是一些用来更改状态与触发更新的函数
  // 它们可以在模板中作为事件处理器绑定
  methods: {
    async getDeviceList() {
      const loading = ElLoading.service({
        lock: true,
        text: '加载中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      let result = {};
      try {
        result = await getCIDListService(this.tokenData);
        let data = result.data;
        this.tableData = data;
      } catch (e) {
        console.log(e);
      } finally {
        loading.close();
      }
    },
    onSubmit() {
      getDeviceList({ token: token });
    },
    handleSizeChange() {
      alert("每页记录数变化" + val);
    },
    handleCurrentChange() {
      alert("页码发生变化" + val);
    },

    //设置项目执行构建部署
    async runCID(index) {
      const loading = ElLoading.service({
        lock: true,
        text: '执行中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        var id = this.tableData[index].ID;
        var run_data = {
          id: id,
          ip: this.ip,
          userId: this.tokenData.userId,
          token: this.tokenData.token,
        };
        var d_re = await runCIDService(run_data);
        if (d_re.code == 0) {
          ElMessage.success("操作成功");
        } else {
          ElMessage.error("操作失败");
        }
      } catch (e) {
        console.log(e);
      } finally {
        loading.close();
      }
    },
    toRunCIDLog(index) {
      var id = this.tableData[index].ID;
      localStorage.setItem("cid_id", id);
      router.push("/cidlog");
    },
    async deleteCID(index) {
      //判断是否删除
      if (!confirm("是否删除")) {
        return;
      }
      
      const loading = ElLoading.service({
        lock: true,
        text: '删除中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        var id = this.tableData[index].ID;
        var delete_data = {
          id: id,
          userId: this.tokenData.userId,
          token: this.tokenData.token,
        };
        var d_re = await deleteCIDService(delete_data);
        if (d_re.code == 0) {
          ElMessage.success("删除成功");
          //刷新页面
          this.getDeviceList();
        } else {
          ElMessage.error("操作失败");
        }
      } catch (e) {
        console.log(e);
      } finally {
        loading.close();
      }
    },
    async updateButtonCID(index) {
      var id = this.tableData[index].ID;
      this.updateForm.name = this.tableData[index].Name;
      this.updateForm.url = this.tableData[index].Url;
      this.updateForm.script = this.tableData[index].Script;
      this.updateForm.time = this.tableData[index].Time;
        this.updateForm.cidtoken = this.tableData[index].Token;
      this.updateForm.id = id;
      this.updateDialogVisible= true;
    },
    async addCID() {
      this.addDialogVisible = false;
      const loading = ElLoading.service({
        lock: true,
        text: '添加中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      let result = {};
      try {
        result = await addCIDService(this.addForm);
        if (result.code == 0) {
          ElMessage.success("添加成功");
          this.getDeviceList()
        } else {
          ElMessage.error("添加失败");
        }
      } catch (e) {
        console.log(e);
      } finally {
        loading.close();
      }
    },
    async updateCID() {
      this.updateDialogVisible = false;
      const loading = ElLoading.service({
        lock: true,
        text: '更新中',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      let result = {};
      try {
        result = await updateCIDService(this.updateForm);
        if (result.code == 0) {
          ElMessage.success("修改成功");
          this.getDeviceList()
        } else {
          ElMessage.error("修改失败");
        }
      } catch (e) {
        console.log(e);
      } finally {
        loading.close();
      }
    },
    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);
      }
    },
    handleServerChange(){
      localStorage.setItem("cid_server", this.tokenData.server);
      this.getDeviceList()
    },
    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.getDeviceList();
  },
};
</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-button
                class="el-button--danger"
                type="primary"
                @click="getDeviceList()"
                >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addDialogVisible = true"
                >添加集成项目</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-select v-model="tokenData.server" @change="handleServerChange">
                <el-option label="gep.ljsea.xyz" value="gep.ljsea.xyz">gep.ljsea.xyz</el-option>
                <el-option label="tx.ljsea.top" value="tx.ljsea.top">tx.ljsea.top</el-option>
                <el-option label="js.ljsea.top" value="js.ljsea.top">阿里云新加坡</el-option>
              </el-select>

            </el-form-item>

            <el-form-item>
              <el-dialog
                v-model="addDialogVisible"
                title="添加集成项目"
                width="50%"
                :before-close="handleClose"
              >
                <!-- 内容主体区域 -->
                <el-form
                  ref="addFormRef"
                  :model="addForm"
                  :rules="addFormRules"
                  label-width="70px"
                >
                  <el-form-item label="项目名称" prop="device_name">
                    <el-input
                      v-model="addForm.name"
                      autocomplete="on"
                      style="width: 600px" 
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="仓库地址" prop="device_ip">
                    <el-input v-model="addForm.url"  style="width: 600px" autocomplete="on"></el-input>
                  </el-form-item>
                  <el-form-item label="定时执行时间" prop="time">
                    <el-select v-model="addForm.time">
                        <el-option label="30s" value="30"></el-option>
                        <el-option label="1分钟" value="60"></el-option>
                        <el-option label="1小时" value="3600"></el-option>
                        <el-option label="1天" value="86400"></el-option>
                    </el-select>
                    自定义时间：
                    <el-input type="textarea" v-model="addForm.time" autocomplete="on" style="width: 600px" />
                  </el-form-item>
                  <el-form-item label="脚本内容" prop="device_status">
                    <el-input type="textarea" v-model="addForm.script" style="width: 600px" :autosize="{ minRows: 4, maxRows: 8 }" />
                  </el-form-item>
                  
                </el-form>
                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="addDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="addCID()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </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="device_name">
                    <el-input
                      v-model="updateForm.name"
                      autocomplete="on"
                      style="width: 600px" 
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="仓库地址" prop="device_ip">
                    <el-input v-model="updateForm.url"  style="width: 600px" autocomplete="on"></el-input>
                  </el-form-item>
                  <el-form-item label="脚本内容" prop="device_status">
                    <el-input type="textarea" v-model="updateForm.script" style="width: 600px" :autosize="{ minRows: 4, maxRows: 8 }" />
                  </el-form-item>
                  <el-form-item label="外部回调Token" prop="device_status">
                    <el-input v-model="updateForm.cidtoken" style="width: 600px" />
                    回调地址：https://{{tokenData.server}}/cid/callback?token={{updateForm.cidtoken}}&id={{updateForm.id}}
                  </el-form-item>

                  <el-form-item label="定时执行时间" prop="time">
                    <el-select v-model="updateForm.time">
                        <el-option label="30s" value="30"></el-option>
                        <el-option label="1分钟" value="60"></el-option>
                        <el-option label="1小时" value="3600"></el-option>
                        <el-option label="1天" value="86400"></el-option>
                    </el-select>
                    自定义时间：
                    <el-input type="textarea" v-model="updateForm.time" autocomplete="on" style="width: 600px" />
                  </el-form-item>
                </el-form>
                <!-- 底部区域 -->
                <template #footer>
                  <span class="dialog-footer">
                    <el-button @click="updateDialogVisible = false"
                      >取消</el-button
                    >
                    <el-button type="primary" @click="updateCID()"
                      >确定</el-button
                    >
                  </span>
                </template>
              </el-dialog>
            </el-form-item>
          </el-form>

          <!-- 表格  :row-style="this.tableRowClassName"-->
          <el-table :data="tableData" width="100%" border>
            :row-style="this.tableRowClassName"
            <el-table-column prop="ID" label="id" width="80"></el-table-column>
            <el-table-column
              prop="Name"
              label="名称"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="Url"
              label="仓库地址"
              width="180"
            ></el-table-column>
            <el-table-column
              prop="Script"
              label="脚本消息"
              show-overflow-tooltip
              width="250"
            ></el-table-column>
            <el-table-column
              prop="Token"
              label="回调Token"
              show-overflow-tooltip
              width="100"
            ></el-table-column>
            <el-table-column label="操作" width="350">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="runCID(scope.$index)"
                  >运行</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="updateButtonCID(scope.$index)"
                  >修改</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="deleteCID(scope.$index)"
                  >删除</el-button
                >
                <el-button
                  type="primary"
                  size="mini"
                  @click.prevent="toRunCIDLog(scope.$index)"
                  >运行日志</el-button
                >
                <!-- <el-button type="danger" size="mini">删除</el-button> -->
              </template>
            </el-table-column>
          </el-table>
          <br />

          <!-- 分页条 -->
          <!-- Pagination 分页 -->
          <!-- <el-pagination
            background
            layout="total,sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :total="1000"
          ></el-pagination> -->
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<style>
.blueRowbg {
  background: "#488aff";
}
</style>