<template>
  <div class="content-box">
    <div class="left">
      <!-- <el-icon :size="23" class="camera"><VideoCameraFilled /></el-icon> -->
      <span class="cameratxt">我的数据源</span>
    </div>
    <div class="scroll">
      <div class="middle">
        <div class="search-manager">
          <div class="filter">
            <div class="condition">
              <el-select v-model="searchInput.dsClassValue" class="sel" placeholder="数据库类型" clearable
                @clear="searchBtn">
                <el-option v-for="item in dsClass.list" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <el-select v-model="searchInput.connectStatus" class="sel" placeholder="连接状态" clearable
                @clear="searchBtn">
                <el-option label="正常" value="1" />
                <el-option label="异常" value="0" />
              </el-select>
              <el-input :clearable="true" @clear="searchBtn" v-model="searchInput.keyWord" class="sel"
                placeholder="数据源名称" />
            </div>
            <el-button color="rgba(0, 97, 255, 1)" type="primary" class="search" @click="searchBtn">
              <el-icon>
                <Search />
              </el-icon>
              <span>查询</span>
            </el-button>
          </div>
          <div>
            <el-button type="primary" color="rgba(0, 97, 255, 1)" plain @click="managerDSClass">数据源类别管理</el-button>
          </div>
        </div>
        <!-- 按钮列表 -->
        <div class="gongneng">
          <el-button type="primary" color="rgba(0, 97, 255, 1)" plain @click="addClick">新增</el-button>
          <!-- <el-button type="primary" color="rgba(0, 97, 255, 1)" plain @click="editClick">编辑</el-button>
          <el-button type="primary" color="rgba(0, 97, 255, 1)" @click="delClick" plain>删除</el-button> -->
        </div>
      </div>
      <div class="footer" v-loading="loading">
        <el-table :row-class-name="tableRowClassName" :data="tableData.list" style="width: 100%" :header-cell-style="{
          background: 'rgba(240, 243, 247, 1)',
          height: '50px',
          border: 0,
        }">
          <!-- <el-table-column align="center" type="selection" width="80" /> -->
          <el-table-column align="center" prop="dsClsName" label="类型" />
          <el-table-column align="center" prop="dsName" label="名称" />
          <el-table-column align="center" prop="dsUrl" width="390" label="连接地址" />
          <el-table-column align="center" prop="dsStatus" width="60" label="连接状态">
            <template #default="scope">
              <span v-if="scope.row.dsStatus == 1" class="normal">正常</span>
              <span v-else class="abnormal">异常</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="dsDescrition" label="描述">
          </el-table-column>
          <el-table-column align="center" prop="dsCreateTime" label="创建时间" width="150">
            <template #default="{ row }">
              <span>{{
                dayjs(row.dsCreateTime).format("YYYY-MM-DD HH:mm:ss")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="dsUpdateTime" label="修改时间" width="150"><template #default="{ row }">
              <span>{{
                dayjs(row.dsUpdateTime).format("YYYY-MM-DD HH:mm:ss")
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template #default="scope">
              <div class="edit">
                <div class="look" @click="editClick(scope.row)">编辑</div>
                <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" icon-color="#f89626"
                  title="是否删除此数据源?" @confirm="deleteClick(scope.row)">
                  <template #reference>
                    <div class="del">删除</div>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页组件 -->
      <div class="pageSize">
        <div></div>
        <el-pagination background :current-page="tableCurrentPage" :page-size="tablePageSize"
          layout="total, prev, pager, next, jumper, slot" :total="tableTotal"
          @update:current-page="handleCurrentChange" />
      </div>

      <!-- 新增/编辑对话框 -->
      <el-dialog class="editDialog" v-model="editVisible" :close-on-click-modal="false" :close-on-press-escape="false"
        :title="titleDialog" align-center width="900" :before-close="cancelEdit" :show-close="false">
        <el-form ref="editRef" :model="editRuleForm" :rules="editRules" label-width="100px" class="demo-ruleForm"
          :size="formSize" label-position="right" status-icon v-loading.fullscreen.lock="dialog_loading"
          element-loading-text="正在验证数据源有效性，请等待...">
          <el-form-item label="类型 :" prop="dsClsId">
            <el-select v-model="editRuleForm.dsClsId" placeholder="请选择类型" style="width: 740px" clearable>
              <el-option v-for="item in dsClass.list" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="名称 :" prop="dsName">
            <el-input v-model="editRuleForm.dsName" placeholder="数据源名称" clearable style="width: 740px" />
          </el-form-item>
          <div v-if="titleDialog == '新增'" style="display: flex; justify-content: space-between">
            <!-- <span class="typeTitle">使用辅助选项请先选择类型</span> -->
            <el-form-item label="辅助选项 :" prop="ip">
              <el-input v-model="editRuleForm.ip" placeholder="数据库服务IP地址" clearable @keyup="paramsChange"
                @blur="paramsChange" @clear="paramsChange" ref="inputRef" maxlength="15" />
            </el-form-item>
            <el-form-item label="端口：" prop="port" style="width: 270px">
              <el-input v-model="editRuleForm.port" placeholder="数据库服务端口号" clearable @keyup="paramsChange"
                @blur="paramsChange" @clear="paramsChange" maxlength="5" />
            </el-form-item>
            <el-form-item label="数据库名称：" prop="dbname" :label-width="'130px'" style="width: 270px">
              <el-input v-model="editRuleForm.dbname" placeholder="数据库名称" clearable @keyup="paramsChange"
                @blur="paramsChange" @clear="paramsChange" maxlength="32" />
            </el-form-item>
          </div>
          <el-form-item label="连接地址 :" prop="dsUrl">
            <el-input v-model="editRuleForm.dsUrl" placeholder="数据库连接地址" :disabled="isDisabled" clearable
              style="width: 740px" />
          </el-form-item>
          <div class="account">
            <el-form-item label="数据库账号 :" prop="dsUser">
              <el-input v-model="editRuleForm.dsUser" placeholder="请输入数据库账号" clearable maxlength="32" />
            </el-form-item>
            <el-form-item label="数据库密码 :" prop="dsPassword">
              <el-input v-model="editRuleForm.dsPassword" placeholder="请输入数据库密码" clearable maxlength="32"
                type="password" />
            </el-form-item>
          </div>
          <el-form-item label="描述 :" prop="dsDescrition">
            <el-input v-model="editRuleForm.dsDescrition" placeholder="请输入该数据库相关简述" clearable type="textarea" :rows="5"
              maxlength="150" show-word-limit style="width: 740px" />
          </el-form-item>
          <el-form-item class="options">
            <el-button color="rgba(41, 109, 227, 1)" class="queding" type="primary"
              @click="confirmEdit(editRef)">确认</el-button>
            <el-button @click="cancelEdit(editRef)">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>

      <!-- 数据源类别管理对话框 -->
      <el-dialog v-model="managerDialogVisible" :row-class-name="tableRowClassName" align-center width="1000"
        title="数据源类别管理" :close-on-click-modal="false" :close-on-press-escape="false" @close="getDsClass"
        class="manager">
        <div>
          <div style="
              display: flex;
              justify-content: space-between;
              margin-bottom: 20px;
            ">
            <el-button type="primary" color="rgba(0, 97, 255, 1)" @click="dsAddModifyClass">增加</el-button>
            <el-input v-model="dsClassSearch" @change="dsClassNameSearch" @keyup.enter="dsClassNameSearch" size="small"
              placeholder="搜索数据源类别名称" style="width: 180px" clearable />
          </div>
          <el-table :data="dsClassTableData.list" stripe style="width: 100%; height: 450px;" v-loading="dsClassLoading"
            element-loading-text="加载中..." :header-cell-style="{
              background: 'rgba(240, 243, 247, 1)',
              height: '50px',
              border: 0,
            }">
            <el-table-column prop="dsClsName" label="数据源类别名称" width="180" align="center" />
            <el-table-column prop="dsClsDriver" label="数据源驱动" width="280" align="center" />
            <el-table-column prop="dsClsCreateTime" width="180" label="创建时间" align="center">
              <template #default="{ row }">
                <span>{{
                  dayjs(row.dsClsCreateTime).format("YYYY-MM-DD HH:mm:ss")
                }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="dsClsUpdateTime" width="180" label="修改时间" align="center">
              <template #default="{ row }">
                <span>{{
                  dayjs(row.dsClsUpdateTime).format("YYYY-MM-DD HH:mm:ss")
                }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" width="120" label="操作">
              <template #default="scope">
                <div style="display: flex">
                  <el-button size="small" @click="dsClassEditRow(scope.row)">编辑</el-button>
                  <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" icon-color="#f89626"
                    title="是否删除此数据源类别?" @confirm="dsClassDeleteRow(scope.row)">
                    <template #reference>
                      <el-button size="small" type="danger">删除</el-button>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div class="pageSize">
            <span></span>
            <el-pagination background :current-page="dsClassCurrentPage" :page-size="dsClassPageCount"
              layout="total, prev, pager, next, jumper, slot" :total="dsClassTableTotal"
              @update:current-page="handleCurdsClassCurrentPageChangerentChange" style="margin: 20px 0" />
          </div>
        </div>
      </el-dialog>

      <!-- 新增/编辑 数据源类别 -->
      <el-dialog v-model="managerAddModifyDialogVisible" :row-class-name="tableRowClassName" :title="dsAddModifyTitle"
        :close-on-click-modal="false" :close-on-press-escape="false" width="30%" top="18vh" class="editDialog">
        <el-form ref="dsClassForm" :model="dsAddModifyRuleForm" :rules="dsAddModifyRules" label-width="100px"
          class="demo-ruleForm" :size="formSize" label-position="right" status-icon>
          <el-form-item label="名称 :" prop="dsClsName">
            <el-input v-model="dsAddModifyRuleForm.dsClsName" maxlength="64" placeholder="数据源类别名称" clearable
              style="width: 740px" />
          </el-form-item>
          <el-form-item label="驱动 :" prop="dsClsDriver">
            <el-input v-model="dsAddModifyRuleForm.dsClsDriver" maxlength="128" placeholder="数据源驱动" clearable
              style="width: 740px" />
          </el-form-item>
          <el-form-item class="options">
            <el-button color="rgba(41, 109, 227, 1)" class="queding" type="primary"
              @click="dsAddModifyConfirmEdit(dsClassForm)">确认</el-button>
            <el-button @click="dsAddModifyCancelEdit(dsClassForm)">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  watch,
  nextTick,
  onBeforeMount,
  onUnmounted,
} from "vue";
// import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import eds from "@/utils/eds.js";
// import { Calendar } from "@element-plus/icons-vue";
// import vidiconsApi from "@/api/vidicons.js";
import { dayjs } from "element-plus";
import lodash from "lodash";
import axios from "axios";
import { useStore } from "vuex";

// 数据================================
const store = useStore();
const api = ref("");
// const router = useRouter();
const loading = ref(false);

// 页面中数据源类别下拉列表参数
const dsClass = reactive({
  list: [],
});
const dsClassTableData = reactive({
  list: [],
});

const searchInput = reactive({
  dsClassValue: "",
  connectStatus: "", // 是否数据源连接状态
  keyWord: "",
}); // 搜索按钮数据

// 编辑功能
const titleDialog = ref("");
const editVisible = ref(false);
const isDisabled = ref(true);
const editRef = ref();
const editRuleForm = reactive({
  dsId: "", // 数据源id
  dsClsId: "", // 数据源类型id
  dsName: "", // 数据源名称
  dsUrl: "", // 数据库连接地址
  dsUser: "", // 数据库账号
  dsPassword: "", // 数据库密码
  dsDescrition: "", // 描述
  ip: "", // 数据库服务IP地址
  port: "", // 数据库服务端口号
  dbname: "", // 数据库名称
});

const inputRef = ref(null);

// 表单验证
const editRules = reactive({
  dsClsId: [
    {
      required: true,
      message: "类型不能为空",
      trigger: "blur",
    },
  ],
  dsName: [
    {
      required: true,
      message: "数据源名称不能为空",
      trigger: "blur",
    },
  ],
  dsUrl: [
    {
      required: true,
      message: "数据库连接地址不能为空",
      trigger: "blur",
    },
  ],
  dsUser: [
    {
      required: true,
      message: "数据库账号不能为空",
      trigger: "blur",
    },
  ],
  dsPassword: [
    {
      required: true,
      message: "数据库密码不能为空",
      trigger: "blur",
    },
  ],
  dsDescrition: [
    {
      required: true,
      message: "描述不能为空",
      trigger: "blur",
    },
  ],
  ip: [
    {
      required: true,
      message: "ip不能为空",
      trigger: "blur",
    },
    {
      // pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/,
      pattern:
        /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: "请输入正确的IP地址",
      trigger: "blur",
    },
  ],
  port: [
    {
      required: true,
      message: "端口不能为空",
      trigger: "blur",
    },
    {
      pattern:
        /^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-3][0-9]|6553[0-5])$/,
      message: "端口号只能是：0到65535",
      trigger: "blur",
    },
    {
      pattern:
        /^([0-9]{1,4}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-3][0-9]|6553[0-5])$/,
      message: "端口号只能是：0到65535",
      trigger: "change",
    },
  ],
  dbname: [
    {
      required: true,
      message: "数据库名称不能为空",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z0-9_]+$/,
      message: "数据库名称只能包含字母、数字和下划线",
      trigger: "blur",
    },
  ],
});

// 编辑数据库类别对话框
const dsClassLoading = ref(false);
const dsClassSearch = ref("");
const managerDialogVisible = ref(false); // 数据源类别对话框的显示隐藏
const managerAddModifyDialogVisible = ref(false); // 新增数据源类别对话框的显示隐藏
const dsClassForm = ref();
const dsAddModifyTitle = ref("");
const dsAddModifyRuleForm = reactive({
  dsClsName: "", // 数据源类别名称
  dsClsDriver: "", // 数据源类别驱动
});
const dsAddModifyRules = reactive({
  dsClsName: [
    {
      required: true,
      message: "数据源类别名称不能为空",
      trigger: "blur",
    },
  ],
  dsClsDriver: [
    {
      required: true,
      message: "数据库类别驱动不能为空",
      trigger: "blur",
    },
    {
      pattern: /^[a-zA-Z\.]+$/,
      message: "数据库名称只能包含字母和点(.)",
      trigger: "blur",
    },
  ],
});
const dsClassTableTotal = ref(0);
const dsClassCurrentPage = ref(1);
const dsClassPageCount = ref(10);
// 查询数据源类别
const managerDSClass = async () => {
  managerDialogVisible.value = true;
  dsClassLoading.value = true;
  let data = {
    currentPage: dsClassCurrentPage.value,
    pageCount: dsClassPageCount.value,
    name: dsClassSearch.value, // 数据源类别名称
    managerId: sessionStorage.getItem("token"),
  };
  let res = await axios({
    method: "get",
    url: api.value + "/wanzai/api/smartDataClass/queryPageSmartDataClass",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  // console.log(res, "数据源类别");
  if (res.data.code == 200) {
    dsClassLoading.value = false;
    dsClassTableData.list = JSON.parse(eds.decryptDes(res.data.data)).list;
    dsClassTableTotal.value = JSON.parse(
      eds.decryptDes(res.data.data)
    ).totalCount;
  } else {
    dsClassLoading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 数据源类别分页
const dsClassCurrentPageChange = (val) => {
  dsClassCurrentPage.value = val;
  managerDSClass();
};

// 编辑数据源类别
const dsClassEditRow = (row) => {
  dsAddModifyTitle.value = "编辑数据源类别";
  managerAddModifyDialogVisible.value = true;

  dsAddModifyRuleForm.dsClsId = row.dsClsId;
  dsAddModifyRuleForm.dsClsName = row.dsClsName;
  dsAddModifyRuleForm.dsClsDriver = row.dsClsDriver;
};
// 删除数据源类别
const dsClassDeleteRow = async (row) => {
  let data = {
    id: row.dsClsId, // 需要删除的id
  };
  let res = await axios({
    method: "get",
    url: api.value + "/wanzai/api/smartDataClass/deleteSmartDataClassById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  // console.log(res, "删除数据源类别");
  if (res.data.code == 200) {
    managerDSClass();
  } else {
    dsClassLoading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 数据源类别填充下拉列表
const getDsClass = async () => {
  let data = {
    currentPage: 1,
    pageCount: 100,
    managerId: sessionStorage.getItem("token"),
  };
  let res = await axios({
    method: "get",
    url: api.value + "/wanzai/api/smartDataClass/queryPageSmartDataClass",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  // console.log(res, "数据源类别");
  if (res.data.code == 200) {
    dsClass.list = [];
    JSON.parse(eds.decryptDes(res.data.data)).list.forEach((item) => {
      dsClass.list.push({
        label: item.dsClsName,
        value: item.dsClsId,
      });
    });
  } else {
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 新增/编辑 数据源类别操作
const dsAddModifyConfirmEdit = (dsClassFormEl) => {
  if (!dsClassFormEl) return;
  dsClassFormEl.validate(async (valid, fields) => {
    if (valid) {
      let data = {
        dsClsName: dsAddModifyRuleForm.dsClsName,
        dsClsDriver: dsAddModifyRuleForm.dsClsDriver,
        managerId: sessionStorage.getItem("token"),
      };
      let url = "insertSmartDataClass";
      if (dsAddModifyTitle.value == "编辑数据源类别") {
        url = "updateSmartDataClassById";
        data.dsClsId = dsAddModifyRuleForm.dsClsId;
      }
      let res = await axios({
        method: "post",
        url: api.value + "/wanzai/api/smartDataClass/" + url,
        headers: {
          token: sessionStorage.getItem("token"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data,
      });
      // console.log(res, "数据源类别");
      if (res.data.code == 200) {
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.message,
          center: true,
        });
        dsAddModifyCancelEdit();
        managerDSClass();
        // getDsClass();
      } else {
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    }
  });
};

// 新增数据源类别对话框按钮的点击事件
const dsAddModifyClass = () => {
  managerAddModifyDialogVisible.value = true;
  dsAddModifyTitle.value = "新增数据源类别";
  dsClassForm.dsClsName = "";
  dsClassForm.dsClsDesc = "";
};

// 查询数据源类别
const dsClassNameSearch = () => {
  dsClassCurrentPage.value = 1;
  managerDSClass();
};

// 新增数据源类别取消按钮
const dsAddModifyCancelEdit = () => {
  managerAddModifyDialogVisible.value = false;
  dsAddModifyClearEditFormData();
};

// 数据源类别添加成功了，清理数据
const dsAddModifyClearEditFormData = () => {
  dsAddModifyRuleForm.dsClsName = "";
  dsAddModifyRuleForm.dsClsDriver = "";
};

// 数据源类别分页
const handleCurdsClassCurrentPageChangerentChange = (value) => {
  // console.log(value);
  dsClassCurrentPage.value = value;
  managerDSClass();
};

// 数据源参数发生变化
const paramsChange = () => {
  if (editRuleForm.dsClsId == "") {
    ElMessage({
      type: "error",
      showClose: true,
      message: "请先选择数据库类型",
      center: true,
    });
    editRuleForm.ip = "";
    editRuleForm.port = "";
    editRuleForm.dbname = "";
    return;
  }

  if (
    editRuleForm.ip == "" &&
    editRuleForm.port == "" &&
    editRuleForm.dbname == ""
  ) {
    editRuleForm.dsUrl = "";
    return;
  }

  dsClass.list.forEach((item) => {
    if (item.value == editRuleForm.dsClsId) {
      if (item.label.toLowerCase().includes("mysql")) {
        editRuleForm.dsUrl =
          "jdbc:mysql://" +
          editRuleForm.ip +
          ":" +
          editRuleForm.port +
          "/" +
          editRuleForm.dbname;
      }
    }
  });
};

// 删除弹窗
const selDelVisible = ref(false);

// 表格数据
const tableData = reactive({
  list: [],
});
const tableCurrentPage = ref(1); // 当前页
const tablePageSize = ref(10); // 每页显示条数
const tableTotal = ref(0); // 当前总数
// 数据源列表
const getList = async () => {
  loading.value = true;
  let data = {
    currentPage: tableCurrentPage.value,
    pageCount: tablePageSize.value,
    dsClsId: searchInput.dsClassValue,
    dsName: searchInput.keyWord, // 数据源名称
    dsStatus: searchInput.connectStatus, // 数据源状态
    managerId: sessionStorage.getItem("token"),
  };
  let res = await axios({
    method: "get",
    url: api.value + "/wanzai/api/smartDataClass/queryPageSmartDataSource",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  // console.log(res, "数据源");
  if (res.data.code == 200) {
    loading.value = false;
    tableData.list = JSON.parse(eds.decryptDes(res.data.data)).list;
    tableTotal.value = JSON.parse(eds.decryptDes(res.data.data)).total || 0;
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
  }
};

// 数据源搜索功能
const searchBtn = lodash.debounce(async () => {
  getList();
}, 300);

// 添加（新增）按钮 （-------------------------------------------）
const addClick = async () => {
  titleDialog.value = "新增";
  editVisible.value = true;
  isDisabled.value = true;
  clearEditFormData();
};

const clearEditFormData = () => {
  editRuleForm.dsId = "";
  editRuleForm.dsClsId = "";
  editRuleForm.dsName = "";
  editRuleForm.dsUrl = "";
  editRuleForm.dsUser = "";
  editRuleForm.dsPassword = "";
  editRuleForm.dsDescrition = "";
  editRuleForm.ip = "";
  editRuleForm.port = "";
  editRuleForm.dbname = "";
};

// 编辑按钮  （-------------------------------------------）
const editClick = async (row) => {
  // console.log(row);
  titleDialog.value = "编辑";
  editVisible.value = true;
  isDisabled.value = false;
  // 表单赋值
  editRuleForm.dsId = row.dsId;
  editRuleForm.dsClsId = row.dsClsId;
  editRuleForm.dsName = row.dsName;
  editRuleForm.dsUrl = row.dsUrl;
  editRuleForm.dsUser = row.dsUser;
  editRuleForm.dsPassword = row.dsPassword;
  editRuleForm.dsDescrition = row.dsDescrition;
  editRuleForm.ip = row.ip;
  editRuleForm.port = row.port;
  editRuleForm.dbname = row.dbname;
};

// 删除按钮
const deleteClick = async (row) => {
  // console.log(row);
  loading.value = true;
  let data = {
    id: row.dsId,
  };
  let res = await axios({
    method: "get",
    url: api.value + "/wanzai/api/smartDataClass/deleteSmartDataSourceById",
    headers: {
      token: sessionStorage.getItem("token"),
      user_head: sessionStorage.getItem("userhead"),
    },
    params: data,
  });
  // console.log(res, "删除数据源");
  if (res.data.code == 200) {
    loading.value = false;
    editVisible.value = false;
    getList();
    ElMessage({
      type: "success",
      showClose: true,
      message: res.data.message,
      center: true,
    });
    cancelEdit();
  } else {
    loading.value = false;
    ElMessage({
      type: "error",
      showClose: true,
      message: res.data.message,
      center: true,
    });
    cancelEdit();
  }
};

// 新增数据源取消按钮
const cancelEdit = () => {
  editVisible.value = false;
  editRef.value.resetFields();
  clearEditFormData();
};

// 添加（新增）、编辑窗口的确定按钮事件
const dialog_loading = ref(false);
const confirmEdit = (formEl) => {
  if (!formEl) return;
  formEl.validate(async (valid, fields) => {
    dialog_loading.value = true;
    if (valid) {
      let data = {
        dsClsId: editRuleForm.dsClsId,
        dsName: editRuleForm.dsName,
        dsUrl: editRuleForm.dsUrl,
        dsUser: editRuleForm.dsUser,
        dsPassword: editRuleForm.dsPassword,
        dsDescrition: editRuleForm.dsDescrition,
      };
      let url = "insertSmartDataSource";
      if (titleDialog.value == "编辑") {
        url = "updateSmartDataSourceById";
        data.dsId = editRuleForm.dsId;
      }
      let res = await axios({
        method: "post",
        url: api.value + "/wanzai/api/smartDataClass/" + url,
        headers: {
          token: sessionStorage.getItem("token"),
          user_head: sessionStorage.getItem("userhead"),
        },
        data,
      });
      // console.log(res, "添加/修改数据源");
      if (res.data.code == 200) {
        dialog_loading.value = false;
        getList();
        ElMessage({
          type: "success",
          showClose: true,
          message: res.data.data,
          center: true,
        });
        cancelEdit();
      } else {
        dialog_loading.value = false;
        ElMessage({
          type: "error",
          showClose: true,
          message: res.data.message,
          center: true,
        });
      }
    }
  });
};

//删除按钮
const delClick = async () => {
  selDelVisible.value = true;
};

// const cancelSelDel = () => {
//   selDelVisible.value = false;
// };

// 表格斑马纹颜色修改
const tableRowClassName = ({ row, rowIndex }) => {
  if (rowIndex % 2 === 0) {
    return "even";
  } else if (rowIndex % 2 !== 0) {
    return "odd";
  }
  return "";
};

// 数据源分页
const handleCurrentChange = (value) => {
  // console.log(value);
  tableCurrentPage.value = value;
  getList();
};

// 挂载前钩子
onBeforeMount(async () => {
  api.value = store.state.user.api;
  getList();
  getDsClass();
});

// 卸载钩子
onUnmounted(() => {
  // document.removeEventListener("keyup", Enters);
});
</script>

<style scoped lang="scss">
.content-box {
  min-width: 1000px;
  width: calc(100vw - 260px);
  height: calc(100vh - 105px);
  margin: 20px auto;
  background-color: #fff;
  color: #fff;
  display: flex;
  flex-direction: column;
  box-shadow: 0px 3px 10px rgba(0, 97, 255, 0.2);

  .left {
    // width: calc(100wh - 40px);
    display: flex;
    align-items: center;
    height: 60px;
    margin: 0 30px;
    border-bottom: 1px solid #ccc;
    color: rgb(0, 0, 0);
    font-size: 18px;
    font-weight: 600;

    .cameratxt {
      display: block;
      height: 60px;
      line-height: 60px;
    }

    .is_active {
      color: rgba(111, 182, 184, 1);
    }
  }

  .scroll {
    height: calc(100% - 61px);
    overflow: auto;
  }

  .middle {
    width: 96%;
    margin: 0 auto;

    color: #000;

    .search-manager {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 10px 0 0 0;

      // border-bottom: 1px solid rgb(231, 231, 231);
      .filter {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        margin: 10px 0 0 0;

        .search {
          color: #fff;
        }

        .condition {
          display: flex;
          align-items: center;
          margin: 10px 30px 10px 0;

          .sel {
            margin-right: 10px;
            width: 220px;
          }

          :deep(.el-input .el-input__inner) {
            font-size: 14px;
          }
        }
      }
    }

    .gongneng {
      margin: 10px 0 20px 0;

      span {
        color: #fff;
      }

      .el-button {
        margin-right: 10px;
      }
    }

    :deep(.cont) {
      width: 60%;
      margin: 20px auto;
    }

    :deep(.download) {
      display: flex;
      align-items: center;
      margin: 10px;
    }

    :deep(.download span) {
      font-size: 16px;
      margin-left: 20px;
    }

    :deep(.cont .el-button) {
      margin-left: 60px;
      margin-bottom: 30px;
    }

    :deep(.cont .accomplish) {
      width: 100%;
      display: flex;
      justify-content: center;
    }

    :deep(.cont .accomplish .el-button) {
      width: 50%;
      margin: 0;
    }
  }

  .footer {
    width: 96%;
    height: calc(100% - 210px);
    // min-height: 300px;
    margin: 10px auto 20px;

    .el-table--fit {
      height: 100%;

      :deep(.el-table__header-wrapper) {
        background-color: #000;
        font-size: 14px;

        tr {
          // color: #000;
        }
      }

      :deep(.el-table__row) {
        height: 50px;
        font-size: 14px;
        // color: #000;

        &:hover {
          td {
            background-color: rgba(223, 236, 254, 1);
          }
        }
      }

      :deep(.el-table__row td) {
        padding: 0;

        // border: 0;
        .normal {
          background-color: rgba(139, 195, 74, 1);
          color: #fff;
          padding: 4px;
        }

        .abnormal {
          background-color: rgba(212, 48, 48, 1);
          color: #fff;
          padding: 4px;
        }
      }

      .el-button--primary {
        margin-left: 5px;
      }

      :deep(.el-table__body .even) {
        background-color: #fff;
      }

      :deep(.el-table__body .odd) {
        background-color: rgba(240, 243, 247, 1);
      }

      :deep(.edit) {
        display: flex;
        align-items: center;
        justify-content: center;
        color: rgba(111, 182, 184, 1);
      }

      :deep(.look) {
        padding: 0 10px;
        cursor: pointer;
        color: rgba(30, 125, 251, 1);
      }

      .del {
        padding: 0 10px;
        color: rgba(212, 48, 48, 1);
        cursor: pointer;
      }

      // :deep(.look):hover {
      //   color: red;
      // }
      // :deep(.del):hover {
      //   color: red;
      // }
    }
  }

  // 编辑按钮
  :deep(.editDialog) {
    //   height: 420px;
    border-radius: 11px;

    .el-dialog__header {
      border-radius: 11px 11px 0 0;
      background: rgba(237, 241, 245, 1);
      font-weight: 600;
      margin: 0;

      .el-dialog__headerbtn {
        outline: none;
      }
    }

    .el-dialog__body {
      padding: 30px 30px 10px 30px;

      .el-form-item__content {
        width: 200px;

        .el-input-group__append {
          background-color: rgba(222, 234, 252, 1);
          color: rgba(0, 97, 255, 1);
          cursor: pointer;
          user-select: none;
        }
      }

      .el-form {
        .typeTitle {
          display: block;
          color: red;
          margin: 0 0 6px 100px;
        }

        .el-form-item {
          margin-bottom: 28px;
        }

        .account {
          display: flex;
          justify-content: space-between;

          .el-form-item {
            .el-form-item__content {
              width: 300px;
            }

            .el-input {
              width: 300px;
            }
          }
        }
      }

      .options {
        margin: 50px 20px 20px 0;
        width: 100%;

        .el-form-item__content {
          display: flex;
          flex-direction: row-reverse;
        }

        .queding {
          color: #fff;
          margin-left: 15px;
        }
      }
    }
  }

  // 删除数据库
  :deep(.closeAccount) {
    // height: 600px;
    overflow: hidden;
    border-radius: 11px;

    .el-dialog__header {
      border-radius: 11px 11px 0 0;
      background: rgba(245, 249, 255, 1);
      font-weight: 600;
      height: 60px;
      padding: 0 20px;
      line-height: 60px;
      margin: 0;
      border-bottom: 1px solid rgba(230, 230, 230, 1);

      .el-dialog__headerbtn {
        outline: none;
      }
    }

    .el-dialog__body {
      padding: 0px 20px 20px 20px;

      // height: 200px;
      // display: flex;
      // flex-direction: column-reverse;
      .content {
        height: 80px;
        font-size: 16px;
        padding: 20px 30px;
        display: flex;

        img {
          width: 25px;
          height: 25px;
          margin: 0 8px 0 0;
        }
      }

      .option {
        display: flex;
        flex-direction: row-reverse;
        align-items: center;
        margin: 10px 0;

        .queding {
          margin-left: 20px;
        }
      }
    }
  }

  :deep(.manager) {
    //   height: 420px;
    border-radius: 11px;

    .el-dialog__header {
      border-radius: 11px 11px 0 0;
      background: rgba(237, 241, 245, 1);
      font-weight: 600;
      margin: 0;

      .el-dialog__headerbtn {
        outline: none;
      }
    }

    .el-dialog__body {
      padding: 30px 30px 10px 30px;

      .el-table--fit {
        height: 100%;

        :deep(.el-table__header-wrapper) {
          background-color: #000;
          font-size: 14px;
        }

        .el-table__row {
          height: 50px;
          font-size: 14px;
          // color: #000;

          &:hover {
            td {
              background-color: rgba(223, 236, 254, 1);
            }
          }
        }

        :deep(.el-table__row td) {
          padding: 0;

          // border: 0;
          .normal {
            background-color: rgba(139, 195, 74, 1);
            color: #fff;
            padding: 4px;
          }

          .abnormal {
            background-color: rgba(212, 48, 48, 1);
            color: #fff;
            padding: 4px;
          }
        }

        .el-button--primary {
          margin-left: 5px;
        }

        :deep(.el-table__body .even) {
          background-color: #fff;
        }

        :deep(.el-table__body .odd) {
          background-color: rgba(240, 243, 247, 1);
        }
      }
    }
  }

  .pageSize {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 30px;

    span {
      color: #000;
    }

    .el-pagination {

      // width: 1600px;
      :deep(.el-pagination__total) {
        color: #000;
      }

      :deep(.el-pagination__goto) {
        color: #000;
      }

      :deep(.el-pagination__classifier) {
        color: #000;
      }

      :deep(.el-input__wrapper) {
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        box-shadow: none;
      }

      :deep(.el-pager li) {
        margin: 0 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.el-pager li.is-active) {
        // background-color: rgba(0, 97, 255, 0.8);
        border: 1px solid rgba(0, 97, 255, 1);
        color: rgba(0, 97, 255, 1);
      }

      :deep(.btn-prev) {
        margin-right: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }

      :deep(.btn-next) {
        margin-left: 5px;
        border: 1px solid rgba(0, 0, 0, 1);
        border-radius: 5px;
        background-color: transparent;
      }
    }
  }
}

.el-input {
  width: 192px;
}
</style>
