<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="模块" prop="moduleName">
        <el-input
          v-model="queryParams.moduleName"
          placeholder="请输入"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="指标字段名" prop="fieldName">
        <el-input
          v-model="queryParams.fieldName"
          placeholder="请输入"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:rule:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:rule:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:rule:remove']"
          >删除</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="模块" align="center" prop="moduleName" >
        <template #default="scope">
          <dict-tag :options="module" :value="scope.row.moduleName" />
        </template>
      </el-table-column>
      <el-table-column label="指标字段名" align="center" prop="fieldName" />
      <el-table-column label="默认值" align="center" prop="defaultValue" />
      <!-- <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag
            :options="
              sys_normal_disable.map((item) => ({
                ...item,
                value: item.value.toString(),
              }))
            "
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="180"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:rule:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:rule:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="postRef" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="类型" prop="ruleType">
          <el-select v-model="form.ruleType" placeholder="类型" disabled>
            <el-option label="空值默认值" :value="1" />
            <el-option label="阈值告警" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="模块" prop="moduleName">
          <el-select
            v-model="form.moduleName"
            placeholder="请选择"
            @change="handleModuleChange"
          >
            <el-option
              v-for="dict in module"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指标字段名" prop="fieldName">
          <!-- <el-input v-model="form.fieldName" placeholder="请输入" /> -->
          <el-select v-model="form.fieldName" placeholder="请选择">
            <el-option
              v-for="dict in fieldOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认值" prop="defaultValue">
          <el-input v-model="form.defaultValue" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Post">
import { listRule, saveRule, delRule } from '@/api/system/rule';

const { proxy } = getCurrentInstance();
const { module } = proxy.useDict('module');
const fieldOptions = ref([]);
const sys_normal_disable = [
  { label: '正常', value: 1, elTagType: 'success' },
  { label: '停用', value: 0, elTagType: 'danger' },
];
const postList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref('');

const data = reactive({
  form: {
    ruleType: 1,
    moduleName: undefined,
    fieldName: undefined,
    defaultValue: undefined,
    status: '1',
    remark: undefined,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    ruleType: 1,
    moduleName: undefined,
    fieldName: undefined,
    status: undefined,
  },
  rules: {
    moduleName: [{ required: true, message: '模块不能为空', trigger: 'blur' }],
    fieldName: [{ required: true, message: '指标不能为空', trigger: 'blur' }],
    defaultValue: [
      { required: true, message: '默认值不能为空', trigger: 'blur' },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
function getList() {
  loading.value = true;
  listRule(queryParams.value).then((response) => {
    postList.value = response.data.records;
    total.value = response.data.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    ruleType: 1,
    moduleName: undefined,
    fieldName: undefined,
    defaultValue: undefined,
    status: 1,
    remark: undefined,
  };
  proxy.resetForm('postRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加规则';
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  form.value = JSON.parse(JSON.stringify(row));
  if(form.value?.moduleName) {
    const moduleItem = module.value.find((item) => item.value === form.value?.moduleName);
    if (moduleItem) {
      fieldOptions.value = moduleItem.remark
        ? moduleItem.remark
            .split(',')
            .map((item) => ({ label: item, value: item }))
        : [];
    }
  }
  open.value = true;
  title.value = '修改规则';
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['postRef'].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        saveRule(form.value).then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        });
      } else {
        saveRule({ ...form.value, id: undefined }).then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除数据项？')
    .then(function () {
      return delRule(row.id);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess('删除成功');
    })
    .catch(() => {});
}

/** 模块选择改变 */
function handleModuleChange(value) {
  form.value.fieldName = undefined;
  const moduleItem = module.value.find((item) => item.value === value);
  if (moduleItem) {
    fieldOptions.value = moduleItem.remark
      ? moduleItem.remark
          .split(',')
          .map((item) => ({ label: item, value: item }))
      : [];
  }
}

getList();
</script>
