<template>
  <div>
    <ContentWrap>
      <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="100px">
        <el-form-item label="模式名称" prop="name">
          <el-input style="width: 300px" v-model="formData.modeName" placeholder="请输入模式名称" />
        </el-form-item>
        <el-form-item label="标题" prop="name">
          <el-input style="width: 300px" v-model="formData.modeTitle" placeholder="请输入标题" />
        </el-form-item>

        <el-form-item label="支持共锁" prop="isColockSupport">
          <el-checkbox v-model="formData.isColockSupport" :value="true" />
        </el-form-item>

        <el-form-item label="描述" prop="modeDescription">
          <el-input
            style="width: 550px"
            v-model="formData.modeDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入描述内容"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-button type="primary" style="margin-left: 500px" @click="SaveWorkflowMode"
          >保 存
        </el-button>
        <el-button @click="goBack">取 消</el-button>
      </el-form>
      <el-form-item label="模式步骤" prop="step" style="margin-left: 30px" />
      <el-radio-group v-model="tabPosition" class="mb-15px" @change="handleTabChange">
        <el-radio-button label="first">表格视图</el-radio-button>
        <el-radio-button label="second">流程视图</el-radio-button>
      </el-radio-group>
      <ContentWrap>
        <TableView
          v-if="tabPosition == 'first'"
          :enableStepTable="enableStepTable"
          :modeId="formData.id"
        />
        <WorkflowView v-else :enableStepTable="enableStepTable" :modeId="formData.id" />
      </ContentWrap>
    </ContentWrap>
  </div>
</template>
<script setup lang="ts">
import TableView from './TableView.vue'
import WorkflowView from './WorkFlowView.vue'
import * as ModeApi from '@/api/custonWorkflow/index'
import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter()
const formLoading = ref(false) // 表单的加载中
const tabPosition = ref('first')
const enableStepTable = ref(false) //新增控制表格新增 模板导入 删除不能点击或者出现
const formData = ref({
  modeName: undefined,
  modeTitle: undefined,
  isColockSupport: false,
  modeDescription: undefined,
  isPreset: undefined,
  id:undefined,
})
// 监听数据变化，设置未保存标记
const hasUnsavedChanges = ref(false) // 标记是否有未保存的更改
// 方法定义
const handleTabChange = (newTab: string) => {
  tabPosition.value = newTab
}

const SaveWorkflowMode = async () => {
  try {
    let data
    let successMessage

    if (formData.value.id) {
      // 有 id，调用修改接口
      data = await ModeApi.updateWorkflowMode(formData.value)
      successMessage = t('common.updateSuccess')
    } else {
      // 没有 id，调用新增接口
      data = await ModeApi.insertWorkflowMode(formData.value)
      successMessage = t('common.createSuccess')
      enableStepTable.value = true
      // 新增成功后，将返回的 id 保存到 formData 中
      if (data) {
        formData.value.id = data
      }
    }

    if (data) {
      message.success(successMessage)
      // 保存成功后重置未保存标记
      hasUnsavedChanges.value = false
    }
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败，请稍后重试')
  }
}
// 监听数据变化，设置未保存标记
watch(
  () => ({
    modeName: formData.value.modeName,
    modeTitle: formData.value.modeTitle,
    isColockSupport: formData.value.isColockSupport,
    modeDescription: formData.value.modeDescription,
    isPreset: formData.value.isPreset
  }),
  () => {
    hasUnsavedChanges.value = true
  },
  { deep: true }
)
// 路由离开守卫
onBeforeRouteLeave((to, from, next) => {
  if (hasUnsavedChanges.value) {
    ElMessageBox.confirm('当前页面有未保存的更改，是否继续离开？', '提示', {
      confirmButtonText: '继续离开',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        next()
      })
      .catch(() => {
        next(false)
      })
  } else {
    next()
  }
})
const goBack = () => {
  // 获取 tagsView store
  const tagsViewStore = useTagsViewStoreWithOut()

  // 获取当前路由对象
  const currentRoute = router.currentRoute.value

  // 方法1：精确删除当前标签（推荐）
  tagsViewStore.delVisitedView(currentRoute)
  router.push('/CustomWorkflow/CW')
}

</script>

<style scoped lang="scss"></style>
