<template>
	<div>
		<el-form :model="form" :rules="rules" ref="ruleForm" label-width="150px">
			<div class="container add_edit">
				<h3 class="margin_b_20">基本信息</h3>
				<div>
					<el-form-item label="两级分类">
						<uni-data-picker placeholder="请选择第一级分类" popup-title="请选择第二级分类" :localdata="categoryOptions" v-model="classes"
							@change="onchange" @nodeclick="onnodeclick" @popupopened="onpopupopened" @popupclosed="onpopupclosed">
						</uni-data-picker>
						<!-- <el-cascader class="sele" v-model="form.categoryOneId" :options="categoryOptions" ref="cascaderObj"
							:props="{ checkStrictly: true, emitPath: false, value: '_id', label: 'name' }">
						</el-cascader> -->
					</el-form-item>
					<!-- <el-form-item label="第二级分类" prop="categoryTwoId" ref="categoryTwoId">
						<el-cascader class="sele" v-model="form.categoryTwoId" :options="categoryOptions" ref="cascaderObj"
							:props="{ checkStrictly: true, emitPath: false, value: '_id', label: 'name' }">
						</el-cascader>
					</el-form-item> -->
					<el-form-item label="排序">
						<el-input v-model.number="form.sort" type="number" min="0"></el-input>
						<div class="remark_txt">数字越小，排名越靠前</div>
					</el-form-item>
					<el-form-item label="商品名称" prop="name" ref="name">
						<el-input placeholder="请输入商品名称" v-model="form.name"></el-input>
					</el-form-item>
				</div>
			</div>
			<div class="container add_edit">
				<h3 class="margin_b_20">商品信息</h3>
				<div>
					<el-form-item label="图片"><uni-file-picker v-model="imgval" fileMediatype="image" returnType="array"
						 @select="imgDelete" limit="6" @delete="Delete" /></el-form-item>
					<el-form-item label="限时精选">
						<!-- <el-checkbox v-model.number="form.limited" :true-label="1" :false-label="0">显示</el-checkbox>
						<div class="remark_txt">此分类将决定商品信息显示在限时精选分类下</div> -->
					</el-form-item>
					<el-form-item label="显示">
						<el-radio-group v-model="form.limited">
							<el-radio label="1">是</el-radio>
							<el-radio label="0">否</el-radio>
						</el-radio-group>
						<div class="remark_txt">此分类将决定商品信息显示在限时精选分类下</div>
					</el-form-item>
					<el-form-item label="热门推荐">
						<!-- <el-checkbox v-model.number="form.hot" :true-label="1" :false-label="0">显示</el-checkbox>
						<div class="remark_txt">此分类将决定商品信息显示在热门推荐分类下</div> -->
					</el-form-item>
					<el-form-item label="显示">
						<el-radio-group v-model="form.hot">
							<el-radio label="1">是</el-radio>
							<el-radio label="0">否</el-radio>
						</el-radio-group>
						<div class="remark_txt">此分类将决定商品信息显示在热门推荐分类下</div>
					</el-form-item>
					<!-- <el-form-item label="商品标签">
						<el-checkbox-group v-model="goodsDatas">
							<el-checkbox v-for="(item, idx) in goodsTags" :label="item.name" :key="idx"></el-checkbox>
						</el-checkbox-group>
						<div class="remark_txt">此选项表示商品所属商品</div>
					</el-form-item> -->
					<el-form-item label="服务标签">
						<el-checkbox-group v-model="serveDatas">
							<el-checkbox v-for="(item, idx) in serveTags" :label="item.id" :key="idx">{{item.tagName}}</el-checkbox>
						</el-checkbox-group>
						<div class="remark_txt">此选项表示商品对应的服务项</div>
					</el-form-item>
					<el-form-item label="商城价" prop="price" ref="price">
						<el-input v-model="form.price" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" min="0.01"></el-input>
						<div class="remark_txt">单位为元，最少为0.01元
						<!-- {{form.price}} 分 = {{form.price / 100}} 元 -->
						</div>
					</el-form-item>
					<el-form-item label="市场价" prop="marketPrice" ref="marketPrice">
						<el-input v-model="form.marketPrice" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" min="0.01"></el-input>
						<div class="remark_txt">单位为元，最少为0.01元
						<!-- {{form.marketPrice}} 分 = {{form.marketPrice / 100}} 元 -->
						</div>
					</el-form-item>
					<el-form-item label="限购量" prop="limit" ref="limit">
						<el-input v-model.number="form.limit" type="number" min="0"></el-input>
						<div class="remark_txt">0为不限购</div>
					</el-form-item>
					<el-form-item label="库存" prop="stockNum" ref="stockNum">
						<el-input v-model.number="form.stockNum" type="number" min="0"></el-input>
					</el-form-item>
					<el-form-item label="已出售数">{{form.saleCnt}}
						<!-- <el-input v-model.number="form.saleCnt" type="number" min="0"></el-input> -->
						<!-- <el-checkbox class="w100" v-model.number="form.showSale" :true-label="1" :false-label="0">显示
						</el-checkbox>
						<div class="remark_txt">勾选此选项将作虚拟销量</div> -->
					</el-form-item>
					<el-form-item label="显示">
						<el-radio-group v-model="form.showSale">
							<el-radio label="0">否</el-radio>
							<el-radio label="1">是</el-radio>
						</el-radio-group>
						<div class="remark_txt">勾选此选项将作虚拟销量</div>
					</el-form-item>
					<el-form-item label="已访问数">{{form.visitCnt}}
						<!-- <el-input v-model.number="form.visitCnt" type="number" min="0"></el-input> -->
						<!-- <el-checkbox class="w100" v-model.number="form.showVisit" :true-label="1" :false-label="0">显示
						</el-checkbox>
						<div class="remark_txt">勾选此选项将作访问销量</div> -->
					</el-form-item>
					<el-form-item label="显示">
						<el-radio-group v-model="form.showVisit">
							<el-radio label="0">否</el-radio>
							<el-radio label="1">是</el-radio>
						</el-radio-group>
						<div class="remark_txt">勾选此选项将作访问销量</div>
					</el-form-item>
					<el-form-item label="已收藏数">{{form.collectCnt}}
						<!-- <el-input v-model.number="form.collectCnt" type="number" min="0"></el-input> -->
						<!-- <el-checkbox class="w100" v-model="form.showCollect" :true-label="1" :false-label="0">显示
						</el-checkbox> -->
						<!-- <div class="remark_txt">勾选此选项将作收藏销量</div> -->
					</el-form-item>
					<el-form-item label="显示">
						<el-radio-group v-model="form.showCollect">
							<el-radio label="0">否</el-radio>
							<el-radio label="1">是</el-radio>
						</el-radio-group>
						<div class="remark_txt">勾选此选项将作收藏销量</div>
					</el-form-item>
					<!-- <el-form-item label="已分享数">{{form.shareCnt}} -->
						<!-- <el-input v-model.number="form.shareCnt" type="number" min="0"></el-input> -->
						<!-- <el-checkbox class="w100" v-model.number="form.showShare" :true-label="1" :false-label="0">显示
						</el-checkbox>
						<div class="remark_txt">勾选此选项将作分享销量</div> -->
					<!-- </el-form-item> -->
					<!-- <el-form-item label="显示">
						<el-radio-group v-model="form.showShare">
							<el-radio label="0">否</el-radio>
							<el-radio label="1">是</el-radio>
						</el-radio-group>
						<div class="remark_txt">勾选此选项将作分享销量</div>
					</el-form-item> -->
					<!-- <el-form-item label="下架时间" prop="sold_out_time" ref="sold_out_time">
						<el-date-picker v-model="form.sold_out_time" type="datetime" placeholder="下架时间" align="center"
							class="time" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"
							:picker-options="pickerOptions"></el-date-picker>
					</el-form-item> -->
					<el-form-item label="状态">
						<el-radio-group v-model="form.state">
							<el-radio label="2">待审核</el-radio>
							<el-radio label="1">销售中</el-radio>
							<el-radio label="0">已下架</el-radio>
						</el-radio-group>
					</el-form-item>
				</div>
			</div>
		</el-form>
	</div>
</template>

<script>
	import E from 'wangeditor';
	export default {
		data() {
			return {
				classes: "",
				categoryOptions: [],
				// categoryOneId: '',//一级分类,
				// categoryTwoId:'',// 二级分类
				goodsDatas: [],
				serveDatas: [],
				goodsTags: [],
				serveTags: [],
				servevalue:[],//服务标签
				form: {
					categoryOneId: '',//一级分类,
					categoryTwoId:'',// 二级分类
					servevalue:[],//服务标签
					cids: [],
					sort: 0,
					name: '',
					desc:'',
					limited: '0',
					hot: '0',
					tags: [],
					price: 0,
					marketPrice: 0,
					limit: 0,
					stockNum: 0,
					saleCnt: 0,
					showSale: 0,
					visitCnt: 0,
					showVisit: 0,
					collectCnt: 0,
					showCollect: 0,
					shareCnt: 0,
					showShare: 0,
					sold_out_time: '',
					state: '2',//0下架 1在售 2 待审核
					serveDatas: [],
					serveTags: [],
					imgs:[],
				},
				imgval:null,//商品图片
				pickerOptions: {
					disabledDate(time) {
						return time.getTime() < Date.now();
					}
				},
				dataId:'',
				rules: {
					categoryOneId: [{
						required: true,
						message: '请选择一级分类',
						trigger: 'change'
					}],
					categoryTwoId: [{
						required: true,
						message: '请选择二级分类',
						trigger: 'change'
					}],
					servevalue:[{
						required: true,
						message: '请选择服务标签',
						trigger: 'change'
					}],
					name: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'change'
					}],
					price: [{
						required: true,
						message: '请输入商城价，必须大于0.01',
						trigger: 'change'
					}],
					marketPrice: [{
						required: true,
						message: '请输入市场价，必须大于0.01',
						trigger: 'change'
					}],
					stockNum: [{
						required: true,
						message: '请输入库存，必须大于0',
						trigger: 'change'
					}],
					limit: [{
						required: true,
						message: '请输入库存，必须大于0',
						trigger: 'change'
					}],
					sort: [{
						required: true,
						message: '请排序',
						trigger: 'change'
					}],
					hot: [{
						required: true,
						message: '请选择是否热门推荐',
						trigger: 'change'
					}],
					limited: [{
						required: true,
						message: '请选择',
						trigger: 'change'
					}],
					state: [{
						required: true,
						message: '请选择商品状态',
						trigger: 'change'
					}],
					imgs: [{
						required: true,
						message: '请选择至少一张图片',
						trigger: 'change'
					}],
					showCollect: [{
						required: true,
						message: '请选择是否展示收藏数',
						trigger: 'change'
					}],
					showSale: [{
						required: true,
						message: '请选择是否展示已售数',
						trigger: 'change'
					}],
					showVisit: [{
						required: true,
						message: '请选择是否展示访问数',
						trigger: 'change'
					}],
					showShare: [{
						required: true,
						message: '请选择是否展示分享数',
						trigger: 'change'
					}],
					desc: [{
						required: true,
						message: '请输入商品详情',
						trigger: 'change'
					}],
					// sold_out_time: [{
					// 	required: true,
					// 	message: '请选择下架时间',
					// 	trigger: 'change'
					// }]
				}
			};
		},
		methods: {
			loadData() {
				var _self=this
				// 获取分类数据
				_self.$axios.get("/goodsCategory/open/list",
				{
					params:{
					},
					headers:{
					}
				}).then(response => {
					let res = response
					if (res.success) {
						_self.categoryOptions=res.data
						var stateDatas = [];
						for (let i = 0; i < _self.categoryOptions.length; i++) {
						  let res = JSON.parse(
							JSON.stringify(_self.categoryOptions[i])
							  .replace(/name/g, 'text')
							  .replace(/id/g, 'value')
							  .replace(/childCategory/g, 'children')
						  );
						  stateDatas.push(res);
						}
						_self.categoryOptions=stateDatas
						
						if (!_self.dataId) {
							_self.classes=_self.categoryOptions[0].children[0].value
							_self.form.categoryOneId = _self.categoryOptions[0].value
							_self.form.categoryTwoId = _self.categoryOptions[0].children[0].value
							return;
						}
						
					} else {
					}
				}).catch(res =>{
				});
				
				// 获取服务标签
				_self.$axios.get("/serviceTag/admin/list",
				{
					params:{
					},
					headers:{
						'Mall-Token': uni.getStorageSync("token")
					}
				}).then(response => {
					let res = response
					if (res.success) {
						res.data.list.forEach(data => {
							_self.form.serveTags.push(data)
							_self.serveTags.push(data)
						})
						
						// var serve = [];
						// for (let i = 0; i < _self.form.serveTags.length; i++) {
						//   let res = JSON.parse(
						// 	JSON.stringify(_self.form.serveTags[i])
						// 	  .replace(/tagName/g, 'text')
						// 	  .replace(/id/g, 'value')
						//   );
						//   serve.push(res);
						// }
						// _self.form.serveTags=serve
						// console.log()
						// if (!_self.dataId) {
						// 	_self.servevalue=_self.form.serveTags[0].value
						// 	_self.form.servevalue = _self.form.serveTags[0].value
						// 	return;
						// }
					} else {
					}
				}).catch(res =>{
				});
			},
			onnodeclick(e) {
							console.log(e);
						},
						onpopupopened(e) {
							console.log('popupopened',e);
						},
						onpopupclosed(e) {
							console.log('popupclosed',e);
						},
						onchange(e) {
							console.log('onchange:', e);
							this.form.categoryOneId = e.detail.value[0].value
							this.form.categoryTwoId = e.detail.value[1].value
						},
						
						
			setChildren(res) {
				res.forEach(item => {
					if (item.children && item.children.length <= 0) {
						item.children = null;
						return;
					}

					this.setChildren(item.children);
				});
			},
			setBaseData(res) {
				console.log(res)
				this.setChildren(res[0].datas);
				this.categoryOptions = res[0].datas;

				this.goodsTags = res[1].datas.filter(x => x.type == '商品');
				this.serveTags = res[1].datas.filter(x => x.type == '服务');
			},
			submitData(callback) {
				this.$refs['ruleForm'].validate((valid, obj) => {
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.form.tags = [...this.goodsDatas, ...this.serveDatas];

						// let cascaderObj = this.$refs.cascaderObj.getCheckedNodes();
						// this.form.cids = cascaderObj[0].path;

						if (typeof callback === 'function') {
							console.log(this.form)
							callback(this.form, true);
						}
					} else {
						if (typeof callback === 'function') {
							
							console.log(this.form)
							callback(this.form, false);
						}
						return false;
					}
				});
			},
			imgDelete(e) {
				console.log(e)
				var img = e.tempFiles[0].file;
				const file = img;
				
				const formData = new FormData();
				formData.append('file', file);
				// 文件上传
				this.$axios.post("/file/open/",formData,
				{
					headers:{
						'Content-type' : 'multipart/form-data'
					}
				}).then(response => {
					let res = response
					if (res.success) {
						console.log(res.data)
						this.form.imgs=res.data
						console.log(this.form.imgs)
					} else {
						uni.showToast({
							icon:'error',
							title: '请重新上传！'
						});
					}
				}).catch(res =>{
				});
				// this.form.imgs.splice(this.form.imgs, 1);
				// this.imageValue.splice(this.imageValue.findIndex(x => x.url == e.url), 1);
			},
			Delete(e) {
				// 删除文件
				this.$axios.delete("/file/open/?url="+this.form.imgs,
				{
				}).then(response => {
					let res = response
					if (res.success) {
						this.form.imgs=''
						console.log(this.form.imgs)
					} else {
						
					}
				}).catch(res =>{
				});
			},
			getData(callback) {
				this.submitData(callback);
			},
			setData(data) {
				console.log(data)
				// serveTags
				for(var i=0;i<this.categoryOptions.length;i++){
					for(var j=0;j<this.categoryOptions[i].children.length;j++)
					if(data.categoryTwoId==this.categoryOptions[i].children[j].value){
						this.classes=this.categoryOptions[i].children[j].value
					}
				}
				data.tags = data.tags || [];
				data.cids = data.cids || [];

				this.goodsDatas = data.tags.filter(x => this.goodsTags.find(t => t.name == x));
				// this.serveDatas = this.serveTags.filter(x => data.goodsServiceTags.find(t => t.id == x.id));
				for(var i=0;i<data.goodsServiceTags.length;i++){
					this.serveDatas.push(data.goodsServiceTags[i].id)
				}
				console.log(this.serveDatas)
				// this.form.cid = data.cid;
				// this.imgval=imgs.split("")
				var tu=[]
				tu.push(data.imgs)
				var stateDatas = [];
				stateDatas=tu[0].split(',')
				this.imgval = []
				for (let key in stateDatas) {
					console.log(stateDatas[key])
					this.imgval.push({
						id: key,
						url: stateDatas[key]
					});
				}
				console.log(this.imgval)
				// this.form.categoryOneId = data.categoryOneId;
				// this.form.categoryTwoId = data.categoryTwoId;

				for (const key in this.form) {
					if (this.form.hasOwnProperty(key) && key != 'cid') {
						this.form[key] = data[key];
					}
				}
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData()
		}
	};
</script>

<style></style>
