<template>
  <div class='p-2'>
    <transition :enter-active-class='proxy?.animate.searchAnimate.enter'
                :leave-active-class='proxy?.animate.searchAnimate.leave'>
      <div v-show='showSearch' class='mb-[10px]'>
        <el-card shadow='hover'>
          <el-form ref='queryFormRef' :model='queryParams' :inline='true'>
            <el-form-item label='页面名称' prop='pageConfigName'>
              <el-input v-model='queryParams.pageConfigName' placeholder='请输入页面名称' clearable
                        @keyup.enter='handleQuery' />
            </el-form-item>
            <el-form-item label='激活标识' prop='activeFlag'>
              <el-select v-model='queryParams.activeFlag' placeholder='请选择激活标识' clearable>
                <el-option v-for='dict in active_flag' :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-card>
      </div>
    </transition>

    <el-card shadow='never'>
      <template #header>
        <el-row :gutter='10' class='mb8'>
          <el-col :span='1.5'>
            <el-button type='primary' plain icon='Plus' @click='handleAdd' v-hasPermi="['system:designPageConfig:add']">
              新增
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='success' plain icon='Edit' :disabled='single' @click='handleUpdate()'
                       v-hasPermi="['system:designPageConfig:edit']">修改
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='danger' plain icon='Delete' :disabled='multiple' @click='handleDelete()'
                       v-hasPermi="['system:designPageConfig:remove']">删除
            </el-button>
          </el-col>
          <el-col :span='1.5'>
            <el-button type='warning' plain icon='Download' @click='handleExport'
                       v-hasPermi="['system:designPageConfig:export']">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch='showSearch' :columns='columns' :search='true'
                         @queryTable='getList'></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading='loading' :data='designPageConfigList' @selection-change='handleSelectionChange'>
        <el-table-column type='selection' width='55' align='center' />
        <el-table-column label='页面配置ID' align='center' prop='pageConfigId' v-if='columns[0].visible' />
        <el-table-column label='页面名称' align='center' prop='pageConfigName' v-if='columns[2].visible' />
        <el-table-column label='页面背景' align='center' prop='pageBackground' v-if='columns[3].visible' />
        <el-table-column label='页面路由' align='center' prop='pageRouting' v-if='columns[4].visible' />
        <el-table-column label='自定义内容' align='center' prop='customContent' v-if='columns[5].visible' />
        <el-table-column label='显示排序' align='center' prop='sortOrder' v-if='columns[6].visible' />
        <el-table-column label='预留字段一' align='center' prop='fieldOne' v-if='columns[7].visible' />
        <el-table-column label='预留字段二' align='center' prop='fieldTwo' v-if='columns[8].visible' />
        <el-table-column label='预留字段三' align='center' prop='fieldThree' v-if='columns[9].visible' />
        <el-table-column label='预留字段四' align='center' prop='fieldFour' v-if='columns[10].visible' />
        <el-table-column label='预留字段五' align='center' prop='fieldFive' v-if='columns[11].visible' />
        <el-table-column label='激活标识' align='center' prop='activeFlag' v-if='columns[13].visible'>
          <template #default='scope'>
            <dict-tag :options='active_flag' :value='scope.row.activeFlag' />
          </template>
        </el-table-column>
        <el-table-column label='备注' align='center' prop='remark' v-if='columns[14].visible' />
        <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
          <template #default='scope'>
            <el-tooltip content='修改' placement='top'>
              <el-button link type='primary' icon='Edit' @click='handleUpdate(scope.row)'
                         v-hasPermi="['system:designPageConfig:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content='删除' placement='top'>
              <el-button link type='primary' icon='Delete' @click='handleDelete(scope.row)'
                         v-hasPermi="['system:designPageConfig:remove']"></el-button>
            </el-tooltip>
          </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-card>
    <!-- 添加或修改大屏设计页面配置对话框 -->
    <el-dialog :title='dialog.title' v-model='dialog.visible' width='1000px' append-to-body>
      <el-form ref='designPageConfigFormRef' :model='form' :rules='rules' label-width='100px'>
        <el-row :gutter='20'>
          <el-col :span='12'>
            <el-form-item label='页面名称' prop='pageConfigName'>
              <el-input v-model='form.pageConfigName' placeholder='请输入页面名称' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='页面背景' prop='pageBackground'>
              <el-input v-model='form.pageBackground' placeholder='请输入页面背景' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='页面路由' prop='pageRouting'>
              <el-input v-model='form.pageRouting' placeholder='请输入页面路由' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='显示排序' prop='sortOrder'>
              <el-input v-model='form.sortOrder' placeholder='请输入显示排序' />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label='自定义内容'>
          <el-input v-model='form.customContent' placeholder='请输入自定义内容' />
        </el-form-item>
        <el-form-item label='激活标识' prop='activeFlag'>
          <el-radio-group v-model='form.activeFlag'>
            <el-radio
              v-for='dict in active_flag'
              :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' placeholder='请输入备注' />
        </el-form-item>
      </el-form>

      <!-- 页面节点表格 -->
      <div class='mt-4'>
        <div class='mb-2 flex justify-between items-center'>
          <span class='text-lg font-medium'>页面节点</span>
          <el-button type='primary' icon='Plus' @click='handleAddPoint'>新增节点</el-button>
        </div>
        <el-table :data='pointList' v-loading='pointLoading' border>
          <el-table-column type='selection' width='55' align='center' />
          <el-table-column label='节点ID' align='center' prop='pagePointId' />
          <el-table-column label='节点编号' align='center' prop='pagePointCode' />
          <el-table-column label='节点名称' align='center' prop='pagePointName' />
          <el-table-column label='节点类型' align='center' prop='pointType' />
          <el-table-column label='组件类型' align='center' prop='componentType' />
          <el-table-column label='X坐标' align='center' prop='posX' />
          <el-table-column label='Y坐标' align='center' prop='posY' />
          <el-table-column label='宽度(px)' align='center' prop='width' />
          <el-table-column label='高度(px)' align='center' prop='height' />
          <el-table-column label='激活标识' align='center' prop='activeFlag'>
            <template #default='scope'>
              <dict-tag :options='active_flag' :value='scope.row.activeFlag' />
            </template>
          </el-table-column>
          <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
            <template #default='scope'>
              <el-tooltip content='修改' placement='top'>
                <el-button link type='primary' icon='Edit' @click='handleUpdatePoint(scope.row)'></el-button>
              </el-tooltip>
              <el-tooltip content='删除' placement='top'>
                <el-button link type='primary' icon='Delete' @click='handleDeletePoint(scope.row)'></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 页面连接线表格 -->
      <div class='mt-4'>
        <div class='mb-2 flex justify-between items-center'>
          <span class='text-lg font-medium'>页面连接线</span>
          <el-button type='primary' icon='Plus' @click='handleAddEdge'>新增连接线</el-button>
        </div>
        <el-table :data='edgeList' v-loading='edgeLoading' border>
          <el-table-column type='selection' width='55' align='center' />
          <el-table-column label='连接线ID' align='center' prop='pageEdgesId' />
          <el-table-column label='线类型' align='center' prop='edgeType' />
          <el-table-column label='原节点ID' align='center' prop='sourceNodeId' />
          <el-table-column label='目标节点ID' align='center' prop='targetNodeId' />
          <el-table-column label='源句柄ID' align='center' prop='sourceHandleId' />
          <el-table-column label='目标句柄ID' align='center' prop='targetHandleId' />
          <el-table-column label='X坐标' align='center' prop='posX' />
          <el-table-column label='Y坐标' align='center' prop='posY' />
          <el-table-column label='激活标识' align='center' prop='activeFlag'>
            <template #default='scope'>
              <dict-tag :options='active_flag' :value='scope.row.activeFlag' />
            </template>
          </el-table-column>
          <el-table-column label='操作' align='center' class-name='small-padding fixed-width'>
            <template #default='scope'>
              <el-tooltip content='修改' placement='top'>
                <el-button link type='primary' icon='Edit' @click='handleUpdateEdge(scope.row)'></el-button>
              </el-tooltip>
              <el-tooltip content='删除' placement='top'>
                <el-button link type='primary' icon='Delete' @click='handleDeleteEdge(scope.row)'></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class='dialog-footer'>
          <el-button :loading='buttonLoading' type='primary' @click='submitForm'>确 定</el-button>
          <el-button @click='cancel'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改页面节点对话框 -->
    <el-dialog :title='pointDialog.title' v-model='pointDialog.visible' width='600px' append-to-body>
      <el-form ref='pointFormRef' :model='pointForm' :rules='pointRules' label-width='100px'>
<!--        <el-form-item label='页面节点ID' prop='pagePointId'>-->
<!--          <el-input v-model='pointForm.pagePointId' placeholder='请输入页面节点ID' />-->
<!--        </el-form-item>-->
        <el-form-item label='节点编号' prop='pagePointCode'>
          <el-input v-model='pointForm.pagePointCode' placeholder='请输入节点编号' />
        </el-form-item>
        <el-form-item label='节点名称' prop='pagePointName'>
          <el-input v-model='pointForm.pagePointName' placeholder='请输入节点名称' />
        </el-form-item>
        <el-form-item label='节点类型' prop='pointType'>
          <el-input v-model='pointForm.pointType' placeholder='请输入节点类型' />
        </el-form-item>
        <el-form-item label='组件类型' prop='componentType'>
          <el-input v-model='pointForm.componentType' placeholder='请输入组件类型' />
        </el-form-item>
        <el-form-item label='X坐标' prop='posX'>
          <el-input-number v-model='pointForm.posX' :min='0' placeholder='请输入X坐标' />
        </el-form-item>
        <el-form-item label='Y坐标' prop='posY'>
          <el-input-number v-model='pointForm.posY' :min='0' placeholder='请输入Y坐标' />
        </el-form-item>
        <el-form-item label='宽度' prop='width'>
          <el-input-number v-model='pointForm.width' :min='0' placeholder='请输入宽度' />
        </el-form-item>
        <el-form-item label='高度' prop='height'>
          <el-input-number v-model='pointForm.height' :min='0' placeholder='请输入高度' />
        </el-form-item>
        <el-form-item label='节点标题' prop='pagePointTitle'>
          <el-input v-model='pointForm.pagePointTitle' placeholder='请输入节点标题' />
        </el-form-item>
        <el-form-item label='数据内容' prop='dataContent'>
          <el-input v-model='pointForm.dataContent' type='textarea' placeholder='请输入数据内容' />
        </el-form-item>
        <el-form-item label='显示排序' prop='sortOrder'>
          <el-input-number v-model='pointForm.sortOrder' :min='0' placeholder='请输入显示排序' />
        </el-form-item>
        <el-form-item label='激活标识' prop='activeFlag'>
          <el-radio-group v-model='pointForm.activeFlag'>
            <el-radio
              v-for='dict in active_flag'
              :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='pointForm.remark' type='textarea' placeholder='请输入备注' />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button type='primary' @click='submitPointForm'>确 定</el-button>
          <el-button @click='cancelPoint'>取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改页面连接线对话框 -->
    <el-dialog :title='edgeDialog.title' v-model='edgeDialog.visible' width='600px' append-to-body>
      <el-form ref='edgeFormRef' :model='edgeForm' :rules='edgeRules' label-width='100px'>
<!--        <el-form-item label='页面连接线ID' prop='pageEdgesId'>-->
<!--          <el-input v-model='edgeForm.pageEdgesId' placeholder='请输入页面连接线ID' />-->
<!--        </el-form-item>-->
        <el-form-item label='线类型' prop='edgeType'>
          <el-input v-model='edgeForm.edgeType' placeholder='请输入线类型' />
        </el-form-item>
        <el-form-item label='原节点ID' prop='sourceNodeId'>
          <el-input v-model='edgeForm.sourceNodeId' placeholder='请输入原节点ID' />
        </el-form-item>
        <el-form-item label='目标节点ID' prop='targetNodeId'>
          <el-input v-model='edgeForm.targetNodeId' placeholder='请输入目标节点ID' />
        </el-form-item>
        <el-form-item label='源句柄ID' prop='sourceHandleId'>
          <el-input v-model='edgeForm.sourceHandleId' placeholder='请输入源句柄ID' />
        </el-form-item>
        <el-form-item label='目标句柄ID' prop='targetHandleId'>
          <el-input v-model='edgeForm.targetHandleId' placeholder='请输入目标句柄ID' />
        </el-form-item>
        <el-form-item label='X坐标' prop='posX'>
          <el-input-number v-model='edgeForm.posX' :min='0' placeholder='请输入X坐标' />
        </el-form-item>
        <el-form-item label='Y坐标' prop='posY'>
          <el-input-number v-model='edgeForm.posY' :min='0' placeholder='请输入Y坐标' />
        </el-form-item>
        <el-form-item label='宽度' prop='width'>
          <el-input-number v-model='edgeForm.width' :min='0' placeholder='请输入宽度' />
        </el-form-item>
        <el-form-item label='高度' prop='height'>
          <el-input-number v-model='edgeForm.height' :min='0' placeholder='请输入高度' />
        </el-form-item>
        <el-form-item label='自定义内容' prop='customContent'>
          <el-input v-model='edgeForm.customContent' type='textarea' placeholder='请输入自定义内容' />
        </el-form-item>
        <el-form-item label='显示排序' prop='sortOrder'>
          <el-input-number v-model='edgeForm.sortOrder' :min='0' placeholder='请输入显示排序' />
        </el-form-item>
        <el-form-item label='激活标识' prop='activeFlag'>
          <el-radio-group v-model='edgeForm.activeFlag'>
            <el-radio
              v-for='dict in active_flag'
              :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='edgeForm.remark' type='textarea' placeholder='请输入备注' />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class='dialog-footer'>
          <el-button type='primary' @click='submitEdgeForm'>确 定</el-button>
          <el-button @click='cancelEdge'>取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name='DesignPageConfig' lang='ts'>
import {
  listDesignPageConfig,
  getDesignPageConfig,
  delDesignPageConfig,
  addDesignPageConfig,
  updateDesignPageConfig
} from '@/api/system/designPageConfig';
import { DesignPageConfigVO, DesignPageConfigQuery, DesignPageConfigForm } from '@/api/system/designPageConfig/types';
import { DesignPagePointVO, DesignPagePointQuery, DesignPagePointForm } from '@/api/system/designPagePoint/types';
import { DesignPageEdgesVO, DesignPageEdgesQuery, DesignPageEdgesForm } from '@/api/system/designPageEdges/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { active_flag } = toRefs<any>(proxy?.useDict('active_flag'));

const designPageConfigList = ref<DesignPageConfigVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const designPageConfigFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `页面配置ID`, visible: true },
  { key: 1, label: `租户编号`, visible: true },
  { key: 2, label: `页面名称`, visible: true },
  { key: 3, label: `页面背景`, visible: true },
  { key: 4, label: `页面路由`, visible: true },
  { key: 5, label: `自定义内容`, visible: true },
  { key: 6, label: `显示排序`, visible: true },
  { key: 7, label: `预留字段一`, visible: false },
  { key: 8, label: `预留字段二`, visible: false },
  { key: 9, label: `预留字段三`, visible: false },
  { key: 10, label: `预留字段四`, visible: false },
  { key: 11, label: `预留字段五`, visible: false },
  { key: 12, label: `删除标志`, visible: false },
  { key: 13, label: `激活标识`, visible: true },
  { key: 14, label: `备注`, visible: false },
  { key: 15, label: `创建部门`, visible: false },
  { key: 16, label: `创建人`, visible: false },
  { key: 17, label: `创建时间`, visible: false },
  { key: 18, label: `更新人`, visible: false },
  { key: 19, label: `更新时间`, visible: false }
]);

const initFormData: DesignPageConfigForm = {
  pageConfigId: undefined,
  pageConfigName: undefined,
  pageBackground: undefined,
  pageRouting: undefined,
  customContent: undefined,
  sortOrder: undefined,
  fieldOne: undefined,
  fieldTwo: undefined,
  fieldThree: undefined,
  fieldFour: undefined,
  fieldFive: undefined,
  activeFlag: '1',
  remark: undefined
};
const data = reactive<PageData<DesignPageConfigForm, DesignPageConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pageConfigId: undefined,
    pageConfigName: undefined,
    pageBackground: undefined,
    pageRouting: undefined,
    customContent: undefined,
    sortOrder: undefined,
    fieldOne: undefined,
    fieldTwo: undefined,
    fieldThree: undefined,
    fieldFour: undefined,
    fieldFive: undefined,
    activeFlag: undefined,
    params: {}
  },
  rules: {
    pageConfigName: [
      { required: true, message: '页面名称不能为空', trigger: 'blur' }
    ],
    activeFlag: [
      { required: true, message: '激活标识不能为空', trigger: 'change' }
    ]
  }
});

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

// 节点相关
const pointList = ref<DesignPagePointVO[]>([]);
const pointLoading = ref(false);
const pointButtonLoading = ref(false);
const pointFormRef = ref<ElFormInstance>();

const pointDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initPointFormData: DesignPagePointForm = {
  pagePointId: undefined,
  pageConfigId: undefined,
  pagePointCode: undefined,
  pagePointName: undefined,
  pointType: undefined,
  componentType: undefined,
  posX: 0,
  posY: 0,
  width: 0,
  height: 0,
  pagePointTitle: undefined,
  dataContent: undefined,
  sortOrder: 0,
  fieldOne: undefined,
  fieldTwo: undefined,
  fieldThree: undefined,
  fieldFour: undefined,
  fieldFive: undefined,
  activeFlag: '1',
  remark: undefined
};

// 连接线相关
const edgeList = ref<DesignPageEdgesVO[]>([]);
const edgeLoading = ref(false);
const edgeButtonLoading = ref(false);
const edgeFormRef = ref<ElFormInstance>();

const edgeDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initEdgeFormData: DesignPageEdgesForm = {
  pageEdgesId: undefined,
  pageConfigId: undefined,
  edgeType: undefined,
  sourceNodeId: undefined,
  targetNodeId: undefined,
  sourceHandleId: undefined,
  targetHandleId: undefined,
  posX: 0,
  posY: 0,
  width: 0,
  height: 0,
  customContent: undefined,
  sortOrder: 0,
  fieldOne: undefined,
  fieldTwo: undefined,
  fieldThree: undefined,
  fieldFour: undefined,
  fieldFive: undefined,
  activeFlag: '1',
  remark: undefined
};

const pointData = reactive<PageData<DesignPagePointForm, DesignPagePointQuery>>({
  form: { ...initPointFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pageConfigId: undefined,
    activeFlag: undefined,
    params: {}
  },
  rules: {}
});

const edgeData = reactive<PageData<DesignPageEdgesForm, DesignPageEdgesQuery>>({
  form: { ...initEdgeFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pageConfigId: undefined,
    activeFlag: undefined,
    params: {}
  },
  rules: {
    sourceNodeId: [
      { required: true, message: '原节点ID不能为空', trigger: 'blur' }
    ],
    targetNodeId: [
      { required: true, message: '目标节点ID不能为空', trigger: 'blur' }
    ]
  }
});

const { queryParams: pointQueryParams, form: pointForm, rules: pointRules } = toRefs(pointData);
const { queryParams: edgeQueryParams, form: edgeForm, rules: edgeRules } = toRefs(edgeData);

/** 查询大屏设计页面配置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listDesignPageConfig(queryParams.value);
  designPageConfigList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  designPageConfigFormRef.value?.resetFields();
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: DesignPageConfigVO[]) => {
  ids.value = selection.map(item => item.pageConfigId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加大屏设计页面配置';
  pointList.value = []; // 清空节点列表
  edgeList.value = []; // 清空连接线列表
};

/** 修改按钮操作 */
const handleUpdate = async (row?: DesignPageConfigVO) => {
  reset();
  const _pageConfigId = row?.pageConfigId || ids.value[0];
  const res = await getDesignPageConfig(_pageConfigId);
  // 处理返回数据
  const { designPagePointList, designPageEdgesList, ...configData } = res.data as any;
  Object.assign(form.value, configData);
  // 设置节点列表
  if (designPagePointList && Array.isArray(designPagePointList)) {
    pointList.value = designPagePointList.map(point => ({
      ...point,
      posX: Number(point.posX),
      posY: Number(point.posY),
      width: Number(point.width),
      height: Number(point.height),
      sortOrder: Number(point.sortOrder)
    }));
  } else {
    pointList.value = [];
  }
  // 设置连接线列表
  if (designPageEdgesList && Array.isArray(designPageEdgesList)) {
    edgeList.value = designPageEdgesList.map(edge => ({
      ...edge,
      posX: Number(edge.posX),
      posY: Number(edge.posY),
      width: Number(edge.width),
      height: Number(edge.height),
      sortOrder: Number(edge.sortOrder)
    }));
  } else {
    edgeList.value = [];
  }
  dialog.visible = true;
  dialog.title = '修改大屏设计页面配置';
};

/** 提交按钮 */
const submitForm = () => {
  designPageConfigFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 将节点列表和连接线列表添加到表单数据中
      const submitData: DesignPageConfigForm = {
        ...form.value,
        designPagePointList: pointList.value,
        designPageEdgesList: edgeList.value
      };

      if (form.value.pageConfigId) {
        await updateDesignPageConfig(submitData).finally(() => buttonLoading.value = false);
      } else {
        await addDesignPageConfig(submitData).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: DesignPageConfigVO) => {
  const _pageConfigIds = row?.pageConfigId || ids.value;
  await proxy?.$modal.confirm('是否确认删除大屏设计页面配置编号为"' + _pageConfigIds + '"的数据项？').finally(() => loading.value = false);
  await delDesignPageConfig(_pageConfigIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/designPageConfig/export', {
    ...queryParams.value
  }, `designPageConfig_${new Date().getTime()}.xlsx`);
};

/** 新增节点按钮操作 */
const handleAddPoint = () => {
  pointForm.value = { ...initPointFormData };
  pointForm.value.pageConfigId = form.value.pageConfigId;
  pointDialog.visible = true;
  pointDialog.title = '添加页面节点';
};

/** 修改节点按钮操作 */
const handleUpdatePoint = async (row: DesignPagePointVO) => {
  pointForm.value = { ...initPointFormData };
  Object.assign(pointForm.value, row);
  pointDialog.visible = true;
  pointDialog.title = '修改页面节点';
};

/** 删除节点按钮操作 */
const handleDeletePoint = async (row: DesignPagePointVO) => {
  await proxy?.$modal.confirm('是否确认删除该页面节点？');
  const index = pointList.value.findIndex(item => item.pagePointId === row.pagePointId);
  if (index > -1) {
    pointList.value.splice(index, 1);
  }
  proxy?.$modal.msgSuccess('删除成功');
};

/** 提交节点表单 */
const submitPointForm = () => {
  pointFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const pointData: DesignPagePointVO = {
        pagePointId: pointForm.value.pagePointId,
        pageConfigId: form.value.pageConfigId,
        pagePointCode: pointForm.value.pagePointCode,
        pagePointName: pointForm.value.pagePointName,
        pointType: pointForm.value.pointType,
        componentType: pointForm.value.componentType,
        posX: Number(pointForm.value.posX),
        posY: Number(pointForm.value.posY),
        width: Number(pointForm.value.width),
        height: Number(pointForm.value.height),
        pagePointTitle: pointForm.value.pagePointTitle,
        dataContent: pointForm.value.dataContent,
        sortOrder: Number(pointForm.value.sortOrder),
        fieldOne: pointForm.value.fieldOne,
        fieldTwo: pointForm.value.fieldTwo,
        fieldThree: pointForm.value.fieldThree,
        fieldFour: pointForm.value.fieldFour,
        fieldFive: pointForm.value.fieldFive,
        activeFlag: pointForm.value.activeFlag,
        remark: pointForm.value.remark
      };

      if (pointForm.value.pagePointId) {
        // 修改节点
        const index = pointList.value.findIndex(item => item.pagePointId === pointForm.value.pagePointId);
        if (index > -1) {
          pointList.value[index] = pointData;
        }
      } else {
        // 新增节点
        // 生成临时ID，确保唯一性
        const tempId = 'temp_' + new Date().getTime();
        pointData.pagePointId = tempId;
        pointList.value.push(pointData);
      }
      proxy?.$modal.msgSuccess('操作成功');
      pointDialog.visible = false;
    }
  });
};

/** 取消节点表单 */
const cancelPoint = () => {
  pointForm.value = { ...initPointFormData };
  pointDialog.visible = false;
};

/** 新增连接线按钮操作 */
const handleAddEdge = () => {
  edgeForm.value = { ...initEdgeFormData };
  edgeForm.value.pageConfigId = form.value.pageConfigId;
  edgeDialog.visible = true;
  edgeDialog.title = '添加页面连接线';
};

/** 修改连接线按钮操作 */
const handleUpdateEdge = async (row: DesignPageEdgesVO) => {
  edgeForm.value = { ...initEdgeFormData };
  Object.assign(edgeForm.value, row);
  edgeDialog.visible = true;
  edgeDialog.title = '修改页面连接线';
};

/** 删除连接线按钮操作 */
const handleDeleteEdge = async (row: DesignPageEdgesVO) => {
  await proxy?.$modal.confirm('是否确认删除该页面连接线？');
  const index = edgeList.value.findIndex(item => item.pageEdgesId === row.pageEdgesId);
  if (index > -1) {
    edgeList.value.splice(index, 1);
  }
  proxy?.$modal.msgSuccess('删除成功');
};

/** 提交连接线表单 */
const submitEdgeForm = () => {
  edgeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const edgeData: DesignPageEdgesVO = {
        pageEdgesId: edgeForm.value.pageEdgesId,
        pageConfigId: form.value.pageConfigId,
        edgeType: edgeForm.value.edgeType,
        sourceNodeId: edgeForm.value.sourceNodeId,
        targetNodeId: edgeForm.value.targetNodeId,
        sourceHandleId: edgeForm.value.sourceHandleId,
        targetHandleId: edgeForm.value.targetHandleId,
        posX: Number(edgeForm.value.posX),
        posY: Number(edgeForm.value.posY),
        width: Number(edgeForm.value.width),
        height: Number(edgeForm.value.height),
        customContent: edgeForm.value.customContent,
        sortOrder: Number(edgeForm.value.sortOrder),
        fieldOne: edgeForm.value.fieldOne,
        fieldTwo: edgeForm.value.fieldTwo,
        fieldThree: edgeForm.value.fieldThree,
        fieldFour: edgeForm.value.fieldFour,
        fieldFive: edgeForm.value.fieldFive,
        activeFlag: edgeForm.value.activeFlag,
        remark: edgeForm.value.remark
      };

      if (edgeForm.value.pageEdgesId) {
        // 修改连接线
        const index = edgeList.value.findIndex(item => item.pageEdgesId === edgeForm.value.pageEdgesId);
        if (index > -1) {
          edgeList.value[index] = edgeData;
        }
      } else {
        // 新增连接线
        // 生成临时ID，确保唯一性
        const tempId = 'temp_' + new Date().getTime();
        edgeData.pageEdgesId = tempId;
        edgeList.value.push(edgeData);
      }
      proxy?.$modal.msgSuccess('操作成功');
      edgeDialog.visible = false;
    }
  });
};

/** 取消连接线表单 */
const cancelEdge = () => {
  edgeForm.value = { ...initEdgeFormData };
  edgeDialog.visible = false;
};

onMounted(() => {
  getList();
});
</script>
