<template>
  <Dialog title="企业权益" v-model="dialogVisible">
		<el-descriptions class="mb-50px" title="企业当前权益" :column="2" border>
			<el-descriptions-item label="是否开启人才地图">{{ info.personMap ? '是' : '否' }}</el-descriptions-item>
			<el-descriptions-item label="是否允许发布众聘职位">{{ info.hireJob ? '是' : '否' }}</el-descriptions-item>
			<el-descriptions-item label="是否允许参加招聘会">{{ info.jobFair ? '是' : '否' }}</el-descriptions-item>
			<!-- <el-descriptions-item label="是否开启新任命">{{ info.newAppointment ? '是' : '否' }}</el-descriptions-item> -->
			<el-descriptions-item label="剩余发布职位数量">{{ info.publishJobCount || 0 }}个</el-descriptions-item>
			<el-descriptions-item label="剩余搜索人才数量">{{ info.searchCount || 0 }}次</el-descriptions-item>
			<el-descriptions-item label="剩余查看简历数量">{{ info.lookCvCount || 0 }}次</el-descriptions-item>
		</el-descriptions>

    <h3 style="color: #303133;">权益设置</h3>
    <el-form
      ref="formRef"
      :model="formData"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="会员套餐" prop="packageId">
        <el-select v-model="formData.packageId" placeholder="请选择会员套餐" @change="handleChange">
					<el-option v-for="val in packageList"	:key="val.id" :label="val.text + `（会员时效增加：${val.day}天）`" :value="val.id" />
				</el-select>
      </el-form-item>
      <el-form-item label="是否激活VIP" prop="entitlement.activateVip" :rules="[{ required: true, message: '请设置是否激活VIP', trigger: 'change' }]">
        <el-switch v-model="formData.entitlement.activateVip" />
        vip激活后到期，权益将无法使用；vip未激活，权益可以持续至额度归零。
      </el-form-item>
      <el-form-item v-if="formData.entitlement.activateVip" label="VIP过期时间" prop="entitlement.vipExpireDate" :rules="[{ required: true, message: '请选择VIP过期时间', trigger: 'change' }]">
        <el-date-picker v-model="formData.entitlement.vipExpireDate" :disabledDate="disabledDates" value-format="x" type="date" placeholder="请选择VIP过期时间" />
      </el-form-item>
      <el-form-item label="发布职位数量" prop="entitlement.publishJobCount" :rules="[{ required: true, message: '请输入发布职位数量', trigger: 'change' }]">
        <el-input-number v-model="formData.entitlement.publishJobCount" :min="0" />
      </el-form-item>
      <el-form-item label="查看简历数量" prop="entitlement.lookCvCount" :rules="[{ required: true, message: '请输入查看简历数量', trigger: 'change' }]">
        <el-input-number v-model="formData.entitlement.lookCvCount" :min="0" />
      </el-form-item>
      <el-form-item label="搜索人才数量" prop="entitlement.searchCount" :rules="[{ required: true, message: '请输入搜索人才数量', trigger: 'change' }]">
        <el-input-number v-model="formData.entitlement.searchCount" :min="0" />
      </el-form-item>
      <el-form-item label="开启人才地图" prop="entitlement.personMap" :rules="[{ required: true, message: '请设置是否开启人才地图', trigger: 'change' }]">
        <el-switch v-model="formData.entitlement.personMap" />
      </el-form-item>
      <el-form-item label="允许发布众聘职位" prop="entitlement.hireJob" :rules="[{ required: true, message: '请设置是否允许发布众聘职位', trigger: 'change' }]">
        <el-switch v-model="formData.entitlement.hireJob" />
      </el-form-item>
      <el-form-item label="允许参加招聘会" prop="entitlement.jobFair" :rules="[{ required: true, message: '请设置是否允许参加招聘会', trigger: 'change' }]">
        <el-switch v-model="formData.entitlement.jobFair" />
      </el-form-item>
      <!-- <el-form-item label="开启新任命" prop="entitlement.newAppointment" :rules="[{ required: true, message: '请设置是否开启新任命', trigger: 'change' }]">
        <el-switch v-model="formData.entitlement.newAppointment" />
      </el-form-item> -->
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'EnterpriseMessageSetVip' })
import { EnterpriseApi } from '@/api/menduner/system/enterprise/message'

const props = defineProps({ packageList: Array })
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  enterpriseId: '',
  packageId: undefined as any,
  entitlement: {
    activateVip: false,
    vipExpireDate: undefined,
    publishJobCount: 0,
    searchCount: 0,
    lookCvCount: 0,
    personMap: false,
    hireJob: false,
    jobFair: false,
    // newAppointment: false
  }
})
const formRef = ref()

// 套餐选择
const item = ref({})
const handleChange = (val) => {
  if (!val) return
  const obj = props.packageList.value.find(e => e.id === val)
  for (let key in formData.value.entitlement) {
    // 会员标识激活时才设置vip过期时间
    if (key === 'vipExpireDate' && obj.activateVip) {
      const currentDate = new Date()
      currentDate.setDate(currentDate.getDate() + obj.day)
      formData.value.entitlement[key] = currentDate.getTime()
    } else if (['publishJobCount', 'searchCount', 'lookCvCount'].includes(key)) {
      // 累加权益
      formData.value.entitlement[key] = info.value[key] ? (info.value[key] + obj[key]) : obj[key]
    } else formData.value.entitlement[key] = obj[key]
  }
}

// 过去的日期不可选
const disabledDates = (date) => {
  const currentDate = new Date()
  currentDate.setDate(currentDate.getDate())
  return date.getTime() < currentDate.getTime()
}

/** 打开弹窗 */
const info = ref({})
const open = async (id: number, vipExpireDate) => {
  dialogVisible.value = true
  resetForm()
	formData.value.enterpriseId = id
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await EnterpriseApi.getEnterprisePackagePrivilege(id)
			info.value = data && data.length ? data[0] : {}
      // 回显数据
      if (info.value && Object.keys(info.value).length) {
        for (let key in formData.value.entitlement) {
          formData.value.entitlement[key] = info.value[key]
        }
      }
      // 设置到期时间
      if (vipExpireDate) formData.value.entitlement.vipExpireDate = vipExpireDate
      // 有到期时间的则是有开启会员标识的
      formData.value.entitlement.activateVip = vipExpireDate ? true : false
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    await EnterpriseApi.updateEnterprisePackage(formData.value)
    dialogVisible.value = false
    message.success('操作成功')
    // 发送操作成功的事件
    emit('success')
    resetForm()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  item.value = {}
  formData.value = {
    enterpriseId: '',
    packageId: undefined,
    entitlement: {
      activateVip: false,
      vipExpireDate: undefined,
      publishJobCount: 0,
      searchCount: 0,
      lookCvCount: 0,
      personMap: false,
      hireJob: false,
      jobFair: false,
      // newAppointment: false
    }
  }
}
</script>