<template>
  <div class="page">
    <el-card shadow="never">
      <el-form inline>
        <!-- 名称 -->
        <el-form-item :label="$t('message.formI18nLabel.name1')">
          <!-- 请输入关键字 -->
          <el-input v-model="searchParams.keyWord" :placeholder="$t('message.ruleEngine.keywordPlaceholder')" clearable @keyup.enter="handleSearch" />
        </el-form-item>
        <!-- 类型 -->
        <el-form-item :label="$t('message.formI18nLabel.type')">
          <!-- 请选择类型 -->
          <el-select v-model="searchParams.types" :placeholder="$t('message.ruleEngine.typePlaceholder')" clearable @clear="() => (searchParams.types = -1)" @change="handleSearch">
            <!-- 主链 -->
            <el-option :label="$t('message.ruleEngine.mainChain')" :value="1" />
            <!-- 子链 -->
            <el-option :label="$t('message.ruleEngine.subChain')" :value="2" />
            <!-- 全部 -->
            <el-option :label="$t('message.ruleEngine.all')" :value="-1" />
          </el-select>
        </el-form-item>
        <!-- 状态 -->
        <el-form-item :label="$t('message.formI18nLabel.status')">
          <!-- 请选择状态 -->
          <el-select v-model="searchParams.status" :placeholder="$t('message.ruleEngine.statusPlaceholder')" clearable @clear="() => (searchParams.status = -1)" @change="handleSearch">
            <!-- 已启动 -->
            <el-option :label="$t('message.ruleEngine.started')" :value="1" />
            <!-- 已停止 -->
            <el-option :label="$t('message.ruleEngine.stopped')" :value="0" />
            <!-- 全部 -->
            <el-option :label="$t('message.ruleEngine.all')" :value="-1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <!-- 查询 -->
          <el-button type="primary" @click="handleSearch">
            <el-icon><ele-Search /></el-icon>
            {{$t('message.formI18nButton.query')}}
          </el-button>
          <!-- <el-button @click="handleReset">
            <el-icon><ele-Refresh /></el-icon>
            重置
          </el-button> -->
        </el-form-item>
        <el-form-item>
          <!-- 新增规则编排 -->
          <el-button type="primary" v-auth="'add'" @click="addOrEdit()">
            <el-icon>
              <ele-FolderAdd />
            </el-icon>
            {{ $t('message.ruleEngine.addRule') }}
          </el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <!-- 序号 -->
        <el-table-column type="index" :label="$t('message.tableI18nColumn.index')" width="80" align="center" />
        <!-- 类型 -->
        <el-table-column prop="types" :label="$t('message.formI18nLabel.type')" width="70" align="center">
          <template #default="scope">
            <!-- 主链 -->
            <el-tag size="small" v-if="scope.row.types == 1">{{$t('message.ruleEngine.mainChain')}}</el-tag>
            <!-- 子链 -->
            <el-tag type="success" size="small" v-else>{{$t('message.ruleEngine.subChain')}}</el-tag>
          </template>
        </el-table-column>
        <!-- 名称 -->
        <el-table-column prop="name" :label="$t('message.formI18nLabel.name1')" show-overflow-tooltip></el-table-column>
        <!-- 描述 -->
        <el-table-column prop="expound" :label="$t('message.formI18nLabel.desc')" show-overflow-tooltip></el-table-column>
        <!-- 创建时间 -->
        <el-table-column prop="createdAt" :label="$t('message.tableI18nColumn.createdAt')" min-width="100" align="center"></el-table-column>
        <!-- 状态 -->
        <el-table-column prop="status" :label="$t('message.formI18nLabel.status')" width="100" align="center">
          <template #default="scope">
            <!-- 已启动 -->
            <el-tag type="success" size="small" v-if="scope.row.status == 1">{{$t('message.ruleEngine.started')}}</el-tag>
            <!-- 已停止 -->
            <el-tag type="info" size="small" v-else>{{$t('message.ruleEngine.stopped')}}</el-tag>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column :label="$t('message.tableI18nColumn.operation')" width="200" align="center">
          <template #default="scope">
            <!-- 停止 -->
            <el-button size="small" text type="info" v-auth="'startOrStop'" v-if="scope.row.status" @click="setStatus(scope.row, 0)">{{ $t('message.ruleEngine.stop') }}</el-button>
            <!-- 启动 -->
            <el-button size="small" text type="primary" v-auth="'startOrStop'" v-else @click="setStatus(scope.row, 1)">{{ $t('message.ruleEngine.start') }}</el-button>
            <!-- 编辑 -->
            <el-button size="small" text type="primary" v-auth="'edit'" @click="addOrEdit(scope.row)">{{ $t('message.tableI18nAction.edit') }}</el-button>
            <!-- 规则编辑 -->
            <el-button size="small" text type="warning" @click="edit(scope.row)">{{ $t('message.ruleEngine.ruleEdit') }}</el-button>
            <!-- 删除 -->
            <el-button size="small" text type="info" v-auth="'del'" @click="onDel(scope.row)">{{ $t('message.tableI18nAction.delete') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="params.total" :total="params.total" v-model:page="params.pageNum" v-model:limit="params.pageSize" @pagination="getList()" />
      <EditForm :model="model" ref="editFormRef" @getList="getList(1)"></EditForm>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, computed } from "vue";
import api from "/@/api/rule";
import { ElMessageBox, ElMessage } from "element-plus";
import { useSearch } from "/@/hooks/useCommon";
import EditForm from "./edit.vue";
import axios from "axios";
import { getToken } from "/@/utils/auth";
import { getRuleServerOrigin } from "/@/utils/origin";
import { useI18n } from 'vue-i18n';
// 国际化
const { locale, t } = useI18n();

const currentLocale = computed(() => locale.value);
const editFormRef = ref();

// 规则引擎模式 node-red、 sagoo-rule
const model: "node-red" | "sagoo-rule" = import.meta.env.VITE_RULE_MODEL;

const searchParams = reactive({
  keyWord: "",
  types: -1,
  status: -1,
});

// 监听搜索参数变化，确保在API请求中正确传递搜索条件
watch(
  searchParams,
  (newVal: any) => {
    // 处理搜索参数的值
    for (const key in newVal) {
      if (newVal[key] === "" || newVal[key] === null) {
        // 如果是类型或状态字段，在清除时设置为-1（全部）
        if (key === "types" || key === "status") {
          params[key] = -1;
          searchParams[key] = -1; // 同步更新searchParams
        } else {
          delete params[key];
        }
      } else {
        params[key] = newVal[key];
      }
    }
  },
  { deep: true }
);

const { params, tableData, getList, loading } = useSearch<any[]>(api.getList, "Data", searchParams);

const headers = {
  Authorization: "Bearer " + getToken(),
};

const flowsUrl = window.location.origin + "/rule-engine/flows";

getList();

// 搜索
const handleSearch = () => {
  getList(1);
};

// 重置功能已在模板中被注释掉
// 如果需要重新启用重置功能，请取消注释并使用以下代码：
/*
const handleReset = () => {
  searchParams.keyWord = '';
  searchParams.types = -1;
  searchParams.status = -1;
  getList(1);
};
*/

const addOrEdit = async (row?: any) => {
  if (row) {
    editFormRef.value.open(row);
    return;
  } else {
    editFormRef.value.open();
  }
};

const setStatus = async (row: any, status: number) => {
  if (model === "sagoo-rule") {
    axios
      .get(getRuleServerOrigin(`/api/v1/rule/${row.flowId}/${status ? "enable" : "stop"}`), { headers })
      .then(() => {
        api
          .setStatus(row.id, status)
          .then(() => {
            // 操作成功
            ElMessage.success(t('message.tableI18nConfirm.handleSuccess'));
            getList();
          })
          .catch(() => {
            // 操作失败
            ElMessage.error(t('message.tableI18nConfirm.handleFailed'));
          });
      })
      .catch(() => {
        // 操作失败
        ElMessage.error(t('message.tableI18nConfirm.handleFailed'));
      });
  } else {
    // 找到所有规则
    const { data: flows } = await axios.get(flowsUrl, { headers });

    const flow = flows.find((item: any) => item.id === row.flowId);

    if (!flow) {
      // 规则不存在
      ElMessage.error(t('message.ruleEngine.ruleNotExist'));
      return;
    }

    // 改变指定规则状态
    flow.disabled = status ? false : true;
    // 设置规则状态
    await axios.post(flowsUrl, flows, { headers });
    api
      .setStatus(row.id, status)
      .then(() => {
        // 操作成功
        ElMessage.success(t('message.tableI18nConfirm.handleSuccess'));
        getList();
      })
      .catch(() => {
        // 操作失败
        ElMessage.error(t('message.tableI18nConfirm.handleFailed'));
      });
  }
};

const edit = async (row: any) => {
  if (model == "sagoo-rule") {
    localStorage.setItem("auth-tokens", `{"access_token":"${getToken()}"}`);
    const url = "/plugin/rule/index.html#" + row.flowId;
    window.open(url);
  } else if (model == "node-red") {
    localStorage.setItem("auth-tokens", `{"access_token":"${getToken()}"}`);
    const url = "/rule-engine/#flow/" + row.flowId;
    window.open(url);
  }
};

const onDel = (row: any) => {
  // 此操作将删除：“${row.name}”，是否继续?
  ElMessageBox.confirm(
    t('message.ruleEngine.deleteRuleMessage', { name: row.name }),
    t('message.tableI18nConfirm.deleteTitle'), {
    confirmButtonText: t('message.tableI18nConfirm.confirmText'),
    cancelButtonText: t('message.tableI18nConfirm.cancelText'),
    type: 'warning',
  }).then(async () => {
    if (model == "sagoo-rule") {
      await axios.delete(getRuleServerOrigin("/api/v1/rules/" + row.flowId), { headers }).catch(() => {
        // 规则不存在
        ElMessage.error(t('message.ruleEngine.ruleNotExist'));
      });
    } else if (model == "node-red") {
      // 找到所有规则
      const { data: flows } = await axios.get(flowsUrl, { headers });

      const flowIndex = flows.findIndex((item: any) => item.id === row.flowId);

      if (flowIndex >= 0) {
        // 删除指定规则
        flows.splice(flowIndex, 1);

        // 删除当前规则下的各个节点信息
        const newFlows = flows.filter((item: any) => {
          if (item.z === row.flowId) {
            return false;
          } else {
            return true;
          }
        });

        // 设置规则状态
        await axios.post(flowsUrl, newFlows, { headers });
      }
    }

    await api.del([row.id as string]);
    // 删除成功
    ElMessage.success(t('message.tableI18nConfirm.deleteSuccess'));
    getList();
  });
};
</script>
