<template>
    <AppLayout :title="title" :show-bg-image="false" >
        <view class="main-list" :style="getBackgroundStyle('k.png')">
			<view class="list-top">
				<view class="list-title">
					<text>{{showTitle}}求职意愿</text>
					<view class="title-line"></view>
				</view>
			</view>
			
            <view class="form-container">
                <uni-forms ref="formRef" v-model="formData" :rules="rules" validate-trigger="submit" >
					<uni-forms-item label="意向岗位：" name="postType" required>
						<uni-easyinput v-model="formData.postType" placeholder="请输入意向岗位"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="期望薪资：" name="salary" required>
						<uni-easyinput v-model="formData.salary" placeholder="请输入期望薪资"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="意向工作区域：" name="regionName" required>
						<uni-easyinput v-model="formData.regionName" placeholder="请输入意向工作区域"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="期望福利：" name="welfare" required>
						<uni-easyinput v-model="formData.welfare" placeholder="请输入期望福利"></uni-easyinput>
					</uni-forms-item>
                    <uni-forms-item label="学历：" name="education"  >
					    <uni-data-select v-model="formData.education" placeholder="请选择学历" :localdata="educationOptions" @change="onEducationChange"></uni-data-select>
                    </uni-forms-item>
					<uni-forms-item label="岗位类型：" name="jobType"  >
					    <uni-data-select v-model="formData.jobType" placeholder="请选择岗位类型" :localdata="jobTypeOptions" @change="onJobTypeChange"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="类型：" name="type"  >
					    <uni-data-select v-model="formData.type" placeholder="请选择类型" :localdata="typeOptions" @change="onTypeChange"></uni-data-select>
					</uni-forms-item>
                    <uni-forms-item label="意向自述：" name="description" >
					    <uni-easyinput type="textarea" v-model="formData.description" placeholder="请输入意向自述"></uni-easyinput>
                    </uni-forms-item>
                </uni-forms>
                <!-- 按钮组 -->
                <view class="button-group">
				  <button class="btn submit-btn" @click="handleSubmit">保存跟进</button>
                  <button class="btn reset-btn"  @click="handleReset">重置</button>
                </view>
			</view>
        </view>
    </AppLayout>
</template>

<script setup>
import { inject, ref, reactive } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
const { $api, navTo, navBack } = inject('globalFunction');
import config from "@/config.js"

const title = ref('');
const showTitle=ref('')
const formData = reactive({
    id: null,
	goalPersonId: '',
	postType: '',
	salary: '',
	regionId: '',
	regionName: '',
	description: '',
	welfare: '',
	education: '',
	jobType: '',
	type: '',
})
const educationOptions=ref([])
const jobTypeOptions=ref([])
const typeOptions=ref([])
const personInfo=ref({
	goalPersonId:'',
	name:'',
	task_type:'',
	task_id:'',
	person_id:''
})
const followWays = ref([])
// 表单引用
const formRef = ref(null)

// 校验规则
const rules = {
	postType: {
		rules: [{
			required: true,
			errorMessage: '请输入意向岗位'
		}]
	},
	salary: {
		rules: [{
			required: true,
			errorMessage: '请输入期望薪资'
		}]
	},
	regionName: {
		rules: [{
			required: true,
			errorMessage: '请输入意向工作区域'
		}]
	},
	welfare: {
		rules: [{
			required: true,
			errorMessage: '请输入期望福利'
		}]
	}
}
const baseUrl = config.imgBaseUrl
const getBackgroundStyle = (imageName) => ({
    backgroundImage: `url(${baseUrl}/dispatch/${imageName})`,
    backgroundSize: 'cover',      // 覆盖整个容器
    backgroundPosition: 'center', // 居中
    backgroundRepeat: 'no-repeat'
});

const getDictionary = async () => {
  try {
    const [eduRes, jobRes, gangweiRes] = await Promise.all([
      $api.myRequest('/system/public/dict/data/type/education'),
      $api.myRequest('/system/public/dict/data/type/job_type'),
      $api.myRequest('/system/public/dict/data/type/gangwei_type')
    ]);
    if (eduRes && eduRes.code == 200) {
      eduRes.data.forEach(item => {
        educationOptions.value.push({
          value: item.dictValue,
          text: item.dictLabel
        });
      });
    }
    if (jobRes && jobRes.code == 200) {
      jobRes.data.forEach(item => {
        jobTypeOptions.value.push({
          value: item.dictValue,
          text: item.dictLabel
        });
      });
    }
    if (gangweiRes && gangweiRes.code == 200) {
      gangweiRes.data.forEach(item => {
        typeOptions.value.push({
          value: item.dictValue,
          text: item.dictLabel
        });
      });
    }
  } catch (error) {
    console.error("获取字典数据失败:", error);
    throw error; // 抛出错误，让外部调用者知道失败了
  }
};
function onEducationChange(e){
	formData.education=e
}
function onJobTypeChange(e){
	formData.jobType=e
}
function onTypeChange(e) {
	formData.type=e
}
const handleSubmit = () => {
  formRef.value?.validate()
    .then(() => {
		let header={
			'Authorization':uni.getStorageSync('Padmin-Token')
		}
		console.log("formData",formData)
		if(formData.id){
			$api.myRequest('/dispatch/job/willingness', formData,'put',9100,header).then((resData) => {
				if(resData && resData.code == 200){
					handleReset()
					uni.showToast({
					  title: '保存成功',
					  icon: 'success',
					  duration: 2000 
					});
					uni.navigateBack()
				}else{
					uni.showToast({
					  title: resData.msg,
					  icon: 'none',
					  duration: 2000
					});
				}
				
			});
		}else{
			$api.myRequest('/dispatch/job/willingness', formData,'post',9100,header).then((resData) => {
				if(resData && resData.code == 200){
					handleReset()
					uni.showToast({
					  title: '保存成功',
					  icon: 'success',
					  duration: 2000 
					});
					uni.navigateBack()
				}else{
					uni.showToast({
					  title: resData.msg,
					  icon: 'none',
					  duration: 2000
					});
				}
				
			});
		}
		
    })
    .catch((errors) => {
      console.log('校验失败:', errors);
    });
};

const handleReset = () => {
	formData.postType=''
	formData.salary=''
	formData.regionId=''
	formData.regionName=''
	formData.description=''
	formData.welfare=''
	formData.education=''
	formData.jobType=''
	formData.type=''
}
onLoad((options) => {
	runAsyncTasks(options)
});
const runAsyncTasks = async (options) => {
  await getDictionary()
  if(options.goalPersonId){
  	formData.goalPersonId=options.goalPersonId
	showTitle.value='新增'
  }
  if(options.item){
  	let dataInfo=JSON.parse(options.item)
  	Object.assign(formData, dataInfo)
	showTitle.value='编辑'
  }
}

</script>

<style lang="stylus" scoped>
.main-list
  background-color: #ffffff
  padding: 20rpx 20rpx 28rpx 20rpx
  margin: 30rpx 30rpx
  box-shadow: 0px 3px 20px 0px rgba(0,105,234,0.1)
  border-radius: 12px
.list-top
  display: flex
  align-items: center
  justify-content: space-between
.list-title
  font-weight: bold
  font-size: 36rpx
  color: #404040
  position: relative

.title-line
  position: absolute
  bottom: -10rpx
  left: 70rpx
  width: 70rpx
  height: 8rpx
  background: linear-gradient(90deg, #FFAD58 0%, #FF7A5B 100%)
  border-radius: 4rpx
.input,
.picker
  flex: 1
.form-container 
  margin-top: 30rpx
:deep(.uni-forms-item__label)
  width: 235rpx !important
  font-size: 28rpx;
  color: #404040;

.button-group {
  display: flex;
  justify-content: space-between;
  padding: 40rpx 20rpx 20rpx;
}

.btn {
  width: 45%;
  height: 80rpx;
  font-size: 30rpx;
  border-radius: 8rpx;
}

.reset-btn {
  background-color: #D8E9FF;
  color: #1176FF;
}

.submit-btn {
  background-color: #368BFF;
  color: white;
}
</style>
