<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="职位名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入职位名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="工作地区" prop="areaId">
        <el-cascader v-model="queryParams.areaId" :options="areaTreeData" clearable :props="{ label: 'name', value: 'id', emitPath: false }"  class="!w-240px" />
      </el-form-item>
      <el-form-item label="职位类型" prop="positionId">
        <el-cascader v-model="queryParams.positionId" :options="positionTreeData" clearable :props="{ label: 'nameCn', value: 'id', emitPath: false }"  class="!w-240px" />
      </el-form-item>
      <el-form-item label="招聘类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择招聘类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_JOB_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工作经验" prop="expType">
        <el-select
          v-model="queryParams.expType"
          placeholder="请选择工作经验"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_EXP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="学历要求" prop="eduType">
        <el-select
          v-model="queryParams.eduType"
          placeholder="请选择学历要求"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_EDUCATION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职位状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择职位状态"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_JOB_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-hasPermi="['menduner:system:job-advertised:query']" @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button v-hasPermi="['menduner:system:job-advertised:query']" @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button v-hasPermi="['menduner:system:job-advertised:update']" @click="handleSetting" type="primary" plain><Icon icon="ep:setting" class="mr-5px" /> 佣金配置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['menduner:system:job-advertised:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true">
      <el-table-column label="职位名称" align="center" prop="name">
        <template #default="scope">{{ formatName(scope.row.name) }}</template>
      </el-table-column>
      <el-table-column label="职位类型" align="center" prop="positionName" />
      <el-table-column label="工作地区" align="center" prop="areaName">
        <template #default="scope">{{ !scope.row.areaId ? '全国' : scope.row.areaName }}</template>
      </el-table-column>
      <el-table-column label="招聘类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MENDUNER_JOB_TYPE" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="工作经验" align="center" prop="expType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MENDUNER_EXP_TYPE" :value="scope.row.expType" />
        </template>
      </el-table-column>
      <el-table-column label="学历要求" align="center" prop="eduType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MENDUNER_EDUCATION_TYPE" :value="scope.row.eduType" />
        </template>
      </el-table-column>
      <el-table-column label="薪资" align="center" prop="payFrom">
        <template #default="scope">
          {{ scope.row.payFrom && scope.row.payTo ? scope.row.payFrom + '-' + scope.row.payTo + '/' + getIntDictOptions(DICT_TYPE.MENDUNER_PAY_UNIT).find(e => e.value === Number(scope.row.payUnit))?.label : '面议' }}
        </template>
      </el-table-column>
      <el-table-column label="点数" align="center" prop="hirePrice">
        <template #default="scope">
          {{ scope.row.hirePrice / 100 }}
        </template>
      </el-table-column>
      <el-table-column label="职位状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MENDUNER_JOB_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <!-- <el-button v-if="scope.row.status === '0'" link type="primary" @click="openForm('update', scope.row.id)">编辑</el-button> -->
          <el-button v-hasPermi="['menduner:system:job-advertised:delete']" link type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button v-hasPermi="['menduner:system:job-advertised:update']" v-if="scope.row.status === '0'" link type="warning" @click="handleAction(0, scope.row.id)">关闭</el-button>
          <el-button v-hasPermi="['menduner:system:job-advertised:update']" v-if="scope.row.status === '1'" link type="success" @click="handleAction(1, 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>

  <!-- 表单弹窗：添加/修改 -->
  <JobAdvertisedForm ref="formRef" :area="areaTreeData" :position="positionTreeData" @success="getList" />

  <JobRadioForm ref="radioRef" @success="getList" />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { JobAdvertisedApi, JobAdvertisedVO } from '@/api/menduner/system/job'
import JobAdvertisedForm from './JobAdvertisedForm.vue'
import JobRadioForm from './RadioForm.vue'
import { dealDictArrayData } from '@/utils/transform/position'
import { getDict } from '@/hooks/web/useDictionaries'
import { EnterpriseApi } from '@/api/menduner/system/enterprise/message'
import { formatName } from '@/utils'

/** 门墩儿-招聘职位 列表 */
defineOptions({ name: 'JobAdvertised' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<JobAdvertisedVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  areaId: undefined,
  name: undefined,
  positionId: undefined,
  type: undefined,
  expType: undefined,
  eduType: undefined,
  content: undefined,
  requirement: undefined,
  status: undefined,
  createTime: '',
  hire: true
})
const queryFormRef = ref() // 搜索的表单

// 职位类型、地区树状列表
const areaTreeData = ref([])
const positionTreeData = ref([])
const getDictData = async () => {
  const { data } = await getDict('areaTreeData', {}, 'areaTreeData')
  const obj = data.find(e => e.name === '中国')
  const list = obj?.children ? obj.children.map(e =>{
    // 市辖区直接显示区
    const municipality = e.children && e.children.length && e.children[0].name === '市辖区'
    if (municipality && e.children[0].children?.length) e.children = e.children[0].children
    return e
  }) : []
  areaTreeData.value = list.length ? [{ name: '全国', id: -1 }, ...list] : []

  const { data: position } = await getDict('positionTreeData', {}, 'positionTreeData')
  positionTreeData.value = position && position.length ? position : []
}
getDictData()

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await JobAdvertisedApi.getJobAdvertisedPage(queryParams)
    if (!data.list || !data.list.length) {
      list.value = []
      total.value = 0
      return
    }
    list.value = dealDictArrayData([], data.list)
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 佣金配置
const radioRef = ref()
const handleSetting = () => {
  radioRef.value.open()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 关闭、激活按钮操作 */
const apiList = [
  { label: '确定关闭该职位吗？', api: JobAdvertisedApi.closeJobAdvertised },
  { label: '确定激活该职位吗？', api: JobAdvertisedApi.enAbleJobAdvertised }
]
const handleAction = async (index: number, id: number) => {
  try {
    await message.confirm(apiList[index].label)
    await apiList[index].api(id)
    message.success('操作成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await EnterpriseApi.deleteJob(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>