<template>
	<div style="padding:10px">
		<q-card inline class="fit shadow-6">
			<q-card-main style="height:80%">
				<q-table ref="table" color="primary" :data="serverData" :columns="columns" separator="cell" selection="multiple" :selected.sync="selected" row-key="id" :pagination.sync="serverPagination" @request="request" :loading="loading" :rows-per-page-label="$t('Rows per page')" :rows-per-page-options="[5,10,20,30,40,50,60,200,500]" :no-data-label="$t('No data')">
					<template slot="top-left" slot-scope="props">
						<q-input v-model="filter.name" type="text" prefix="标题：" />&nbsp;&nbsp;
						<q-select v-model="filter.line" :options="linekindlist" prefix="食堂：" style="width:160px" clearable />&nbsp;&nbsp;
						<q-datetime v-model="filter.datetime" type="date" prefix="日期：" clearable />&nbsp;&nbsp;
						<q-btn push dense color="primary" icon="search" @click="search">{{$t('Search')}}</q-btn>&nbsp;&nbsp;
						<q-btn push dense color="primary" icon="add" @click="addsaveRecipes">{{$t('Add')}}</q-btn>&nbsp;&nbsp;
						<!-- <q-btn push dense color="primary" icon="add" @click="gotoadd">{{$t('Add')}}</q-btn>&nbsp;&nbsp; -->
						<q-btn push dense color="primary" icon="cloud_download" @click="downloadtemp">&nbsp;菜单模板下载</q-btn>&nbsp;&nbsp;
					</template>
					<template slot="top-right" slot-scope="props">
						<q-uploader inverted-light 
							prefix="菜谱导入"
							color="warning" 
							ref="attachmentUploader" 
							name="file" 
							extensions="xls,xlsx"
							 hide-upload-button 
							 @add="$refs['attachmentUploader'].upload()" 
							:headers="{'Accept': 'application/json;charset=utf-8'}" 
							:url="uploadurl" clearable 
							:url-factory="importexcel" 
							id="daoru"
							@finish="uploadresult">	</q-uploader>
						<q-btn flat round dense :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" @click="props.toggleFullscreen" />
					</template>
					<template slot="top-selection" slot-scope="props">
						<q-btn icon="create" color="positive" label="启用" @click="updateDRecipessStatuslist (1)" />&nbsp;&nbsp;
						<q-btn icon="create" color="negative" label="停用" @click="updateDRecipessStatuslist (0)" />
					</template>
					<q-td slot="body-cell-id" slot-scope="props" :props="props" style="width:200px">
						<q-btn small round push glossy dense icon="edit" color="primary" @click="editRecipes(props.value,1)"></q-btn>
						<q-btn small round push glossy dense icon="delete" color="red" @click="delRecipes(props.value)"></q-btn>
						<!--<q-btn-dropdown color="secondary" label="操作" no-wrap>
                <q-list link>
                  <q-item v-close-overlay @click.native="editRecipes(props.value,1)">
                    <q-item-main>
                      <q-item-tile sublabel>修改</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay @click.native="delRecipes(props.value)" >
                    <q-item-main>
                      <q-item-tile sublabel >删除</q-item-tile>
                    </q-item-main>
                  </q-item>
                  <q-item v-close-overlay>
                    <q-item-main>
                    <q-item-tile sublabel>关闭弹窗</q-item-tile>
                    </q-item-main>
                  </q-item>
                </q-list>
            </q-btn-dropdown>-->
					</q-td>
				</q-table>
			</q-card-main>
		</q-card>
		<!-- 新增修改页面 -->
		<q-modal v-model="editModal" maximized>
			<q-modal-layout>
				<q-toolbar slot="header">
					<q-btn flat round dense @click="editModal = false" icon="reply" />
					<q-toolbar-title v-if="subtype=='edit'">{{$t('Edit')}}</q-toolbar-title>
					<q-toolbar-title v-if="subtype=='add'">{{$t('Add')}}</q-toolbar-title>

				</q-toolbar>
				<q-toolbar slot="footer">
					<q-toolbar-title></q-toolbar-title>
					<q-btn round color="red" @click="saveUpdateRecipes" v-if="subtype=='edit'">{{$t('Save')}}</q-btn>
					<q-btn round color="red" @click="saveRecipes" v-if="subtype=='add'">{{$t('Add')}}</q-btn>
					<q-btn round @click="editModal = false">{{$t('Cancel')}}</q-btn>
				</q-toolbar>
				<div class="layout-padding">
					<q-field class="liststype">
						<q-input v-model="tempRecipes.title" float-label="标题" />
					</q-field>
					<q-field class="liststype">
						<q-select v-model="tempRecipes.line" :options="linekindlist" float-label="所属食堂" />
					</q-field>
					<q-field class="liststype">*请用英文“A”符号分隔菜品名称，实现换行</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.am_zs" float-label="早餐-主食" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.am_fs" float-label="早餐-副食" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.am_qt" float-label="早餐-其它" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.pm_zs" float-label="午餐-主食" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.pm_fs" float-label="午餐-副食" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.pm_bc" float-label="午餐-拌菜" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.pm_qt" float-label="午餐-其它" />
					</q-field>
					<q-field class="liststype">
						<q-input v-model="tempRecipes.soup" float-label="汤品" />
					</q-field>
					<q-field class="liststype">
						<q-item style="    width: 100%;    padding: 0;">
							<q-datetime v-model="tempRecipes.datetime" type="date" float-label="日期：" style="    width: 100%;    padding: 0;" />
						</q-item>
					</q-field>
					<q-field class="liststype">
						<q-select v-model="tempRecipes.weekday" :options="weekdayOptions" float-label="星期" />
					</q-field>
					<q-field class="liststype">
						<q-select v-model="tempRecipes.status" :options="yeornoOptions" float-label="启用" />
					</q-field>

					<q-field class="liststype">
						<q-input v-model="tempRecipes.memo" float-label="描述" />
					</q-field>

				</div>
			</q-modal-layout>
		</q-modal>
	</div>
</template>

<script>
	import {
		getRecipesPagedList,
		delRecipes,
		updateRecipesStatus,
		saveRecipes,
		editRecipes,
		loadRecipes,
		updateRecipessStatus,
		saveexceldata
	} from "@/service/recipes/recipes.js";
	import tool from "@/service/other/tool";
	import { getSysCodelistByKindcode } from "@/service/syscodelist/syscodelist";
	export default {
		name: "recipes",
		data() {
			return {
				uploadurl: "/manager/znzl/file/upload/videoandimgurl?uploadPar=adv&",
				serverData: [],
				kindlist: [],
				linekindlist: [],
				menuModal: false,
				tempFunction: {
					id: 0,
					name: "",
					moduleId: 0,
					module: "",
					code: "",
					description: ""
				},
				serverPagination: {
					page: 1,
					rowsNumber: 0, // specifying this determines pagination is server-side
					rowsPerPage: 10 // current rows per page being displayed
				},
				nextserverPagination: {
					page: 1,
					rowsNumber: 0, // specifying this determines pagination is server-side
					rowsPerPage: 100 // current rows per page being displayed
				},
				selectOptions: [{
						label: "启用",
						value: "1",
						selected: true
					},
					{
						label: "停用",
						value: "0"
					}
				],
				yeornoOptions: [{
						label: "是",
						value: "1",
						selected: true
					},
					{
						label: "否",
						value: "0"
					}
				],
				weekdayOptions: [{
						label: "星期一",
						value: "星期一",
						selected: true
					},
					{
						label: "星期二",
						value: "星期二"
					},
					{
						label: "星期三",
						value: "星期三"
					},
					{
						label: "星期四",
						value: "星期四"
					},
					{
						label: "星期五",
						value: "星期五"
					},
					{
						label: "星期六",
						value: "星期六"
					},
					{
						label: "星期日",
						value: "星期日"
					}
				],
				columns: [{
						name: "title",
						required: true,
						label: "标题",
						align: "left",
						field: "title",
						sortable: false
					},
					{
						name: "line",
						required: true,
						label: "所属食堂",
						align: "center",
						field: "line",
						sortable: false
					},

					{
						name: "datetime",
						label: "日期",
						field: "datetime",
						sortable: false,
						align: "center"
					},
					{
						name: "weekday",
						label: "星期",
						field: "weekday",
						sortable: false,
						align: "center"
					},
					{
						name: "statusname",
						label: "启用状态",
						field: "statusname",
						sortable: false,
						align: "center"
					},
					{
						name: "memo",
						label: "描述",
						field: "memo",
						sortable: false,
						align: "left"
					},
					{
						name: "id",
						required: true,
						label: this.$t("ID"),
						align: "center",
						field: "id"
					}
				],
				filter: {
					name: "",
					pid: "",
					datetime: "",
					line:""
				},
				selected: [],
				datalist: [],
				loading: false,
				editModal: false,
				subtype: "add",
				recipeslist: [],//食堂列表
				tempRecipes: {
					id: "",
					title: "",
					status: "",
					datetime: "",
					holiweekdayday: "",
					memo: "",
					am_zs: "",
					am_fs: "",
					am_qt: "",
					pm_zs: "",
					pm_fs: "",
					pm_qt: "",
					pm_bc: "",
					soup: "",
					line: ""
				}
			};
		},
		methods: {
			uploadresult (){
			 

			},
			async request(props) {
				this.loading = true;
				this.serverPagination = props.pagination;
				let table = this.$refs.table,
					{
						page,
						rowsPerPage,
						sortBy,
						descending
					} = props.pagination;
				let query = {
					pageNum: page,
					pageSize: rowsPerPage,
					sortBy: sortBy,
					descending: descending,
					title: this.filter.name,
					line:this.filter.line,
					datetime: this.filter.datetime != undefined && this.filter.datetime != null ?
						tool.GMTToStr(this.filter.datetime) :
						""
				};

				let dataRes = await getRecipesPagedList(query);
				let data = dataRes.data.data;

				this.serverPagination.rowsNumber = data.total;
				this.serverData = data.list;
				// this.getSysRecipesListByTypeAndNum();
				setTimeout(() => {
					this.loading = false;
				}, 500);
				this.getCodelistByKindcode();
				this.getLineCodelistByKindcode();
			},
			async getCodelistByKindcode() {
				this.kindlist = [];
				let kindlist_code = await getSysCodelistByKindcode("ADV_TYPE");
				if(kindlist_code.data.data.length > 0) {
					for(var item of kindlist_code.data.data) {
						let obj = {
							label: item.codename,
							value: item.codevalue
						};
						this.kindlist.push(obj);
					}
				}
			},
			
			async getLineCodelistByKindcode() {
				this.linekindlist = [];
				let linekindlist_code = await getSysCodelistByKindcode("LINE_TYPE");
				if(linekindlist_code.data.data.length > 0) {
					for(var item of linekindlist_code.data.data) {
						let obj = {
							label: item.codename,
							value: item.codevalue
						};
						this.linekindlist.push(obj);
					}
				}
			},
			async delRecipes(id) {
				try {
					await this.$q.dialog({
						title: "删除操作",
						message: this.$t("Comfirm do it"),
						position: "right",
						ok: {
							push: true,
							label: "确认"
						},
						cancel: {
							push: true,
							color: "negative",
							label: "取消"
						}
					});
					await delRecipes({
						id: id
					});
					this.$q.notify({
						type: "positive",
						message: this.$t("Successfully"),
						position: "bottom-right"
					});
					this.search();
				} catch(e) {}
			},
			/**
			 * 批量更新状态
			 */
			async updateDRecipessStatuslist(type) {
				try {
					await this.$q.dialog({
						title: this.$t("Batch do it"),
						message: this.$t("Comfirm do it"),
						ok: {
							push: true,
							label: "提交"
						},
						cancel: {
							push: true,
							color: "negative",
							label: "取消"
						}
					});
					let idlist = this.selected.map(s => {
						return s.id;
					});
					await updateRecipessStatus(idlist.join(","), type);
					this.$q.notify({
						type: "positive",
						message: this.$t("Successfully"),
						position: "bottom-right"
					});
					this.selected = [];
					this.search();
				} catch(e) {}
			},
			/**用户修改 */
			editRecipes(id, type) {
				this.subtype = "edit";
				let editRecipes = this.serverData.filter(s => {
					return s.id === id;
				});

				if(editRecipes && editRecipes.length > 0) {
					this.tempRecipes = JSON.parse(JSON.stringify(editRecipes[0]));
				} else {
					return true;
				}
				this.editModal = true;
			},
			async saveUpdateRecipes() {
				if(
					this.tempRecipes.line == "" ||
					this.tempRecipes.am_zs == "" ||
					this.tempRecipes.am_fs == "" ||
					this.tempRecipes.am_qt == "" ||
					this.tempRecipes.pm_zs == "" ||
					this.tempRecipes.pm_fs == "" ||
					this.tempRecipes.pm_bc == "" ||
					this.tempRecipes.pm_qt == "" ||
					this.tempRecipes.soup == "" ||
					this.tempRecipes.datetime == "" ||
					this.tempRecipes.weekday == ""
				) {
					this.$q.notify({
						message: "请完善信息，除描述外其他项不能为空",
						type: "negative",
						icon: "error_outline",
						timeout: 3000,
						position: "center"
					});
					return false;
				}
				this.tempRecipes.datetime =
					this.tempRecipes.datetime != undefined &&
					this.tempRecipes.datetime != null ?
					tool.GMTToStr(this.tempRecipes.datetime) :
					"";
				await editRecipes(this.tempRecipes);
				this.$q.notify({
					type: "positive",
					message: this.$t("Saved successfully"),
					position: "bottom-right"
				});
				this.editModal = false;
				this.search();
			},
			search() {
				this.request({
					pagination: this.serverPagination,
					filter: this.filter
				});
			},
			/**
			 * 更新用户
			 */
			async saveRecipes() {
				this.tempRecipes.pid = this.pid;
				this.tempRecipes.datetime =
					this.tempRecipes.datetime != undefined &&
					this.tempRecipes.datetime != null ?
					tool.GMTToStr(this.tempRecipes.datetime) :
					"";
				if(
					this.tempRecipes.line == "" ||
					this.tempRecipes.am_zs == "" ||
					this.tempRecipes.am_fs == "" ||
					this.tempRecipes.am_qt == "" ||
					this.tempRecipes.pm_zs == "" ||
					this.tempRecipes.pm_fs == "" ||
					this.tempRecipes.pm_bc == "" ||
					this.tempRecipes.pm_qt == "" ||
					this.tempRecipes.soup == "" ||
					this.tempRecipes.datetime == "" ||
					this.tempRecipes.weekday == ""
				) {
					this.$q.notify({
						message: "请完善信息，除描述外其他项不能为空",
						type: "negative",
						icon: "error_outline",
						timeout: 3000,
						position: "center"
					});
					return false;
				}
				await saveRecipes(this.tempRecipes);
				this.$q.notify({
					type: "positive",
					message: this.$t("Saved successfully"),
					position: "bottom-right"
				});
				this.editModal = false;
				this.search();
			},
			search() {
				this.request({
					pagination: this.serverPagination,
					filter: this.filter
				});
			},
			addsaveRecipes() {
				this.pid = "1";
				this.tempRecipes = {};
				this.tempRecipes.status = "1";
				this.subtype = "add";
				this.editModal = true;
			},
			handleChange() {
				let obj = this.imFile;
				this.fileTemp = obj.raw;
				this.importexcel(this.fileTemp);
			},
			async saveexcel(data) {
				await saveRecipes(data);
			},
			downloadtemp() {
				window.open("https://nw.sy-metro.com:6104/caipu.xlsx");
			},
			expexcel() {
				document.getElementById("daoru").click;
			},
			//新增
			gotoadd() {
				this.$router.push("/sysrecipesadd");
			},
			importexcel(file, xhr) {
				let _this = this;
				// 通过DOM取文件数据
				this.file = file;
				var rABS = false; //是否将文件读取为二进制字符串
				var f = this.file;
				var reader = new FileReader();
				//if (!FileReader.prototype.readAsBinaryString) {
				FileReader.prototype.readAsBinaryString = function(f) {
					var binary = "";
					var rABS = false; //是否将文件读取为二进制字符串
					var pt = this;
					var wb; //读取完成的数据
					var outdata;
					var reader = new FileReader();
					reader.onload = function(e) {
						var bytes = new Uint8Array(reader.result);
						var length = bytes.byteLength;
						for(var i = 0; i < length; i++) {
							binary += String.fromCharCode(bytes[i]);
						}
						var XLSX = require("xlsx");
						if(rABS) {
							wb = XLSX.read(btoa(fixdata(binary)), {
								//手动转化
								type: "base64"
							});
						} else {
							wb = XLSX.read(binary, {
								type: "binary"
							});
						}
						outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); //outdata就是你想要的东西
						let list = [];
						for(let ii = 0; ii < outdata.length; ii++) {
							let entity = outdata[ii];

							let newobj = {
								title: entity.标题,
								status: "0",
								datetime: entity.日期,
								weekday: entity.星期,
								memo: entity.说明,
								am_zs: entity.早餐主食,
								am_fs: entity.早餐副食,
								am_qt: entity.早餐其它,
								pm_zs: entity.午餐主食,
								pm_fs: entity.午餐副食,
								pm_bc: entity.午餐拌菜,
								pm_qt: entity.其它,
								soup: entity.汤品,
								line: entity.所属食堂
							};
							_this.saveexcel(newobj);
							// _this.datalist.push(newobj);
						}
					
						
						_this.search();
//						_this.$refs['attachmentUploader'].reset()
							_this.$q.notify({
								type: "positive",
								message: _this.$t("Saved successfully"),
								position: "bottom-right"
							});
						//保存数据
					};
					reader.readAsArrayBuffer(f);
				};
				if(rABS) {
					reader.readAsArrayBuffer(f);
				} else {
					reader.readAsBinaryString(f);
				}
			}
		},

		mounted() {
			this.request({
				pagination: this.serverPagination,
				filter: this.filter
			});
		}
	};
</script>
<style scoped>
	.liststype {
		width: 98%;
		/* padding-left: 4%; */
		/* float: left; */
	}
</style>