<template>
	<div class="form-submit">
		<div class="i-layout-page-header">
			<PageHeader class="product_tabs" hidden-breadcrumb>
				<div slot="title">
					<router-link :to="{ path: `${roterPre}/marketing/czcard_list` }">
						<div class="font-sm after-line">
							<span class="iconfont iconfanhui"></span>
							<span class="pl10">返回</span>
						</div>
					</router-link>
					<span v-text="$route.params.id ? '编辑充值卡' : '添加充值卡'" class="mr20 ml16"></span>
				</div>
			</PageHeader>
		</div>
		<Card :bordered="false" dis-hover class="ivu-mt">
			<Form :model="formData" :label-width="150">

				<FormItem label="名称" required>
					<Input v-model="formData.title" v-width="320" placeholder="请输入充值卡名称"></Input>
				</FormItem>
				<FormItem label="金额" required>
					<Input v-model="formData.amount" v-width="320" type="number" placeholder="请输入充值卡金额"></Input>
				</FormItem>
				<!-- <FormItem label="等级" required>
					<Input v-model="formData.level" v-width="320" type="number" placeholder="请输入充值卡等级"></Input>
				</FormItem> -->
				<FormItem label="次卡数量" required>
					<Input v-model="formData.batch_num" v-width="320" type="number" placeholder="请输入次卡数量"></Input>
				</FormItem>
			</Form>
		</Card>
		<Card :bordered="false" dis-hover class="fixed-card"
			:style="{ left: `${!menuCollapse ? '200px' : isMobile ? '0' : '80px'}` }">
			<Form>
				<FormItem>
					<Button type="primary" class="submission" @click="save">立即创建</Button>
				</FormItem>
			</Form>
		</Card>
		<!-- 选择商品-->
		<Modal v-model="modals" title="商品列表" footerHide scrollable width="900" @on-cancel="cancel">
			<goods-list ref="goodslist" :ischeckbox="true" :isdiy="true" :goodsType="1" @getProductId="getProductId"
				v-if="modals"></goods-list>
		</Modal>
		<Modal v-model="storeModals" title="门店列表" footerHide scrollable width="900" @on-cancel="cancelStore">
			<store-list ref="storelist" @getStoreId="getStoreId" v-if="storeModals"></store-list>
		</Modal>

		<Modal v-model="modalPic" width="960px" scrollable footer-hide closable title='上传' :mask-closable="false"
			:z-index="1">
			<uploadPictures :isChoice="isChoice" @getPic="getPic" :gridBtn="gridBtn" :gridPic="gridPic" v-if="modalPic">
			</uploadPictures>
		</Modal>
	</div>
</template>

<script>
	import {
		mapState
	} from "vuex";
	import storeList from "@/components/storeList";
	import goodsList from '@/components/goodsList';
	import {
		couponCategoryApi,
		couponSaveApi,
		addSuper,
		couponDetailApi,
		superInfo,
		addCzcard
	} from "@/api/marketing";
	import {
		brandList
	} from "@/api/product";
	// import { formatDate } from '@/utils/validate';
	import Setting from "@/setting";
	import uploadPictures from '@/components/uploadPictures';
	export default {
		name: "storeCouponCreate",
		components: {
			goodsList,
			storeList,
			uploadPictures
		},
		data() {
			return {
				checkPidList: [], //父级有关id集合 （需求禁止删除子级，用于删除整个商品）
				isAllChecked: false, //表头是否被选中
				gridPic: {
					xl: 6,
					lg: 8,
					md: 12,
					sm: 12,
					xs: 12
				},
				gridBtn: {
					xl: 4,
					lg: 8,
					md: 8,
					sm: 8,
					xs: 8
				},
				isChoice: '单选',
				modalPic: false,
				roterPre: Setting.roterPre,
				disabled: false,
				storesList: [],
				formData: {
					title: '',
					amount: '',
					batch_num: '',
					// level: '',
					type: 0
				},
				categoryList: [],
				brandList: [],
				productList: [],
				isMinPrice: 0,
				isCouponTime: 1,
				isReceiveTime: 0,
				modals: false,
				datetime1: [],
				datetime2: [],
				storeModals: false,
				currentTab: '1',
				imageType: '',
				chooseModals: false,
				keyword: '',
				searchTableData: [],
				tableData: [],
			};
		},
		computed: {
			...mapState("admin/layout", ["isMobile", "menuCollapse"]),
		},
		created() {
			this.getBrandList();
			this.getCategoryList();
			if (this.$route.params.id) {
				this.formData.id = this.$route.params.id
				this.getCouponDetail();
			}
		},
		methods: {
			onchangeIsShow(row) {
				// this.tableData.forEach(item=>{
				// item.attrValue.forEach(i => {
				// 	if(row.unique == i.unique) {
				// 		console.log('i.is_yue:',i.is_yue);
				// 		// i.is_yue = !i.is_yue;
				// 	}
				// })
				// })
			},
			getProductId(data) {
				this.modals = false;
				// console.log(data)
				// let uni = 
				let list = this.tableData.concat(data);
				let uni = this.unique(list);
				uni.forEach((i) => {
					i.is_yue = i.is_yue ? true : false;
					i.number = i.number || 0;
					i.days = i.days || 0;
				})
				this.tableData = uni;
				console.log(uni,'uni')
			},
			checkboxItem(e) {
				let id = parseInt(e.rowid);
				if (e.row.product_id) {
					// let index = this.checkUidList.indexOf(id);
					// if(index !== -1){
					//   this.checkUidList = this.checkUidList.filter((item)=> item !== id);
					// }else{
					//   this.checkUidList.push(id);
					// }
					let pIndex = this.checkPidList.indexOf(e.row.product_id);
					if (pIndex !== -1 && !e.checked) {
						this.checkPidList = this.checkPidList.filter((item) => item !== e.row.product_id);
					}
					if (pIndex === -1 && e.checked) {
						this.checkPidList.push(e.row.product_id);
					}
				} else {
					let pIndex = this.checkPidList.indexOf(id);
					if (pIndex !== -1 && !e.checked) {
						this.checkPidList = this.checkPidList.filter((item) => item !== id);
					}
					if (pIndex === -1 && e.checked) {
						this.checkPidList.push(id);
					}
				}
				this.isAllChecked = this.$refs.xTree.isAllCheckboxChecked();
			},
			checkboxAll() {
				this.isAllChecked = this.$refs.xTree.isAllCheckboxChecked();
				if (!this.isAllChecked) {
					this.checkPidList = [];
				}
				console.log('fgfg', this.isAllChecked);
			},
			searchWord() {
				let list = []
				this.tableData.forEach(item => {
					let obj = item.store_name.indexOf(this.keyword);
					if (obj != -1) {
						list.push(item)
					}
				})
				if (this.keyword) {
					this.searchTableData = list;
				} else {
					this.searchTableData = []
				}
			},
			addGoods() {
				this.modals = true;
			},
			// 选择商品
			changeGoods() {
				this.modals = true;
			},
			// 选择图片
			modalPicTap(type) {
				this.imageType = type;
				this.modalPic = true;
				this.$refs.formItem.validateField("image")
			},
			// 选中图片
			getPic(pc) {
				this.formData[this.imageType] = pc.att_dir;
				this.modalPic = false;
				// this.$refs.formItem.validateField("image")
			},
			//删除门店
			delte(row) {
				this.storesList.forEach((item, index) => {
					if (row.id == item.id) {
						this.storesList.splice(index, 1)
					}
				})
			},

			//添加门店
			addStore() {
				this.storeModals = true;
			},

			//关闭门店弹窗
			cancelStore() {
				this.storeModals = false;
			},
			uniqueId(arr) {
				const res = new Map();
				return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
			},
			unique(arr) {
				const res = new Map();
				return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
			},
			getStoreId(data) {
				this.storeModals = false;
				let list = this.storesList.concat(data);
				let uni = this.uniqueId(list);
				this.storesList = uni;
			},
			// 品类
			getCategoryList() {
				couponCategoryApi(1).then(async (res) => {
					res.data.forEach((val) => {
						val.cate_name = `${val.html}${val.cate_name}`;
					});
					this.categoryList = res.data;
				});
			},
			//品牌
			getBrandList() {
				brandList().then(res => {
					this.brandList = res.data;
				})
			},
			// 充值卡
			getCouponDetail() {
				superInfo(this.$route.params.id)
					.then((res) => {
						let data = res.data[0];
						this.formData.name = data.name;
						this.formData.is_forever = data.is_forever;
						this.formData.grade = data.grade;
						this.formData.discount = data.discount;
						this.formData.valid_date = data.valid_date / 60 / 60 / 24;
						this.formData.icon = data.icon;
						this.formData.image = data.image;
						this.formData.is_show = data.is_show;
						this.formData.mark = data.mark;
						this.formData.is_funds = data.is_funds;
						let list = []
						data.product.forEach(item => {
							let obj = {
								id: item.product_id,
								store_name: item.product_name,
								price: item.price,
								is_yue: item.is_yue? true: false,
								days: item.days,
								number: item.number,
								spu: item.spu,
							}
							
							
							list.push(obj)
						})
						this.tableData = list
					})
					.catch((err) => {
						this.$Message.error(err.msg);
					});
			},
			makeDate(data) {
				let date = new Date(data);
				let YY = date.getFullYear() + "-";
				let MM =
					(date.getMonth() + 1 < 10 ?
						"0" + (date.getMonth() + 1) :
						date.getMonth() + 1) + "-";
				let DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				let hh =
					(date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
				let mm =
					(date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
					":";
				let ss =
					date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				return YY + MM + DD + " " + hh + mm + ss;
			},
			// 上一页：
			upTab() {
				if (this.currentTab == '2') {
					this.currentTab = (Number(this.currentTab) - 1).toString();
				}
			},
			// 创建
			save() {
				let that = this
				if (!that.formData.title) {
					return that.$Message.error("请输入充值卡名称");
				}
				// if (!that.formData.level) {
				// 	return that.$Message.error("请输入充值卡等级");
				// }
				
				if (!that.formData.batch_num) {
					return that.$Message.error("请输入充值卡次卡数量");
				}
				if (!that.formData.amount) {
					return that.$Message.error("请输入充值卡金额");
				}
	
				addCzcard(that.formData)
					.then((res) => {
						this.disabled = true;
						this.$Message.success(res.msg);
						setTimeout(() => {
							this.$router.push({
								path: this.roterPre + "/marketing/czcard_list",
							});
						}, 1000);
					})
					.catch((err) => {
						this.$Message.error(err.msg);
					});
			},
			cancel() {
				this.modals = false;
			},
			// 删除商品
			remove(productId) {
				for (let index = 0; index < this.productList.length; index++) {
					if (this.productList[index].product_id == productId) {
						this.productList.splice(index, 1);
					}
				}
				this.formData.product_id = "";
				this.productList.forEach((value) => {
					if (this.formData.product_id) {
						this.formData.product_id += `,${value.product_id}`;
					} else {
						this.formData.product_id += `${value.product_id}`;
					}
				});
			},
			//批量设置
			batchSet() {
				this.modalsSet = true;
			},
			//批量删除
			delAll() {
				if (this.isAllChecked && (this.tableData.length == this.searchTableData.length || !this.searchTableData
						.length)) {
					this.tableData = []
				} else {
					this.tableData = this.tableData.filter(item => !this.checkPidList.some(ele => ele === item.id));
				}
				this.checkPidList = [];
				this.isAllChecked = false;
			},
			//删除
			del(row) {
				if (this.searchTableData.length) {
					this.searchTableData.forEach((i, index) => {
						if (row.id == i.id) {
							this.searchTableData.splice(index, 1)
						}
					})
					this.tableData.forEach((i, index) => {
						if (row.id == i.id) {
							return this.tableData.splice(index, 1)
						}
					})
				} else {
					this.tableData.forEach((i, index) => {
						if (row.id == i.id) {
							return this.tableData.splice(index, 1)
						}
					})
				}
				if (this.isAllChecked && !this.tableData.length) {
					this.isAllChecked = false;
					this.checkPidList = []
				} else {
					let index = this.checkPidList.indexOf(row.id);
					this.checkPidList.splice(index, 1)
				}
			},
		},
	};
</script>

<style scoped lang="stylus">
	.tips {
		display: inline-bolck;
		font-size: 12px;
		font-weight: 400;
		color: #999999;
		margin-top: 10px;
	}

	.imgPic {
		.info {
			width: 60%;
			margin-left: 10px;
		}

		.pictrue {
			height: 36px;
			margin: 7px 3px 0 3px;

			img {
				height: 100%;
				display: block;
			}
		}
	}

	.productType {
		width: 120px;
		height: 60px;
		background: #FFFFFF;
		border-radius: 3px;
		border: 1px solid #E7E7E7;
		float: left;
		text-align: center;
		padding-top: 8px;
		position: relative;
		cursor: pointer;
		line-height: 23px;
		margin-right: 12px;

		&.on {
			border-color: #1890FF;
		}

		.name {
			font-size: 14px;
			font-weight: 600;
			color: rgba(0, 0, 0, 0.85);

			&.on {
				color: #1890FF;
			}
		}

		.title {
			font-size: 12px;
			font-weight: 400;
			color: #999999;
		}

		.jiao {
			position: absolute;
			bottom: 0;
			right: 0;
			width: 0;
			height: 0;
			border-bottom: 26px solid #1890FF;
			border-left: 26px solid transparent;
		}

		.iconfont {
			position: absolute;
			bottom: -3px;
			right: 1px;
			color: #FFFFFF;
			font-size: 12px;
		}
	}

	.info {
		color: #888;
		font-size: 12px;
	}

	.ivu-input-wrapper {
		width: 320px;
	}

	.ivu-input-number {
		width: 160px;
	}

	.ivu-date-picker {
		width: 320px;
	}

	.ivu-icon-ios-camera-outline {
		width: 58px;
		height: 58px;
		border: 1px dotted rgba(0, 0, 0, 0.1);
		border-radius: 4px;
		background-color: rgba(0, 0, 0, 0.02);
		line-height: 58px;
		cursor: pointer;
		vertical-align: middle;
	}

	.upload-list {
		width: 58px;
		height: 58px;
		border: 1px dotted rgba(0, 0, 0, 0.1);
		border-radius: 4px;
		margin-right: 15px;
		display: inline-block;
		position: relative;
		cursor: pointer;
		vertical-align: middle;
	}

	.upload-list img {
		display: block;
		width: 100%;
		height: 100%;
	}

	.ivu-icon-ios-close-circle {
		position: absolute;
		top: 0;
		right: 0;
		transform: translate(50%, -50%);
	}

	.form-submit {
		/deep/.ivu-card {
			border-radius: 0;
		}

		margin-bottom: 79px;

		.fixed-card {
			position: fixed;
			right: 0;
			bottom: 0;
			left: 200px;
			z-index: 99;
			box-shadow: 0 -1px 2px rgb(240, 240, 240);

			/deep/ .ivu-card-body {
				padding: 15px 16px 14px;
			}

			.ivu-form-item {
				margin-bottom: 0;
			}

			/deep/ .ivu-form-item-content {
				margin-right: 124px;
				text-align: center;
			}

			.ivu-btn {
				height: 36px;
				padding: 0 20px;
			}
		}
	}

	/deep/.vxe-tree-cell {
		padding-left: 0 !important;
	}

	.picBox {
		display: inline-block;
		cursor: pointer;

		.upLoad {
			width: 58px;
			height: 58px;
			line-height: 58px;
			border: 1px dotted rgba(0, 0, 0, 0.1);
			border-radius: 4px;
			background: rgba(0, 0, 0, 0.02);
		}

		.pictrue {
			width: 60px;
			height: 60px;
			border: 1px dotted rgba(0, 0, 0, 0.1);
			margin-right: 10px;

			img {
				width: 100%;
				height: 100%;
			}

		}

		.iconfont {
			color: #CCCCCC;
			font-size 26px;
			text-align center
		}

	}

	.vxeTable {
		border-top: 1px dotted #eee;
		margin-top 20px;
	}

	/deep/ .vxe-tree--btn-wrapper {
		left: 0;
	}
</style>