<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="120px">
						<uni-forms-item label="客户名称" name="cusName" class="f-c-right" required>
							<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" name="productCategory" v-if="formData.productType == '电阻器'" required>
							<uni-data-select v-model="formData.productCategory" :localdata="productCategoryList" 
								placeholder="请选择产品类别" />
						</uni-forms-item>
						<uni-forms-item label="产品大类" class="f-c-right" name="productCategories" 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" name="classification" v-if="formData.productType == '管壳'">
							<uni-data-select v-model="formData.classification" :localdata="classificationList" 
								placeholder="请选择产品分类" />
						</uni-forms-item>
						<uni-forms-item label="问题现象" name="ppNameLabel" class="f-c-right">
							<uni-data-select v-model="formData.ppNameLabel" :localdata="problemPhenomenonList" 
								placeholder="请选择问题现象" />
						</uni-forms-item>
						<uni-forms-item label="问题现象描述" name="ppNameDescribe" class="f-c-right">
							<uni-easyinput v-model="formData.ppNameDescribe" type="textarea" placeholder="请详细描述问题现象" />
						</uni-forms-item>
						<uni-forms-item label="使用数量" name="employQuantity" 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="使用方法" name="employMethod" class="f-c-right">
							<uni-easyinput v-model="formData.employMethod" placeholder="请输入使用方法" />
						</uni-forms-item>
						<uni-forms-item label="问题发生阶段" name="posName" class="f-c-right" required>
							<uni-data-select v-model="formData.posName" :localdata="problemStageList" 
								placeholder="请选择问题发生阶段" />
						</uni-forms-item>
						<uni-forms-item label="用户诉求标签" name="customerAppealLabels" class="f-c-right" required>
							<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" required>
							<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" required>
							<uni-data-select v-model="formData.isReturnzero" :localdata="isReturnzeroYesNoList" 
								placeholder="请选择是否需要归零" />
						</uni-forms-item>
						<uni-forms-item label="业务员" name="salesman" class="f-c-right">
							<uni-easyinput v-model="formData.salesman" placeholder="请输入业务员" />
						</uni-forms-item>
						<uni-forms-item label="联系方式" name="salesmanPhone" 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: 20rpx;
}

/* 顶部占位高度，避免内容被头部遮挡 */
.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;
}

/* 加载遮罩 */
.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;
  position: relative; /* 为伪元素定位做准备 */
}

/* 日期选择器样式 */
:deep(.uni-date-x .uni-date__x-input) {
  padding-left: 20rpx;
  color: #919191;
}

/* ======== 强制显示必填项红色标识 ======== */

/* 方案1: 使用伪元素在标签前添加红色星号 */
:deep(.uni-forms-item--required)::before {
  content: '*';
  color: #ff4d4f !important;
  position: absolute;
  left: -16rpx;
  top: 50%;
  transform: translateY(-50%);
  font-size: 28rpx !important;
  font-weight: bold !important;
  z-index: 10;
}

/* 调整标签内边距，避免文本与星号重叠 */
:deep(.uni-forms-item__label) {
  padding-left: 16rpx !important;
}

/* 方案2: 增强内置必填项标识的样式（备用方案） */
:deep(.uni-forms-item--required .uni-forms-item__required) {
  display: inline !important;
  color: #ff4d4f !important;
  margin-right: 8rpx !important;
  font-size: 28rpx !important;
  font-weight: bold !important;
}

/* 方案3: 直接在标签文本中显示星号（最可靠的后备方案） */
:deep(.uni-forms-item--required .uni-forms-item__label::before) {
  content: '*';
  color: #ff4d4f !important;
  margin-right: 4rpx;
}
</style>