<template>
	<view class="f-straight wrapper">
		<uni-forms ref="form" :modelValue="formData" :rules="rules" validateTrigger="bind" label-width="90px" label-align="right">
			<uni-forms-item label="职位类型" name="positionId" required>
        <view class="positionTemplate">
          <uni-data-picker class="picker" popup-title="请选择职位类型" v-model="formData.positionId" :localdata="dictObj?.positionTreeData || []" :clear-icon="false" :map="{ text: 'nameCn', value: 'id'}"></uni-data-picker>
          <button v-if="formData.positionId" class="btn" type="primary" size="mini" @click="useJobTemplate">职位模板</button>
        </view>
			</uni-forms-item>
			<uni-forms-item required label="职位名称" name="name">
        <uni-easyinput v-model="formData.name" placeholder="请填写职位名称"></uni-easyinput>
			</uni-forms-item>
      <uni-forms-item label="到期时间" name="expireTime" required>
				<view class="d-flex">
          <picker mode="date" :value="formData.expireTime" :disabled="expireTimeDisabled" :start="startDate" @change="expireTimeChange">
            <view class="uni-input ss-m-t-20" :style="{'opacity': expireTimeDisabled ? '0.5' : '1'}">{{ formData.expireTime }}</view>
          </picker>
          <uni-data-checkbox selectedColor="#00B760" class="ss-m-l-50 ss-m-t-14" multiple v-model="soFar" :localdata="[{ text: '长期有效', value: 1 }]" @change="handleChangeSofar"></uni-data-checkbox>
        </view>
			</uni-forms-item>
      <uni-forms-item label="岗位职责" name="content" required>
        <RichEditor ref="contentRef" :richValue="formData.content" @blur="val => editorBlur('content', val)" :max="1500" />
			</uni-forms-item>
      <uni-forms-item label="岗位要求 " name="requirement" required>
        <RichEditor ref="requirementRef" :richValue="formData.requirement" @blur="val => editorBlur('requirement', val)" :max="1500" />
			</uni-forms-item>
		</uni-forms>
    <!-- 确认框 -->
    <uni-popup ref="confirm" type="dialog">
      <uni-popup-dialog
        type="warn"
        cancelText="取消"
        confirmText="确认"
        title="系统提示"
        content="您确定要放弃目前岗位描述的内容吗？"
        @confirm="handleConfirm"
        @close="handleClose"
      ></uni-popup-dialog>
    </uni-popup>
	</view>
</template>
<script setup>
import { ref, unref } from 'vue'
import { dictObj } from '@/utils/position.js'
import { getNextDate } from '@/utils/date'
import { getRecruitPositionDetails } from '@/api/new/position'
import { dateToTimestamp } from '@/utils/date.js'
import RichEditor from '@/components/RichEditor'
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  }
})

const formData = ref({
  positionId: props.data?.positionId || '',
  name: props.data?.name || '' + new Date().getTime().toString(), // + new Date().getTime().toString()
  expireTime: props.data?.expireTime || getNextDate(15, 'YYYY-MM-DD', 'day'),
  content: props.data?.content || '',
  requirement: props.data?.requirement || ''
})

const startDate = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) // 不可选时间
const expireTimeDisabled = ref(props.data?.expireTime === null ? true : false)
// 至今
const handleChangeSofar = (e) => {
  const value = e.detail.value.length ? e.detail.value[0] : ''
  expireTimeDisabled.value = value ? true : false
}
const expireTimeChange = (e) => {
  formData.value.expireTime = e?.detail?.value
}

const rules = {
	positionId:{
		rules: [{required: true, errorMessage: '请选择职位类型' }]
	},
	name:{
		rules: [{required: true, errorMessage: '请填写职位名称' }]
	},
	expireTime:{
		rules: [{required: true, errorMessage: '请选择职位到期时间' }]
	},
	content:{
		rules: [{required: true, errorMessage: '请填写岗位职责' }]
	},
	requirement:{
		rules: [{required: true, errorMessage: '请填写岗位要求' }]
	},
}

const editorBlur = (key, val) => {
  formData.value[key] = val || ''
}

const pushTemplate = () => {
  formData.value.content = jobTemplateRes.value.content
  formData.value.requirement = jobTemplateRes.value.requirement
  uni.showToast({ title: '模板填充完成！', icon: 'success' })
}

const confirm = ref()
const handleClose = () => {
  confirm.value.close()
}
const handleConfirm = () => {
  try {
    uni.showLoading({ title: '替换中...', mask: true })
    pushTemplate()
  } catch (error) {
    uni.showToast({ title: '替换失败', icon: 'error' })
    console.log(error)
  } finally {
    uni.hideLoading()
  }
}

const jobTemplateRes = ref({})
const useJobTemplate = async () => {
  if (!formData.value.positionId) return Snackbar.warning('请先选择职位类型')
  // 获取职位模板内容-赋值
  const res = await getRecruitPositionDetails(formData.value.positionId)
  if (!res?.data || !res.data .content || !res.data .requirement) {
    uni.showToast({ title: '此职位类型没有可使用的模板！', icon: 'none', duration: 2000 })
    return
  }
  jobTemplateRes.value = res.data
  if (formData.value?.content || formData.value?.requirement) {
    // 弹窗提示
    confirm.value.open()
  } else {
    // 无内容点击默认填充
    pushTemplate()
  }
}

const form = ref()
const contentRef = ref()
const requirementRef = ref()
const soFar = ref(props.data?.expireTime === null ? [1] : [])
const getQuery = async () => {
  const valid = await unref(form).validate()
  if (!valid) return
  contentRef.value?.isExceedValidate(true, true, '岗位职责字数超出限制')
  requirementValid.value?.isExceedValidate(true, true, '岗位要求字数超出限制')

  const obj = {
    hirePrice: 0,
    soFar: Boolean(soFar.value?.length),
    hire: false,
    ...formData.value
  }

  obj.expireTime = obj.soFar ? null : dateToTimestamp(obj.expireTime)
  obj && Object.keys(obj).length && Object.keys(obj).forEach(key => { if (['areaId', 'eduType', 'expType'].includes(key) && obj[key] === -1)  obj[key] = null })
  return obj
}

defineExpose({
  getQuery
})

</script>
<style lang="scss" scoped>
.positionTemplate {
  text-align: right;
 .btn {
  width: 90px;
  line-height: 34px;
  margin-top: 10px;
 }
}

:deep(.uni-forms-item__content) {
	max-width: 100%;
	overflow: hidden;
}
</style>
