<template>
	<div class="xianzhiziyuan-add">

		<div class="form">
			<div class="form-item" style="display: flex;padding: 20px 0px;">
				<div class="form-label width30">
					<span class=" required">*</span>资源名称：
				</div>
				<input placeholder="请输入" type="text" v-model="form.name">
			</div>

			<div class="form-item" style="display: flex;padding: 20px 0px;" @click="goodsType('goodsType')">
				<div class="form-label width30">
					<span class=" required">*</span>资源类别：
				</div>
				<div style="
						width: 65%;
						display: flex;
            justify-content: space-between;
            padding-right: 10px;">
					<div v-if="goodsTypeArray.length==0" style="color: #6c6c6c;">请选择</div>
					<div v-if="goodsTypeArray.length==0" style="color: #6c6c6c;"> ></div>
					<span v-else v-for="item in goodsTypeArray">
					{{ item.value + ',' }}
				</span>
				</div>
			</div>
			<div class="form-item" style="display: flex;padding: 20px 0px;" @click="openParkSelect('useTypeText')">
				<div class="form-label width30">
					使用方式：
				</div>
				<div
				 style="width: 60%;
						display: flex;
            justify-content: space-between;
            padding-right: 10px;"
				>
					<div :style="{color: !form.useTypeText ? '#6c6c6c':''}">
						{{ form.useTypeText ? form.useTypeText : '请选择' }}
					</div>

				</div>
				<div style="text-align: left;color: #6c6c6c;" v-if="goodsTypeArray.length==0"> ></div>
			</div>
			<div class="form-item" style="display: flex;padding: 20px 0px;">
				<div class="form-label width30">
					<span class=" required">*</span>参考金额（元）：
				</div>
				<input placeholder="请输入" type="text" v-model="form.initUseMoney">
			</div>

			<div class="form-item" style="display: flex;padding: 20px 0px;">
				<div class="form-label width30">
					<span class=" required">*</span>联系人：
				</div>
				<input placeholder="请输入" type="text" v-model="form.connectName">
			</div>
			<div class="form-item" style="display: flex;padding: 20px 0px;">
				<div class="form-label width30">
					<span class=" required">*</span>联系电话：
				</div>
				<input placeholder="请输入" type="text" v-model="form.connectPhone">
			</div>
			<div class="form-item" style="padding: 20px 0px;">
				<div class="form-label width30">
					<span class=" required">*</span>资源图片：
				</div>
				<van-uploader
				 :multiple="true"
				 v-model="componentsFileUrlList"
				 :max-count="6"
				 :after-read="afterRead"
				 :before-delete="beforeDelete"
				></van-uploader>
			</div>

			<div class="form-item">
				<div class="form-label" style="padding: 5px 0px;">
					<span class=" required">*</span>资源描述：
				</div>
				<div style="margin-top: 8px;">
					<van-field
					 v-model="form.info"
					 autosize
					 maxlength="5000"
					 placeholder="请输入留言"
					 rows="2"
					 show-word-limit
					 type="textarea"
					/>
				</div>
			</div>


		</div>
		<div class="btn-view">
			<button class="btn btn1" @click="goBack()">关闭</button>
			<button class="btn btn2" @click="submitData(2)">保存</button>
			<button class="btn btn2" @click="submitData(0)">提交</button>
		</div>
		<zhaozu-select
		 ref="zhaozuSelect"
		 :columns="dc_data.sunan_renting_type"
		 @getZhaozuType="getZhaozuType"
		/>
		<current-select
		 :columns="userType"
		 ref="userType"
		 @getAboultPark="getAboultPark"
		/>
	</div>
</template>

<script>
import { Field, Form, Toast } from 'vant'
import currentSelect from '@/pages/resource-release/componets/current-select.vue'
import zhaozuSelect from '@/pages/resource-release/componets/zhaozuSelect.vue'
import axios from 'axios'
import Base from '@/pages/base/base.vue'
import { add, getTmpInfoByUserId } from '@/service/api_goodsReport'
import auth from '@/service/auth'

export default {
	name: 'xianzhiziyuan-add',
	components: {
		Form, Field, currentSelect, zhaozuSelect
	},
	mixins: [Base],
	data() {
		return {
			myFileList: [],
			sunan_renting_type: [],
			dc_data: {},
			userType: [
				{ text: '租赁', value: 1 },
				{ text: '购买', value: 2 }
			],
			dc_key: ['sunan_renting_type'],
			pattern: /\d{6}/,
			active: '',
			form: {},
			fileList: [],
			id: '',
			goodsTypeArray: [],
			componentsFileUrlList: []
		}
	},
	mounted() {
		this.initDict(this.dc_key).then((res) => {
			console.log(this.dc_data)
			this.getTmpInfoByUserId()
			this.sunan_renting_type = this.dc_data.sunan_renting_type.map((e) => {
				return {
					text: e.label,
					value: e.value
				}
			})
			this.$forceUpdate()
		})

	},
	methods: {
		goBack() {
			this.$router.go(-1)
		},
		getTmpInfoByUserId() {
			getTmpInfoByUserId({ id: auth.currUser().id }).then((e) => {
				console.log(e.data == true)
				if (e.code == 200 && e.data) {
					const { data: res } = e
					console.log(res)
					this.id = res.id
					this.form.name = res.name
					let goodsTypeArray = res.types.split()
					this.goodsTypeArray = goodsTypeArray.map((e) => {
						return {
							label: e,
							value: e
						}
					})
					this.form.info = res.info
					let myFileList = res.pictureUrl.split(',')
					this.myFileList = myFileList
					this.componentsFileUrlList = myFileList.map((e) => {
						return {
							url: process.env.VUE_APP_API_URL + '/FileController/download/' + e,
							isImage: true
						}
					})
					this.form.connectPhone = res.connectPhone
					this.form.connectName = res.connectName
					this.form.initUseMoney = res.initUseMoney
					this.form.useTypeText = res.useType == 1 ? '租赁' : '购买'
				}
			})
		},
		async submitData(status) {
			console.log(this.goodsTypeArray)
			if (!this.form.name || this.form.name.length == 0) return Toast('请填写资源名称')
			if (!this.goodsTypeArray || this.goodsTypeArray.length == 0) return Toast('请选择资源类别')
			if (!this.form.useTypeText || this.form.useTypeText.length == 0) return Toast('请选择使用方式')
			if (!this.form.initUseMoney || this.form.initUseMoney.length == 0) return Toast('请填写参考金额')
			if (!this.form.connectName || this.form.connectName.length == 0) return Toast('请填写联系人')
			if (!this.form.connectPhone || this.form.connectPhone.length == 0) return Toast('请填写联系电话')
			if (!this.myFileList || this.myFileList.length == 0) return Toast('请上传招租图片')
			if (!this.form.info || this.form.info.length == 0) return Toast('请填写资源描述')

			console.log(this.goodsTypeArray)
			let goodsTypeArray = this.goodsTypeArray.map((e) => {
				return e.value
			})
			console.log(this.id)
			let params = {
				types: goodsTypeArray.toString(),
				useType: this.form.useTypeText == '租赁' ? 1 : 2,
				pictureUrl: this.myFileList.join(','),
				connectName: this.form.connectName,
				connectPhone: this.form.connectPhone,
				info: this.form.info,
				status: status,
				id: this.id,
				name: this.form.name,
				initUseMoney: this.form.initUseMoney,
				createdBy: auth.currUser().id
			}
			let data = await add(params)

			if (data.code == 200 && status == 0) {
				Toast('提交成功')
				this.$router.go(-1)
			} else {
				console.log(this.id)
				this.getTmpInfoByUserId()
				Toast('保存成功')

			}

			console.log(params)
		},
		getZhaozuType(e) {
			console.log(e)
			this.goodsTypeArray = e
		},
		goodsType(type) {
			this.$refs.zhaozuSelect.setVisible(true)
		},
		beforeDelete(file, detail) {
			// this.handleImagUrlList = []
			console.log(file, detail)
			const vm = this
			// name.index代表图片的索引
			vm.myFileList.splice(detail.index, 1)
			return (file, name) => {
				const fileIndex = name.index
				vm.myFileList[detail.index].splice(fileIndex, 1)
			}
		},
		uploadImg(file) {
			const _this = this
			const formParam = new FormData() // 创建form对象
			formParam.append('file', file.file)// 通过append向form对象添加数据
			console.log(formParam.get('file')) // FormData私有类对象，访问不到，可以通过get判断值是否传进去
			// upload(formParam).then((res) => {
			//     console.log(res)
			// })
			const config = {
				headers: {
					'Content-Type': 'multipart/form-data',
					'MVVM-Key': String(new Date().getTime()),
					'xx': 'anything'
				} // 这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
			} // 添加请求头
			return new Promise((resolve, reject) => {
				axios.post('/industryParkApi/wx/fileController/upload', formParam, config)
				 .then(response => {
					 let files = response.data.data.substring(1, response.data.data.length)
					 files = files.substring(0, files.length - 1)
					 console.log(_this.$common.castEval(files))
					 _this.fileUrlList.push(_this.$common.castEval(files))
				 }).catch((err, x) => {
					reject(err, x)
				})
			})
		},
		async afterRead(file) {
			let myFileList = []
			let data = await this.$common.uploadImg(file)
			for (let i = 0; i < data.length; i++) {
				this.myFileList.push(data[i])
			}

			this.$forceUpdate()
		},
		getAboultPark(e, key) {
			console.log(e)
			this.form[key] = e.text
			this.$forceUpdate()
		},
		openParkSelect(type) {
			this.$refs.userType.setVisible(true, {}, type)
		},
		onFailed(errorInfo) {
			console.log('failed', errorInfo)
		}
	}
}
</script>

<style lang="scss">
.overhidden {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}

.mt24 {
	margin-top: 24px;
}

.mb24 {
	margin-bottom: 24px;
}

.width30 {
	width: 30%;
}

.xianzhiziyuan-add {
	.form {
		width: 80vw;
		margin: 32px 5vw;
		padding: 5% 5vw;
		background: white;

		.form-label {
			//width: 20%;
		}

		.form-item {
			width: 100%;
			border-bottom: 2px solid #CCCCCC;
			padding-bottom: 20px;
		}

		.required {
			color: red
		}

		.van-field {
			background: #F7F7F7 !important;
		}
	}

	.btn-view {
		display: flex;
		justify-content: space-between;
		width: 90%;
		padding: 0 5%;
		height: 100px;
		position: fixed;
		bottom: 0;
		left: 0;

		.btn1 {
			background: rgba(87, 134, 218, 0.4);
			color: #13336B;
		}

		.btn2 {
			background: #1F3D74;
			color: #FFFFFF;
		}
	}

	.btn {
		width: 206px;
		height: 68px;
		background: #1d18bc;
		line-height: 68px;
		color: white;
	}
}
</style>
