<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>流程管理</span>
          <div>
            <el-button type="warning" @click="openMigrateDialog" style="margin-right: 8px;">流程迁移</el-button>
            <el-button type="primary" @click="handleAdd">新增流程</el-button>
          </div>
        </div>
      </template>

      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="流程编码">
          <el-input v-model="queryParams.processCode" placeholder="请输入流程编码" clearable />
        </el-form-item>
        <el-form-item label="流程名称">
          <el-input v-model="queryParams.processName" placeholder="请输入流程名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: auto; min-width: 120px;">
            <el-option label="草稿" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已停用" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="tableData" border>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="code" label="流程编码" />
        <el-table-column prop="name" label="流程名称" />
        <el-table-column prop="category" label="分类" />
        <el-table-column prop="version" label="版本" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="260">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleDesign(row)">设计</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button v-if="row.status === 0" link type="success" @click="handlePublish(row)">发布</el-button>
            <el-button v-if="row.status === 1" link type="warning" @click="handleStop(row)">停用</el-button>
            <el-button v-if="row.status === 2" link type="success" @click="handleEnable(row)">启用</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        class="pagination"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
      />
    </el-card>

    <!-- 新增流程 - 基本信息弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增流程" width="500px">
      <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">
        <el-form-item label="流程编码" prop="code">
          <el-input v-model="addForm.code" placeholder="请输入流程编码" />
        </el-form-item>
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="addForm.category" placeholder="请输入分类" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="addForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">下一步：设计流程</el-button>
      </template>
    </el-dialog>

    <!-- 编辑流程 - 基本信息弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑流程信息" width="700px">
      <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="120px">
        <el-form-item label="流程编码">
          <el-input v-model="editForm.code" disabled />
        </el-form-item>
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="分类">
          <el-input v-model="editForm.category" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editForm.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <template #label>
            节点名称字段
            <el-tooltip placement="top" content="导入流程时，按此字段的值匹配对应的流程节点" raw-content>
              <el-icon style="margin-left: 4px; cursor: help;"><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="editForm.nodeFieldName" placeholder="如：节点名称，对应 Excel 中的列名" />
        </el-form-item>
        <el-form-item>
          <template #label>
            归属人字段
            <el-tooltip placement="top" content="导入流程时，按此字段的值匹配 sys_user 表中的用户，匹配成功则该流程属于该用户" raw-content>
              <el-icon style="margin-left: 4px; cursor: help;"><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <el-input v-model="editForm.ownerFieldName" placeholder="如：发起人，对应 Excel 中的列名" />
        </el-form-item>
        <el-form-item label="业务编号字段">
          <el-input v-model="editForm.bizFieldName" placeholder="如：customerName，列表中显示为该字段的值" />
        </el-form-item>
      </el-form>

      <div class="form-fields-section">
        <div class="form-fields-header">
          <span class="form-fields-title">流程表单字段</span>
          <el-button type="primary" size="small" @click="addFormField">添加字段</el-button>
        </div>
        <el-table :data="editFormFields" size="small" border style="width: 100%">
          <el-table-column label="字段名" min-width="120">
            <template #default="{ $index }">
              <el-input v-model="editFormFields[$index].name" placeholder="英文标识" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="显示名" min-width="120">
            <template #default="{ $index }">
              <el-input v-model="editFormFields[$index].label" placeholder="中文显示名" size="small" />
            </template>
          </el-table-column>
          <el-table-column label="类型" width="120">
            <template #default="{ $index }">
              <el-select v-model="editFormFields[$index].type" placeholder="类型" size="small" style="width: 100%">
                <el-option v-for="opt in fieldTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="必填" width="70" align="center">
            <template #default="{ $index }">
              <el-checkbox v-model="editFormFields[$index].required" />
            </template>
          </el-table-column>
          <el-table-column label="多选" width="70" align="center">
            <template #default="{ $index }">
              <el-checkbox
                v-model="editFormFields[$index].multiple"
                :disabled="editFormFields[$index].type !== 'select'"
              />
            </template>
          </el-table-column>
          <el-table-column label="选项" width="90" align="center">
            <template #default="{ $index }">
              <el-button
                link
                type="primary"
                size="small"
                :disabled="editFormFields[$index].type !== 'select'"
                @click="openOptionDialog($index)"
              >
                配置选项
              </el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="70" align="center">
            <template #default="{ $index }">
              <el-button link type="danger" size="small" @click="removeFormField($index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-empty v-if="editFormFields.length === 0" description="暂无字段，点击上方按钮添加" :image-size="60" style="padding: 10px 0;" />
      </div>

      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 下拉选项配置弹窗 -->
    <el-dialog v-model="optionDialogVisible" title="配置下拉选项" width="500px">
      <div v-if="optionEditingField" class="option-edit-tip">
        字段：{{ optionEditingField.label || optionEditingField.name }}
        <el-checkbox v-model="optionEditingField.multiple" style="margin-left: 16px;">允许多选</el-checkbox>
      </div>
      <el-table :data="optionList" size="small" border>
        <el-table-column label="显示文本" min-width="140">
          <template #default="{ $index }">
            <el-input v-model="optionList[$index].label" placeholder="显示文本" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="选项值" min-width="140">
          <template #default="{ $index }">
            <el-input v-model="optionList[$index].value" placeholder="选项值" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="70" align="center">
          <template #default="{ $index }">
            <el-button link type="danger" size="small" @click="removeOption($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" size="small" style="margin-top: 12px;" @click="addOption">添加选项</el-button>
      <template #footer>
        <el-button @click="optionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOptions">保存</el-button>
      </template>
    </el-dialog>

    <!-- 流程迁移弹窗 -->
    <el-dialog v-model="migrateDialogVisible" title="流程迁移" width="550px">
      <el-form label-width="100px">
        <el-form-item label="源流程版本">
          <el-select v-model="migrateFromId" placeholder="请选择旧版本流程" style="width: 100%" @change="onMigrateFromChange">
            <el-option v-for="def in migrateDefinitionList" :key="def.id" :label="`${def.name}（v${def.version}）${def.status === 0 ? ' [设计]' : def.status === 1 ? ' [已发布]' : ' [已停用]'}`" :value="def.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标版本">
          <el-select v-model="migrateToId" placeholder="请选择新版本流程" style="width: 100%" :disabled="!migrateFromId">
            <el-option v-for="def in migrateTargetList" :key="def.id" :label="`${def.name}（v${def.version}）${def.status === 0 ? ' [设计]' : def.status === 1 ? ' [已发布]' : ' [已停用]'}`" :value="def.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-alert type="warning" :closable="false" style="margin-bottom: 12px;">
        <template #title>
          迁移将把所有运行中的实例从源版本切换到目标版本，节点按名称匹配。不兼容的实例将被跳过。操作不可逆，请确认后执行。
        </template>
      </el-alert>
      <template #footer>
        <el-button @click="migrateDialogVisible = false">取消</el-button>
        <el-button type="warning" :disabled="!migrateFromId || !migrateToId" :loading="migrating" @click="confirmMigrate">确认迁移</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { listDefinition, getDefinition, updateDefinition, deleteDefinition, publishDefinition, stopDefinition, enableDefinition } from '@/api/flow/definition'
import { migrateInstances } from '@/api/flow/instance'
import type { FlowDefinition, FormField, FormFieldOption } from '@/types/flow'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const tableData = ref<FlowDefinition[]>([])
const total = ref(0)
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  processCode: undefined as string | undefined,
  processName: undefined as string | undefined,
  status: undefined as number | undefined
})

// 新增流程弹窗
const addDialogVisible = ref(false)
const addFormRef = ref<FormInstance>()
const addForm = reactive({
  code: '',
  name: '',
  category: '',
  description: ''
})
const addFormRules: FormRules = {
  code: [{ required: true, message: '请输入流程编码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入流程名称', trigger: 'blur' }]
}

// 编辑流程弹窗
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<Partial<FlowDefinition>>({
  id: undefined,
  code: '',
  name: '',
  category: '',
  description: ''
})
const editFormRules: FormRules = {
  name: [{ required: true, message: '请输入流程名称', trigger: 'blur' }]
}
const editFormFields = ref<FormField[]>([])
const fieldTypeOptions = [
  { label: '文本', value: 'text' },
  { label: '多行文本', value: 'textarea' },
  { label: '数字', value: 'number' },
  { label: '日期', value: 'date' },
  { label: '下拉选择', value: 'select' }
]

function addFormField() {
  editFormFields.value.push({ name: '', label: '', type: 'text', required: false })
}

function removeFormField(index: number) {
  editFormFields.value.splice(index, 1)
}

function getEditFormSchema(): string {
  const validFields = editFormFields.value.filter(f => f.name.trim() && f.label.trim())
  return validFields.length > 0 ? JSON.stringify(validFields) : ''
}

function parseEditFormSchema(schema?: string) {
  editFormFields.value = []
  if (!schema) return
  try {
    const parsed = JSON.parse(schema)
    if (Array.isArray(parsed)) {
      editFormFields.value = parsed
    }
  } catch {
    editFormFields.value = []
  }
}

// 下拉选项编辑
const optionDialogVisible = ref(false)
const optionEditingIndex = ref<number | null>(null)
const optionEditingField = ref<FormField | null>(null)
const optionList = ref<FormFieldOption[]>([])

function openOptionDialog(index: number) {
  optionEditingIndex.value = index
  optionEditingField.value = editFormFields.value[index]
  const rawOptions = optionEditingField.value.options || []
  optionList.value = rawOptions.map((opt: any) => {
    if (typeof opt === 'string') {
      return { label: opt, value: opt }
    }
    return { label: String(opt.label ?? opt.value), value: opt.value }
  })
  optionDialogVisible.value = true
}

function addOption() {
  optionList.value.push({ label: '', value: '' })
}

function removeOption(index: number) {
  optionList.value.splice(index, 1)
}

function saveOptions() {
  if (optionEditingIndex.value === null || !optionEditingField.value) return
  const validOptions = optionList.value.filter(opt => String(opt.label).trim() !== '' && String(opt.value).trim() !== '')
  editFormFields.value[optionEditingIndex.value].options = validOptions
  editFormFields.value[optionEditingIndex.value].multiple = optionEditingField.value.multiple
  optionDialogVisible.value = false
}

function statusText(status: number) {
  return ['草稿', '已发布', '已停用'][status] || '未知'
}

function statusTagType(status: number) {
  return ['info', 'success', 'danger'][status] || 'info'
}

async function loadData() {
  if (loading.value) return
  loading.value = true
  try {
    const res = await listDefinition(queryParams)
    tableData.value = res.list
    total.value = res.total
  } catch (e: any) {
    ElMessage.error('加载流程列表失败' + (e?.displayMsg || e?.message ? '：' + (e.displayMsg || e.message) : ''))
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

function handleQuery() {
  queryParams.pageNum = 1
  loadData()
}

function handlePageChange() {
  loadData()
}

function handleSizeChange() {
  queryParams.pageNum = 1
  loadData()
}

function resetQuery() {
  queryParams.processCode = undefined
  queryParams.processName = undefined
  queryParams.status = undefined
  handleQuery()
}

// 新增流程：打开基本信息弹窗
function handleAdd() {
  Object.assign(addForm, { code: '', name: '', category: '', description: '' })
  addDialogVisible.value = true
}

// 确认新增，跳转到设计器
async function confirmAdd() {
  const valid = await addFormRef.value?.validate().catch(() => false)
  if (!valid) return
  addDialogVisible.value = false
  router.push({
    path: '/flow/designer',
    query: {
      mode: 'create',
      code: addForm.code,
      name: addForm.name,
      category: addForm.category,
      description: addForm.description
    }
  })
}

// 设计流程：跳转到设计器
function handleDesign(row: FlowDefinition) {
  router.push({
    path: '/flow/designer',
    query: {
      mode: 'edit',
      id: String(row.id),
      code: row.code,
      name: row.name,
      category: row.category,
      description: row.description
    }
  })
}

// 编辑流程信息：打开编辑弹窗
async function handleEdit(row: FlowDefinition) {
  Object.assign(editForm, row)
  try {
    const def = await getDefinition(row.id)
    parseEditFormSchema(def.formSchema)
  } catch {
    parseEditFormSchema('')
  }
  editDialogVisible.value = true
}

// 确认编辑信息
async function confirmEdit() {
  const valid = await editFormRef.value?.validate().catch(() => false)
  if (!valid) return
  const data: Partial<FlowDefinition> = {
    ...editForm,
    formSchema: getEditFormSchema()
  }
  await updateDefinition(data)
  ElMessage.success('修改成功')
  editDialogVisible.value = false
  loadData()
}

async function handlePublish(row: FlowDefinition) {
  try {
    await ElMessageBox.confirm(`确认发布流程 "${row.name}" 吗？`, '提示', { type: 'warning' })
    await publishDefinition(row.id)
    ElMessage.success('发布成功')
    loadData()
  } catch {
    // cancel
  }
}

async function handleStop(row: FlowDefinition) {
  try {
    await ElMessageBox.confirm(`确认停用流程 "${row.name}" 吗？`, '提示', { type: 'warning' })
    await stopDefinition(row.id)
    ElMessage.success('停用成功')
    loadData()
  } catch {
    // cancel
  }
}

async function handleEnable(row: FlowDefinition) {
  try {
    await ElMessageBox.confirm(`确认启用流程 "${row.name}" 吗？`, '提示', { type: 'warning' })
    await enableDefinition(row.id)
    ElMessage.success('启用成功')
    loadData()
  } catch {
    // cancel
  }
}

async function handleDelete(row: FlowDefinition) {
  try {
    await ElMessageBox.confirm(`确认删除流程 "${row.name}" 吗？`, '提示', { type: 'warning' })
    await deleteDefinition(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch {
    // cancel
  }
}

// 流程迁移
const migrateDialogVisible = ref(false)
const migrateFromId = ref<number | null>(null)
const migrateToId = ref<number | null>(null)
const migrateDefinitionList = ref<FlowDefinition[]>([])
const migrateTargetList = ref<FlowDefinition[]>([])
const migrating = ref(false)

async function openMigrateDialog() {
  migrateFromId.value = null
  migrateToId.value = null
  migrateTargetList.value = []
  // 加载全部流程定义（不受分页限制）
  try {
    const res = await listDefinition({ pageNum: 1, pageSize: 999 })
    migrateDefinitionList.value = res.list
  } catch {
    migrateDefinitionList.value = [...tableData.value]
  }
  migrateDialogVisible.value = true
}

function onMigrateFromChange() {
  migrateToId.value = null
  const from = migrateDefinitionList.value.find(d => d.id === migrateFromId.value)
  if (!from) { migrateTargetList.value = []; return }
  migrateTargetList.value = migrateDefinitionList.value.filter(d => d.id !== from.id)
}

async function confirmMigrate() {
  if (!migrateFromId.value || !migrateToId.value) return
  try {
    await ElMessageBox.confirm(
      `确认将所有运行中的实例从源版本 v${migrateDefinitionList.value.find(d => d.id === migrateFromId.value)?.version} 迁移到目标版本 v${migrateTargetList.value.find(d => d.id === migrateToId.value)?.version} 吗？此操作不可逆。`,
      '确认迁移', { type: 'warning' }
    )
  } catch { return }
  migrating.value = true
  try {
    const res = await migrateInstances(migrateFromId.value, migrateToId.value)
    ElMessage.success(`迁移完成，共迁移 ${res.migratedCount} 个实例`)
    migrateDialogVisible.value = false
    loadData()
  } catch (e: any) {
    ElMessage.error(e?.message || '迁移失败')
  } finally { migrating.value = false }
}

onMounted(loadData)
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.search-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
.form-fields-section {
  margin-top: 16px;
  border-top: 1px solid #ebeef5;
  padding-top: 16px;
}
.form-fields-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.form-fields-title {
  font-weight: bold;
  color: #303133;
}
</style>
