<template>
  <v-card class="pa-5 card-box d-flex align-center justify-center flex-column" style="height: 600px;">
    <CtForm ref="formPageRef" :items="items" style="width: 600px;"></CtForm>
    <div>
      <v-btn class="half-button mr-3" color="primary" variant="outlined" @click="handleCancel">{{ $t('common.cancel') }}</v-btn>
      <v-btn color="primary" class="half-button" @click="handleSave">{{ $t('common.submit') }}</v-btn>
    </div>
  </v-card>
</template>

<script setup>
defineOptions({ name: 'system-post-add'})
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from '@/hooks/web/useI18n'
import { getEnterprisePostDetail, createEnterprisePost, updateEnterprisePost } from '@/api/recruit/enterprise/system/post'
import Snackbar from '@/plugins/snackbar'

const route = useRoute()
const router = useRouter()
const { t } = useI18n()
const formPageRef = ref()
let query = reactive({})
const items = ref({
  options: [
    {
      type: 'ifRadio',
      key: 'status',
      value: '0',
      label: '状态 *',
      width: 90,
      items: [
        { label: '正常', value: '0' },
        { label: '停用', value: '1' }
      ]
    },
    {
      type: 'text',
      key: 'nameCn',
      value: null,
      label: '岗位中文名称 *',
      rules: [v => !!v || '请填写岗位中文名称']
    },
    {
      type: 'text',
      key: 'nameEn',
      value: null,
      label: '岗位英文名称 *',
      rules: [v => !!v || '请填写岗位英文名称']
    },
    {
      type: 'text',
      key: 'code',
      value: null,
      label: '岗位缩写'
    },
    {
      type: 'number',
      key: 'sort',
      value: null,
      label: '岗位级别 *',
      rules: [v => !!v || '请填写岗位级别']
    },
    {
      type: 'text',
      key: 'remark',
      value: null,
      label: '备注'
    }
  ]
})

const getPostDetail = async (id) => {
  const data = await getEnterprisePostDetail(id)
  if (!data) return
  query.id = data.id
  items.value.options.forEach(val => {
    val.value = data[val.key]
  })
}

const handleCancel = () => {
  router.push('/recruit/enterprise/systemManagement/postManagement')
}

const handleSave = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  items.value.options.forEach(val => {
    query[val.key] = val.value
  })
  const api = query.id ? updateEnterprisePost : createEnterprisePost
  await api(query)
  Snackbar.success(t('common.submittedSuccessfully'))
  handleCancel()
}

if (route.query && route.query.id) {
  if (route.query.id) getPostDetail(route.query.id)
}
</script>

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