<template>
	<view class="con-body">
		<view class="con-bg">
			<!-- 头部 -->
			<customHeader ref="customHeaderRef" :title="'质量反馈新增'" :leftFlag="true" :rightFlag="true">
				<template #right>
					<view class="head-right" @click="submitForm">
						<uni-icons custom-prefix="iconfont" type="icon-phonebaocun" size="22"
							color="#B7D2FF"></uni-icons>保存
					</view>
				</template>
			</customHeader>

			<!-- 高度来避免头部遮挡 -->
			<view class="top-height"></view>

			<!-- 正文内容 -->
			<view class="white-bg">
				<view class="form-con">
					<uni-forms ref="formRef" :model="formData" :rules="rules" label-width="100px">
						<uni-forms-item label="客户名称" name="cusName" class="f-c-right">
							<view @click="chooseCustomer" class="form-item-container">
								<text class="name">{{ formData.cusName || '点击选择客户' }}</text>
							</view>
						</uni-forms-item>						
						<uni-forms-item label="产品类型" name="productType" class="f-c-right">
							<uni-data-select v-model="formData.productType" :localdata="productTypeList"
							placeholder="请选择产品类型"/>
						</uni-forms-item>
						<uni-forms-item label="产品类别" class="f-c-right" v-if="formData.productType == '电阻器'">
							<uni-data-select v-model="formData.productCategory" :localdata="productCategoryList" 
								placeholder="请选择产品类别" />
						</uni-forms-item>
						<uni-forms-item label="产品大类" class="f-c-right" v-if="formData.productType == '管壳'">
							<uni-data-select v-model="formData.productCategories" :localdata="productCategoriesList" 
								placeholder="请选择产品大类" />
						</uni-forms-item>
						<uni-forms-item label="产品分类" class="f-c-right" v-if="formData.productType == '管壳'">
							<uni-data-select v-model="formData.classification" :localdata="classificationList" 
								placeholder="请选择产品分类" />
						</uni-forms-item>
						<uni-forms-item label="问题现象" class="f-c-right">
							<uni-data-select v-model="formData.ppNameLabel" :localdata="problemPhenomenonList" 
								placeholder="请选择问题现象" />
						</uni-forms-item>
						<uni-forms-item label="问题现象描述" name="problemDescription" class="f-c-right">
							<uni-easyinput v-model="formData.ppNameDescribe" type="textarea" placeholder="请详细描述问题现象" />
						</uni-forms-item>
						<uni-forms-item label="使用数量" name="usageQuantity" class="f-c-right">
							<uni-easyinput v-model.number="formData.employQuantity" type="number" placeholder="请输入使用数量" />
						</uni-forms-item>
						<uni-forms-item label="问题数量" name="problemQuantity" class="f-c-right">
							<uni-easyinput v-model.number="formData.problemQuantity" type="number" placeholder="请输入问题数量" />
						</uni-forms-item>
						<uni-forms-item label="使用方法" class="f-c-right">
							<uni-easyinput v-model="formData.employMethod" placeholder="请输入使用方法" />
						</uni-forms-item>
						<uni-forms-item label="问题发生阶段" class="f-c-right">
							<uni-data-select v-model="formData.posName" :localdata="problemStageList" 
								placeholder="请选择问题发生阶段" />
						</uni-forms-item>
						<uni-forms-item label="用户诉求标签" class="f-c-right">
							<uni-data-select v-model="formData.customerAppealLabels" :multiple="true"  :localdata="customerAppealLabelList" 
								placeholder="请选择用户诉求标签" />
						</uni-forms-item>
						<uni-forms-item label="用户诉求" name="customerAppeal" class="f-c-right">
							<uni-easyinput v-model="formData.customerAppeal" type="textarea" placeholder="请输入用户诉求" />
						</uni-forms-item>
						<uni-forms-item label="是否返厂" name="isReturnfactory" class="f-c-right">
							<uni-data-select v-model="formData.isReturnfactory" :localdata="isReturnfactoryYesNoList" 
								placeholder="请选择是否返厂" />
						</uni-forms-item>
						<uni-forms-item label="是否需要归零" name="isReturnzero" class="f-c-right">
							<uni-data-select v-model="formData.isReturnzero" :localdata="isReturnzeroYesNoList" 
								placeholder="请选择是否需要归零" />
						</uni-forms-item>
						<uni-forms-item label="业务员" class="f-c-right">
							<uni-easyinput v-model="formData.salesman" placeholder="请输入业务员" />
						</uni-forms-item>
						<uni-forms-item label="联系方式" class="f-c-right">
							<uni-easyinput v-model="formData.salesmanPhone" placeholder="请输入联系方式" />
						</uni-forms-item>
						<uni-forms-item label="答复日期" name="replyTime" class="uni-forms-item is-direction-top is-top">
							<uni-datetime-picker type="date" :clear-icon="false" v-model="formData.replyTime" @change="changeDate" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		reactive,
		onUnmounted,
		computed
	} from 'vue'
	import customHeader from '@/components/customHeader.vue'
	import {
		getGuestList
	} from '@/api/business.js'
	import {
		isEmpty
	} from '@/utils/validate.js'
	import {
		listgetResistorTypeList,
		listgetProductCategoriesList,
		listgetClassificationList,
		listgetProblemPhenomenonList,
		listgetProblemStageList,
		listgetCustomerAppealLabelList,
		qualityFeedbackAdd,
	} from '@/api/eqf/qualityFeedback.js'


	let customerUser = reactive({})
	// 客户相关
	const guestList = ref([])
	const guestArr = ref([])
	const guestIndex = ref(0)

	/// 正确的数据绑定示例
const formData = ref({
  leader: '',          // 我方领导
  userDemand: '',      // 用户诉求
  isReturnFactory: '否', // 是否返厂
  isNeedReset: '否',     // 是否需要归零
  salesman: '',        // 业务员
  contact: '',         // 联系方式
  productCategory: '', // 产品分类
  productType: '电阻器',     // 产品类型
  problemPhenomenon: '', // 问题现象
  problemDescription: '', // 问题现象描述
  usageQuantity: '',   // 使用数量
  problemQuantity: '', // 问题数量
  usageMethod: '',      // 使用方法
  cusName: '',
  customerId: '',
  ppNameLabel: '',
  ppNameDescribe: '',
  employQuantity: '',
  problemQuantity: '', // 问题数量
  employMethod: '',
  posName: '',
  customerAppealLabels: [],
  customerAppeal: '',
  isReturnfactory: '',
  isReturnzero:	'',
  salesman: '',
  salesmanPhone: '',
  replyTime: '',
});

// 添加表单验证规则
const rules = {
  cusName: {
    rules: [
      {
        required: true,
        errorMessage: '请选择客户'
      }
    ]
  },
  productType: {
    rules: [
      {
        required: true,
        errorMessage: '请选择产品类型'
      }
    ]
  },
  productCategory: {
    rules: [
      {
        required: true,
        errorMessage: '请选择产品类别',
        validateFunction: (rule, value, data, callback) => {
          // 只有当产品类型为电阻器时才验证
          if (data.productType === '电阻器' && !value) {
            callback('请选择产品类别');
          } else {
            callback();
          }
        }
      }
    ]
  },
  productCategories: {
    rules: [
      {
        required: true,
        errorMessage: '请选择产品大类',
        validateFunction: (rule, value, data, callback) => {
          // 只有当产品类型为管壳时才验证
          if (data.productType === '管壳' && !value) {
            callback('请选择产品大类');
          } else {
            callback();
          }
        }
      }
    ]
  },
  classification: {
    rules: [
      {
        required: true,
        errorMessage: '请选择产品分类',
        validateFunction: (rule, value, data, callback) => {
          // 只有当产品类型为管壳时才验证
          if (data.productType === '管壳' && !value) {
            callback('请选择产品分类');
          } else {
            callback();
          }
        }
      }
    ]
  },
  posName: {
    rules: [
      {
        required: true,
        errorMessage: '请选择问题发生阶段'
      }
    ]
  },
  customerAppealLabels: {
    rules: [
      {
        required: true,
        errorMessage: '请选择用户诉求标签',
        validateFunction: (rule, value, data, callback) => {
          if (!value || value.length === 0) {
            callback('请选择用户诉求标签');
          } else {
            callback();
          }
        }
      }
    ]
  },
  customerAppeal: {
    rules: [
      {
        required: true,
        errorMessage: '请输入用户诉求'
      }
    ]
  },
  isReturnzero: {
    rules: [
      {
        required: true,
        errorMessage: '请选择是否需要归零'
      }
    ]
  }
}
// 定义产品分类列表
const productTypeList =[
	{ text: '电阻器', value: '电阻器' },
	{ text: '管壳', value: '管壳' },
  	// 其他产品类型...
]
// 是/否选项
const isReturnfactoryYesNoList = [
	{ text: '是', value: '是' },
	{ text: '否', value: '否' },
	{ text: '在途', value: '在途' }
]
// 是/否选项
const isReturnzeroYesNoList = [
	{ text: '是', value: '是' },
	{ text: '否', value: '否' },
]

//产品类别
const productCategoryList = ref([]);
//产品大类
const productCategoriesList = ref([]);
//	产品分类
const classificationList = ref([]);
//问题现象
const problemPhenomenonList = ref([]);
//问题发生阶段
const problemStageList = ref([]);
//用户诉求标签
const customerAppealLabelList = ref([]);


// 初始化产品类别数据
const initProductCategoryData = async () => {
  try {
    // 这里需要根据实际的API接口进行调用，以下为示例
    // 加载产品类别数据
    // 使用listgetResistorTypeList接口获取电阻器类型数据
	const resistorTypeRes = await listgetResistorTypeList();
	productCategoryList.value = resistorTypeRes.rows.map(item => ({
		text: item.resistorTypeText,  // 显示文本
		value: item.resistorTypeValue  // 对应的值
	}));
    
    // 加载产品大类数据
	const productCategories = await listgetProductCategoriesList();
	console.log(productCategories)
    productCategoriesList.value = productCategories.rows.map(item => ({
		text: item.productCategoriesText,  // 显示文本
		value: item.productCategoriesValue  // 对应的值
	}));
    
    // 加载产品分类数据
	const classification = await listgetClassificationList();
    classificationList.value = classification.rows.map(item => ({
		text: item.classificationText,  // 显示文本
		value: item.classificationValue  // 对应的值
	}));

	//问题现象
	const problemPhenomenon = await listgetProblemPhenomenonList();
	console.log(problemPhenomenon)
	problemPhenomenonList.value = problemPhenomenon.rows.map(item => ({
		text: item.problemPhenomenonText,  // 显示文本
		value: item.problemPhenomenonValue  // 对应的值
	}));

	//问题发生阶段
	const problemStage = await listgetProblemStageList();
	problemStageList.value = problemStage.rows.map(item => ({
		text: item.problemStageText,  // 显示文本
		value: item.problemStageValue  // 对应的值
	}));
	
	//用户诉求标签
	const customerAppealLabel = await listgetCustomerAppealLabelList();
	customerAppealLabelList.value = customerAppealLabel.rows.map(item => ({
		text: item.customerAppealLabelText,  // 显示文本
		value: item.customerAppealLabelValue  // 对应的值
	}));
  } catch (error) {
    console.error('加载产品类别数据失败:', error);
    uni.showToast({ title: '加载产品类别数据失败', icon: 'none' });
  }
};


	// 表单引用 & 客户选择器引用
	const formRef = ref(null)
	const customHeaderRef = ref(null)
	// 选择客户页面跳转
	function chooseCustomer() {
		uni.navigateTo({
			url: '/pages/business/EQF/components/chooseCus'
		})
	}
	//定义数据接收的值
	let selectedCustomer = reactive(null)

	//监听时间
	onMounted(() => {
		uni.$on('onCustomerSelected', handleCustomerSelected)
		initProductCategoryData();
	})
	//取消监听
	onUnmounted(() => {
		uni.$off('onCustomerSelected', handleCustomerSelected)
	})

	//处理 接收数据
	const handleCustomerSelected = (data) => {
		formData.value.cusName = data.cusName
		formData.value.customerId = data.cusId
	}
	// 提交表单
	const submitForm = async () => {
		try {
			// 表单校验
			await formRef.value.validate()
			console.log(formData,"5555")
			const res = await qualityFeedbackAdd(formData.value);
			uni.showToast({
				title: '提交成功',
				icon: 'success'
			})
			  uni.$emit('refreshMarketList');
			  setTimeout(() => {
			        uni.navigateBack(1);
			      }, 1500);
			      
			console.log('表单数据:', formData.value)
		} catch (err) {
			console.log('表单验证失败:', err)
		}
	}

</script>

<style scoped>
.con-body {
	background-color: #F8F8F8;
}

.con-bg {
	padding-bottom: 20px;
}

.top-height {
	height: 80rpx;
}

.white-bg {
	padding: 20rpx;
	background-color: #FFFFFF;
}

.form-con {
	margin-top: 20rpx;
}

.f-c-right {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 10rpx 0;
}

.form-section {
	margin-bottom: 30rpx;
	padding: 10rpx;
	background-color: #F9F9F9;
	border-radius: 8rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
	padding-left: 10rpx;
	border-left: 4rpx solid #007AFF;
}

.loading-mask {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.3);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 9999;
}

:deep(.uni-forms) {
	width: 100%;
}

:deep(.uni-forms-item) {
	margin-bottom: 20rpx;
}

:deep(.uni-date-x .uni-date__x-input) {
	padding-left: 20rpx;
	color: #919191;
}

/* 隐藏默认必填项标记，使用自定义样式 */
:deep(.uni-forms-item__required) {
	display: none;
}
</style>