<template>
  <div class="detail_container">
    <bg-breadcrumb></bg-breadcrumb>
    <div class="main_container">
      <bg-filter-group
        @search="changeSearch"
        v-model="filter.keyword"
        inputWidth="380px"
        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.notify_method" placeholder="请选择" style="width: 300px">
                <el-option
                  v-for="(item, index) in noticeTypes"
                  :key="'noticeTypes' + index"
                  :label="item.name"
                  :value="item.value">
                </el-option>
              </el-select>
            </div>
            <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 stateOptions"
                  :key="'stateOptions' + 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: 300px"
                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 v-slot:notify_method="{ row }">
              {{ row.notify_method.map((e) => METHODS[e]).join("，") }}
            </template>
            <template v-slot:notify_recipients="{ row }">
              {{ row.notify_recipients.length }}
            </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 }">
              {{ dateStringToDate(row.created_at) }}
            </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>
    <!-- 删除 -->
    <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 { reactive, ref, onBeforeMount, toRefs, computed, watch, nextTick, watchEffect } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { Search } from "@element-plus/icons-vue";
import bgBreadcrumb from "@/components/bg-breadcrumb.vue";
import { useRouter } from "vue-router";
import { dateStringToDate } from "@/components/env";
const METHODS = {
  dingtalk: "钉钉",
  sms: "短信",
};
const router = useRouter();

const dataTable = ref(null);

const state = reactive({
  noticeTypes: [
    {
      name: "全部",
      value: "",
    },
    {
      name: "钉钉",
      value: "dingtalk",
    },
    {
      name: "短信",
      value: "sms",
    },
  ],
  stateOptions: [
    {
      name: "全部",
      value: "",
    },
    {
      name: "启用",
      value: 1,
    },
    {
      name: "停用",
      value: 2,
    },
  ], // 状态
  headers: [
    {
      label: "预警规则名称",
      prop: "metric_name",
      width: 200,
    },
    {
      label: "预警分类",
      prop: "class_parent_name",
    },
    {
      label: "预警对象",
      prop: "class_name",
    },
    {
      label: "预警指标",
      prop: "metric_config_name",
    },
    {
      label: "通知方式",
      prop: "notify_method",
    },
    {
      label: "通知人数",
      prop: "notify_recipients",
    },
    {
      label: "是否启用",
      prop: "is_enabled",
    },
    {
      label: "创建人",
      prop: "created_by",
    },
    {
      label: "创建时间",
      prop: "created_at",
      width: 160,
    },
    {
      label: "操作",
      prop: "action",
      width: 136,
      fixed: "right",
    },
  ],
  tableRows: [], // 表格数据
  selected: [], //选择数据
  tableTotal: 0, // 表格数据条数
  filter: {
    notify_method: "", // 通知方式
    is_enabled: "", // 状态
    time: [],
    keyword: "",
    page: 1,
    limit: 10,
  }, // 表格筛选项
  actionRow: null, // 当前操作的数据
  delDialog: false, // 删除弹窗
  delType: 0, // 1-单条删除 2-批量删除
});

const selectRows = (data) => {
  state.selected = data.selection;
};

const clearSelected = () => {
  dataTable.value.clearTable();
}; // 清空

const batchDelete = () => {
  console.log("批量删除");
  if (!state.selected || state.selected.length == 0) {
    ElMessage.error("请先勾选要删除的数据");
    return;
  }
  state.delType = 2;
  state.delDialog = true;
}; // 批量删除

const goDetail = (row) => {
  console.log("去详情");
  router.push({
    path: "/forewarning/rule-set/detail",
    query: {
      id: row.id,
    },
  });
}; // 查看详情

const changeSearch = (val) => {
  state.filter.keyword = val;
  changePage(1);
}; // 表格关键字筛选

const filterAction = () => {
  changePage(1);
}; // 查询按钮

const filterClear = () => {
  state.filter = {
    notify_method: "", // 通知方式
    is_enabled: "", // 状态
    time: "",
    keyword: "",
    page: 1,
    limit: 10,
  };
  changePage(1);
}; // 重置筛选项

const selectable = (row, index) => {
  return row.is_enabled === 2;
};
const getTableRows = () => {
  let [start_time = "", end_time = ""] = state.filter.time || [];
  let params = {
    ...state.filter,
    start_time,
    end_time,
  };
  Reflect.deleteProperty(params, "time");
  axios
    .get(`/v1/api/alert_rules/list`, {
      params,
    })
    .then((res) => {
      if (res.data.code == 200) {
        state.tableRows = res.data.data?.list || [];
        state.tableTotal = res.data.data.total_count;
      } else {
        ElMessage.error(res.data.data);
      }
    });
}; // 获取表格数据

const changePage = (page) => {
  state.filter.page = page;
  getTableRows();
}; // 改变页码

const changeSize = (size) => {
  state.filter.limit = size;
  changePage(1);
}; // 改变每页条数

const stateChange = ({ id, is_enabled }) => {
  const params = {
    id,
    is_enabled,
  };
  axios.put(`/v1/api/alert_rules/is_enabled`, params).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("状态修改成功");
      changePage(1);
    } else {
      ElMessage.error(res.data.msg);
      row.state = row.state == 1 ? 2 : 1;
    }
  });
};

const addRule = () => {
  router.push({
    path: `/forewarning/rule-set/add`,
  });
}; // 新增规则

const editRow = (row) => {
  router.push({
    path: `/forewarning/rule-set/edit`,
    query: {
      id: row.id,
    },
  });
}; // 编辑

const deleteRow = (row) => {
  state.actionRow = row;
  state.delType = 1;
  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;
    });
  }
  axios
    .delete("/v1/api/alert_rules", {
      data: {
        ids,
      },
    })
    .then((res) => {
      if (res.data.code == "200") {
        ElMessage.success("删除成功");
        state.delDialog = false;
        clearSelected();
        changePage(1);
      } else {
        ElMessage.error(res.data.msg);
      }
    });
}; // 确定删除

onBeforeMount(() => {
  getTableRows();
});

const { headers, tableRows, tableTotal, filter, noticeTypes, stateOptions, delDialog } = toRefs(state);
</script>

<style lang="scss" scoped>
.detail_container {
  width: 100%;
  height: calc(100vh - 56px);
  padding: 0 24px;
  min-height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  .main_container {
    height: 100%;
    .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 {
      height: calc(100% - 70px);
      width: 100%;
      padding: 0 16px;
      .table {
        max-height: calc(100% - 64px);
      }
    }
  }
}
</style>
