<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="demandDirection" required >
					    <uni-data-select v-model="formData.demandDirection" placeholder="请选择需求方向" :localdata="trainNeedOptions" @change="onTrainNeedChange"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="授课方式：" name="courseWay" required>
					    <uni-data-select v-model="formData.courseWay" placeholder="请选择授课方式" :localdata="classMethodOptions" @change="onClassMethodChange"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="课程类型：" name="courseType" required >
					    <uni-data-select v-model="formData.courseType" placeholder="请选择课程类型" :localdata="questionClassificationOptions" @change="onQuestionClassificationChange"></uni-data-select>
					</uni-forms-item>
					<uni-forms-item label="培训时间：" name="trainDate" required>
						<uni-datetime-picker type="date" placeholder="请选择培训时间"  v-model="formData.trainDate" @maskClick="onTrainDateChange" />
					</uni-forms-item>
					<uni-forms-item label="培训费用预算：" name="trainFee" required>
						<uni-easyinput v-model="formData.trainFee" placeholder="请输入培训费用预算"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item label="培训地点：" name="trainAddress" required>
						<uni-easyinput v-model="formData.trainAddress" placeholder="请输入培训地点"></uni-easyinput>
					</uni-forms-item>
                    <uni-forms-item label="培训目标：" name="trainGoal" required>
					    <uni-easyinput type="textarea" v-model="formData.trainGoal" placeholder="请输入培训目标"></uni-easyinput>
                    </uni-forms-item>
					<uni-forms-item label="建议与意见：" name="opinions" >
					    <uni-easyinput type="textarea" v-model="formData.opinions" 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: '',
	demandDirection: '',
	trainDate: '',
	trainAddress: '',
	trainFee: '',
	courseWay: '',
	courseType: '',
	trainGoal: '',
	opinions: ''
})
const trainNeedOptions=ref([])
const classMethodOptions=ref([])
const questionClassificationOptions=ref([])
// 表单引用
const formRef = ref(null)

// 校验规则
const rules = {
	demandDirection: {
		rules: [{
			required: true,
			errorMessage: '请选择需求方向'
		}]
	},
	courseWay: {
		rules: [{
			required: true,
			errorMessage: '请选择授课方式'
		}]
	},
	courseType: {
		rules: [{
			required: true,
			errorMessage: '请选择课程类型'
		}]
	},
	trainDate: {
		rules: [{
			required: true,
			errorMessage: '请选择培训时间'
		}]
	},
	trainFee: {
		rules: [{
			required: true,
			errorMessage: '请输入培训费用预算'
		}]
	},
	trainAddress: {
		rules: [{
			required: true,
			errorMessage: '请输入培训地点'
		}]
	},
	trainGoal: {
		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 [trainRes, classRes, questionRes] = await Promise.all([
      $api.myRequest('/system/public/dict/data/type/train_need'),
      $api.myRequest('/system/public/dict/data/type/class_method'),
      $api.myRequest('/system/public/dict/data/type/question_classification')
    ]);
    if (trainRes && trainRes.code == 200) {
      trainRes.data.forEach(item => {
        trainNeedOptions.value.push({
          value: item.dictValue,
          text: item.dictLabel
        });
      });
    }
    if (classRes && classRes.code == 200) {
      classRes.data.forEach(item => {
        classMethodOptions.value.push({
          value: item.dictValue,
          text: item.dictLabel
        });
      });
    }
    if (questionRes && questionRes.code == 200) {
      questionRes.data.forEach(item => {
        questionClassificationOptions.value.push({
          value: item.dictValue,
          text: item.dictLabel
        });
      });
    }
  } catch (error) {
    console.error("获取字典数据失败:", error);
    throw error; // 抛出错误，让外部调用者知道失败了
  }
};
function onTrainNeedChange(e){
	formData.demandDirection=e
}
function onClassMethodChange(e){
	formData.courseWay=e
}
function onQuestionClassificationChange(e) {
	formData.courseType=e
}
function onTrainDateChange(e){
	formData.trainDate=e
}
const handleSubmit = () => {
  formRef.value?.validate()
    .then(() => {
		let header={
			'Authorization':uni.getStorageSync('Padmin-Token')
		}
		if(formData.id){
			$api.myRequest('/dispatch/train/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/train/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.demandDirection=''
	formData.trainDate=''
	formData.trainAddress=''
	formData.trainFee=''
	formData.courseWay=''
	formData.courseType=''
	formData.trainGoal=''
	formData.opinions=''
}
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>
