<script setup lang="ts">
	import { onLoad } from '@dcloudio/uni-app'
	import Navigate from '@/utils/page/navigate'
	import { reactive, ref } from 'vue'
	import { useUserStore } from '@/store/modules/user'
	import { useGlobSetting } from '/@/hooks/setting'
	import * as NongzhiAPI from '@/api/model/nongzhi'
	import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
	import ConfirmDialog from '@/components/ConfirmDialog/index.vue'
	const userStore = useUserStore()
	const globSetting = useGlobSetting()
	let enterpriseId = null;
	onLoad((options) => {
		let param = JSON.parse(decodeURIComponent(options.param));
		uni.setNavigationBarTitle({
		  title: param.name
		});
		enterpriseId = param.id;
		getDetailData(enterpriseId);
		queryByCategoryAndCode(0,null);
		queryByCategory();
		getGoodsQueryById();
	})
	const toastRef = ref()
	const unitPopupRef = ref(null);
	const uploadRef = ref()
	const bgColorData = ["#EEFAEB","#EFF1FF","#FFF3F1","#E8F7F7","#FFF3E7","#FAF8EA"];
	const pageData = reactive({
		data:null,
		enterpriseCers:[],
		
		isPopupShow:false,
		unitPopup:false,
		unitOptions:[],
		unitVal:[],
		
		productImageArr:[],
		
		categoryPopup:false,
		categoryOptions:[],
		categoryText:[],
		categoryVal:[],
		
		enterpriseProduct:[],
		contactName:"",
		showConfirmDialog:false,
		
		rules: [
			{
			    name: 'name',
			    rule: ['required'],
			    msg: ['请输入商品名称'],
			},
			/* {
				name: "mobile",
				rule: ["required", "isMobile"],
				msg: ["请输入联系电话", "请输入正确的联系电话"]
			}, */
			{
                name: 'category',
                rule: ['required'],
                msg: ['请选择商品分类'],
            },{
                name: 'minSellPrice',
                rule: ['required'],
                msg: ['请输入最小销售价'],
            },{
                name: 'maxSellPrice',
                rule: ['required'],
                msg: ['请输入最大销售价'],
            },
			{
			    name: 'unit',
			    rule: ['required'],
			    msg: ['请选择单位'],
			},
			{
			    name: 'image',
			    rule: ['required'],
			    msg: ['请选择商品图片'],
			},
		]
	})
	let productInfo = reactive({
		id:"",
		name:"",// 商品名称
		// mobile:"", // 联系方式
		category:"", // 分类
		minSellPrice:"", // 最小销售价
		maxSellPrice: "", // 最大销售价
		unit: "", // 单位
		unitCode:"", // 单位编码
		enterpriseId:"", // 企业ID
		image:""
	})
	function getGoodsQueryById(){
		NongzhiAPI.getGoodsQueryById({enterpriseId:enterpriseId}).then((res) => {
			pageData.enterpriseProduct =  res;
		})
	}
	// 文件上传
	function handleUpload(file) {
		const tempFilePaths = file.tempFilePaths;
		// 处理每张选中的图片
		for(let i = 0; i < tempFilePaths.length; i++){
			uni.uploadFile({
			    url: `${globSetting.apiUrl + globSetting.urlPrefix}/sys/common/upload`, // 直接使用上传接口URL
			    filePath: tempFilePaths[i],
			    name: 'file',
			    formData: {
			        biz: 'temp',
			    },
			    header: {
			        'X-Access-Token': userStore.getToken,
			    },
			    success: (res) => {
			        if (res.statusCode === 200) {
			            const data = JSON.parse(res.data)
			            if (data.code === 200 || data.code === 0) {
			                toastRef.value.show({
			                    type: 'success',
			                    text: '上传成功',
			                })
							pageData.productImageArr[0] = data.message // 保存返回的图片信息
			            }
			        }
			    },
			    fail: (err) => {
			        toastRef.value.show({
			            type: 'error',
			            text: '上传失败',
			        })
					uploadRef.value.clearFiles()
					pageData.productImageArr[0] = null
			        
			    },
			})
		}
	}
	// 文件删除
	function handleDelete(file,type) {
		uploadRef.value.clearFiles()
		pageData.productImageArr[0] = null
	}
	function changeCategory(e){
		productInfo.category = e.value;
		pageData.categoryPopup = false;
	}
	function selectCompleteUnit(e){
		productInfo.unit = e.text[e.text.length-1];
		pageData.unitPopup = false;
	}
	function changeUnit(e){
		let val = e.value;
		queryByCategoryAndCode(val,e);
	}
	function handleSelectCategory(){
		pageData.categoryPopup = true;
	}
	function handleSelectUnit(){
		pageData.unitPopup = true;
	}
	// 查询商品分类
	function queryByCategory(){
		LinghuoyonggongAPI.gitListByCodeDict({ code : 'category'}).then(res=>{
			pageData.categoryOptions = res;
			let textArr = [];
			for(let i = 0; i < res.length; i++){
				textArr.push(res[i].itemText);
			}
			pageData.categoryText = textArr;
		})
	}
	// 查询单位字典
	function queryByCategoryAndCode(code,e){
		LinghuoyonggongAPI.queryByCategoryAndCode({ category : 2,code : code}).then(res=>{
			if(res.length){
				let dataArr = [];
				for(let i = 0; i < res.length; i++){
					let obj = {text:"",value:""};
					obj.text = res[i].name;
					obj.value = res[i].code;
					dataArr.push(obj);
				}
				if(!pageData.unitOptions.length){
					pageData.unitOptions = dataArr;
				}else{
					unitPopupRef.value.setRequestData(dataArr, e.layer);
				}
			}else{
				unitPopupRef.value.end();
			}
		})
	}
	
	// 发布
	const formRef = ref()
	function addData(){
		productInfo.image = pageData.productImageArr[0];
		formRef.value.validator(productInfo, pageData.rules, true).then((res) => {
			if (res.isPassed) {
				NongzhiAPI.postGoodsAdd(productInfo).then((res) => {
					toastRef.value.show({
					    type: 'success',
					    text: '发布成功',
					})
					pageData.isPopupShow = false;
					setTimeout(()=>{
						getGoodsQueryById();
					},500)
				})
			}
		})
		
	}
	function getDetailData(id){
		NongzhiAPI.getEnterpriseDetail({ id }).then((res) => {
			pageData.enterpriseCers =  res.enterpriseCers.split(",");
			pageData.data = res;
			pageData.contactName = res.contactPerson.substring(0,1) + new Array(res.contactPerson.length).join('*');
			productInfo.unitCode = res.enterpriseCode;
			productInfo.enterpriseId = res.id;
		})
	}
	function getBgColor(index:any){
		if(index < 6){
			return bgColorData[index];
		}else{
			return bgColorData[Math.floor(Math.random() * 5)];
		}
	}
	function handlePublish() {
		productInfo.id = "";
		productInfo.name = "";
		// productInfo.mobile = "";
		productInfo.category = "";
		productInfo.minSellPrice = "";
		productInfo.maxSellPrice = "";
		productInfo.unit = "";
		productInfo.image = "";
		pageData.productImageArr = [];
		pageData.isPopupShow = true;
	}
	function makePhoneCall(){
		uni.makePhoneCall({
			phoneNumber: pageData.data.contactMobile
		});
	}
</script>
<template>
	<view class="w-full h-95vh bg-#E6F5E8 detail_page">
		<view class="module_width top_content">
			<view class="enterprise_logo_view"><image class="enterprise_logo" mode="heightFix" :src="pageData.data.enterpriseLogoUrl" /></view>
			<view class="enterprise_business">主营：{{pageData.data.businessScope}}</view>
			<view class="enterprise_description">{{pageData.data.profile}}</view>
		</view>
		<view class="module_width middle_content">
			<view class="module_title">资质证书</view>
			<view class="module_separate"></view>
			<view class="module_qualification">
				<view class="qualification_item" :style="`height:126rpx;background:${getBgColor(index)}`" v-for="(item,index) in pageData.enterpriseCers" :key="index">
					<image class="enterprise_logo" mode="heightFix" :src="item" />
					<!-- <view class="qualification_name ellipsis">{{item}}</view> -->
				</view>
			</view>
		</view>
		<view class="module_width footer_content">
			<view class="module_title">主营产品</view>
			<view class="module_separate"></view>
			<view class="module_business">
				<view class="business_item" v-for="item in pageData.enterpriseProduct" :key="item.id">
					<image class="business_img" mode="heightFix" :src="item.image" />
					<view class="qualification_name ellipsis">{{item.name}}</view>
					<view class="qualification_price ellipsis">¥{{item.minSellPrice}}<text> ~ </text> {{item.maxSellPrice}}<text class="qualification_text">/{{item.unit}}</text></view>
				</view>
			</view>
		</view>
		
		<view class="make-phone-view">
			<fui-button text="我要购买" bold radius="96rpx" @click="pageData.showConfirmDialog=true;" height="80rpx"/>
		</view>
		
	</view>
	<!-- 确认对话框 -->
	<ConfirmDialog
	    v-model:show="pageData.showConfirmDialog"
	    title="温馨提示"
	    :content="`你将与${pageData.contactName}进行电话沟通，若继续，请点击确认按钮！`"
	    cancelText="取消"
	    confirmText="确认"
	    @confirm="makePhoneCall"
	/>
	
	<fui-fab position="right" distance="10" bottom="240" width="120" @click="handlePublish">
	    <view class="text-white text-center">
	        <view class="fab-icon" />
	        <view style="font-size: 24rpx">发布产品</view>
	    </view>
	</fui-fab>
	
	<fui-bottom-popup :show="pageData.isPopupShow" @close="pageData.isPopupShow = false">
		<view class="fui-custom__wrap yr_person_popup">
			<view class="popup_top">
				<uni-icons type="left" size="24" color="#333333" @click="pageData.isPopupShow = false"></uni-icons>
				<view class="add_person_text" style="font-size:36rpx;">产品信息</view>
				<view class="del_person_btn"></view>
			</view>
			<view class="popup_content">
				<fui-form  label-weight="auto" ref="formRef" top="10">
					<fui-input required label="商品名称" placeholder="请输入商品名称" v-model="productInfo.name" label-width="212" size="28"></fui-input>
					
					<fui-input @click="handleSelectCategory" required label="商品分类" placeholder="请选择商品分类" disabled :value="productInfo.category" label-width="212" size="28"></fui-input>

					<!-- <fui-input required  maxlength="11" label="联系电话" placeholder="请输入联系电话" v-model="productInfo.mobile" label-width="212" size="28"></fui-input> -->
					<fui-form-item asterisk label="价格（元）" label-width="212" size="28">
						<fui-input type="number" v-model="productInfo.minSellPrice" style="width: 120rpx !important" :borderBottom="false" :padding="[0]" placeholder="最低价" size="28"></fui-input>
						<template v-slot:right>
							<view style="color: #CCCCCC;margin-right: 40rpx;">—</view>
							<fui-input v-model="productInfo.maxSellPrice" type="number" style="width: 120rpx !important;" :borderBottom="false" :padding="[0]" placeholder="最高价" size="28"></fui-input>
							<fui-text v-if="productInfo.unit==''" size="28" text="单位" color="#cccccc" @click="handleSelectUnit()"></fui-text>
							<fui-text v-else :text="productInfo.unit" size="28" @click="handleSelectUnit()"></fui-text>
						</template>
					</fui-form-item>
					
					<fui-form-item asterisk label="商品图片" :bottomBorder="false">
						<template v-slot:vertical>
							<uni-file-picker :value="pageData.productImageArr" ref="uploadRef" limit="1" :auto-upload="false" @select="handleUpload" @delete="handleDelete"/>
						</template>
					</fui-form-item>
				</fui-form>
			</view>
			<fui-button style="margin-top:36rpx;" text="保存" bold radius="96rpx" @click="addData" height="80rpx"/>
		</view>
	</fui-bottom-popup>
	
	<fui-bottom-popup :show="pageData.unitPopup">
		<view class="fui-scroll__wrap">
			<view class="fui-title">请选择</view>
			<fui-cascader ref="unitPopupRef" :value="pageData.unitVal" stepLoading @change="changeUnit" @complete="selectCompleteUnit" :options="pageData.unitOptions"></fui-cascader>
			<view class="fui-icon__close" @tap.stop="pageData.unitPopup=false">
				<fui-icon name="close" :size="48"></fui-icon>
			</view>
		</view>
	</fui-bottom-popup>
	
	<fui-picker :options="pageData.categoryText" layer="1" :show="pageData.categoryPopup" @change="changeCategory" @cancel="pageData.categoryPopup = false" zIndex="9999"></fui-picker>
	
	
	<fui-toast ref="toastRef" />
</template>

<style lang="less" scoped>
.detail_page{
	display: flex;
	flex-wrap: wrap;
	justify-content: center;
	align-items: flex-start;
	align-content: flex-start;
	padding-bottom: 40rpx;
	.module_width{
		width: 690rpx;
		margin-top: 24rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding:28rpx;
		box-sizing: border-box;
	}
	.ellipsis{
	  white-space: nowrap;
	  overflow: hidden;
	  text-overflow: ellipsis;
	}
	.top_content{
		.enterprise_logo_view{
			width: 630rpx;
			display:flex;
			align-items: flex-start;
			.enterprise_logo{
				height: 80rpx;
			}
		}
		.enterprise_business{
			width: 636rpx;
			padding:8rpx 20rpx;
			border-radius: 8rpx;
			background: linear-gradient(233.81deg, rgba(92, 181, 110, 1) 0%, rgba(100, 214, 62, 1) 100%);
			font-size: 24rpx;
			font-weight: 500;
			line-height: 40rpx;
			color: #FFFFFF;
			margin-top: 32rpx;
		}
		.enterprise_description{
			margin-top: 20rpx;
			font-size: 24rpx;
			font-weight: 400;
			letter-spacing: 0px;
			line-height: 40rpx;
			color: #333333;
			text-align: justify;
			vertical-align: middle;
			text-indent: 2em;
		}
	}
	.middle_content{
		
	}
	.module_title{
		font-size: 32rpx;
		font-weight: 500;
		line-height: 40rpx;
		color: #333333;
		text-align: justify;
		vertical-align: middle;
	}
	.module_separate{
		margin-top: 20rpx;
		width: 128rpx;
		height: 6rpx;
		opacity: 1;
		background: linear-gradient(233.81deg, #5CB56E 0%, #64D63E 100%);
	}
	.module_qualification{
		margin-top: 6rpx;
		display: flex;
		flex-wrap: wrap;
		align-items: flex-start;
		align-content: flex-start;
		.qualification_item{
			width: 198rpx;
			height: 166rpx;
			margin-left: 20rpx;
			margin-top: 26rpx;
			border-radius: 8rpx;
			padding-top: 8rpx;
			box-sizing: border-box;
			display: flex;
			flex-wrap: wrap;
			justify-content: center;
			.enterprise_logo{
				height: 114rpx;
				max-width: 160rpx;
			}
			.qualification_name{
				height: 40rpx;
				line-height: 40rpx;
				font-size: 20rpx;
				color: #333333;
				max-width: 160rpx;
			}
		}
		.qualification_item:nth-child(3n+1){
			margin-left: 0rpx;
		}
	}
	
	
	.module_business{
		display: flex;
		flex-wrap: wrap;
		align-items: flex-start;
		align-content: flex-start;
		justify-content: space-between;
		.business_item{
			width: 310rpx;
			height: 292rpx;
			margin-top: 24rpx;
			border-radius: 16rpx;
			box-sizing: border-box;
			display: flex;
			flex-wrap: wrap;
			justify-content: center;
			background: #F9FAFB;
			.business_img{
				width: 310rpx;
				height: 180rpx;
				opacity: 1;
				border-radius: 16rpx 16rpx 0rpx 0rpx;
			}
			.qualification_name{
				height: 48rpx;
				line-height: 48rpx;
				font-size: 32rpx;
				color: #000000;
				max-width: 280rpx;
				margin-top: 6rpx;
			}
			.qualification_price{
				height: 48rpx;
				width: 280rpx;
				opacity: 1;
				font-size: 32rpx;
				font-weight: 400;
				letter-spacing: 0px;
				line-height: 48rpx;
				text-align: center;
				color: #5DB66F;
				.qualification_text{
					font-size: 12px;
				}
			}
		}
		.business_item:nth-child(odd){
			margin-left: 0rpx;
		}
	}
}
::v-deep .fui-fab__btn-main {
	background: linear-gradient(124.25deg, #a5d63f 0%, #5db66f 100%) !important;
	box-shadow: 0px 1px 8px #5db66f;
}

.fui-scroll__wrap {
	padding-top: 30rpx;
	position: relative;
}

.fui-title {
	font-size: 30rpx;
	font-weight: bold;
	text-align: center;
	padding-bottom: 24rpx;
}

.fui-icon__close {
	position: absolute;
	top: 24rpx;
	right: 24rpx;
}

.make-phone-view{
	width: 690rpx;
	height: 80rpx;
	position: fixed;
	left: 30rpx;
	bottom: 20rpx;
}
</style>
