<template>
	<div class="article-manager">
		<Card :bordered="false" dis-hover class="ivu-mt">
			<Form ref="artFrom" :model="artFrom" :label-width="75" label-position="right" @submit.native.prevent>
				<Row type="flex" :gutter="24">
					<Col v-bind="grid">
					<FormItem label="商户分类：" label-for="merchant_category_id">
						<el-cascader v-model="artFrom.category_id" size="small" :options="classifySelect"
							:props="{ emitPath: false,value:'merchant_category_id',label:'category_name' }"
							clearable></el-cascader>
					</FormItem>
					</Col>
					<Col v-bind="grid">
					<FormItem label="商户类型：" label-for="mer_type_id">
						<el-cascader v-model="artFrom.type_id" size="small" :options="typeSelect"
							:props="{ emitPath: false ,value:'mer_type_id',label:'type_name'}" clearable></el-cascader>
					</FormItem>
					</Col>
					<Col v-bind="grid">
					<FormItem label="商户搜索：" label-for="store_name">
						<Input search enter-button placeholder="请输入商品名称/关键字/ID" v-model="artFrom.store_name"
							@on-search="userSearchs" />
					</FormItem>
					</Col>
				</Row>
			</Form>
			<div class="Button">
				<Button type="primary" @click="add('添加')" class="bnt mr15" icon="md-add">添加商户</Button>
			</div>
			<Table ref="table" :columns="columns" :data="tableList" class="ivu-mt mt25" :loading="loading" highlight-row
				no-data-text="暂无数据" no-filtered-data-text="暂无筛选结果">
				<template slot-scope="{ row }" slot="image">
					<div class="tabBox_img" v-viewer>
						<img v-lazy="row.image" />
					</div>
				</template>
				<template slot-scope="{ row, index }" slot="state">
					<i-switch v-model="row.status" :value="row.status" :true-value="1" :false-value="0"
						@on-change="changeSwitch(row)" size="large">
						<span slot="open">开启</span>
						<span slot="close">禁用</span>
					</i-switch>
				</template>
				<template slot-scope="{ row, index }" slot="product_state">
					<i-switch v-model="row.mer_state" :value="row.mer_state" :true-value="1" :false-value="0"
						@on-change="changeProSwitch(row)" size="large">
						<span slot="open">开启</span>
						<span slot="close">禁用</span>
					</i-switch>
				</template>
				<template slot-scope="{ row, index }" slot="is_audit">
					<i-switch v-model="row.is_audit" :value="row.is_audit" :true-value="1" :false-value="0"
						@on-change="changeExamineSwitch(row)" size="large">
						<span slot="open">开启</span>
						<span slot="close">关闭</span>
					</i-switch>
				</template>

				<template slot-scope="{ row, index }" slot="action">
					<!-- <a @click="onLogo(row)">登录</a>
					<Divider type="vertical" /> -->
					<a @click="edit(row)">编辑</a>
					<Divider type="vertical" />
					<a @click="openPwd(row)">修改密码</a>
				</template>
			</Table>
			<div class="acea-row row-right page">
				<Page :total="total" :current="artFrom.page" show-elevator show-total @on-change="pageChange"
					:page-size="artFrom.limit" />
			</div>
		</Card>
		<!-- 新增编辑-->
		<Modal v-model="modals" @on-cancel="onCancel" scrollable footer-hide closable :title="`${modelTit}商户`"
			:mask-closable="false" width="700">
			<Form ref="formInline" :model="formInline" :rules="ruleValidate" :label-width="150"
				:label-position="labelPosition2" @submit.native.prevent>
				<FormItem label="商户名称：" label-for="mer_name" prop="mer_name">
					<Input placeholder="请输入商户名称" v-model="formInline.mer_name" />
				</FormItem>
				<FormItem label="商户分类：" label-for="category_id" prop="category_id">
					<el-cascader v-model="formInline.category_id" size="small" :options="classifySelect"
						:props="{ emitPath: false,value:'merchant_category_id',label:'category_name' }"
						clearable></el-cascader>
				</FormItem>
				<FormItem label="商户类型：" label-for="type_id" prop="type_id">
					<el-cascader v-model="formInline.type_id" size="small" :options="typeSelect"
						:props="{ emitPath: false ,value:'mer_type_id',label:'type_name'}" clearable></el-cascader>
				</FormItem>
				<FormItem label="商户负责人名称：" label-for="real_name" prop="real_name">
					<Input placeholder="请输入商户负责人名称" v-model="formInline.real_name" />
				</FormItem>
				<FormItem label="商户负责人手机号：" label-for="real_name" prop="real_name">
					<Input placeholder="请输入商户负责人手机号" v-model="formInline.mer_phone" />
				</FormItem>
				<FormItem label="商户账号：" label-for="account" prop="account">
					<Input placeholder="请输入商户账号" v-model="formInline.account" />
				</FormItem>
				<FormItem label="商户密码：" label-for="pwd" prop="pwd">
					<Input type="password" placeholder="请输入商户密码" v-model="formInline.pwd" />
				</FormItem>
				<FormItem label="商户地址：" label-for="mer_address" prop="mer_address">
					<Input placeholder="请输入商户地址" v-model="formInline.mer_address" />
				</FormItem>
				<FormItem label="商户简介：" label-for="introduction" prop="introduction">
					<Input placeholder="请输入商户简介" v-model="formInline.introduction" />
				</FormItem>
				<FormItem label="身份证：" label-for="Idcard" prop="Idcard">
					<Input placeholder="请输入身份证" v-model="formInline.Idcard" />
				</FormItem>
				<FormItem label="店铺logo" prop="image">
					<div class="acea-row">
						<div class="upLoad acea-row row-center-wrapper" @click="modalPicTap('image')">
							<Icon v-if="!formInline.image" type="ios-camera-outline" size="26" />
							<img style="width: 100px;height: 100px;" v-else v-lazy="formInline.image" />
						</div>
						<Input v-model="formInline.image" style="display: none"></Input>
					</div>
				</FormItem>
				<FormItem label="门头照片" prop="shopImg">
					<div class="acea-row">
						<div class="upLoad acea-row row-center-wrapper" @click="modalPicTap('shopImg')">
							<Icon v-if="!formInline.shopImg" type="ios-camera-outline" size="26" />
							<img style="width: 100px;height: 100px;" v-else v-lazy="formInline.shopImg" />
						</div>
						<Input v-model="formInline.shopImg" style="display: none"></Input>
					</div>
				</FormItem>

				<Button type="primary" size="large" long @click="handleSubmit('formInline')">提交</Button>

			</Form>
		</Modal>
		<Modal v-model="modalPic" width="1024px" 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>
		<!-- 修改密码 -->
		<Modal v-model="pwd" @on-cancel="onCancel" scrollable footer-hide closable title="修改密码" :mask-closable="false"
			width="700">
			<Form ref="pwdinfo" :model="pwdinfo" :rules="rulepwd" :label-width="150" :label-position="labelPosition2"
				@submit.native.prevent>
				<FormItem label="密码：" label-for="pwd" prop="pwd">
					<Input type="password" placeholder="请输入密码" v-model="pwdinfo.pwd" />
				</FormItem>
				<FormItem label="确认密码：" label-for="pwd_two" prop="pwd_two">
					<Input type="password" placeholder="请再次输入密码" v-model="pwdinfo.pwd_two" />
				</FormItem>

				<Button type="primary" size="large" long @click="changePassword('pwdinfo')">提交</Button>
			</Form>
		</Modal>
	</div>
</template>

<script>
	import toExcel from '../../utils/Excel.js';
	import {
		mapState
	} from 'vuex';
	import {
		exportProductList
	} from '@/api/export';
	import uploadPictures from '@/components/uploadPictures';
	import {
		merchentlist,
		getmerchent,
		addadmin,
		changepwd,
		lst,
		typeList,
		forbidden,
		openMerchant,
		merchantLoginApi,
		openMerchantProduct
	} from '@/api/shop';
	import {
		setCookies
	} from '@/libs/util';
	import {
		PrevLoading
	} from '@/utils/loading.js';
	import {
		formatFlatteningRoutes,
		findFirstNonNullChildren
	} from '@/libs/system';
	export default {
		name: 'shop_list',
		components: {
			uploadPictures
		},
		computed: {
			...mapState('userLevel', ['categoryId']),
			labelPosition2() {
				return this.isMobile ? 'top' : 'right';
			},
		},
		data() {
			return {
				template: false,
				grid: {
					xl: 6,
					lg: 8,
					md: 12,
					sm: 24,
					xs: 24,
				},
				gridBtn: {
					xl: 4,
					lg: 8,
					md: 8,
					sm: 8,
					xs: 8,
				},
				gridPic: {
					xl: 6,
					lg: 8,
					md: 12,
					sm: 12,
					xs: 12,
				},
				artFrom: {
					page: 1,
					limit: 10,
					type_id: '',
					category_id: '',
					type: '1',
				},
				list: [],
				tableList: [],
				classifySelect: [],
				typeSelect: [],
				loading: false,
				isChoice: '单选',
				columns: [{
						title: '商户ID',
						key: 'mer_id',
						width: 80,
					},
					{
						title: '商户头像',
						slot: 'image',
						minWidth: 80,
					},
					{
						title: '商户名称',
						key: 'mer_name',
						minWidth: 100,
					},
					{
						title: '商户类型',
						key: 'type_name',
						minWidth: 100,
					},
					{
						title: '商户分类',
						key: 'category_name',
						minWidth: 100,
					},
					{
						title: '商家姓名',
						key: 'real_name',
						minWidth: 100,
					},
					{
						title: '商家手机号',
						key: 'mer_phone',
						minWidth: 150,
					},
					{
						title: '审核',
						slot: 'is_audit',
						minWidth: 150,
					},
					{
						title: '状态',
						slot: 'state',
						width: 100,
						filters: [{
								label: '开启',
								value: 1,
							},
							{
								label: '禁用',
								value: 0,
							},
						],
					},
					{
						title: '商户商品',
						slot: 'product_state',
						width: 100,
						filters: [{
								label: '显示',
								value: 1,
							},
							{
								label: '关闭',
								value: 0,
							},
						],
					},
					{
						title: '操作',
						slot: 'action',
						fixed: 'right',
						minWidth: 220,
					},
				],
				data: [],
				total: 0,
				goodsId: '',
				modals: false,
				modalPic: false,
				pwd: false,
				modelTit: '',
				formInline: {
					mer_name: '',
					category_id: '',
					type_id: '',
					real_name: '',
					account: '',
					pwd: '',
					mer_phone: '',
					mer_address: '',
					Idcard: '',
					introduction: '',
					shopImg: '',
					image: '',
				},
				pwdinfo: {
					pwd: '',
					pwd_two: ''
				},
				rulepwd: {
					pwd: [{
						required: true,
						message: '请输入密码',
						trigger: 'blur'
					}],
					pwd_two: [{
						required: true,
						message: '请再次输入密码',
						trigger: 'blur'
					}],
				},
				ruleValidate: {
					mer_name: [{
						required: true,
						message: '请输入商户名称',
						trigger: 'blur'
					}],
					real_name: [{
						required: true,
						message: '请输入商户负责人名称',
						trigger: 'blur'
					}],
					account: [{
						required: true,
						message: '请输入商户账号',
						trigger: 'blur'
					}],
					pwd: [{
						required: true,
						message: '请输入商户密码',
						trigger: 'blur'
					}],
					mer_phone: [{
						required: true,
						message: '请输入联系人手机号',
						trigger: 'blur'
					}],
					mer_address: [{
						required: true,
						message: '请输入商户地址',
						trigger: 'blur'
					}],
					introduction: [{
						required: true,
						message: '请输入商户关键字',
						trigger: 'blur'
					}],
				},
			};
		},
		watch: {
			$route() {
				if (this.$route.fullPath === this.$routeProStr + '/product/product_list?type=5') {
					this.getPath();
				}
			},
		},
		created() {
			this.gettype();
			this.getclassify();
			this.getDataList();
		},
		activated() {
			// this.goodsCategory();
			if (this.$route.fullPath === this.$routeProStr + '/product/product_list?type=5') {
				this.getPath();
			} else {
				this.getDataList();
			}
		},
		methods: {
			modalPicTap(picTit) {
				this.modalPic = true;
				this.modals = false;
				this.picTit = picTit;
			},
			formatTwoStageRoutes(arr) {
				if (arr.length <= 0) return false;
				const newArr = [];
				const cacheList = [];
				arr.forEach((v) => {
					if (v && v.meta && v.meta.keepAlive) {
						newArr.push({
							...v
						});
						cacheList.push(v.name);
						this.$store.dispatch('keepAliveNames/setCacheKeepAlive', cacheList);
					}
				});
				return newArr;
			},
			onLogo(row) {
				merchantLoginApi({}, row.mer_id)
					.then(res => {
						console.log(res, 'rens');
						let data = res.data;
						let expires = this.getExpiresTime(data.expires_time);
						// 记录用户登陆信息
						setCookies('uuid', data.user_info.id, expires);
						setCookies('token', data.token, expires);
						setCookies('expires_time', data.expires_time, expires);

						this.$store.commit('userInfo/uniqueAuth', data.unique_auth);
						this.$store.commit('userInfo/userInfo', data.user_info);
						// 保存菜单信息
						this.$store.commit('menus/setopenMenus', []);
						this.$store.commit('menus/getmenusNav', data.menus);
						this.$store.dispatch('routesList/setRoutesList', data.menus);
						let arr = formatFlatteningRoutes(this.$router.options.routes);
						this.formatTwoStageRoutes(arr);
						this.$store.commit('menus/setOneLvMenus', arr);
						let routes = formatFlatteningRoutes(data.menus);
						console.log(routes);
						this.$store.commit('menus/setOneLvRoute', routes);

						// 记录用户信息
						this.$store.commit('userInfo/name', data.user_info.account);
						this.$store.commit('userInfo/avatar', data.user_info.head_pic);
						this.$store.commit('userInfo/access', data.unique_auth);
						this.$store.commit('userInfo/logo', data.logo);
						this.$store.commit('userInfo/logoSmall', data.logo_square);
						this.$store.commit('userInfo/version', data.version);
						this.$store.commit('userInfo/newOrderAudioLink', data.newOrderAudioLink);
						this.login_captcha = 0;
						PrevLoading.start();
						return this.$router.push({
							path: findFirstNonNullChildren(res.data.menus).path || this.$routeProStrshop +
								'/',
						});
						setTimeout(location.reload(), 3000)
					})
					.catch(res => {
						this.$message.error(res.message);
					});

			},
			getExpiresTime(expiresTime) {
				let nowTimeNum = Math.round(new Date() / 1000);
				let expiresTimeNum = expiresTime - nowTimeNum;
				return parseFloat(parseFloat(parseFloat(expiresTimeNum / 60) / 60) / 24);
			},
			getPic(pc) {
				console.log(pc, 'info');
				switch (this.picTit) {
					case 'image':
						this.formInline.image = pc.att_dir;
						break;
					case 'shopImg':
						this.formInline.shopImg = pc.att_dir;
						break;
					default:
				}
				console.log(this.formInline, '');
				this.modalPic = false;
				this.modals = true;
			},
			getPath() {
				this.columns2 = [...this.columns];
				if (name !== '1' && name !== '2') {
					this.columns2.shift({
						type: 'selection',
						width: 60,
						align: 'center',
					});
				}
				this.artFrom.page = 1;
				this.artFrom.type = this.$route.query.type.toString();
				this.getDataList();
			},
			// 商户类型；
			gettype() {
				console.log('进入');
				typeList()
					.then((res) => {
						this.typeSelect = res.data;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			// 商户分类；
			getclassify() {
				console.log('进入');
				lst()
					.then((res) => {
						this.classifySelect = res.data;
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			// 商户列表
			getDataList() {
				this.loading = true;
				this.artFrom.type_id = this.artFrom.type_id || '';
				this.artFrom.category_id = this.artFrom.category_id || '';
				merchentlist(this.artFrom)
					.then((res) => {
						let data = res.data;
						this.tableList = data.list;
						this.total = data.count;
						// this.$nextTick(() => {
						// 	//确保dom加载完毕
						// 	this.setChecked();
						// });
						this.loading = false;
					})
					.catch((res) => {
						this.loading = false;
						this.$Message.error(res.msg);
					});
			},
			pageChange(status) {
				this.artFrom.page = status;
				this.getDataList();
			},
			// 表格搜索
			userSearchs() {
				this.artFrom.page = 1;
				this.getDataList();
			},
			// 商户开启关闭
			changeSwitch(row) {
				forbidden({
						mer_id: row.mer_id,
						status: row.status
					})
					.then((res) => {
						this.$Message.success(res.msg);
					})
					.catch((res) => {
						row.is_show = !row.is_show ? 1 : 0;
						this.$Message.error(res.msg);
					});
			},
			// 商户商品开启关闭
			changeProSwitch(row) {
				openMerchant({
						mer_id: row.mer_id,
						mer_state: row.mer_state
					})
					.then((res) => {
						this.$Message.success(res.msg);
					})
					.catch((res) => {
						row.is_show = !row.is_show ? 1 : 0;
						this.$Message.error(res.msg);
					});
			},
			// 商户审核开启关闭
			changeExamineSwitch(row) {
				openMerchantProduct({
						mer_id: row.mer_id,
						is_audit: row.is_audit
					})
					.then((res) => {
						this.$Message.success(res.msg);
					})
					.catch((res) => {
						row.is_show = !row.is_show ? 1 : 0;
						this.$Message.error(res.msg);
					});
			},
			// 编辑
			edit(row) {
				this.$modalForm(getmerchent({}, row.mer_id)).then(() => this.getDataList());
			},
			// 添加
			add(name) {
				this.modelTit = name;
				this.modals = true;
			},
			handleSubmit(name) {
				console.log(this.formInline, '123456');
				this.$refs[name].validate((valid) => {
					if (valid) {
						if (this.formInline.category_id == '') return this.$Message.warning('请选择商户分类');
						if (this.formInline.type_id == '') return this.$Message.warning('请选择商户类型');
						addadmin(this.formInline)
							.then(async (res) => {
								this.$Message.success(res.msg);
								this.modals = false;
								this.getDataList();
								this.$refs[name].resetFields();
							})
							.catch((res) => {
								this.$Message.error(res.msg);
							});
					} else {
						return false;
					}
				});
			},
			onCancel() {
				this.$refs['formInline'].resetFields();
			},
			// 确认
			del(row, tit, num) {
				let delfromData = {
					title: tit,
					num: num,
					url: `product/product/${row.id}`,
					method: 'DELETE',
					ids: '',
					un: 1,
				};
				this.$modalSure(delfromData)
					.then((res) => {
						this.$Message.success(res.msg);
						this.tableList.splice(num, 1);
					})
					.catch((res) => {
						this.$Message.error(res.msg);
					});
			},
			openPwd(row) {
				this.goodsId = row.mer_id
				this.pwd = true
			},
			changePassword(name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						changepwd(this.pwdinfo, this.goodsId)
							.then(async (res) => {
								this.$Message.success(res.msg);
								this.pwd = false;
								this.$refs[name].resetFields();
							})
							.catch((res) => {
								this.$Message.error(res.msg);
							});
					} else {
						return false;
					}
				});
			}
		},
	};
</script>
<style scoped lang="stylus">
	/deep/.ivu-modal-mask {
		z-index: 999 !important;
	}

	/deep/.ivu-modal-wrap {
		z-index: 999 !important;
	}

	.Box {
		>>>.ivu-modal-body {
			height: 700px;
			overflow: auto;
		}
	}

	.batch-box {
		>>>.ivu-modal-body {
			overflow: auto;
			min-height: 350px;
		}
	}

	.tabBox_img {
		width: 36px;
		height: 36px;
		border-radius: 4px;
		cursor: pointer;

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

	.bg {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.5);
		z-index: 11;
	}

	/deep/.happy-scroll-content {
		width: 100%;

		.demo-spin-icon-load {
			animation: ani-demo-spin 1s linear infinite;
		}

		@keyframes ani-demo-spin {
			from {
				transform: rotate(0deg);
			}

			50% {
				transform: rotate(180deg);
			}

			to {
				transform: rotate(360deg);
			}
		}

		.demo-spin-col {
			height: 100px;
			position: relative;
			border: 1px solid #eee;
		}
	}

	.labelInput {
		border: 1px solid #dcdee2;
		width: 20%;
		padding: 0 5px;
		border-radius: 5px;
		min-height: 30px;
		cursor: pointer;

		.span {
			color: #c5c8ce;
		}

		.iconxiayi {
			font-size: 12px;
		}
	}
</style>