<template>
	<view class="total-page page-box task-bg">
		<Nav title="资产评估" :genre="1" :toBack="true" is_fixed></Nav>
		<view class="p-b40">
			<!-- 身份认证start -->
			<view class="m-t20 m-lr30 text-color-12">
				<view class="sys-background-fff r-20 p-lr30 p-t30">
					<en-select v-model="propertyData.modelType" :local-data="typeOption" label="评估模型"
						placeholder="请选择评估模型"></en-select>
					<en-input v-model="propertyData.address" label="评估地址" disabled="disabled" placeholder="请输入评估地址"
						@inputBut="inputBut"></en-input>
					<en-input v-model="propertyData.complexName" :label="'小区名称'" disabled="disabled"
						placeholder="请输入小区名称"> </en-input>
					<en-input :value="propertyData.lng+','+propertyData.lat" disabled="disabled" label="评估坐标"
						placeholder="地址经纬度"></en-input>
					<en-input v-model="propertyData.area" :label="'建筑面积'" placeholder="请输入建筑面积"> </en-input>
					<en-select v-model="propertyData.district" :local-data="districtOption" :label="'所属区域'"
						placeholder="请选择所属区域"> </en-select>
				</view>
			</view>
      <view class="m-t20 m-lr30 text-color-12">
			<view class="sys-background-fff r-20 m-t20 p-lr30" v-if="propertyData.modelType*1===1">
				<en-select v-model="propertyData.houseType" :local-data="houseTypeOption" label="房屋类型"
					placeholder="请选择房屋类型"></en-select>
			</view>
			</view>
        <view class="m-t20 m-lr30 text-color-12">
			<view class="sys-background-fff r-20 m-t20 p-lr30" v-if="propertyData.modelType*1===2">
				<EnRadio v-model="propertyData.is_rent" label="是否出租" :list="statusOption"> </EnRadio>
				<EnRadio v-model="propertyData.is_morgaged" label="是否抵押" :list="statusOption"> </EnRadio>
				<EnRadio v-model="propertyData.is_occupied" label="是否占用" :list="statusOption"> </EnRadio>
				<EnRadio v-model="propertyData.is_seizured" label="是否查封" :list="statusOption"> </EnRadio>
			</view>
			</view>
          <view class="m-t20 m-lr30 text-color-12">
			<view class="sys-background-fff r-20 m-t20 p-lr30" v-if="propertyData.modelType*1===3">
				<en-select v-model="propertyData.level_id" :local-data="levelOption" :label="'土地等级'"
					placeholder="请选择土地等级"> </en-select>
				<en-select v-model="propertyData.transfer_method" :local-data="transferMethodOption" :label="'出让方式'"
					placeholder="请选择出让方式"> </en-select>
				<en-select v-model="propertyData.land_use" :local-data="landUseOption" :label="'土地用途'"
					placeholder="请选择土地用途"> </en-select>
				<en-select v-model="propertyData.land_source" :local-data="landSourceOption" :label="'土地来源'"
					placeholder="请选择土地来源"> </en-select>
				<en-input v-model="propertyData.age_limit" :label="'出让年限'" placeholder="请输入出让年限"> </en-input>
				<en-input v-model="propertyData.investment" :label="'投资强度'" placeholder="请输入投资强度"> </en-input>
				<en-input v-model="propertyData.plot_mix" :label="'最小容积'" placeholder="请输入最小容积率"> </en-input>
				<en-input v-model="propertyData.plot_max" :label="'最大容积'" placeholder="请输入最大容积率"> </en-input>
				<en-input v-model="propertyData.greening_mix" :label="'最小绿化'" placeholder="请输入最小绿化面积"> </en-input>
				<en-input v-model="propertyData.greening_max" :label="'最大绿化'" placeholder="请输入最大绿化面积"> </en-input>
				<en-input v-model="propertyData.height_mix" :label="'最小高度'" placeholder="请输入最小建筑高度"> </en-input>
				<en-input v-model="propertyData.height_max" :label="'最大高度'" placeholder="请输入最大建筑高度"> </en-input>
			</view>
			</view>
		</view>
		<EnButton class="m-b50" :is_fixed="false" :text="'评估'" @onSubmit="onSubmit"></EnButton>
    <popupModuleVue ref="popupModuleRef"></popupModuleVue>
    <Tab class="tabs_height" :tab-index="2"></Tab>
	</view>
</template>

<script>
	import EnUpload from "@/components/en-from/en-upload/en-upload.vue";
	import EnSelect from "@/components/en-from/en-select/en-select.vue";
	import EnRadio from "@/components/en-from/en-radio/en-radio.vue";
	import EnInput from "@/components/en-from/en-input/en-input.vue";
  import {
    getValuationOption,
    predictProperty
  } from "@/api/valuation.js"
  import tools from "@/service/tools";
  import popupModuleVue from "@/pages/index/module/popup-module.vue";
	export default {
		components: {
      popupModuleVue,
			EnInput,
			EnSelect,
			EnRadio,
			EnUpload,
		},
		data() {
			return {
				typeOption: [{
					value: 1,
					text: '住宅模型'
				}, {
					value: 2,
					text: '公建模型'
				}, {
					value: 3,
					text: '土地模型'
				}, {
					value: 4,
					text: '工业模型'
				}],
				statusOption: [{
					value: 1,
					text: '是'
				}, {
					value: 0,
					text: '否'
				}],
				houseTypeOption: [],
				levelOption: [],
				transferMethodOption: [],
				landUseOption: [],
				landSourceOption: [],
				districtOption: [{
					value: 1,
					text: '甘井子区'
				}, {
					value: 2,
					text: '中山区'
				}, {
					value: 3,
					text: '西岗区'
				}, {
					value: 4,
					text: '沙河口区'
				}, {
					value: 5,
					text: '旅顺口区'
				}, {
					value: 6,
					text: '金州区'
				}, {
					value: 7,
					text: '瓦房店市'
				}, {
					value: 8,
					text: '庄河市'
				}, {
					value: 9,
					text: '普兰店区'
				}],
				propertyData: {
					level_id: 1,
					transfer_method: 1,
					land_use: 1,
					land_source: 1,
					investment: 0,
					plot_mix: 0,
					plot_max: 0,
					height_mix: 0,
					height_max: 0,
					greening_mix: 0,
					greening_max: 0,
					age_limit: 0,
					floor_area: 0,
					lat: 0,
					lng: 0,
					is_sold: 0,
					is_rent: 0,
					is_morgaged: 0,
					is_occupied: 0,
					is_seizured: 0,
					address: '',
					modelType: '',
					area: '',
					district: '',
					houseType: '',
					complexName: '',
				},
				propertyRes: {
					unit_price: '',
          total_price: '',
					predict_msg: '',
				},
				location: {
					lat: 0,
					lng: 0,
					address: '',
					districtName: '',
					complexName: ''
				},
			};
		},
		onLoad(options) {},
		onShow() {},
		watch: {
      'propertyData.modelType':function(){
        if(this.propertyData.modelType>0){
          this.getValuationOption()
        }
      }
    },
		mounted() {},
		methods: {
			async inputBut() {
				let that = this;
				try {
					// 选择位置
					uni.chooseLocation({
            latitude:38.913943,
            longitude:121.614794,
						success: function(res) {
              console.log(res)
							// 更新数据
							that.propertyData.lng = res.longitude;
							that.propertyData.lat = res.latitude;
							that.propertyData.address = res.address;
							that.propertyData.complexName = res.name || '';
							// 根据地址信息设置区域
							that.setDistrictByAddress(res.address);
							console.log('当前位置的经度：' + res.longitude);
							console.log('当前位置的纬度：' + res.latitude);
						},
						fail: async function(err) {
							console.log('获取位置失败：', err);
							// 如果是授权被拒绝
							if (err.errMsg.indexOf('auth deny') !== -1) {
								try {
									// 引导用户手动开启授权
									await showAuthorizeGuide();
								} catch (e) {
									console.log('授权引导失败：', e);
								}
							}
						}
					});
				} catch (err) {
					console.log('获取位置失败：', err);
					if (err.errMsg && (err.errMsg.includes('auth deny') || err.errMsg.includes('fail cancel'))) {
						uni.showToast({
							title: '需要位置权限才能选择地址',
							icon: 'none'
						});
					}
				}
			},
			// 检查位置权限
			checkLocationAuth() {
				return new Promise((resolve) => {
					uni.getSetting({
						success: (res) => {
							const authSetting = res.authSetting;
							resolve(authSetting['scope.userLocation'] || false);
						},
						fail: () => {
							resolve(false);
						}
					});
				});
			},
			// 选择位置
			// chooseLocation() {
			// 	return new Promise((resolve, reject) => {
			// 		uni.chooseLocation({
			// 			success: resolve,
			// 			fail: reject
			// 		});
			// 	});
			// },
			showAuthorizeGuide() {
				return new Promise((resolve, reject) => {
					uni.showModal({
						title: '位置权限未开启',
						content: '需要您授权位置信息才能提供此服务，请到设置中开启权限',
						confirmText: '去设置',
						success: (modalRes) => {
							if (modalRes.confirm) {
								// 打开小程序设置页面
								uni.openSetting({
									success: (openRes) => {
										if (openRes.authSetting['scope.userLocation']) {
											uni.showToast({
												title: '授权成功',
												icon: 'success'
											});
											resolve();
										} else {
											uni.showToast({
												title: '授权失败',
												icon: 'none'
											});
											reject();
										}
									}
								});
							} else {
								reject();
							}
						}
					});
				});
			},
			// 根据地址设置区域
			setDistrictByAddress(address) {
				if (!address) return;
				const districtText = this.extractDistrictFromAddress(address);
				if (districtText) {
					const district = this.districtOption.find(item =>
						districtText.includes(item.text) || item.text.includes(districtText)
					);
					if (district) {
						this.propertyData.district = district.value;
					}
				}
			},
			// 从地址中提取区域信息
			extractDistrictFromAddress(address) {
				if (!address) return '';
				// 简单的区域提取逻辑，可以根据实际需求调整
				for (let district of this.districtOption) {
					if (address.includes(district.text)) {
						return district.text;
					}
				}
				return '';
			},
			setLocation(res) {
				console.log("收到监听", res)
				this.propertyData.address = res.address
				this.propertyData.lat = res.lat
				this.propertyData.lng = res.lng
				this.propertyData.complexName = res.complexName
				this.setDistrictByAddress(res.address);
				// this.districtOption.forEach(item => {
				// 	if (res.districtName === item.text) {
				// 		this.propertyData.district = item.value
				// 	}
				// })
			},
			getValuationOption() {
				if (this.propertyData.houseType === "") {
					this.propertyData.houseType = 0
				}
          getValuationOption({
            "modelType": this.propertyData.modelType*1
          }).then(res => {
            if (res.code === 0) {
              if (this.propertyData.modelType*1 === 1) {
                // res.data.houseTypeOption.
                this.houseTypeOption = res.data.houseTypeOption.map(({ id,name }) => ({
                  value: id,
                  text: name
                }));
                console.log(this.houseTypeOption)
              } else if (this.propertyData.modelType*1 === 3) {
                this.levelOption =  res.data.levelOption.map(({ id,name }) => ({
                  value: id,
                  text: name
                }));
                this.transferMethodOption =  res.data.transferMethodOption.map(({ id,name }) => ({
                  value: id,
                  text: name
                }));
                this.landUseOption =  res.data.landUseOption.map(({ id,name }) => ({
                  value: id,
                  text: name
                }));
                this.landSourceOption =  res.data.landSourceOption.map(({ id,name }) => ({
                  value: id,
                  text: name
                }));
                this.propertyData.land_source = this.landSourceOption[0].value
              }
            }
          })
			},
			onSubmit() {
				console.log('提交评估数据', this.propertyData)
				predictProperty({
          level_id: this.propertyData.level_id*1,
          transfer_method: this.propertyData.transfer_method*1,
          land_use: this.propertyData.land_use*1,
          land_source: this.propertyData.land_source*1,
          investment: this.propertyData.investment*1,
          plot_mix: this.propertyData.plot_mix*1,
          plot_max: this.propertyData.plot_max*1,
          height_mix: this.propertyData.height_mix*1,
          height_max: this.propertyData.height_max*1,
          greening_mix: this.propertyData.greening_mix*1,
          greening_max: this.propertyData.greening_max*1,
          age_limit: this.propertyData.age_limit*1,
          floor_area: this.propertyData.floor_area*1,
          lat: this.propertyData.lat*1,
          lng: this.propertyData.lng*1,
          is_sold: this.propertyData.is_sold*1,
          is_rent: this.propertyData.is_rent*1,
          is_morgaged: this.propertyData.is_morgaged*1,
          is_occupied: this.propertyData.is_occupied*1,
          is_seizured: this.propertyData.is_seizured*1,
          address:  this.propertyData.address,
          modelType: this.propertyData.modelType*1,
          area: this.propertyData.area*1,
          district: this.propertyData.district*1,
          houseType: this.propertyData.houseType*1,
          complexName:this.propertyData.complexName,
        }).then(res => {
					if (res.code === 0) {
						console.log(res, 'res');
						this.propertyRes = res.data
						this.propertyRes.total_price = (res.data.unit_price*this.propertyData.area).toFixed(2)
            this.$refs.popupModuleRef.openPop(5,this.propertyRes)
					} else {
						tools.error(res.msg)
					}
				})
			},
			setMapMarker(lng, lat, status) {
				if (this.marker === undefined) {
					this.marker = new AMap.Marker({
						position: new AMap.LngLat(lng, lat),
						offset: new AMap.Pixel(-10, -10),
						icon: "//vdata.amap.com/icons/b18/1/2.png", //添加 icon 图标 URL
						title: "标记位",
					});
					this.map.add(this.marker);
				} else {
					this.marker.setPosition(new AMap.LngLat(lng, lat));
				}
				if (status) {
					this.location.lat = lat
					this.location.lng = lng
					AMap.plugin("AMap.Geocoder", () => {
						let geocoder = new AMap.Geocoder({
							city: "大连市", // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
							extensions: "all"
						});
						let lnglat = [this.location.lng, this.location.lat];
						geocoder.getAddress(lnglat, (status, result) => {
							if (status === "complete" && result.info === "OK") {
								// result为对应的地理位置详细信息
								console.log(result.regeocode)
								if (result.regeocode.formattedAddress !== undefined && result.regeocode
									.formattedAddress !== "") {
									this.location.address = result.regeocode.formattedAddress;
									this.location.districtName = result.regeocode.addressComponent
										.district;
									if (result.regeocode.pois !== undefined && result.regeocode.pois
										.length > 0) {
										this.location.complexName = result.regeocode.pois[0].name
									}
								}
							}
						});
					});
				}
			},
		},
	}
</script>

<style lang="scss" scoped>
	.input-item:last-child {
		margin-top: 30rpx;
	}

	.input-send {
		display: flex;
		justify-content: flex-start;
		align-items: center;
		border-bottom: 1px solid #E5E5E5;

		.login-input {
			width: calc(100% - 150rpx);
		}

		.login-send {
			width: 100rpx;
			text-align: center;
			margin-left: 20rpx;
			border: 1rpx solid #0FB160;
			border-radius: 50rpx;
		}
	}

	.left-w {
		width: 210rpx;
		min-width: 210rpx;
		color: #333333;
	}

	.iconfont {
		font-size: 36rpx;
		color: #333333;
	}

	.class-c-6C6F93 {
		color: #0FB160;
	}

	.agreement-data {
		border-radius: 30rpx 30rpx 0 0;

		.data-title {
			width: 100%;
			border-radius: 30rpx 30rpx 0 0;
		}

		.data-content {
			padding: 20rpx 40rpx;

			.content-box {
				height: 600rpx;
			}
		}

		.data-but {
			height: 96rpx;
			line-height: 96rpx;
			text-align: center;
			margin: 0 75rpx;
		}
	}
</style>
