<template>
	<div class="my-container">
		<div class="bill-main">
			<module-view :propConfig="config" ref="moduleView" @pagination="getDataList" @search="getDataList"
				@resert="onRefresh" @clickHandle="clickHandle" @detail="openEdit" @onRefresh="onRefresh">
			</module-view>
		</div>
		<!-- 新增/编辑弹窗 -->
		<el-dialog :title="popTitle+'属性'" :visible.sync="dialogFormVisible" width="50%">
			<by-form :propConfig="addConfig" ref="addFormId">
				<template v-slot:status class="clearfix">
					<el-radio class="fl" style="margin-top: 8px;" v-model="radio" :label="0">正常</el-radio>
					<el-radio class="fl" style="margin-top: 8px;" v-model="radio" :label="1">禁用</el-radio>
				</template>
				<template v-slot:attributeValue>
					<div style="margin-bottom: 20px;" v-if="tableConfig.length>0">
						<div v-for="(item,index) of tableConfig" :key="index">
							<div>{{item.title}} <i class="el-icon-circle-close" @click="closeGroup(index)"></i>
							</div>
							<div class="clearfix">
								<el-tag class="item-tab fl" :disable-transitions="true" :key="i" v-for="(tag,i) of item.list" closable
									@close="handleClose(tag,index)">
									{{tag}}
								</el-tag>
								<by-input style="width: 150px;" class="fl" :ref="'getValue_'+index" maxlength="20"></by-input>
								<el-button class="fl" @click="showInput(index)">添加</el-button>
							</div>
						</div>
					</div>
					<div style="display: flex;">
						<div style="margin-right: 20px;">
							<label>规格：</label>
							<div class="el-input el-input--small" style="width: calc(100% - 56px);">
								<input type="text" v-model="norms" placeholder="请输入规格" class="el-input__inner" maxlength="20">
							</div>
						</div>
						<div style="margin-right: 20px;">
							<label>规格值：</label>
							<div class="el-input el-input--small" style="width: calc(100% - 56px);">
								<input type="text" v-model="normsValue" placeholder="请输入规格值" class="el-input__inner" maxlength="20">
							</div>
						</div>
						<div @click="doComfirm" style="height: 32px;" class="el-button el-button--primary el-button--small">确定</div>
					</div>
				</template>
			</by-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="dialogFormVisible = false">取 消</el-button>
				<el-button type="primary" @click="confirm">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>
<script lang="ts">
	import { Component, Prop, Vue, Watch } from "vue-property-decorator";
	import api from "@/api/currency";
	import Assembly from "@/components/Assembly/material.vue";
	import AssemblyNature from "@/components/Assembly/nature.vue";
	import AttributeValue from "@/components/Assembly/attributeValue.vue";
	import ForTab from "@/components/ForTab/index.vue";
	@Component({ components: { ForTab } })
	export default class Attribute extends Vue {
		// 右边
		baseURL : any = process.env.VUE_APP_BASE_API
		loading : any = null
		norms : any = ''
		normsValue : any = ''
		timeNum = 0;
		timer : any = null
		popTitle : any = ''
		radio : any = 0
		dialogFormVisible : boolean = false
		tableConfig : any = []
		config : any = {
			attr: {
				calculateH: true
			},
			search: {
				attr: {
					size: 'mini',
				},
				columns: [
					[{
						span: 6,
						label: '名称',
						prop: 'name',
						component: 'by-input',
						labelWidth: '80px',
						compConfig: {
							attr: {
								placeholder: '请输入名称',
								clearable: true
							},
						},
					},
					{
						span: 6,
						label: '状态',
						prop: 'status',
						component: 'by-select',
						labelWidth: '80px',
						compConfig: {
							attr: {
								placeholder: '请选择状态',
								clearable: true,
								size: 'small',
								data: [{
									value: 0,
									label: '正常'
								}, {
									value: 1,
									label: '禁用'
								}]
							}
						}
					},
					{
						span: 6,
						label: '属性类型',
						prop: 'attributeType',
						component: 'by-select',
						labelWidth: '90px',
						compConfig: {
							attr: {
								placeholder: '请选择属性类型',
								clearable: true,
								size: 'small',
								data: [{
									value: 0,
									label: '销售属性'
								}, {
									value: 1,
									label: '基本属性'
								}]
							}
						}
					},
					]
				]
			},
			tool: {
				tools: {
					add: true,
					delete: true,
					search: true,
					refresh: true
				}
			},
			table: {
				attr: {
					size: 'mini',
					align: 'left',
					checkbox: true,
				},
				columns: [{
					width: 300,
					title: '名称',
					field: 'name',
					isDetail: true,
				}, {
					width: 500,
					title: '属性值',
					field: 'attributeValue',
					component: AttributeValue,
				},
				{
					width: 100,
					title: '属性类型',
					field: 'attributeType',
					component: AssemblyNature,
				}, {
					width: 80,
					title: '状态',
					field: 'status',
					align: 'center',
					component: Assembly,
				}, {
					width: 120,
					title: '操作',
					action: true,
					plugins: [{
						icon: 'el-icon-edit',
						name: '编辑',
						audit: '',
						event: {
							click: (item : any) => {
								(this as any).openEdit(item)
							}
						}
					}, {
						name: '删除',
						event: {
							click: (item : any) => (this as any).doDelete(item)
						}
					}]
				}]
			},
		}
		addConfig = {
			attr: {
				size: 'small',
				rules: {
					name: [{
						required: true, message: '请输入名称', trigger: 'blur'
					}],
					attributeType: [{
						required: true, message: '请输入销售属性', trigger: 'blur'
					}],
				}
			},
			columns: [
				[
					{
						span: 23,
						labelWidth: '80px',
						label: '名称',
						prop: 'name',
						component: 'by-input',
					},
					{
						span: 23,
						labelWidth: '80px',
						label: '显示状态',
						slot: true,
						prop: 'status',
					},
					{
						span: 23,
						labelWidth: '80px',
						label: '属性类型',
						slot: true,
						prop: 'attributeType',
						component: 'by-select',
						compConfig: {
							attr: {
								placeholder: '请选择数据',
								clearable: true,
								data: [{
									value: 0,
									label: '销售属性'
								}, {
									value: 1,
									label: '基本属性'
								}]
							}
						}
					},
					{
						span: 23,
						labelWidth: '80px',
						label: '属性值',
						slot: true,
						prop: 'attributeValue',
					},
				],
			]
		}
		mounted() {
			this.timer = setInterval(() => {
				this.getDataList()
			}, 300)
		}
		// 添加
		showInput(index : any) {
			let inputValue = (this as any).$refs['getValue_' + index][0].getValue();
			// console.log(this.tableConfig[index]);
			if (this.tableConfig[index].list.indexOf(inputValue) !== -1) {
				this.$message.warning('规格值已重复，请重新输入');
				return (this as any).$refs['getValue_' + index][0].clearValue()
			};
			if (inputValue) {
				this.tableConfig[index].list.push(inputValue);
			}
			(this as any).$refs['getValue_' + index][0].clearValue();
		}
		// 删除标签
		handleClose(tag : any, index : any) {
			this.$confirm('确定删除吗', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				this.tableConfig[index].list.splice(this.tableConfig[index].list.indexOf(tag), 1);
			}).catch(() => this.$message.info('已取消删除'));
		}
		// 删除数组
		closeGroup(index : any) {
			this.$confirm('确定删除吗', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				this.tableConfig.splice(index, 1)
			}).catch(() => this.$message.info('已取消删除'));
		}
		// 添加新规格
		doComfirm() {
			this.normsValue = this.normsValue.trim();
			this.norms = this.norms.trim();
			if (!this.normsValue || !this.norms) return (this as any).$message.warning('请添加完整的规格');
			for (let v of this.tableConfig) {
				if (v.title == this.norms) return (this as any).$message.warning('规格名不能重复添加');
			}
			let obj : any = {
				title: this.norms,
				field: this.norms + '_field_name',
				list: [this.normsValue]
			}
			this.tableConfig.push(obj);
			this.norms = '';
			this.normsValue = '';
		}
		// 确认新增/编辑
		confirm() {
			(this as any).$refs.addFormId.validate().then(() => {
				if (this.tableConfig.length <= 0) return this.$message.warning('验证未通过，请添加完整的规格');
				let query = (this as any).$refs.addFormId.getValue();
				query.status = this.radio;
				for (let v of this.tableConfig) {
					if (v.list.length <= 0) return this.$message.warning('规格值不能为空')
				}
				query.attributeValue = JSON.stringify(this.tableConfig)
				this.dialogFormVisible = false;
				// console.log(query);
				if (this.popTitle === '新增') {
					api.saveList(query, 'maindataMaterialAttribute').then((res : any) => {
						if (res.code === 200) {
							this.$message.success('新增成功');
							this.getDataList();
						} else this.$message.error(res.msg);
					}).catch(() => {});
				} else if (this.popTitle === '编辑') {
					api.updateList(query, 'maindataMaterialAttribute').then((res : any) => {
						if (res.code === 200) {
							this.$message.success('编辑成功');
							this.getDataList();
						} else this.$message.error(res.msg);
					}).catch(() => {});
				}

			}).catch(() => {});
		}
		// 获取列表数据
		getDataList() {
			if (!this.$refs.moduleView) {
				if (this.timeNum > 5) {
					clearInterval(this.timer)
				}
				this.timeNum++;
				return
			}
			clearInterval(this.timer)
			let query = (this.$refs.moduleView as any).getQuery();
			// console.log('表单字段 ==> ', query);
			this.getPageList(query)
		}
		getPageList(query : any) {
			let loading = this.$loading({ target: '.main-container' });
			api.pageList(query, 'maindataMaterialAttribute').then((res : any) => {
				loading.close();
				if (res.code === 200) {
					(this.$refs.moduleView as any).setTableValue(res.data.records);
					let page = {
						pageNo: res.data.current, //当前页
						pageSize: res.data.size, //每页条数
						total: res.data.total //总条数
					};
					(this.$refs.moduleView as any).setPage(page);
				} else this.$message.error(res.msg);
			}).catch(() => loading.close());
		}
		// 工具栏方法
		clickHandle(e : any) {
			if (e === 'onAdd') this.onAdd();
			if (e === 'onDelete') this.onDelete();
		}
		// 打开新增
		onAdd() {
			this.popTitle = '新增'
			this.dialogFormVisible = true;
			this.radio = 0
			this.tableConfig = [];
			this.$nextTick(() => (this as any).$refs.addFormId.setValue());
		}
		// 打开编辑
		openEdit(e : any) {
			this.popTitle = '编辑';
			let loading = this.$loading({ target: '.main-container' });
			api.single({ id: e.id }, 'maindataMaterialAttribute').then((res : any) => {
				loading.close();
				if (res.code === 200) {
					let data = res.data;
					this.dialogFormVisible = true;
					this.radio = data.status;
					if (data.attributeValue) this.tableConfig = JSON.parse(data.attributeValue);
					setTimeout(() => { (this as any).$refs.addFormId.setValue(data) }, 0);
				}
			}).catch(() => loading.close());
		}
		// 工具栏删除
		onDelete() {
			let selectData = (this.$refs.moduleView as any).getSelectData()
			let ids = '';
			if (selectData.length > 0) {
				selectData.map((v : any) => {
					ids += v.id + ','
				})
			} else return this.$message.warning('请选择删除数据');
			ids = ids.slice(0, ids.length - 1);
			this.$confirm('确定删除吗,此操作不能撤销！', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				api.deleteList({ ids: ids }, 'maindataMaterialAttribute').then((res : any) => {
					if (res.code === 200) {
						this.getDataList();
						this.$message.success('删除成功');
					} else this.$message.error(res.msg);
				})
			}).catch(() => this.$message.info('已取消删除'));
		}
		// 操作删除
		doDelete(item : any) {
			this.$confirm('确定删除吗,此操作不能撤销！', '注意', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				center: true
			}).then(() => {
				api.deleteList({ ids: item.id }, 'maindataMaterialAttribute').then((res : any) => {
					if (res.code === 200) {
						this.getDataList();
						this.$message.success('删除成功');
					} else this.$message.error(res.msg);
				})
			}).catch(() => this.$message.info('已取消删除'));
		}
		// 刷新/重置
		onRefresh() {
			(this as any).$refs.moduleView.clearSearch();
			this.getDataList();
		}
	}
</script>
<style lang="scss" scoped>
	.my-container {
		width: 100%;
		box-sizing: border-box;
		display: flex;
		padding: 16px;
		height: 100%;

		.bill-left {
			position: relative;
			border-right: solid #EEE 1px;
			flex-shrink: 0;

			.bill-tab {
				width: 150px;
				height: 100%;
				transition: all .5s;
				overflow: hidden;
			}

			.tab-title {
				font-size: 16px;
				padding-bottom: 16px;
				width: 200px;
			}
		}

		.item-tab {
			margin-right: 16px;
		}

		.bill-main {
			width: 100%;
			box-sizing: border-box;
			position: relative;
			height: 100%;
			overflow-y: hidden;
		}
	}
</style>