<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="detail_container-main">
      <Slide v-model="node" />
      <div class="main-content">
        <bg-filter-group @search="changeSearch" v-model="filter.metric_name" placeholder="请输入指标名称">
          <template v-slot:left_action>
            <div class="apaas_button">
              <el-button type="primary" @click="addRule">
                <bg-icon style="font-size: 12px; color: #fff; margin-right: 8px" icon="#bg-ic-add"></bg-icon>
                新增
              </el-button>
              <el-button type="default" @click="batchDelete">批量删除</el-button>
              <span class="header_info">
                已选择 <span style="color: #202531; font-weight: bold"> {{ state.selected.length }} </span> 项
              </span>
              <span class="header_info can_click_text" @click="clearSelected">清空</span>
            </div>
          </template>
          <template v-slot:filter_group>
            <div class="left-filter filter_list">
              <div class="filter_item">
                <span class="filter_title">启用状态</span>
                <el-select v-model="filter.is_enabled" placeholder="请选择" style="width: 300px">
                  <el-option
                    v-for="(item, index) in isEnabledOptions"
                    :key="'isEnabledOptions' + index"
                    :label="item.name"
                    :value="item.value">
                  </el-option>
                </el-select>
              </div>
              <div class="filter_item">
                <span class="filter_title">创建时间</span>
                <el-date-picker
                  style="width: 400px"
                  v-model="filter.time"
                  type="datetimerange"
                  value-format="yyyy-MM-DD HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间" />
              </div>
            </div>
            <div class="right-action apaas_button">
              <el-button type="primary" @click="filterAction"> 查询 </el-button>
              <el-button type="default" @click="filterClear"> 重置 </el-button>
            </div>
          </template>
        </bg-filter-group>
        <div class="table_container">
          <div class="table bg-scroll">
            <bg-table
              ref="dataTable"
              :headers="headers"
              :rows="tableRows"
              @selectAc="selectRows"
              :selectable="selectable"
              :isIndex="true"
              :select="true"
              :stripe="true">
              <template v-slot:metric_name="{ row }">
                <span class="can_click_text" @click="goDetail(row)">
                  {{ row.metric_name }}
                </span>
              </template>
              <template #is_enabled="{ row }">
                <bg-switch
                  @click="stateChange(row)"
                  :labels="['否', '是']"
                  :values="[2, 1]"
                  v-model="row.is_enabled"></bg-switch>
              </template>
              <template v-slot:created_at="{ row }">
                {{ row.created_at ? row.created_at.split("+")[0].replace("T", " ").replace("Z", " ") : "-" }}
              </template>
              <template v-slot:action="{ row }">
                <bg-table-btns2 :limit="3" :tableData="tableRows">
                  <bg-table-btn :disabled="row.is_enabled != 2" @click="editRow(row)">编辑</bg-table-btn>
                  <bg-table-btn :disabled="row.is_enabled != 2" @click="deleteRow(row)">删除</bg-table-btn>
                </bg-table-btns2>
              </template>
            </bg-table>
          </div>
          <bg-pagination
            :page="filter.page"
            :size="filter.size"
            :total="tableTotal"
            @change-page="changePage"
            @change-size="changeSize">
          </bg-pagination>
        </div>
      </div>
    </div>
    <!-- 删除 -->
    <el-dialog class="dialog_box" title="删除" v-model="delDialog" width="420px">
      <div>确定要删除吗？</div>
      <template v-slot:footer>
        <div class="apaas_button">
          <el-button type="default" @click="delDialog = false">取消</el-button>
          <el-button type="primary" @click="delConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import { reactive, ref, onBeforeMount, toRefs, computed, watch, nextTick, watchEffect } from "vue";
import Slide from "./modules/slide.vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { useRouter } from "vue-router";
const router = useRouter();
const node = ref({});
watch(
  () => node.value,
  (n) => {
    if (n?.data.class_id) {
      getTableRows();
    }
  },
  { deep: true }
);
const dataTable = ref(null);
const state = reactive({
  isEnabledOptions: [
    {
      name: "全部",
      value: "",
    },
    {
      name: "启用",
      value: 1,
    },
    {
      name: "禁用",
      value: 2,
    },
  ], // 状态
  headers: [
    {
      label: "指标名称",
      prop: "metric_name",
      width: 200,
    },
    {
      label: "是否启用",
      prop: "is_enabled",
    },
    {
      label: "创建人",
      prop: "created_by",
    },
    {
      label: "创建时间",
      prop: "created_at",
      width: 160,
    },
    {
      label: "操作",
      prop: "action",
      width: 136,
      fixed: "right",
    },
  ],
  filter: {
    notice_method: "", // 通知方式
    is_enabled: "", // 状态
    time: [],
    metric_name: "",
    page: 1,
    page_size: 10,
  },
  tableRows: [], // 表格数据
  selected: [], //选择数据
  tableTotal: 0, // 表格数据条数
  actionRow: null, // 当前操作的数据
  delDialog: false, // 删除弹窗
  delType: 0, // 1-单条删除 2-批量删除
});
const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
}; // 改变页码
const changeSize = (size) => {
  state.filter.page_size = size;
  changePage(1);
}; // 改变每页条数
const changeSearch = (val) => {
  state.filter.metric_name = val;
  changePage(1);
};
const filterAction = () => {
  changePage(1);
};
const filterClear = () => {
  state.filter = {
    is_enabled: "", // 状态
    time: [],
    metric_name: "",
    page: 1,
    page_size: 10,
  };
  changePage(1);
};
const selectable = (row, index) => {
  return row.is_enabled === 2;
};
const getTableRows = () => {
  let params = { ...state.filter, class_id: node.value.data.class_id };
  //   axios.get("/v1/api/metric_config/list", { params }).then((res) => {
  axios.get("/v1/api/metric_config/list").then((res) => {
    if (res.data.code == 200) {
      state.tableRows =
        res.data.data?.list?.map((e) => {
          return {
            ...e,
          };
        }) || [];
      state.tableTotal = res.data.data.total_count;
    }
  });
};
const goDetail = (row) => {
  router.push({
    path: "/forewarning/indicator-config/detail",
    query: {
      id: row.id,
      class_id: node.value.data.class_id,
      type_name: node.value.node.parent.data.class_name,
      target_name: node.value.data.class_name,
    },
  });
}; // 查看详情
const selectRows = (data) => {
  state.selected = data.selection;
};
const deleteRow = (row) => {
  state.actionRow = row;
  state.delType = 1;
  state.delDialog = true;
  //   console.log("删除");
}; // 删除
const batchDelete = () => {
  //   console.log("批量删除");
  if (!state.selected || state.selected.length == 0) {
    ElMessage.error("请先勾选要删除的数据");
    return;
  }
  state.delType = 2;
  state.delDialog = true;
}; // 批量删除
const delConfirm = () => {
  let ids = [];
  if (state.delType == 1) {
    ids.push(state.actionRow.id);
  } else {
    ids = state.selected.map((e) => {
      return e.id;
    });
  }
  //   console.log(ids);
  state.delDialog = false;
  axios
    .delete("/v1/api/metric_config", {
      data: {
        ids,
      },
    })
    .then((res) => {
      if (res.data.code == 200) {
        ElMessage.success("删除成功");
        changePage(1);
        clearSelected();
      } else {
        ElMessage.error(res.data.msg);
      }
    });
}; // 确定删除
const clearSelected = () => {
  dataTable.value.clearTable();
}; // 清空
const addRule = () => {
  //   console.log("新增");
  router.push({
    path: `/forewarning/indicator-config/add`,
    query: {
      class_id: node.value.data.class_id,
    },
  });
}; // 新增规则
const editRow = (row) => {
  //   console.log("编辑");
  router.push({
    path: `/forewarning/indicator-config/edit`,
    query: {
      id: row.id,
      class_id: node.value.data.class_id,
    },
  });
}; // 编辑
const stateChange = async (row) => {
  await nextTick();
  const params = {
    id: row.id,
    is_enabled: row.is_enabled,
  };
  axios.put("/v1/api/metric_config", params).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success(`状态更新成功`);
      getTableRows();
    } else {
      row.is_enabled = row.is_enabled == 1 ? 2 : 1;
      ElMessage.error(res.data.msg);
    }
  });
};
const { headers, tableRows, tableTotal, filter, noticeTypes, isEnabledOptions, delDialog } = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  height: calc(100vh - 56px);
  padding: 0 24px;
  min-height: 100%;
  &-main {
    width: 100%;
    height: calc(100% - 46px);
    display: flex;
    align-items: center;
    padding-bottom: 16px;
  }

  .main-content {
    height: 100%;
    width: calc(100% - 336px);
    background-color: #fff;
    box-shadow: 0 1px 4px 0 rgba(0, 7, 101, 0.15);
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: stretch;
    .filter-group {
      .left-filter {
        flex: 1;
        display: flex;
        justify-content: start;
        flex-wrap: wrap;
      }
      .right-action {
        width: 144px;
        padding-bottom: 16px;
        .el-button {
          width: 64px;
        }
      }
    }
    .table_container {
      flex: 1;
      width: 100%;
      padding: 0 16px;
      position: relative;
      .table {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: calc(100% - 64px);
      }
      .bg-pagination {
        height: 64px;
        position: absolute;
        right: 0;
        bottom: 0;
        padding: 16px;
        margin-top: 0;
      }
    }
  }
}
</style>
