<template>
	<div style="padding-top: 10px;">
		<i-page-header :title="pageTitle"></i-page-header>
		<Card :bordered="false" dis-hover class="ivu-mt">
			<!-- <Form ref="orderData" :model="orderData">
                <Row :gutter="24" type="flex">
					<Col>
					    <FormItem label="UID：" label-for="uid">
					        <Input placeholder="用户UID" v-model="orderData.uid"/>
					    </FormItem>
					</Col>
					<Col>
					    <FormItem label="绑定手机：" label-for="mobile">
					        <Input placeholder="绑定手机号码" v-model="orderData.mobile"/>
					    </FormItem>
					</Col>
					<Col>
					    <FormItem label="购买时间：">
					        <DatePicker v-model="orderData.time" format="yyyy/MM/dd HH:mm:ss" type="datetimerange" placement="bottom-start" placeholder="自定义时间" style="width: 300px;" class="mr20" :options="options"></DatePicker>
					    </FormItem>
					</Col>
					<Col>
					    <Button label="default" type="primary" icon="ios-search"  class="mr15" style="margin-top: 32px;" @click="orderSearch()">搜索</Button>
					</Col>
                </Row>
            </Form> -->
			<Col>
			<Button type="primary" class="export" icon="ios-share-outline" @click="sendOpen">添加商品</Button>
			</Col>
			<Table :columns="columns" :data="orderList" ref="table" :loading="loading" highlight-row no-data-text="暂无数据"
				no-filtered-data-text="暂无筛选结果" class="orderData mt25">
				<template slot-scope="{ row, index }" slot="order_id">
					<span v-text="row.order_id" style="display: block;"></span>
				</template>
				<template slot-scope="{ row, index }" slot="uid">
					<div>{{row.nickname || '微信用户'}}[UID:{{row.uid}}]</div>
					<div>{{row.mobile || '未绑定手机号'}}</div>
				</template>
				<template slot-scope="{ row, index }" slot="imgs">
					<div v-if="row.imgs.length>0" style="display: flex;">
						<img v-for="item in row.imgs" v-lazy="item" :src="item" v-image-preview
							style="width: 60px;cursor: pointer" />
					</div>
				</template>

				<template slot-scope="{ row, index }" slot="handle">
					<div><el-button plain size="mini" @click="">查看评论</el-button></div>
					<br />
					<div><el-button plain size="mini" @click="">删除</el-button></div>
				</template>
			</Table>
			<div class="acea-row row-right page">
				<Page :total="page.count" show-elevator show-total @on-change="tapPage" :page-size="page.pageSize" />
			</div>
		</Card>

		<Modal v-model="sendModel" title="添加商品" @on-ok="sendOk('sendFormValidate')" @on-cancel="sendCancel" width="900">
			<Form :model="sendData" :label-width="labelWidth" :rules="ruleValidate" ref="sendFormValidate">
				<FormItem label="商品名称" prop="name">
					<Input v-model="sendData.name" type="text" placeholder="请输入商品名称"></Input>
				</FormItem>
				<FormItem label="兑换积分" prop="points">
					<Input v-model="sendData.name" type="number" placeholder="请输入兑换积分"></Input>
				</FormItem>
				<FormItem label="商品库存" prop="stock">
					<Input v-model="sendData.stock" type="number" placeholder="请输入商品库存"></Input>
				</FormItem>
				<FormItem label="封面图片" prop="image">
					<div class="clearfix">
						<div class="upimg-item fx-r fx-bc fx-ac" style="" v-if="sendData.image">
							<img v-lazy="sendData.image" :src="sendData.image" v-image-preview />
							<i class="el-icon-error img-remove-btn" @click="removeImg(index)"></i>
						</div>
						<ui-upload style="float: left;" :upUrl="upUrl" fileName="上传图片" :headers="upHeaders"
							:updata="{isz:0,code:'goods'}" @onUpload="onUpload" v-if="sendData.image == ''"></ui-upload>
					</div>
				</FormItem>
				<FormItem label="图片" prop="imgs">
					<div class="clearfix">
						<div class="upimg-item fx-r fx-bc fx-ac" style="" v-for="(item,index) in sendData.imgs"
							:key="index">
							<img v-lazy="item" :src="item" v-image-preview />
							<i class="el-icon-error img-remove-btn" @click="removeImgs(index)"></i>
						</div>
						<ui-upload style="float: left;" :upUrl="upUrl" fileName="上传图片" :headers="upHeaders"
							:updata="{isz:0,code:'goods'}" @onUpload="onUploads"
							v-if="sendData.imgs.length<6"></ui-upload>
					</div>
				</FormItem>
				<FormItem label="商品详情" prop="content">
					<Toolbar style="border: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig" />
					<!-- 编辑器 -->
					<Editor style="height: 400px; overflow-y: hidden;border: 1px solid #ccc;"
						:defaultConfig="editorConfig" v-model="sendData.content" @onChange="onChange"
						@onCreated="onCreated" />
				</FormItem>
			</Form>
			<div slot="footer">
				<Button size="large" :loading="modal_loading" @click="sendCancel">取消</Button>
				<Button type="primary" size="large" :loading="modal_loading"
					@click="sendOk('sendFormValidate')">提交</Button>
			</div>
		</Modal>
	</div>
</template>
<script>
	import axios from 'axios'
	import {
		DomEditor
	} from '@wangeditor/editor'
	import {
		Editor,
		Toolbar
	} from '@wangeditor/editor-for-vue'
	import IPageHeader from "../../../layouts/system/page-header/index";
	import {
		SystemShowTemplateList
	} from "../../../api/system/user";
	import Setting from '@/setting';
	import UiUpload from "@/ui/upload/index";
	import {
		upLoad
	} from '../../../api/system/sys'

	export default {
		name: "pointsList",
		components: {
			SystemShowTemplateList,
			IPageHeader,
			UiUpload,
			Editor,
			Toolbar
		},
		computed: {},
		data() {
			return {
				editor: null,
				toolbarConfig: {
					// toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
					excludeKeys: ['group-video', 'emotion', 'fullScreen'],
				},
				editorConfig: {
					placeholder: "请输入内容...",
					// autoFocus: false,

					// 所有的菜单配置，都要在 MENU_CONF 属性下
					MENU_CONF: {
						uploadImage: {

						},
					},
				},
				modal_loading: false,
				ruleValidate: {
					name: [{
						required: true,
						message: '请输入商品名称',
						trigger: 'blur'
					}],
					content: [{
						required: true,
						message: '请输入商品详情',
						trigger: 'blur'
					}],
					stock: [{
						required: true,
						message: '请输入商品库存',
						trigger: 'blur'
					}],
					image: [{
						required: true,
						message: '请上传封面图片'
					}],
					imgs: [{
						required: true,
						message: '请上传轮播图片'
					}],
					points: [{
						required: true,
						message: '请输入兑换积分',
						trigger: 'blur'
					}],
				},
				labelWidth: 120,
				upHeaders: {},
				upUrl: '',
				sendData: {
					points: '',
					stock: '',
					name: '',
					content: '',
					image: '',
					imgs: []
				},
				sendModel: false,
				pageTitle: "积分商品",
				options: {
					shortcuts: [{
							text: '今天',
							value() {
								const end = new Date();
								const start = new Date();
								start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(), new Date()
									.getDate()));
								return [start, end];
							}
						},
						{
							text: '昨天',
							value() {
								const end = new Date();
								const start = new Date();
								start.setTime(start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(),
									new Date().getDate() - 1)));
								end.setTime(end.setTime(new Date(new Date().getFullYear(), new Date().getMonth(),
									new Date().getDate())));
								return [start, end];
							}
						},
						{
							text: '最近7天',
							value() {
								const end = new Date();
								const start = new Date();
								start.setTime(start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(),
									new Date().getDate() - 6)));
								return [start, end];
							}
						},
						{
							text: '最近30天',
							value() {
								const end = new Date();
								const start = new Date();
								start.setTime(start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(),
									new Date().getDate() - 29)));
								return [start, end];
							}
						},
						{
							text: '本月',
							value() {
								const end = new Date();
								const start = new Date();
								start.setTime(start.setTime(new Date(new Date().getFullYear(), new Date().getMonth(),
									1)));
								return [start, end];
							}
						},
						{
							text: '本年',
							value() {
								const end = new Date();
								const start = new Date();
								start.setTime(start.setTime(new Date(new Date().getFullYear(), 0, 1)));
								return [start, end];
							}
						}
					]
				},

				orderData: {
					uid: "",
					status: "all",
					time: [],
					mobile: "",
					show_template_id: "",
				},
				columns: [{
						title: 'ID',
						align: 'center',
						key: 'id',
						align: 'center'
					},
					{
						title: '商品封面',
						align: 'center',
						slot: 'imgs',
						align: 'center'
					},
					{
						title: '商品名',
						key: 'name',
						align: 'center'
					},
					{
						title: '积分',
						align: 'center',
						key: 'points',
						align: 'left'
					},

					{
						title: '时间',
						align: 'center',
						key: 'add_time',
						align: 'left'
					},
					{
						title: '操作',
						align: 'center',
						slot: 'handle',
						align: 'left'
					},
				],
				loading: false,
				orderList: [],
				orderDatalist: {},
				orderId: 0,
				page: {
					total: 0, // 总条数
					page: 1, // 当前页
					pageSize: 10 // 每页显示条数
				},
			}
		},

		created() {
			if (this.$route.query.title) {
				this.pageTitle = this.$route.query.title;
			}
			if (this.$route.query.uid) {
				this.orderData.uid = parseInt(this.$route.query.uid);
			}
			if (this.$route.query.show_template_id) {
				this.orderData.show_template_id = parseInt(this.$route.query.show_template_id);
			}
			this.initView();
		},
		methods: {
			onCreated(editor) {
				this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
				console.log(this.editor.getMenuConfig());

			},
			onChange(editor) {
				console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
			},
			getEditorText() {
				const editor = this.editor;
				if (editor == null) return;

				console.log(editor.getText()); // 执行 editor API
			},
			printEditorHtml() {
				const editor = this.editor;
				if (editor == null) return;

				console.log(editor.getHtml()); // 执行 editor API
			},
			initView: function() {
				let that = this
				var upHeaders = {};
				this.upUrl = Setting.apiBaseURL + "/systemv1/upload/index";
				const token = this.$utils.util.cookies.get('system_token');
				if (token) {
					upHeaders['SYSTEM-ACC-TOKEN'] = token;
				}
				this.upHeaders = upHeaders;

				this.editorConfig.MENU_CONF['uploadImage'] = {
					async customUpload(file, insertFn) {
						const formData = new FormData()
						formData.append('file', file)
						formData.append('code', 'good')
						formData.append('isz', '0')
						// formData.append('sign', this.generateSign(file.name)) // 自定义签名

						try {
							// const response = await axios.post(that.upUrl, formData, {
							// 	headers: {
							// 		'SYSTEM-ACC-TOKEN': token
							// 	}
							// })
							upLoad(formData).then(res => {
								insertFn(res.data.img)
							})
							
							// if (response.data.success) {
							// 	 // 插入图片到编辑器
							// }
						} catch (error) {
							console.error('上传失败:', error)
						}
					}
				}
			},
			onUpload: function(res) {
				if (res.code == -1) {
					Notice.error({
						title: "系统提示",
						content: res.msg
					});
				} else {
					this.sendData.image = res.data.img;
				}
			},
			onUploads: function(res) {
				if (res.code == -1) {
					Notice.error({
						title: "系统提示",
						content: res.msg
					});
				} else {
					this.sendData.imgs.push(res.data.img);
				}
			},
			removeImgs: function(index) {
				// this.$delete(this.sendData.imgs, index);
			},
			removeImg: function(index) {
				// this.$delete(this.sendData.imgs, index);
				this.sendData.image = ''
			},
			sendOpen() {
				this.sendModel = true
			},
			sendCancel() {
				this.sendModel = false
				this.sendData = {
					content: '',
					imgs: []
				}
				console.log('sendCancel');
			},
			sendOk(name) {
				console.log(this.sendData.content);
				this.$refs[name].validate((valid) => {
					if (valid) {
						this.sendCancel()
						this.$Message.success('发布成功!');
					} else {}
				})
			},
			tabsHandleClick: function(tab, event) {
				this.page.page = 1;
				this.getData();
			},
			orderSearch: function() {
				this.page.page = 1;
				this.getData();
			},
			/**
			 * 分页
			 */
			tapPage: function(index) {
				this.page.page = index;
				this.getData();
			},
			/**
			 * 获取数据
			 */
			getData: function() {
				var that = this;
				// this.loading = true;
				var data = {
					page: that.page.page,
					...that.orderData
				};
				// SystemShowTemplateList(data)
				//     .then(res=>{
				//         that.loading = false;
				//         if(res.code == 200) {
				//             that.orderList = res.data.list;
				//             that.page.pageSize = res.data.pageSize;
				//             that.page.count = res.data.pageCount;
				//         } else {
				//             that.$alert(res.msg);
				//         }
				//     })
				//     .catch(err=>{
				//         that.loading = false;
				//         that.$alert("网络繁忙，加载失败，请稍等片刻在尝试!", '系统提示');
				//     });
			},

		}
	}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
	@import "~vue2-editor/dist/vue2-editor.css";

	.upimg-item {
		width: 82px;
		height: 82px;
		margin-right: 5px;
		overflow: hidden;
		float: left;
		margin-bottom: 5px;
		position: relative;
	}

	.upimg-item img {
		width: 82px;
		cursor: pointer;
	}

	.img-remove-btn {
		position: absolute;
		top: 0px;
		right: 0px;
		font-size: 24px;
	}
</style>