<template>
    <el-dialog title="设备动作选择" v-model="open" :modal= false width="80%" center :style="{ 'z-index': '3000' }">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <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="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-table v-loading="loading" :data="actionConfigList" @current-change="handleSelectionChange" @row-dblclick="handleRowDbClick">
            <el-table-column width="50" align="center" >
              <template v-slot="scope">
                  <el-radio v-model="selectedItemId" :label="scope.row.actionId" @change="handleRowChange(scope.row)">{{""}}</el-radio>
              </template>
          </el-table-column>
            <el-table-column label="设备" align="center" prop="equipmentName" />
            <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)" disabled></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" />
        </el-table>

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

        <template #footer>
            <div class="dialog-footer">
            <el-button type="primary" @click="confirmSelect">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="ActionConfig">
import { changeStatus, listActionConfig, getActionConfig, delActionConfig, addActionConfig, updateActionConfig } from "@/api/hnyz/actionConfig";
import { getEquipmentList } from "@/api/hnyz/equipment";
import { ElMessageBox } from "element-plus";
import { onMounted, watch } from "vue";
import ConditionGroup from "@/components/DCS/ConditionGroup.vue";
onMounted(() => {
  getEquipmentOptions();
});

const emit = defineEmits(["onSelected"])

// 初始化触发条件 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 selectedRows = ref([]);
const selectedItemId = ref(null);

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();
}
const show = () => {
  open.value = true
}
defineExpose({
  show
})

// 表单重置
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 confirmSelect() {
  open.value = false;
  if(selectedItemId ==null || selectedItemId==0){
    ElMessageBox.alert("请至少选择一条数据！", "提示", {
      type: "warning",
    });
    return;
  }
  emit('onSelected', selectedRows);
}

function handleRowChange(row) {
  if(row){
    selectedRows.value = row;
  }
}
function handleSelectionChange(row) {
    if (row) {
       selectedRows.value = row;
    }
}
function handleRowDbClick(row) {
    if (row) {
        selectedRows.value = row;
        emit('onSelected', selectedRows);
        open.value = false;
    }
}

getList();
</script>