<template>
	<view :class="mask ? 'tl-show': ''">
		<!-- <u-navbar :title="title" :autoBack="true" :placeholder="true" leftIconColor="#fff"
			:titleStyle="{ color: '#ffffff' }" bgColor="#FD4B09">
			<template slot="right">
				<u-icon name="checkmark" color="#fff" @click="submit"></u-icon>
			</template>
		</u-navbar> -->
		<u-cell-group :border="false">
			<u-cell :border="false" center title="基础信息"></u-cell>
		</u-cell-group>
		<u--form labelPosition="left" :model="form" ref="form" labelWidth="150rpx"
			style="margin-top: 10rpx;margin-bottom: 150rpx;">
			<view style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;">
				<view style="padding: 0 10rpx;">
					<u-form-item label="公司名称" prop="cname" borderBottom>
						<u-input v-model="form.cname" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="联系人" prop="cname" borderBottom>
						<u-input v-model="form.attn" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="联系电话" prop="cname" borderBottom>
						<u-input v-model="form.tel" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="地址" labelWidth="80rpx" :borderBottom="false"
						@click="filterAll(['corpsAddrList','corpsAddrList'])">
						({{form.corpsAddrList.length}})
						<u-input border="none" inputAlign="right" suffixIcon="plus-circle" disabled
							disabledColor="#ffffff" />
					</u-form-item>
					<u-cell-group :border="false">
						<u-swipe-action>
							<u-swipe-action-item :options="options" v-for="(item,index) in form.corpsAddrList"
								:key="index" @click="address(index)">
								<u-cell @click="change(item,index)" :iconStyle="{ color: '#fd4b09' }" :titleStyle="{
										width:'550rpx',
										overflow:'hidden',
										whiteSpace: 'nowrap',
										textOverflow: 'ellipsis',
										oTextOverflow:'ellipsis'
									}" :icon="item.addrType == 0?'map':'car'" :title="item.detailedAddress" :isLink="true"
									:borderBottom="form.corpsAddrList.length-1 == index?false:true">
								</u-cell>
							</u-swipe-action-item>
						</u-swipe-action>
					</u-cell-group>
				</view>
			</view>
			<u-cell-group :border="false">
				<u-cell :border="false" center title="类别信息" :arrow-direction="category==false?'up':'down'"
					:value="category==false?'展开':'收起'" :isLink="true" @click="category = !category"></u-cell>
			</u-cell-group>
			<view style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;">
				<view style="padding: 0 10rpx;">
					<u-form-item label="供应商类别" labelWidth="160rpx" :borderBottom="category==false?false:true"
						@click="filterAll(['corpsTypeName','corpsTypeId'])">
						<u-input v-model="form.corpsTypeName" inputAlign="right" border="none" placeholder="请选择"
							disabled disabledColor="#ffffff">
						<template slot="suffix" style="text-align: center;">
							<u-icon name="plus-circle" size="18" @click.native.stop="newCategory()"></u-icon>
						</template>
						</u-input>
					</u-form-item>
					<view v-if="category">
						<u-form-item label="供应商标签1" prop="mailbox" borderBottom labelWidth="180rpx">
							<u-input v-model="form.labels[0]" inputAlign="right" border="none" placeholder="请输入" />
						</u-form-item>
						<u-form-item label="供应商标签2" prop="mailbox" labelWidth="180rpx" borderBottom>
							<u-input v-model="form.labels[1]" inputAlign="right" border="none" placeholder="请输入" />
						</u-form-item>
						<u-form-item label="供应商标签3" prop="mailbox" labelWidth="180rpx" borderBottom>
							<u-input v-model="form.labels[2]" inputAlign="right" border="none" placeholder="请输入" />
						</u-form-item>
						<u-form-item label="供应商标签4" prop="mailbox" labelWidth="180rpx" :borderBottom="false">
							<u-input v-model="form.labels[3]" inputAlign="right" border="none" placeholder="请输入" />
						</u-form-item>
					</view>
				</view>
			</view>
			<u-cell-group :border="false">
				<u-cell :border="false" center title="商务信息" :arrow-direction="customer==false?'up':'down'"
					:value="customer==false?'展开':'收起'" :isLink="true" @click="customer = !customer"></u-cell>
			</u-cell-group>
			<view style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;" v-if="customer">
				<view style="padding: 0 10rpx;">
					<u-form-item label="供应商经理" labelWidth="160rpx" prop="mailbox" borderBottom>
						<u-input v-model="form.adminProfiles" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="预付款" prop="mailbox" borderBottom>
						<u-input v-model="form.creditGrant" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="欠款额度" prop="mailbox" borderBottom>
						<u-input v-model="form.arrears" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="银行帐号" prop="mailbox" borderBottom>
						<u-input v-model="form.accountNo" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
					<u-form-item label="开户银行" prop="mailbox" :borderBottom="false">
						<u-input v-model="form.accountBank" inputAlign="right" border="none" placeholder="请输入" />
					</u-form-item>
				</view>
			</view>
			<u-cell-group :border="false">
				<u-cell :border="false" center title="图片信息" :arrow-direction="enclosure==false?'up':'down'"
					:value="enclosure==false?'展开':'收起'" :isLink="true" @click="enclosure = !enclosure"></u-cell>
			</u-cell-group>
			<view style="width: calc(96%);margin: 0 auto;background-color: #fff;border-radius: 20rpx;" v-if="enclosure">
				<view style="padding: 10rpx 10rpx;">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="10"></u-upload>
				</view>
			</view>
		</u--form>
		<view style="width: 100%;position: fixed;bottom: 0;background-color: #fff;">
			<view style="width: 96%;;margin: 20rpx auto;">
				<u-button @click="submit" type="success" color="#fd4b09" shape="circle" text="确认提交"></u-button>
			</view>
		</view>
		<u-popup :show="show" @close="show = false,mask = false,formTwo = {}" closeable :closeOnClickOverlay="false"
			zIndex="10070">
			<view style="width: 96%;margin: auto auto;margin-top: 20rpx;padding-bottom: 20rpx;">
				<text>添加地址</text>
				<!-- <u-divider style="margin-bottom: 10rpx;"></u-divider>
				<view style="display: flex;justify-content: space-around;" :key="addrType">
					<view style="padding-bottom: 10rpx;" :class="addrType == 0?'selectedAddress':''"
						@click="selected(0)">供应商地址</view>
					<view style="padding-bottom: 10rpx;" :class="addrType == 1?'selectedAddress':''"
						@click="selected(1)">物流地址</view>
				</view>
				<u-divider style="margin-top: 0rpx;"></u-divider> -->
				<u--form labelPosition="left" :model="formTwo" labelWidth="150rpx">
					<!-- <u-form-item label="省市区" borderBottom @click="filterAll(['addr','addr'])">
						<u-input v-model="formTwo.addr" border="none" placeholder="请选择" suffixIcon="arrow-right"
							disabled disabledColor="#ffffff" />
					</u-form-item> -->
					<u-form-item label="详细地址" borderBottom>
						<u-input v-model="formTwo.detailedAddress" border="none" placeholder="请输入">
							<template slot="suffix">
								<u-button @tap="getMap" type="success" size="mini" icon="map" color="#fd4b09"></u-button>
							</template>
						</u-input>
					</u-form-item>
				</u--form>
				<view style="display: flex;justify-content: space-between;padding-top: 20rpx;">
					<!-- <view style="width: 45%;">
						<u-button text="全部清空" type="warning" @click="confirmEmptying"></u-button>
					</view> -->
					<view style="width: 96%;margin: 0 auto;background-color: red;">
						<u-button text="保存" type="primary" @click="confirmSearch" color="#fd4b09"></u-button>
					</view>
				</view>
			</view>
		</u-popup>
		<u-picker :show="dropDown" ref="uPicker" :defaultIndex="[0,0,0]" :columns="columns" :keyName="keyName"
			@cancel="dropDown = false,mask = false" @confirm="confirm" @change="changeHandler">
		</u-picker>
	</view>
</template>

<script>
	import {
		urbanAreas,
		customerType,
		saveChanges,
		queryDetail,
		removeAddr,
		removeFile
	} from "@/api/views/customer/index.js"
	import http from '@/http/api.js'
	import {
		clientId,
		clientSecret
	} from '@/common/setting'
	export default {
		data() {
			return {
				form: {
					labels: ["", "", "", ""],
					corpsAddrList: []
				},
				customer: false,
				enclosure: false,
				category: false,
				title: "创建供应商",
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#fc0107',
					}
				}],
				formTwo: {},
				mask: false,
				show: false,
				dropDown: false,
				columns: [],
				keyName: "",
				addrType: 0,
				fileList1: [],
				screen: [],
				type: false,
				iNdex: 0
			}
		},
		onLoad(data) {
			if (data.id) {
				uni.setNavigationBarTitle({
					title: '供应商详情'
				})
				this.title = "供应商详情"
				this.query(data.id)
			} else {
				uni.setNavigationBarTitle({
					title: '创建供应商'
				})
				this.title = "创建供应商"
			}
		},
		methods: {
			getMap() {
				let this_ = this
				uni.chooseLocation({
					success: function(res) {
						this_.$set(this_.formTwo, "dimension", res.latitude)
						this_.$set(this_.formTwo, "longitude", res.longitude)
						this_.$set(this_.formTwo, "detailedAddress", res.address)
					}
				});
			},
			change(item, index) {
				this.show = true
				this.mask = true
				this.formTwo = item
				this.iNdex = index
				this.type = true
				// let this_ = this
				// uni.chooseLocation({
				//     success: function (res) {
				// 		this_.$set(this_.form.corpsAddrList[index],"dimension",res.latitude)
				// 		this_.$set(this_.form.corpsAddrList[index],"longitude",res.longitude)
				// 		this_.$set(this_.form.corpsAddrList[index],"detailedAddress",res.address)
				//     }
				// });
			},
			query(id) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				queryDetail({
					id: id
				}).then(res => {
					this.form = res.data
					this.fileList1 = res.data.corpsFiles
					this.form.labels = res.data.labels ? res.data.labels.split(',') : []
					if (this.form.labels.length < 4) {
						for (let item in 4) {
							this.form.labels.push("")
						}
					}
					uni.hideLoading();
				})
			},
			//提交
			submit() {
				if (!this.form.cname) {
					return uni.showToast({
						title: '供应商名称不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.attn) {
					return uni.showToast({
						title: '联系人不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.tel) {
					return uni.showToast({
						title: '电话不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (this.form.corpsAddrList.length == 0) {
					return uni.showToast({
						title: '送货地址不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.corpsTypeId) {
					return uni.showToast({
						title: '供应商类别不能为空',
						icon: 'none',
						mask: true
					});
				}
				let data = {
					...this.form,
					code: this.form.cname,
					corpsFiles: this.fileList1
				}
				data.corpsFiles.forEach(item => delete item.status)
				let this_ = this
				uni.showModal({
					title: '提示',
					content: '是否确认保存',
					success: function(rest) {
						if (rest.confirm == true) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							let labels = []
							for (let item of data.labels) {
								if (item) {
									labels.push(item)
								}
							}
							saveChanges({
								...data,
								corpType: "GYS",
								labels: labels.join(',')
							}).then(res => {
								uni.showToast({
									icon: "none",
									title: '保存成功',
									mask: true
								});
								setTimeout(function() {
									this_.query(res.data.id)
								}, 1000);
								uni.hideLoading();
							})
						}
					}
				})
			},
			newCategory(){
				uni.$u.route('/pages/views/product/customerType',{
					corpType:'GYS'
				});
			},
			//集合筛选条件
			filterAll(screen) {
				this.screen = screen
				switch (screen[1]) {
					case "corpsAddrList":
						this.show = true
						this.mask = true
						break;
					case "corpsTypeId":
						this.mask = true
						customerType({
							corpType: 'GYS',
							parentId: 0
						}).then(res => {
							this.columns = [res.data]
							if (res.data.length > 0) {
								if (res.data[0].hasChildren == true) {
									customerType({
										corpType: 'GYS',
										parentId: res.data[0].id
									}).then(rest => {
										this.columns.push(rest.data)
										this.dropDown = true
										this.keyName = "title"
									})
								} else {
									this.dropDown = true
									this.keyName = "title"
								}

							}
						})
						break;
					case "addr":
						uni.showLoading({
							title: '加载中',
							mask: true
						});
						urbanAreas({
							parentCode: "00"
						}).then(res => {
							this.columns = [res.data]
							urbanAreas({
								parentCode: res.data[0].id
							}).then(rest => {
								this.columns.push(rest.data)
								urbanAreas({
									parentCode: rest.data[0].id
								}).then(resth => {
									this.columns.push(resth.data)
									this.dropDown = true
									this.keyName = "name"
									uni.hideLoading();
								})
							})
						})
						this.show = true
						this.mask = true
						break;
				}
			},
			changeHandler(e) {
				const {
					columnIndex,
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				if (this.screen[1] == "corpsTypeId") {
					if(e.value[e.columnIndex].hasChildren){
						if (e.columnIndex == 0) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							customerType({
								corpType: 'GYS',
								parentId: e.value[e.columnIndex].id
							}).then(res => {
								picker.setColumnValues(1, res.data)
								if (res.data[0].hasChildren == true) {
									customerType({
										corpType: 'GYS',
										parentId: res.data[0].id
									}).then(rest => {
										picker.setColumnValues(2, rest.data)
										uni.hideLoading();
									})
								} else {
									uni.hideLoading();
								}
							})
						}
						if (e.columnIndex == 1) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							customerType({
								corpType: 'GYS',
								parentId: e.value[e.columnIndex].id
							}).then(res => {
								picker.setColumnValues(2, res.data)
								uni.hideLoading();
							})
						}
					}
				}
				if (this.screen[1] == "addr") {
					if (e.columnIndex == 0) {
						uni.showLoading({
							title: '加载中',
							mask: true
						});
						urbanAreas({
							parentCode: e.value[e.columnIndex].id
						}).then(rest => {
							picker.setColumnValues(1, rest.data)
							urbanAreas({
								parentCode: rest.data[0].id
							}).then(resth => {
								picker.setColumnValues(2, resth.data)
								uni.hideLoading();
							})
						})
					}
					if (e.columnIndex == 1) {
						uni.showLoading({
							title: '加载中',
							mask: true
						});
						urbanAreas({
							parentCode: e.value[e.columnIndex].id
						}).then(rest => {
							picker.setColumnValues(2, rest.data)
							uni.hideLoading();
						})
					}
				}
			},
			// 确认选中
			confirm(e) {
				if (this.screen[1] == "addr") {
					this.formTwo.addr = e.value[0].name + e.value[1].name + e.value[2].name
				} else if (this.screen[1] == "corpsTypeId") {
					this.form[this.screen[0]] = e.value[e.values.length-1].title
					this.form[this.screen[1]] = e.value[e.values.length-1].id
				} else {
					this.formTwo[this.screen[0]] = e.value[0].cname
					this.formTwo[this.screen[1]] = e.value[0].id
				}
				this.dropDown = false
				this.mask = false
				this.columns = []
			},
			//删除地址
			address(index) {
				let this_ = this
				uni.showModal({
					title: '提示',
					content: '是否确认删除',
					success: function(rest) {
						if (rest.confirm == true) {
							if (this_.form.corpsAddrList[index].id) {
								uni.showLoading({
									title: '加载中',
									mask: true
								});
								removeAddr({
									ids: this_.form.corpsAddrList[index].id
								}).then(res => {
									this_.form.corpsAddrList.splice(index, 1);
									uni.hideLoading();
								})
							} else {
								this_.form.corpsAddrList.splice(index, 1);
							}
						}
					}
				})
			},
			//切换地址信息
			selected(type) {
				// this.addrType = type
				this.$set(this, 'addrType', type)
				this.formTwo = {}
			},
			//保存地址
			confirmSearch() {
				if (!this.formTwo.detailedAddress) {
					return uni.showToast({
						title: '请输入详细地址',
						icon: 'none',
						mask: true
					});
				}
				if (this.type) {
					this.form.corpsAddrList[this.iNdex] = {
						...this.formTwo,
						type: this.addrType
					}
					this.type = false
				} else {
					this.form.corpsAddrList.push({
						...this.formTwo,
						type: this.addrType
					})
				}
				this.formTwo = {}
				this.addrType = 0
				this.show = false
				this.mask = false
			},
			// 删除图片
			deletePic(event) {
				let this_ = this
				uni.showModal({
					title: '提示',
					content: '是否确认删除',
					success: function(rest) {
						if (rest.confirm == true) {
							if (this_[`fileList${event.name}`][event.index].id) {
								removeFile({
									ids: this_[`fileList${event.name}`][event.index].id
								}).then(res => {
									this_[`fileList${event.name}`].splice(event.index, 1)
								})
							} else {
								this_[`fileList${event.name}`].splice(event.index, 1)
							}
						}
					}
				})
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						sort: this.fileList1.length,
						fileName: JSON.parse(result).data.originalName,
						url: JSON.parse(result).data.link
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: http.config.baseURL +
							'/blade-resource/oss/endpoint/put-file', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							// 供应商端认证参数
							'Authorization': 'Basic ' + Base64.encode(clientId + ':' + clientSecret),
							'Blade-Auth': 'bearer ' + uni.getStorageSync('accessToken')
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data)
							}, 1000)
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.tl-show {
		overflow: hidden;
		position: fixed;
		height: 100%;
		width: 100%;
	}

	::v-deep .u-cell__body {
		padding: 0rpx 25rpx;
		margin: 10rpx 0;
	}

	::v-deep .u-cell__title-text {
		color: #244e96;
	}

	::v-deep .u-form-item__body__left__content__label {
		color: #fd4b09;
	}

	.selectedAddress {
		border-bottom: 1rpx solid #fd4b09;
		color: #fd4b09;
	}
</style>
