<template>
  <ContentWrap>
    <!--      顶部新增表单-->
    <el-form ref="formRef" v-loading="formLoading" :model="formData" label-width="100px">
      <el-form-item label="角色">
        <el-select v-model="formData.roleId" placeholder="请选择角色" style="width: 300px">
          <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="页面" prop="pageType">
        <el-select v-model="formData.pageType" placeholder="请选择页面" style="width: 300px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COCKPIT_PAGE_TYPE)"
            :key="dict.value"
            :value="dict.value"
            :label="dict.label"
          />
        </el-select>
      </el-form-item>
      <el-button
        type="primary"
        style="margin-left: 500px"
        @click="submitForm"
        v-if="!isUpdate"
        :disabled="isSuccess"
        >保 存
      </el-button>
      <el-button type="primary" style="margin-left: 500px" @click="submitForm" v-else
        >修改
      </el-button>
      <el-button @click="goBack">取 消</el-button>
    </el-form>
  </ContentWrap>
  <ContentWrap v-if="showTable">
    <!--      底部数据表格和预览-->
    <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'" :page-id="formData.id" />
      <LookView v-else :page-id="formData.id" />
    </ContentWrap>
  </ContentWrap>
</template>
<script setup lang="ts">
import TableView from './TableView.vue'
import LookView from './LookView.vue'
import * as rolePageApi from '@/api/system/rolePage/index'
import * as RoleApi from '@/api/system/role'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { useTagsViewStoreWithOut } from '@/store/modules/tagsView'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const router = useRouter()
const route = useRoute()
const roleList = ref([] as RoleApi.RoleVO[]) // 角色的列表
const formLoading = ref(false) // 表单的加载中
const tabPosition = ref('first')

const formData = reactive({
  id: undefined,
  roleId: undefined,
  pageType: undefined
})
const showTable = ref(false) //是否展示底部表格区
const isUpdate = route.query.id
const isSuccess = ref(false) // 新增成功后禁用按钮
// 监听数据变化，设置未保存标记
watch(
  () => ({
    roleId: formData.roleId
  }),
  { deep: true }
)

onMounted(() => {
  getRoleData() //角色下拉数据
  if (isUpdate) {
    editData()
    showTable.value = true
  }
})

// 角色下拉数据
const getRoleData = async () => {
  const data = await RoleApi.getSimpleRoleList()
  roleList.value = data
  console.log(data, '数据格式')
}

// 方法定义
const handleTabChange = (newTab: string) => {
  tabPosition.value = newTab
}

// 编辑时数据渲染
const editData = async () => {
  const data = await rolePageApi.selectRolePageById(route.query.id)
  formData.id = data.id
  formData.roleId = data.roleId
  formData.pageType = data.pageType
  console.log(data, 'hnudhiahauihasihi')
}
// 提交表单
const submitForm = async () => {
  try {
    let data
    let successMessage
    if (isUpdate) {
      // 有 id，调用修改接口
      data = await rolePageApi.updateRolePage(formData)
      successMessage = t('common.updateSuccess')
    } else {
      // 没有 id，调用新增接口
      console.log(formData, '数据格式')
      data = await rolePageApi.insertRolePage(formData)
      successMessage = t('common.createSuccess')
      showTable.value = true //新增成功后显示下发列表
      isSuccess.value = true //新增成功后保存按钮不显示
      // 新增成功后，将返回的 id 保存到 formData 中
      if (data) {
        formData.id = data
      }
    }
    if (data) {
      message.success(successMessage)
    }
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败，请稍后重试')
  }
}

//退出页面
const goBack = () => {
  // 获取 tagsView store
  const tagsViewStore = useTagsViewStoreWithOut()
  // 获取当前路由对象
  const currentRoute = router.currentRoute.value
  // 方法1：精确删除当前标签（推荐）
  tagsViewStore.delVisitedView(currentRoute)
  router.push('/system/rolePage');
  (formData.id = undefined), (formData.roleId = undefined), (formData.pageType = undefined)
}
</script>

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