<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="流程页面" prop="pageId">
        <el-select v-model="queryParams.pageId" placeholder="请选择流程页面" clearable style="width: 200px;">
          <el-option v-for="dict in pageOptions" :key="dict.pageId" :label="dict.pageName" :value="dict.pageId" />
        </el-select>
      </el-form-item>
      <el-form-item label="管道种类" prop="pipeClass">
        <el-input v-model="queryParams.pipeClass" placeholder="请输入管道种类" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="管道名称" prop="remark">
        <el-input v-model="queryParams.remark" placeholder="请输入管道名称" @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="['hnyz:pipelineInstance:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['hnyz:pipelineInstance:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['hnyz:pipelineInstance:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['hnyz:pipelineInstance:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="pipelineInstanceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="管道名称" align="center" prop="remark" />
      <el-table-column label="流程页面" align="center" prop="pageName" />
      <el-table-column label="管道种类" align="center" prop="pipeClass" />

      <!-- <el-table-column label="X 坐标" align="center" prop="x" />
      <el-table-column label="Y 坐标" align="center" prop="y" />
      <el-table-column label="管道宽度" align="center" prop="pipeWidth" />
      <el-table-column label="管道长度" align="center" prop="pipeLength" />
      <el-table-column label="旋转角度" align="center" prop="rotate" /> -->
      <!-- <el-table-column label="关联模型 ID" align="center" prop="modelId" /> -->
      <!-- <el-table-column label="流通条件" align="center" prop="flowCondition" :show-overflow-tooltip="false">
        <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.flowCondition" placement="top"
            :popper-style="{ maxWidth: '600px' }">
            <span class="ellipsis">{{ formatCondition(scope.row.flowCondition) }}</span>
          </el-tooltip>
        </template>
</el-table-column>
<el-table-column label="反转条件" align="center" prop="reverseCondition" :show-overflow-tooltip="false">
  <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.reverseCondition" placement="top"
            :popper-style="{ maxWidth: '600px' }">
            <span class="ellipsis">{{ formatCondition(scope.row.reverseCondition) }}</span>
          </el-tooltip>
        </template>
</el-table-column>

<el-table-column label="管道种类切换条件" align="center" prop="dynamicPipelineCondition" :show-overflow-tooltip="false">
  <template #default="scope">
          <el-tooltip class="item" effect="dark" :content="scope.row.dynamicPipelineCondition" placement="top"
            :popper-style="{ maxWidth: '600px' }">
            <span class="ellipsis">{{ formatCondition(scope.row.dynamicPipelineCondition) }}</span>
          </el-tooltip>
        </template>
</el-table-column> -->

      <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:pipelineInstance:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['hnyz:pipelineInstance: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="pipelineInstanceRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="流程页面" prop="pageId">
          <el-select v-model="form.pageId" placeholder="请选择流程名称" filterable>
            <el-option v-for="dict in pageOptions" :key="dict.pageId" :label="dict.pageName"
              :value="dict.pageId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="X 坐标" prop="x">
          <el-input v-model="form.x" placeholder="请输入X 坐标,单位为%" />
        </el-form-item>
        <el-form-item label="Y 坐标" prop="y">
          <el-input v-model="form.y" placeholder="请输入Y 坐标,单位为%" />
        </el-form-item>
        <el-form-item label="管道长度" prop="pipeLength">
          <el-input v-model="form.pipeLength" placeholder="请输入宽度,单位为%" />
        </el-form-item>
        <el-form-item label="旋转角度" prop="rotate">
          <el-input v-model="form.rotate" placeholder="请输入旋转角度" />
        </el-form-item>
        <el-form-item label="管道宽度" prop="pipeWidth">
          <el-input v-model="form.pipeWidth" placeholder="请输入高度,单位为px" />
        </el-form-item>
        <el-form-item label="模型种类" prop="modelId">
          <el-select v-model="form.modelId" placeholder="请选择对应模型" disabled>
            <el-option v-for="dict in modelOptions" :key="dict.modelId" :label="dict.modelName" :value="dict.modelId" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="管道种类" prop="pipeClass">
          <el-input v-model="form.pipeClass" placeholder="请输入管道种类" />
        </el-form-item> -->
        <el-form-item label="管道种类" prop="pipeClass">
          <el-select v-model="form.pipeClass" placeholder="请选择管道种类">
            <el-option label="蓝色" value="compressed_air" />
            <el-option label="黄色" value="heat_exchange_fluid" />
            <el-option label="紫色" value="stench" />
            <el-option label="灰色" value="materials" />
            <el-option label="橙色" value="steam" />
            <el-option label="红色" value="red" />
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="流通条件" prop="condition">
          <PipeStatusConditionGroup v-model:group="form.condition" :codeOptions="valveCodeOptions" />
        </el-form-item> -->
        <el-form-item label="流通条件" prop="flowCondition">
          <div style="border: 1px solid #dcdfe6; padding: 12px; border-radius: 4px; width: 100%;">
            <PipeStatusConditionGroup :group="flowConditionJson" :codeOptions="equipmentOptions" />
          </div>
        </el-form-item>

        <el-form-item label="反转条件" prop="reverseCondition">
          <div style="border: 1px solid #dcdfe6; padding: 12px; border-radius: 4px; width: 100%;">
            <PipeStatusConditionGroup :group="reverseConditionJson" :codeOptions="equipmentOptions" />
          </div>
        </el-form-item>

        <el-form-item label="管道切换" prop="dynamicPipelineCondition">
          <div style="width: 100%;">
            <PipeClassConditionGroup v-model="form.dynamicPipelineCondition" :codeOptions="equipmentOptions" />
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="form.id != null" type="success" @click="submitSave">保 存</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PipelineInstance">
import { listPipelineInstance, getPipelineInstance, delPipelineInstance, addPipelineInstance, updatePipelineInstance } from "@/api/hnyz/pipelineInstance";
import PipeStatusConditionGroup from "@/components/DCS/PipeStatusConditionGroup.vue";
import PipeClassConditionGroup from "@/components/DCS/PipeClassConditionGroup.vue";
import { getEquipmentList } from "@/api/hnyz/equipment";
import { getModelSelectList } from "@/api/hnyz/modelComponent";

import { onMounted, watch } from "vue";
import { getPageList } from "@/api/hnyz/pageControl";


onMounted(() => {
  getPageOptions();
  getEquipmentOptions();
  getModelOptions();
});

const pageOptions = ref([]);// 流程选项
// 获取总流程选项
function getPageOptions() {
  getPageList({}).then(response => {
    pageOptions.value = response.data;
  });
}

const modelOptions = ref([]);// 模型选项
// 获取模型选项 
function getModelOptions() {
  getModelSelectList().then(response => {
    modelOptions.value = response.data;
  });
}

// 初始化触发条件 JSON 数据
const flowConditionJson = reactive({
  operator: 'AND',
  conditions: []
})
const reverseConditionJson = reactive({
  operator: 'AND',
  conditions: []
})
//获取设备列表，用于select框
const equipmentOptions = ref([]);
function getEquipmentOptions() {
  getEquipmentList().then(response => {
    equipmentOptions.value = response.data
  })
}
const { proxy } = getCurrentInstance();

const pipelineInstanceList = 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,
    pageId: 19,
    x: null,
    y: null,
    pipeWidth: null,
    pipeLength: null,
    rotate: null,
    modelId: null,
    pipeClass: null,
    flowCondition: null,
    reverseCondition: null,
    dynamicPipelineCondition: null,
    status: null,
  },
  rules: {
    pageId: [
      { required: true, message: "流程页面不能为空", trigger: "blur" }
    ],
    modelId: [
      { required: true, message: "关联模型不能为空", trigger: "blur" }
    ],
  }
});

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

// 解析已有 JSON 数据（编辑时）
watch(
  () => form.value.flowCondition,
  (val) => {
    try {
      const parsed = JSON.parse(val)
      Object.assign(flowConditionJson, parsed)
    } catch {
      Object.assign(flowConditionJson, { operator: 'AND', conditions: [] })
    }
  },
  { immediate: true }
)
watch(
  () => form.value.reverseCondition,
  (val) => {
    try {
      const parsed = JSON.parse(val)
      Object.assign(reverseConditionJson, parsed)
    } catch {
      Object.assign(reverseConditionJson, { operator: 'AND', conditions: [] })
    }
  },
  { immediate: true }
)

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

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

/** 查询管道实例管理列表 */
function getList() {
  loading.value = true;
  listPipelineInstance(queryParams.value).then(response => {
    pipelineInstanceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    pageId: 21,
    x: 20,
    y: 20,
    pipeWidth: 8,
    pipeLength: 10,
    rotate: 0,
    modelId: 15,
    pipeClass: 'steam',
    flowCondition: null,
    dynamicPipelineCondition: null,
    reverseCondition: null,
    status: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: '相关管道'
  };
  proxy.resetForm("pipelineInstanceRef");
}

//条件组重置
function resetCondition() {
  Object.assign(flowConditionJson, { operator: 'AND', conditions: [] })
  Object.assign(reverseConditionJson, { operator: 'AND', conditions: [] })
}

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

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

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

/** 新增按钮操作 */
function handleAdd() {
  reset();
  resetCondition();
  open.value = true;
  title.value = "添加管道实例管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  resetCondition();
  const _id = row.id || ids.value
  getPipelineInstance(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改管道实例管理";
  });
}

function submitSave() {
  proxy.$refs["pipelineInstanceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updatePipelineInstance(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          getList();
        });
      }
    }
  });
}

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

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

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

getList();
</script>
