<template>
	<div class="container add_edit">
		<el-form :model="form" ref="ruleForm" :rules="rules" label-width="100px">
			<el-form-item label="上级分类">
				<el-select class="sele" v-model="form.pid" placeholder="请选择" :disabled="dataId != ''">
					<el-option v-for="(item, idx) in classData" :key="idx" :label="item.name" :value="item.id">
					</el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="分类名称" prop="name" ref="name">
				<el-input v-model="form.name" placeholder="分类名称"></el-input>
			</el-form-item>
			<el-form-item label="图标">
				<uni-file-picker v-model="imageValue" fileMediatype="image" returnType="object"
					:image-styles="imageStyle" @select="imgUpload" @delete="imgDelete" />
			</el-form-item>
			<el-form-item label="排序">
				<el-input type="number" v-model.number="form.sort" min="0" placeholder="请输入排序"></el-input>
				<div class="remark_txt">此处排序将决定前端模块的位置，数字越小，位置越前</div>
			</el-form-item>
			<el-form-item label="状态">
				<el-switch v-model="form.state" active-color="#ff6a6c" inactive-color="#bbb" active-value="1"
					inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item>
				<el-button class="confirm_btn" @click="submitForm('ruleForm')">确 定</el-button>
				<el-button @click="returnPage">返回列表</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	import bus from '@/common/bus';
	const __name = 'usemall-goods-category';
	import { cos } from '@/util/cos.js'
	export default {
		props: {},
		data() {
			return {
				dataId: '',
				form: {
					sort: 0,
					pid: '',
					name: '',
					icon: '',
					state: '1',
					level:'',
					id:'',
				},
				imageValue: null,
				imageStyle: {
					height: '150px',
					width: '150px'
				},
				classData: [],
				rules: {
					name: [{
						required: true,
						message: '请输入分类名称',
						trigger: 'change'
					}]
				},
				now_date:'',//当前时间
			};
		},
		methods: {
			loadData() {
				this.getNowDate()
				//获取依据数据
				this.$axios.get("/goodsCategory/open/list",
				{
					params:{
					},
					headers:{
					}
				}).then(response => {
					let res = response
					if (res.success) {
						this.classData = res.data
						console.log(this.classData)
					} else {
					}
				}).catch(res =>{
				});
				// this.$db[__name]
				// 	.where({
				// 		pid: ''
				// 	})
				// 	.tolist({
				// 		page: 1,
				// 		rows: 500
				// 	})
				// 	.then(res => {
				// 		if (res.code == 200) {
				// 			this.classData = res.datas.filter(x => !x.pid);
				// 			this.classData.unshift({
				// 				_id: '',
				// 				name: '请选择'
				// 			});
				// 		}
				// 	});

				if (!this.dataId) {
					return;
				}
				

				// this.$db[__name].tofirst(this.dataId).then(res => {
				// 	if (res.code == 200) {
				// 		for (let item in this.form) {
				// 			this.form[item] = res.datas[item];
				// 		}
				// 		if (this.form.img) {
				// 			this.imageValue = {};
				// 			this.imageValue.url = this.form.img;
				// 		}
				// 	}
				// });
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						console.log(!this.form.pid)
						console.log(this.form.name)
						if(!this.form.pid){
							var level=1
						}else{
							level=2
						}
						if (!this.dataId) {//新增
							this.$axios.post("/goodsCategory/admin/save",
							{
								'createBy':uni.getStorageSync("nickName"),//创建人
								'createTime':this.now_date,//创建时间
								"name": this.form.name,
								"icon": this.form.icon,
								"level": level,
								'sort':this.form.sort,//排序
								'state':this.form.state,
								'pid':this.form.pid
							},
							{
								headers:{
									'Mall-Token': uni.getStorageSync("token")
								}
							}).then(response => {
								let res = response
								if (res.success) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								} else {
								}
							}).catch(res =>{
							});
							// this.$db[__name].add(this.form).then(res => {
							// 	if (res.code == 200) {
							// 		this.getOpenerEventChannel().emit('loadData');
							// 		this.returnPage();
							// 	}
							// });
						} else {
							this.$axios.put("/goodsCategory/admin/update",
							{
								'createBy':this.form.createBy,//创建人
								'createTime':this.form.createTime,//创建时间
								'updateBy':uni.getStorageSync("nickName"),//更新人
								'updateTime':this.now_date,//更新时间
								"name": this.form.name,
								"icon": this.form.icon,
								"level": this.form.level,
								"pid": this.form.pid,
								'sort':this.form.sort,//排序
								'state':this.form.state,
								'id':this.dataId
							},
							{
								headers:{
									'Mall-Token': uni.getStorageSync("token")
								}
							}).then(response => {
								let res = response
								if (res.success) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								} else {
									alert(res.message)
								}
							})
							// this.$db[__name].update(this.dataId, this.form).then(res => {
							// 	if (res.code == 200) {
							// 		this.getOpenerEventChannel().emit('loadData');
							// 		this.returnPage();
							// 	}
							// });
						}
					}
				});
			},
			imgUpload(e) {
				this.form.icon = e.tempFilePaths[0];
				const file = this.form.icon;
				let Key = e.tempFiles[0].name
				cos.postObject(
					{
						Bucket: 'jinganminsu-1320402385',
						Region: 'ap-nanjing',
						Key: Key,
						FilePath: file,
						onProgress: (info) => {
							// console.log(info)
						}
					},
					(err, data) => {
						if (err) {
							console.log('上传失败', err)
						} else {
							console.log('上传成功', data)
				
							uni.hideLoading()
							let imgUrl = 'https://' + data.Location
							this.form.icon =imgUrl
							
						}
					}
				)
				
			},
			imgDelete() {
				this.imageValue = null;
				this.form.icon = '';
			},
			returnPage() {
				bus.$emit('tab-close');
				this.$router.push('/pages/goods/classify/goods_classify');
			},
			//获取当前时间
			getNowDate() {
			  var _this = this;
			  // this.timer = setInterval(function() {
				var aData = new Date();
				var month = aData.getMonth() < 9 ? "0" + (aData.getMonth() + 1) : aData.getMonth() + 1;
				var date = aData.getDate() <= 9 ? "0" + aData.getDate() : aData.getDate();
				var date2 = aData.getDate() <= 9 ? "0" + (aData.getDate()-1) : (aData.getDate()-1);
				var Hour = aData.getHours() <= 9 ? "0" + (aData.getHours()) : aData.getHours();
				var Miunte = aData.getMinutes() <= 9 ? "0" + (aData.getMinutes()) : aData.getMinutes();
				var Seconds = aData.getSeconds() <= 9 ? "0" + (aData.getSeconds()) : aData.getSeconds();
				// console.log(aData.getTime())
				_this.now_date = aData.getFullYear() + "-" + month + "-" + date + ' '+ Hour +":"+ Miunte +":"+ Seconds;
				// console.log(aData.getFullYear() + "-" + month + "-" + date2)昨天
			  // }, 86400000);
			},
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
			this.form.sort=this.$route.query.sort
			if(!this.$route.query.pid){
				return
			}else{
				this.form.pid=this.$route.query.pid.slice(0,19)
			}
			this.form.name=this.$route.query.name
			this.form.icon=this.$route.query.icon
			this.form.state=this.$route.query.state
			this.form.level=this.$route.query.level
			if (this.$route.query.icon) {
				this.imageValue = {};
				this.imageValue.url = this.$route.query.icon;
			}
		}
	};
</script>

<style></style>
