<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 NongjifuwuAPI from '@/api/model/nongjifuwu'
	import * as LinghuoyonggongAPI from '@/api/model/linghuoyonggong'
	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);
		getProvince(0,null);
		postMachineryQueryById();
	})
	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: 'areaText',
			    rule: ['required'],
			    msg: ['请选择服务区域'],
			},{
                name: 'minPrice',
                rule: ['required'],
                msg: ['请输入最低价'],
            },{
                name: 'maxPrice',
                rule: ['required'],
                msg: ['请输入最高价'],
            },
			{
			    name: 'image',
			    rule: ['required'],
			    msg: ['请选择商品图片'],
			},
		]
	})
	let productInfo = reactive({
		id:"",
		name:"",// 商品名称
		mobile:"", // 联系方式
		
		province:"", // 省
		city:"", // 市
		districts:"", // 区县
		
		minPrice:"", // 最小销售价
		maxPrice: "", // 最大销售价
		image:"", // 农机图片
		
		enterpriseId:"", // 企业ID
		areaText:'',
	})
	function handleSelectArea(){
		pageData.unitPopup = true;
	}
	function postMachineryQueryById(){
		NongjifuwuAPI.postMachineryQueryById({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 selectCompleteUnit(e){
		const text = e.text;
		const areaAttr = ['province','city','districts'];
		for(let i = 0; i < text.length;i++){
			productInfo[areaAttr[i]] = text[i];
		}
		productInfo.areaText = text.join('');
		pageData.unitPopup = false;
	}
	function changeUnit(e){
		let val = e.value;
		getProvince(val,e);
	}
	function handleSelectUnit(){
		pageData.unitPopup = true;
	}
	// 获取下一级地区
	function getProvince(code,e) {
		if(e && e.layer >=2){
			unitPopupRef.value.end();
			return;
		}
		LinghuoyonggongAPI.queryConditions({ parentCode : 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) {
				NongjifuwuAPI.postMachineryAdd(productInfo).then((res) => {
					toastRef.value.show({
					    type: 'success',
					    text: '发布成功',
					})
					pageData.isPopupShow = false;
					setTimeout(()=>{
						postMachineryQueryById();
					},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.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.province = "";
		productInfo.city = "";
		productInfo.districts = "";
		productInfo.minPrice = "";
		productInfo.maxPrice = "";
		productInfo.image = "";
		productInfo.areaText = "";
		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" v-if="pageData.data">
			<!-- <view class="enterprise_logo_view"><image class="enterprise_logo" mode="heightFix" :src="pageData.data.enterpriseLogoUrl" /></view> -->
			<view class="enterprise_logo_view"><text class="enterprise_name">{{pageData.data.enterpriseName}}</text></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="`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="business_item" v-for="item in pageData.enterpriseProduct" :key="item.id">
				<image class="business_img" src="/static/images/test/test.jpg" />
				<view class="yr-right">
					<view>
						<view class="product-name">{{item.name}}</view>
						<view class="services-range">服务范围：{{item.province}}{{item.city}}{{item.districts}}</view>
					</view>
					<view class="services-price text-red"><text class="font-size24">¥</text><text class="font-size32">{{item.minPrice}}~{{item.maxPrice}}</text class="text-grey font-size24"> /亩</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">农机信息</view>
				<view class="del_person_btn"></view>
			</view>
			<view class="popup_content">
				<fui-form  label-weight="auto" ref="formRef" top="0">
					<fui-input required label="农机名称" borderTop placeholder="请输入农机名称" v-model="productInfo.name" label-width="220" size="28"></fui-input>
					<fui-input required  maxlength="11" label="联系电话" placeholder="请输入联系方式" v-model="productInfo.mobile" label-width="220" size="28"></fui-input>
					<fui-input @click="handleSelectArea" required label="服务区域" placeholder="请选择服务区域" disabled :value="productInfo.areaText" label-width="220" size="28"></fui-input>
					
					<fui-form-item asterisk label="价格（元/亩）" labelSize="28" label-width="220" size="28">
						<fui-input v-model="productInfo.minPrice" :borderBottom="false" :padding="[0]" placeholder="最低价"></fui-input>
						<template v-slot:right>
							<view style="color: #CCCCCC;margin-right: 40rpx;">—</view>
							<fui-input v-model="productInfo.maxPrice" :borderBottom="false" :padding="[0]" placeholder="最高价"></fui-input>
						</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 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-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_name{
				font-size: 32rpx;
				font-weight: 500;
				line-height: 40rpx;
				color: #333333;
			}
		}
		.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;
		}
	}
	
	
	
	.business_item{
		border-bottom: 1px solid #EEEEEE;
		margin-top: 24rpx;
		padding-bottom: 20rpx;
		display: flex;
		justify-content: space-between;
		.business_img{
			width: 160rpx;
			height: 160rpx;
			border-radius: 8rpx;
		}
		.yr-right{
			width: 450rpx;
			display: flex;
			flex-wrap: wrap;
			align-content:space-between;
			padding:4rpx 0rpx;
			.product-name{
				height: 40rpx;
				line-height: 40rpx;
				font-size: 32rpx;
				font-weight: 500;
				color: #333333;
			}
			.services-range{
				font-size: 24rpx;
				font-weight: 400;
				height: 32rpx;
				line-height: 32rpx;
				color: #555555;
			}
			.services-price{
				height: 40rpx;
			}
			.text-red{color:#F2130D;}
			.text-grey{color:#999999;}
			.font-size24{font-size: 24rpx;}
			.font-size32{font-size: 32rpx;}
		}
	}
	.business_item:last-child{
		border-bottom:none;
	}
}
::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>
