<template>
	<div>
		<Modal v-model="isTemplate" scrollable footer-hide closable :title="title" :z-index="1" width="700"
			@on-cancel="cancel">
			<div class="article-manager">
				<Card :bordered="false" dis-hover>
					<Form ref="formItem" :model="formItem" :label-width="labelWidth" :label-position="labelPosition"
						:rules="ruleValidate" @submit.native.prevent>
						<Row type="flex" :gutter="24">
							<Col span="24" v-if="openErp">
							<Col v-bind="grid">
							<FormItem label="erp门店：" prop="erp_shop_id">
								<Button
									@click="tapErp">{{formItem.erp_shop_id?formItem.erp_shop_id:"请选择erp门店"}}</Button>
							</FormItem>
							</Col>
							</Col>
							<!-- <Col span="24">
							<Col v-bind="grid">
							<FormItem label="所属门店：" prop="store_id">
								<Select v-model="formItem.store_id" clearable filterable @on-change="userSearchs"
									class="input-add">
									<Option v-for="item in staffData" :value="item.id" :key="item.id">{{ item.name }}
									</Option>
								</Select>
							</FormItem>
							</Col>
							</Col> -->
							<Col span="24">
							<Col v-bind="grid">
							<FormItem label="头像：" prop="image">
								<div class="picBox" @click="modalPicTap('单选')">
									<div class="pictrue" v-if="formItem.avatar"><img v-lazy="formItem.avatar"></div>
									<div class="upLoad" v-else>
										<div class="iconfont">+</div>
									</div>
								</div>
							</FormItem>
							</Col>
							</Col>
							<Col span="24" >
							<Col v-bind="grid">
							<FormItem label="姓名：" prop="name" label-for="name">
								<Input v-model="formItem.name" placeholder="请输入姓名" />
							</FormItem>
							</Col>
							</Col>
							<Col span="24">
							<Col v-bind="grid">
							<FormItem label="别名：" prop="name" label-for="alias">
								<Input v-model="formItem.alias" placeholder="请输入别名" />
							</FormItem>
							</Col>
							</Col>
							<Col span="24">
							<Col v-bind="grid">
							<FormItem label="手机号：" label-for="mobile" prop="mobile">
								<Input v-model="formItem.mobile" placeholder="请输入手机号" />
							</FormItem>
							</Col>
							</Col>
							<Col span="24" class="mt20">
							  <Col v-bind="grid">
							    <FormItem label="性别：">
							      <RadioGroup v-model="formItem.gender">
							        <Radio :label="0">
							          <Icon type="social-apple"></Icon>
							          <span>女</span>
							        </Radio>
							        <Radio :label="2">
							          <Icon type="social-android"></Icon>
							          <span>男</span>
							        </Radio>
							      </RadioGroup>
							    </FormItem>
							  </Col>
							</Col>
							<Col span="24">
							<Col v-bind="grid">
							<FormItem label="职务：" label-for="position" prop="position">
								<Input v-model="formItem.position" placeholder="请输入职务" />
							</FormItem>
							</Col>
							</Col>
							<Col span="24">
							<Col v-bind="grid">
							<FormItem label="住址：" label-for="address" prop="address">
								<Input v-model="formItem.address" placeholder="请输入住址" />
							</FormItem>
							</Col>
							</Col>
							<Col span="24">
							<Col v-bind="grid">
							<FormItem label="部门：" label-for="main_department" prop="main_department">
								<el-cascader placeholder="请选择部门" :options="departmentList" :value="formItem.main_department"
									v-width="320" :props="{ checkStrictly: true,value: 'id',label: 'name' }"
									clearable @change="changeBm"></el-cascader>
							</FormItem>
							</Col>
							</Col>
						</Row>
						<Row style="justify-content: space-around;">
							<Col>
							<Button type="primary" class="btn"
								@click="handleSubmit('formItem')">提交</Button>
							</Col>
						</Row>
						<Spin size="large" fix v-if="spinShow"></Spin>
					</Form>
				</Card>

				<Modal v-model="modalPic" width="960px" scrollable footer-hide closable title='上传提货点logo'
					:mask-closable="false" :z-index="1">
					<uploadPictures :isChoice="isChoice" @getPic="getPic" :gridBtn="gridBtn" :gridPic="gridPic"
						v-if="modalPic"></uploadPictures>
				</Modal>
				<Modal v-model="modalErp" width="700px" scrollable footer-hide closable title='erp门店'
					:mask-closable="false" :z-index="1">
					<erpList ref="refErp" @getProductId="getProductId"></erpList>
				</Modal>
			</div>
		</Modal>
		<Modal v-model="modals" title="商品列表" class="paymentFooter" scrollable width="900" :footer-hide="true">
			<goods-list ref="goodslist" @getProductId="getGoodsId" v-if="modals" :ischeckbox="true" :isLive="true"
				:storeType="1"></goods-list>
		</Modal>
	</div>
</template>

<script>
	// import { keyApi} from '@/api/setting';
	import goodsList from '@/components/goodsList'
	import {
		keyApi,
		storeGetInfoApi,
		cityApi,
		storeUpdateApi,
		cascaderList,
		staffListInfo,
		getDepartmentList,
		addYg,
		editYg
	} from '@/api/store';
	import {
		erpConfig
	} from "@/api/erp";
	// import { keyApi, storeUpdateApi, storeGetInfoApi, cityApi } from '@/api/setting';
	import {
		mapState
	} from 'vuex';
	import uploadPictures from '@/components/uploadPictures';
	import erpList from './erpList.vue';
	import Maps from '@/components/map/map.vue'
	export default {
		name: 'systemSt',
		components: {
			uploadPictures,
			Maps,
			erpList,
			goodsList
		},
		props: {},
		data() {
			let validatePhone = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('请填写手机号'));
				} else if (!/^1[3456789]\d{9}$/.test(value)) {
					callback(new Error('手机号格式不正确!'));
				} else {
					callback();
				}
			};
			let validateUpload = (rule, value, callback) => {
				if (!this.formItem.avatar) {
					callback(new Error('请上传头像'))
				} else {
					callback()
				}
			};
			return {
				isEdit: 0,//0->添加 1->编辑
				staffData: [],
				goodsList: [],
				modals: false,
				treeSelect: [],
				modalErp: false,
				openErp: false,
				isTemplate: false,
				title: '',
				formItem: {
					name: '',
					avatar: '',
					mobile: '',
					alias: '',
					address: '',
					main_department: '',
					direct_leader: 'ZhouFengYu'
				},
				spinShow: false,
				addresData: [],
				ruleValidate: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'blur'
					}],
					address: [{
						required: true,
						message: '请输入地址地址',
						trigger: 'blur'
					}],

					mobile: [{
						required: true,
						validator: validatePhone,
						trigger: 'blur'
					}],
					avatar: [{
						required: true,
						validator: validateUpload,
						trigger: 'change'
					}]
				},
				mapKey: '',
				grid: {
					xl: 20,
					lg: 20,
					md: 20,
					sm: 24,
					xs: 24
				},
				gridPic: {
					xl: 6,
					lg: 8,
					md: 12,
					sm: 12,
					xs: 12
				},
				gridBtn: {
					xl: 4,
					lg: 8,
					md: 8,
					sm: 8,
					xs: 8
				},
				modalPic: false,
				isChoice: '单选',
				pid: 0,
				isApi: 0,
				add: 0,
				departmentList: []
			}
		},
		created() {
			this.getDepartmentList()
			this.goodsCategory();
			this.getErpConfig();
			this.getKey();
			// this.getInfo();
			let data = {
				pid: 0
			}
			this.cityInfo(data);
			this.staffList()
			if(this.isEdit == 0) {
				this.formItem = {
					name: '',
					avatar: '',
					mobile: '',
					alias: '',
					address: '',
					main_department: '',
					direct_leader: 'ZhouFengYu'
				}
			}
		},
		computed: {
			...mapState('admin/layout', [
				'isMobile'
			]),
			labelWidth() {
				return this.isMobile ? undefined : 120;
			},
			labelPosition() {
				return this.isMobile ? 'top' : 'right';
			}
		},
		mounted: function() {},
		methods: {
			changeBm(res) {
				console.log(res);
				this.formItem.main_department = res[res.length -1 ]
				this.formItem.department = [this.formItem.main_department]
			},
			getDepartmentList() {
				getDepartmentList().then(res => {
					console.log(res);
					this.departmentList = res.data
				})
			},
			userSearchs() {
				// this.orderData.page = 1;
				// this.searchList();
			},
			// 门店列表
			staffList() {
				let data = {
					page: 0,
					limit: 0,
				};
				staffListInfo()
					.then((res) => {
						this.staffData = res.data;
					})
					.catch((err) => {
						this.$Message.error(err.msg);
					});
			},
			//对象数组去重；
			unique(arr) {
				const res = new Map();
				return arr.filter((arr) => !res.has(arr.product_id) && res.set(arr.product_id, 1))
			},
			getGoodsId(data) {
				let list = this.goodsList.concat(data);
				let uni = this.unique(list);
				this.goodsList = uni;
				this.$nextTick(res => {
					setTimeout(() => {
						this.modals = false
					}, 300)
				})
			},
			bindDelete(index) {
				this.goodsList.splice(index, 1)
			},
			// 门店分类；
			goodsCategory() {
				cascaderList(1).then(res => {
					this.treeSelect = res.data;
				}).catch(res => {
					this.$Message.error(res.msg);
				})
			},
			getProductId(id) {
				this.formItem.erp_shop_id = id;
				this.modalErp = false;
				this.$refs.formItem.validateField("erp_shop_id");
			},
			tapErp() {
				this.$refs.refErp.currentid = this.formItem.erp_shop_id;
				this.modalErp = true;
				this.$refs.formItem.validateField("erp_shop_id");
			},
			getErpConfig() {
				erpConfig().then(res => {
					this.openErp = res.data.open_erp;
				}).catch(err => {
					this.$Message.error(err.msg);
				})
			},
			clearFrom() {
				this.goodsList = [];
				this.formItem = {
					name: '',
					avatar: '',
					mobile: '',
					alias: '',
					address: '',
					main_department: '',
					direct_leader: 'ZhouFengYu'
				}
				this.add = 0;
				this.isApi = 0;
			},
			cancel() {
				console.log('关闭');
				this.isTemplate = false;
				// this.$refs['formItem'].resetFields();
				this.clearFrom();
			},
			addchack(e, selectedData) {
				e.forEach((i, index) => {
					if (index == 0) {
						this.formItem.province = i
					} else if (index == 1) {
						this.formItem.city = i
					} else if (index == 2) {
						this.formItem.area = i
					} else {
						this.formItem.street = i
					}
				})
				this.formItem.address = (selectedData.map(o => o.label)).join("/");
			},
			cityInfo(data) {
				cityApi(data).then(res => {
					this.addresData = res.data
				})
			},
			loadData(item, callback) {
				item.loading = true;
				cityApi({
					pid: item.value
				}).then(res => {
					item.children = res.data;
					item.loading = false;
					callback();
				});
			},
			// 地图信息获取
			getCoordinates(data) {
				this.formItem.latitude = data.location.lat || 34.34127
				this.formItem.longitude = data.location.lng || 108.93984
				if (this.isApi) {
					// // this.formItem.detailed_address = data.address
					let components = data.addressComponents;
					if (this.formItem.detailed_address.indexOf(components.street) == -1) {
						this.formItem.detailed_address = data.address + (components.town ? components.town : '');
					}
				}
			},
			// 查找位置
			onSearch() {
				if (this.$refs.mapChild) {
					this.$refs.mapChild.searchKeyword(this.formItem.detailed_address)
				}
			},
			// key值
			getKey() {
				keyApi().then(res => {
					this.mapKey = res.data.key
				}).catch(res => {
					this.$Message.error(res.msg)
				})
			},
			// 详情
			getInfo(id) {
				let that = this;
				that.$refs['formItem'].resetFields();
				that.formItem.id = id;
				that.spinShow = true;
				storeGetInfoApi(id).then(res => {
					this.isApi = 1;
					let addressSelect = [];
					this.formItem = res.data.info;
					this.formItem.erp_shop_id = res.data.info.erp_shop_id || 0;
					let a = []
					a.push(res.data.info.day_start)
					a.push(res.data.info.day_end)
					this.formItem.day_time = a
					if (res.data.info.province) {
						addressSelect.push(res.data.info.province)
					}
					if (res.data.info.city) {
						addressSelect.push(res.data.info.city)
					}
					if (res.data.info.area) {
						addressSelect.push(res.data.info.area)
					}
					if (res.data.info.street) {
						addressSelect.push(res.data.info.street)
					}
					this.$set(this.formItem, 'valid_range', (this.formItem.valid_range) / 1000)
					this.formItem.addressSelect = addressSelect;
					this.onSearch();
					that.spinShow = false;
				}).catch(function(res) {
					that.spinShow = false;
					that.$Message.error(res.msg);
				})
			},
			// 选择图片
			modalPicTap() {
				this.modalPic = true;
				this.$refs.formItem.validateField("avatar")
			},
			// 选中图片
			getPic(pc) {
				this.formItem.avatar = pc.att_dir;
				this.modalPic = false;
				this.$refs.formItem.validateField("avatar")
			},
			// 营业时间
			onchangeTime(e) {
				this.formItem.day_time = e;
			},
			// 提交
			handleSubmit(name) {
				this.$refs[name].validate((valid) => {
					if (valid) {
						if(this.formItem.id) {
							editYg({
								id: this.formItem.id,
								name:  this.formItem.name,
								avatar:  this.formItem.avatar,
								mobile:  this.formItem.mobile,
								alias:  this.formItem.alias,
								address:  this.formItem.address,
								main_department:  this.formItem.main_department,
								department: this.formItem.department,
								uid: this.formItem.uid,
								userid: this.formItem.userid,
								direct_leader: 'ZhouFengYu'
							}).then(async res => {
								this.$Message.success(res.msg);
								this.isTemplate = false;
								this.$emit('success')
								// this.clearFrom();
							}).catch(res => {
								this.$Message.error(res.msg);
							})
						}else {
							addYg(this.formItem).then(async res => {
								this.$Message.success(res.msg);
								this.isTemplate = false;
								this.$emit('success')
								// this.clearFrom();
							}).catch(res => {
								this.$Message.error(res.msg);
							})
						}
						
					} else {
						return false;
					}
				})

			}
		}
	}
</script>

<style scoped lang="stylus">
	.tips {
		display: inline-bolck;
		font-size: 12px;
		font-weight: 400;
		color: #999;
	}

	.box {
		display flex flex-wrap wrap .box-item {
			position relative margin-right 20px width 60px height 60px margin-bottom 10px img {
				width 100% height 100%
			}

			.icon {
				position absolute;
				top: -10px;
				right -10px;
			}
		}

		.upload-box {
			width 60px height 60px margin-bottom 10px display flex align-items center justify-content center background #ccc
		}
	}

	.map-sty {
		width: 90%;
		text-align: right;
		margin: 0 0 0 10%;
	}

	/deep/.ivu-card-body {
		padding 16px 0 0 0 !important;
	}
	.footer {
		width 100%;
		height 50px;
		box-shadow: 0px -2px 4px 0px rgba(0, 0, 0, 0.05);
		margin-top 50px;
	}
	.btn /deep/.ivu-btn-primary {
		width 86px;
	}
	.btn {
		margin-top: 20px;
	}
	.inputW {
		width 400px;
	}
	.ivu-mt {
		min-width 580px;
	}
	.picBox {
		display: inline-block;
		cursor: pointer;
		.upLoad {
			width: 58px;
			height: 58px;
			line-height: 58px;
			border: 1px dotted rgba(0, 0, 0, 0.1);
			border-radius: 4px;
			background: rgba(0, 0, 0, 0.02);
		}
		.pictrue {
			width: 60px;
			height: 60px;
			border: 1px dotted rgba(0, 0, 0, 0.1);
			margin-right: 10px;
			img{
				width: 100%;
				height: 100%;
			} 
		}
		.iconfont {
			color: #CCCCCC;
			font-size 26px;
			text-align center;
		}
	}
</style>