<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="流程名称" prop="flowName">
        <el-input
          v-model="queryParams.flowName"
          class="!w-240px"
          clearable
          placeholder="请输入流程名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button plain type="primary" @click="openForm('create')">
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" style="width: 100%">
      <el-table-column label="流程名称" align="center" prop="flowName" min-width="120" />
      <el-table-column label="流程类型" align="center" min-width="90">
        <template #default="scope">
          {{
            getStrDictOptions(DICT_TYPE.FLOW_TYPE).find((dict) => dict.value === scope.row.type)
              ?.label || '-'
          }}
        </template>
      </el-table-column>
      <el-table-column
        label="流程链接"
        align="center"
        prop="flowUrl"
        min-width="120"
        show-overflow-tooltip
      />

      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column
        label="备注"
        align="center"
        prop="remark"
        show-overflow-tooltip
        min-width="150"
      />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row)"> 编辑 </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    append-to-body
    @closed="handleDialogClosed"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
      <el-form-item label="所属分组" prop="groupId">
        <el-select v-model="formData.groupId" placeholder="请选择所属分组" class="w-full">
          <el-option
            v-for="group in groupList"
            :key="group.id"
            :label="group.groupName"
            :value="group.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="流程类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择流程类型" clearable>
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.FLOW_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="流程名称" prop="flowName">
        <!-- <el-input v-model="formData.flowName" placeholder="请输入流程名称" /> -->
        <lang-input v-model="formData.flowName" placeholder="请输入流程名称" />
      </el-form-item>

      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="formData.sort"
          :min="0"
          controls-position="right"
          class="!w-100%"
        />
      </el-form-item>

      <el-form-item label="菜单图标">
        <IconSelect v-model="formData.icon" clearable />
      </el-form-item>

      <el-form-item label="首页地址" prop="indexUrl">
        <el-input v-model="formData.indexUrl" placeholder="请输入首页地址" />
      </el-form-item>

      <el-form-item label="流程链接" prop="flowUrl">
        <el-input v-model="formData.flowUrl" placeholder="请输入流程链接" />
      </el-form-item>

      <el-form-item label="App流程链接" prop="appUrl">
        <el-input v-model="formData.appUrl" placeholder="请输入App流程链接" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :value="0">正常</el-radio>
          <el-radio :value="1">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="submitLoading"> 确 定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import { formatDate } from '@/utils/formatTime'
import { createFlow, getFlowList, updateFlow, deleteFlow, getGroupList } from '@/api/flow'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
// --- 响应式数据 ---
const loading = ref(false)
const list = ref([])
const total = ref(0)
const groupList = ref([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  flowName: undefined
})
const queryFormRef = ref(null)

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref(null)
const submitLoading = ref(false)
const formData = reactive({
  id: undefined,
  groupId: undefined,
  flowName: '',
  flowUrl: '',
  appUrl: '',
  remark: '',
  status: 0, // 默认正常，
  indexUrl: '', // 前端路由地址，后端不存储，仅供前端使用
  sort: 0,
  type: undefined // 流程类型
})

const formRules = reactive({
  groupId: [{ required: true, message: '请选择所属分组', trigger: 'change' }],
  flowName: [{ required: true, message: '请输入流程名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
  flowUrl: [{ required: true, message: '请输入流程链接', trigger: 'blur' }],
  // appUrl: [{ required: true, message: '请输入App流程链接', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  indexUrl: [{ required: true, message: '请输入首页地址', trigger: 'blur' }],
  type: [{ required: true, message: '请选择流程类型', trigger: 'change' }]
})

// --- 方法 ---

const getList = async () => {
  loading.value = true
  try {
    const res = await getFlowList(queryParams)
    list.value = res.list
    total.value = res.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const openForm = (type, row) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增流程' : '编辑流程'

  if (type === 'create') {
    formData.id = undefined
    formData.groupId = undefined
    formData.flowName = ''
    formData.indexUrl = ''
    formData.flowUrl = ''
    formData.appUrl = ''
    formData.remark = ''
    formData.status = 0 // 新增时默认正常
    formData.sort = 0 // 新增时默认排序为0
    formData.type = undefined
  } else {
    // 编辑模式：深拷贝，避免直接修改表格数据
    Object.assign(formData, JSON.parse(JSON.stringify(row)))
    // 确保 status 有值，防止后端返回 null 导致单选框异常
    if (formData.status === null || formData.status === undefined) {
      formData.status = 0
    }
  }

  // 清除校验状态
  formRef.value?.clearValidate()
}

// 对话框关闭时重置表单
const handleDialogClosed = () => {
  formRef.value?.resetFields()
}

const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const submitData = { ...formData }

        if (formData.id) {
          await updateFlow(submitData)
          ElMessage.success('修改成功')
        } else {
          await createFlow(submitData)
          ElMessage.success('新增成功')
        }

        dialogVisible.value = false
        await getList()
      } catch (error) {
        console.error(error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除该项吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await deleteFlow(id)
    ElMessage.success('删除成功')
    await getList()
  } catch (error) {
    // ignore
  }
}

onMounted(async () => {
  getList()
  const res = await getGroupList()
  groupList.value = res.list || []
})
</script>

<style scoped></style>
