<template>
	<div class="app-list-content">
		<x-crud class="liu-crud-wrap" @load="onLoad">
			<template #table-column-userId="{scope}">
				<i class="el-icon-success" v-if="scope.row.userId != 0" style="color:#67C23A;font-size:19px;"></i>
				<i class="el-icon-success" v-else style="color:#C0C4CC;font-size:19px;"></i>
			</template>
			<template #table-column-avatar="{scope}">
				<cl-avatar shape="circle" :size="24" :src="scope.row.avatar" :style="{ margin: 'auto' }"></cl-avatar>
			</template>

			<template #table-column-incomeNotice="{scope}">
				<el-switch
					v-model="scope.row.remind"
					active-value="1"
					inactive-value="0"
					@change="
						v => {
							changeNotice(scope.row.id, v);
						}
					"
				></el-switch>
			</template>

			<template #table-column-status="{scope}">
				<el-switch
					v-model="scope.row.status"
					active-value="1"
					inactive-value="0"
					@change="
						v => {
							changeStatus(scope.row.id, v);
						}
					"
				></el-switch>
			</template>

			<!-- 添加 -->
			<template #slot-add-ad-btn>
				<el-button type="primary" size="mini" @click="addBtnFn">添加</el-button>
			</template>
		</x-crud>

		<el-dialog title="请员工扫下方图片完成绑定" :visible.sync="showMiniCode" width="600px">
			<div style="text-align:center;">
				<img :src="miniCodeSrc" style="margin:0 auto;width:280px;" />
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="showMiniCode = false">取 消</el-button>
				<el-button type="primary" @click="showMiniCode = false">确 定</el-button>
			</span>
		</el-dialog>

		<!-- 新增弹窗 -->
		<el-dialog
			:title="`${addOrModify == 1 ? '添加' : '修改'}员工`"
			:visible.sync="addDialog"
			:close-on-click-modal="false"
			width="600px"
		>
			<div class="ad-modal-content">
				<el-form :model="adForm" :rules="ruleForm" ref="adForm" label-width="100px" class="demo-form">
					<el-form-item label="姓名" prop="name">
						<el-input v-model="adForm.name" placeholder="请输入姓名" size="small"></el-input>
					</el-form-item>
					<el-form-item label="角色" prop="roleId">
						<el-select v-model="adForm.roleName" size="small" placeholder="请选择角色" @change="selRoleFn">
							<el-option
								v-for="(item, index) in roleList"
								:key="index"
								:value="item.roleName"
							>{{ item.roleName }}</el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="登陆密码" prop="password">
						<el-input v-model="adForm.password" placeholder="请输入登录密码" type="password" size="small"></el-input>
					</el-form-item>
					<el-form-item label="备注">
						<el-input v-model="adForm.remark" type="textarea" size="small"></el-input>
					</el-form-item>
					<el-form-item label="收款通知" prop="remind">
						<el-switch v-model="adForm.remind" active-value="1" inactive-value="0"></el-switch>
					</el-form-item>
					<el-form-item label="启用状态" prop="status">
						<el-switch v-model="adForm.status" active-value="1" inactive-value="0"></el-switch>
					</el-form-item>
				</el-form>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button size="small" @click="resetForm">取 消</el-button>
				<el-button type="primary" size="small" @click="submitForm('adForm')">确认</el-button>
			</div>
		</el-dialog>
		<!-- 选择商品 -->
		<sel-member
			:show.sync="selMemberModal"
			@confirm="selMemberConfirmFn"
			@cancel="selMemberModal = false"
		></sel-member>
		<!-- 权限设置 -->
		<role-set :show.sync="roleShow" :info="modifyData" />
	</div>
</template>

<script>
import selMember from '@/components/module/sel-member';
import roleSet from '@/components/role-set';

export default {
	name: 'list-ad',
	components: {
		selMember,
		roleSet
	},
	data() {
		return {
			app: null,
			//修改弹窗
			modifyData: {},
			//新增或者修改弹窗
			addOrModify: 1,
			addDialog: false,
			showMiniCode: false,
			miniCodeSrc: '',
			adForm: {
				name: '',
				roleId: '',
				roleName: '',
				remind: '1',
				password: '',
				userId: '',
				remark: '',
				status: '1'
			},
			ruleForm: {
				name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
				roleName: [{ required: true, message: '请选择角色', trigger: 'change' }],
				password: { required: true, message: '请输入密码', trigger: 'blur' }
			},
			// 角色列表
			roleList: [],
			// 商品列表
			selMemberModal: false,
			memberData: {},
			// 权限设置
			roleShow: false
		};
	},
	methods: {
		// api
		getRole() {
			if (!this.$util.isEmpty(this.roleList)) return this.roleList;
			this.$service.role.list().then(res => {
				this.roleList = res.list;
			});
		},
		delBtnFn(item) {
			this.$confirm('是否删除该员工?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					this.$service.staff.delete({ id: item.id }).then(res => {
						this.$message.success('删除成功!');
						this.app.refresh({ type: this.tabIndex });
					});
				})
				.catch();
		},
		// operate
		authBtnFn(item) {
			this.modifyData = item;
			this.roleShow = true;
		},
		modifyBtnFn(item) {
			this.$service.staff
				.info({
					id: item.id
				})
				.then(async staffInfo => {
					let memberInfo = {};

					if (staffInfo.userId && staffInfo.userId != '0') {
						memberInfo = await this.$service.member.info({ userId: staffInfo.userId });
					}

					this.getRole();

					this.memberData = memberInfo;

					this.addOrModify = 2;
					this.modifyData = staffInfo;
					this.addDialog = true;
					let data = JSON.parse(JSON.stringify(staffInfo));
					data.startTime = this.$util.$formatDate(data.startTime);
					data.endTime = this.$util.$formatDate(data.endTime);
					if (this.$util.isEmpty(data)) return;
					Object.keys(this.adForm).forEach(i => {
						// if (i == 'password') return false;
						this.adForm[i] = data[i];
					});

					this.ruleForm.password.required = false;
				});
		},
		addBtnFn() {
			this.getRole();
			this.addOrModify = 1;
			this.addDialog = true;
			this.memberData = {};

			this.adForm = {
				name: '',
				roleId: '',
				roleName: '',
				remind: '1',
				password: '',
				userId: '',
				remark: '',
				status: '1'
			};

			this.ruleForm.password.required = true;
		},
		// 切换收款通知
		changeNotice(id, val) {
			this.$service.common.updateRemind({ id, remind: val }).then(res => {
				this.$message.success('操作成功');
				this.app.refresh();
			});
		},
		// 启用状态
		changeStatus(id, val) {
			this.$service.common.updateStatus({ id, status: val }).then(res => {
				this.$message.success('操作成功');
				this.app.refresh();
			});
		},
		// dialog
		selRoleFn(val) {
			let index = this.roleList.findIndex(e => e.roleName == val);
			this.adForm.roleId = this.roleList[index].id;
			console.log('this.adForm.roleId', this.adForm.roleId);
		},
		resetForm() {
			this.$refs['adForm'].resetFields();
			this.memberData = {};
			this.addDialog = false;
		},

		addFn() {
			let adForm = JSON.parse(JSON.stringify(this.adForm));
			let host = null;
			delete adForm.roleName;
			if (this.addOrModify == 1) {
				host = () => {
					return this.$service.shopAdmin.prepareBind(this.adForm);
				};
			} else {
				host = () => {
					return this.$service.shopAdmin.update({
						id: this.modifyData.id,
						...adForm
					});
				};
			}
			host(adForm).then(res => {
				this.miniCodeSrc = res.miniCode;
				this.showMiniCode = true;
				this.resetForm();
				this.app.refresh({ type: this.tabIndex });
			});
		},
		// 选择会员
		selGoods() {
			this.selMemberModal = true;
			setTimeout(() => {
				console.log(this.memberData);
			}, 6000);
		},
		selMemberConfirmFn(item) {
			this.memberData = item;
			this.adForm.userId = item.id;
			this.selMemberModal = false;
		},
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.addFn();
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		// x-crud 组件ad
		onLoad({ ctx, app }) {
			this.app = app;
			ctx.service(this.$service.shopAdmin)
				.set('table', {
					columns: [
						{
							prop: 'id',
							label: 'id',
							align: 'center',
							width: 100
						},
						{
							prop: 'avatar',
							label: '头像',
							align: 'center',
							width: 90,
							formatter: row => {
								return row.avatar;
							}
						},
						{
							prop: 'name',
							label: '姓名',
							align: 'center',
							formatter: row => {
								return row.name;
							}
						},
						{
							prop: 'mobile',
							label: '手机号',
							align: 'center',
							formatter: row => {
								return row.mobile;
							}
						},
						{
							prop: 'roleName',
							label: '角色',
							align: 'center',
							width: 100,
						},
						{
							prop: 'incomeNotice',
							label: '收款通知',
							align: 'center'
						},
						{
							prop: 'status',
							label: '启用状态',
							align: 'center'
						},
						{
							prop: 'lastLogin',
							label: '最后登录',
							align: 'center'
						},
						{
							prop: 'addDate',
							label: '添加时间',
							align: 'center'
						}
					],
					// 操作列
					op: {
						visible: true, // 是否显示
						// 同 element-ui Table-column Attributes
						props: {
							width: 120,
							align: 'center',
							fixed: 'right',
							label: '操作'
						},
						// 布局，请移步 `layout`
						layout: ['slot-auth', 'slot-modify', 'slot-del']
					}
				})
				.set('layout', [
					['slot-tabs'],
					['flex1', 'slot-add-ad-btn', 'refresh-btn'],
					['data-table'],
					['flex1', 'pagination']
				])
				// .on('refresh', async (params, { next, render }) => {
				// 	// 继续执行刷新
				// 	let { list } = await next(params);
				// 	list.map((e, index) => {
				// 		e.index = index;
				// 		e.imgUrl = e.smallImgList[0];
				// 	});
				// 	this.list = list;
				// 	render(list);
				// })
				.done();
			app.refresh({ type: this.tabIndex });
		},
		resetForm(formName) {
			let formNamed = formName || 'form';
			this.$refs[formNamed].resetFields();
			this.addDialog = false;
		},
	}
};
</script>

<style lang="scss" scoped>
// module
.ad-modal-content {
	.member-wrap {
		line-height: 1.4;
		margin-bottom: 10px;
		.member-det {
			font-size: 12px;
			margin-left: 10px;
		}
	}
}
</style>