<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备" prop="equipmentId">
        <el-input v-model="queryParams.equipmentId" placeholder="请输入设备id" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="动作类型" prop="actionType">
        <el-select v-model="queryParams.actionType" placeholder="请选择动作类型" clearable style="width: 200px;">
          <el-option v-for="dict in action_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="单位" prop="unit">
        <el-select v-model="queryParams.unit" placeholder="请选择单位" clearable style="width: 200px;">
          <el-option v-for="dict in unit_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="触发类型" prop="triggerType">
        <el-select v-model="queryParams.triggerType" placeholder="请选择触发类型" clearable style="width: 200px;">
          <el-option v-for="dict in trigger_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="状态" clearable style="width: 240px">
          <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </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="['hnyz:actionConfig:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['hnyz:actionConfig:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['hnyz:actionConfig:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['hnyz:actionConfig:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="actionConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="动作id" align="center" prop="actionId" />
      <el-table-column label="设备id" align="center" prop="equipmentId" />
      <el-table-column label="动作类型" align="center" prop="actionType">
        <template #default="scope">
          <dict-tag :options="action_type" :value="scope.row.actionType" />
        </template>
      </el-table-column>
      <el-table-column label="动作值" align="center" prop="value" />
      <el-table-column label="单位" align="center" prop="unit">
        <template #default="scope">
          <dict-tag :options="unit_type" :value="scope.row.unit" />
        </template>
      </el-table-column>
      <el-table-column label="触发类型" align="center" prop="triggerType">
        <template #default="scope">
          <dict-tag :options="trigger_type" :value="scope.row.triggerType" />
        </template>
      </el-table-column>
      <el-table-column label="触发条件" align="center" prop="triggerCondition" :show-overflow-tooltip="false">
        <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.triggerCondition" placement="top">
            <span class="ellipsis">{{ formatCondition(scope.row.triggerCondition) }}</span>
          </el-tooltip>
        </template>
      </el-table-column>


      <el-table-column label="触发延迟(s)" align="center" prop="triggerDelay" />
      <el-table-column label="启用状态" align="center" width="100">
        <template #default="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['hnyz:actionConfig:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['hnyz:actionConfig: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="650px" append-to-body>
      <el-form ref="actionConfigRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备选择" prop="equipmentId">
          <el-select v-model="form.equipmentId" placeholder="请选择设备" clearable filterable>
            <el-option v-for="dict in equipmentOptions" :key="dict.equipmentId" :label="dict.equipmentName"
              :value="dict.equipmentId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="动作类型" prop="actionType">
          <el-select v-model="form.actionType" placeholder="请选择动作类型">
            <el-option v-for="dict in action_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="动作值" prop="value">
          <el-input v-model="form.value" placeholder="请输入动作值" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-select v-model="form.unit" placeholder="请选择单位">
            <el-option v-for="dict in unit_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="触发类型" prop="triggerType">
          <el-select v-model="form.triggerType" placeholder="请选择触发类型">
            <el-option v-for="dict in trigger_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="触发条件" prop="triggerCondition">
          <el-input v-model="form.triggerCondition" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <!--  嵌入 JSON 构造器组件 -->
        <el-form-item label="触发条件" prop="triggerCondition">
          <div style="border: 1px solid #dcdfe6; padding: 12px; border-radius: 4px; width: 100%;">
            <ConditionGroup :group="triggerConditionJson" :equipmentOptions="equipmentOptions" />
          </div>
        </el-form-item>
        <el-form-item label="触发延迟" prop="triggerDelay">
          <el-input v-model="form.triggerDelay" placeholder="请输入触发延迟(单位：秒)" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="启用状态">
          <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>
      <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="ActionConfig">
import { changeStatus, listActionConfig, getActionConfig, delActionConfig, addActionConfig, updateActionConfig } from "@/api/hnyz/actionConfig";
import { getEquipmentList } from "@/api/hnyz/equipment";
import { onMounted, watch } from "vue";
import ConditionGroup from "@/components/DCS/ConditionGroup.vue";
onMounted(() => {
  getEquipmentOptions();
});

// 初始化触发条件 JSON 数据
const triggerConditionJson = reactive({
  operator: 'AND',
  conditions: []
})

//获取设备列表，用于select框
const equipmentOptions = ref([]);
function getEquipmentOptions() {
  getEquipmentList().then(response => {
    equipmentOptions.value = response.data
  })
}
const { proxy } = getCurrentInstance();
const { trigger_type, action_type, unit_type, sys_normal_disable } = proxy.useDict('trigger_type', 'action_type', 'unit_type', 'sys_normal_disable');

const actionConfigList = 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: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipmentId: null,
    actionType: null,
    unit: null,
    triggerType: null,
    status: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
// 解析已有 JSON 数据（编辑时）
watch(
  () => form.value.triggerCondition,
  (val) => {
    try {
      const parsed = JSON.parse(val)
      Object.assign(triggerConditionJson, parsed)
    } catch {
      Object.assign(triggerConditionJson, { operator: 'AND', conditions: [] })
    }
  },
  { immediate: true }
)

// 实时更新 JSON 字符串到 form
watch(
  () => triggerConditionJson,
  (val) => {
    form.value.triggerCondition = JSON.stringify(val)
  },
  { deep: true }
)

// 格式化触发条件(表单不完全显示)
function formatCondition(val) {
  if (!val) return ''
  try {
    const obj = JSON.parse(val)
    return JSON.stringify(obj).slice(0, 30) + '...'
  } catch {
    return val.length > 30 ? val.slice(0, 30) + '...' : val
  }
}


/** 查询动作配置管理列表 */
function getList() {
  loading.value = true;
  listActionConfig(queryParams.value).then(response => {
    actionConfigList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    actionId: null,
    equipmentId: null,
    actionType: null,
    value: null,
    unit: null,
    triggerType: null,
    triggerCondition: null,
    triggerDelay: null,
    status: "0",
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  // 重置触发条件 JSON 数据
  Object.assign(triggerConditionJson, {
    type: 'group',
    operator: 'AND',
    conditions: []
  })

  proxy.resetForm("actionConfigRef");
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加动作配置管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _actionId = row.actionId || ids.value
  getActionConfig(_actionId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改动作配置管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["actionConfigRef"].validate(valid => {
    if (valid) {
      if (form.value.actionId != null) {
        updateActionConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addActionConfig(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _actionIds = row.actionId || ids.value;
  proxy.$modal.confirm('是否确认删除动作配置管理编号为"' + _actionIds + '"的数据项？').then(function () {
    return delActionConfig(_actionIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('hnyz/actionConfig/export', {
    ...queryParams.value
  }, `actionConfig_${new Date().getTime()}.xlsx`)
}

/** 状态修改 */
function handleStatusChange(row) {
  let text = row.status == "0" ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '"id为"' + row.actionId + '"的数据项吗?').then(function () {
    return changeStatus(row.actionId, row.status);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.status = row.status == "0" ? "1" : "0";
  });
}
getList();
</script>
