<template>
	<view :class="mask ? 'tl-show': ''">
		<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="客户分类" borderBottom
						@click="customerTypeShow = true">
						<u-input border="corpsTypeName" inputAlign="right" disabled placeholder="请选择客户分类"
							 v-model="form.corpsTypeName" disabledColor="#ffffff" />
					</u-form-item>
					
					<u-form-item label="电话" prop="tel" borderBottom>
						<u-input v-model="form.tel" inputAlign="right" border="none" placeholder="请输入电话" />
					</u-form-item>
					<u-form-item label="业务员" borderBottom
						@click="filterAll(['salesmanName','salesmanId'])">
						<u-input border="none" inputAlign="right" disabled placeholder="请选择业务员"
							 v-model="form.salesmanName" disabledColor="#ffffff" />
					</u-form-item>
					<u-form-item label="账期" prop="cname" borderBottom>
						<u-input v-model="form.accountPeriod" inputAlign="right" border="none" 
						placeholder="请输入帐期" />
					</u-form-item>
					
					<u-form-item label="发货仓库" borderBottom 
					@click="filterAll(['deliveryWarehouseName','deliveryWarehouseId'])">
						<u-input border="none" inputAlign="right" disabled placeholder="请选择发货仓库"
							 v-model="form.deliveryWarehouseName" disabledColor="#ffffff" />
					</u-form-item>
					
					<u-form-item label="商城价格" borderBottom
					@click="filterAll(['priceSystem','priceSystem'])">
						<u-input border="none" inputAlign="right" disabled placeholder="请选择商城价格"
							 v-model="form.priceSystem" disabledColor="#ffffff" />
					</u-form-item>
					
					<u-form-item label="信用额度" prop="creditLimit" borderBottom>
						<u-input v-model="form.creditLimit" inputAlign="right" border="none"
						 placeholder="请输入帐期" />
					</u-form-item>
					<u-form-item label="使用信用额度" prop="useCreditLimit" borderBottom >
						<u-input v-model="form.useCreditLimit" inputAlign="right"
						 disabled disabledColor="#fff" border="none" placeholder="请输入帐期" />
					</u-form-item>
					<u-form-item label="备注" prop="cname" borderBottom>
						<u--textarea v-model="form.remarks" border="none" placeholder="请输入备注" ></u--textarea>
					</u-form-item>
					
					<!-- <u-form-item label="送货地址" :borderBottom="false"
						@click="filterAll(['corpsAddrList','corpsAddrList'])">
						({{form.corpsAddrList.length}})
						<u-input border="none" inputAlign="right" suffixIcon="plus-circle" disabled
							disabledColor="#ffffff" />
					</u-form-item> -->
				</view>
			</view>
			
			<u-cell-group :border="false">
				<u-cell :border="false" center title="客户联系人" :arrow-direction="customerContact==false?'up':'down'"
					:value="customerContact==false?'展开':'收起'" :isLink="true" @click="customerContact = !customerContact">
					<view slot="title" class="u-slot-title" style="display: flex; align-items: center;">
						<text style="color: #244e96;width: 150rpx;">客户联系人</text>
						<view style="margin-left: 10rpx; background: #fd4b09;color: #fff;border-radius: 10rpx;padding: 5rpx 10px;" 
						@click.stop="contactsAddfun">
							新增
						</view>
					</view>
				</u-cell>
			</u-cell-group>
			<view style="width: calc(96%);margin: 0 auto;border-radius: 20rpx;"
			 v-if="customerContact">
				<view style="padding: 10rpx 20rpx;margin: 20rpx 0;background-color: #fff;box-sizing: border-box;" 
				v-for="(item,index) in form.corpsAttnList" :key="index">
				<view style="display: flex;align-items: center;justify-content: space-between;font-size: 32rpx;margin: 10rpx 0;">
					<view style="color: #fd4b09;">序号{{index + 1}}</view>
					<view style="margin-left: 10rpx; background: #fd4b09;color: #fff;border-radius: 10rpx;padding: 5rpx 10px;" 
					@click="contactsDelfun('联系人',index,item.id)" >
						删除
					</view>
				</view>
					<u-form-item label="联系人" prop="cname" borderBottom>
						<u-input v-model="item.cname" inputAlign="right" border="none" placeholder="请输入联系人" />
					</u-form-item>
					<u-form-item label="电话" prop="cname" borderBottom>
						<u-input v-model="item.tel" inputAlign="right" border="none" placeholder="请输入电话" />
					</u-form-item>
					<u-form-item label="备注" prop="cname" borderBottom>
						<u--textarea v-model="item.remarks" border="none" placeholder="请输入备注" ></u--textarea>
					</u-form-item>
				</view>
			</view>
			
			<u-cell-group :border="false">
				<u-cell :border="false" center title="地址信息" :arrow-direction="addressInformation==false?'up':'down'"
					:value="addressInformation==false?'展开':'收起'" :isLink="true" @click="addressInformation = !addressInformation">
					<view slot="title" class="u-slot-title" style="display: flex; align-items: center;">
						<text style="color: #244e96;width: 150rpx;">地址信息</text>
						<view style="margin-left: 10rpx; background: #fd4b09;color: #fff;border-radius: 10rpx;padding: 5rpx 10px;" 
						@click.stop="corpsAddrfun">
							新增
						</view>
					</view>
				</u-cell>
			</u-cell-group>
			<view style="width: calc(96%);margin: 0 auto;border-radius: 20rpx;"
			 v-if="addressInformation">
				<view style="padding: 10rpx 20rpx;margin: 20rpx 0;background-color: #fff;box-sizing: border-box;" 
				v-for="(item,index) in form.corpsAddrList" :key="index">
				<view style="display: flex;align-items: center;justify-content: space-between;font-size: 32rpx;margin: 10rpx 0;">
					<view style="color: #fd4b09;">序号{{index + 1}}</view>
					<view style="margin-left: 10rpx; background: #fd4b09;color: #fff;border-radius: 10rpx;padding: 5rpx 10px;" 
					@click="contactsDelfun('地址',index,item.id)" >
						删除
					</view>
				</view>
					<u-form-item label="联系人" prop="cname" borderBottom>
						<u-input v-model="item.contacts" inputAlign="right" border="none" placeholder="请输入联系人" />
					</u-form-item>
					<u-form-item label="电话" prop="cname" borderBottom>
						<u-input v-model="item.tel" inputAlign="right" border="none" placeholder="请输入联系人" />
					</u-form-item>
					<u-form-item label="地址" prop="cname" borderBottom 
					@click="belongtoareafun(index)" >
						<u-input v-model="item.belongtoarea" inputAlign="right" border="none" placeholder="请输入地址" />
					</u-form-item>
					<u-form-item label="详细地址" prop="cname" borderBottom>
						<u--textarea v-model="item.detailedAddress" border="none" placeholder="请输入详细地址" ></u--textarea>
					</u-form-item>
					<u-form-item label="备注" prop="cname" borderBottom>
						<u--textarea v-model="item.remarks" border="none" placeholder="请输入备注" ></u--textarea>
					</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; display: flex;">
				<u-button @click="corpsDescSubmitfun" type="success" color="#fd4b09" shape="circle" text="确认提交"></u-button>
			</view>
		</view>
		
		<!-- 客户分类多级选择 -->
		<u-picker :show="customerTypeShow" ref="customerTypeUPicker" keyName="title"
			:columns="customerTypeColumns" 
			@confirm="customerTypeConfirm" @change="customerTypeChange" @cancel="customerTypeShow = false">
		</u-picker>
		
		<!-- 单列的选择框 -->
		<u-picker :show="pickerShow" :columns="pickerColumns" :keyName="pickerKeyName" 
		@cancel="pickerShow = false" @confirm="pickerConfirm"></u-picker>
		
		<!-- 地址信息多级选择 -->
		<u-picker :show="belongtoareaShow" ref="belongtoareaUPicker" keyName="name"
			:columns="regionSelectData" 
			@confirm="belongtoareaConfirm" @change="belongtoareaChange" @cancel="belongtoareaShow = false">
		</u-picker>
		
		
		<!-- <u-popup :show="DZpopupShow" @close="DZpopupShow = 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-top: 0rpx;"></u-divider>
				<u--form labelPosition="left" :model="formTwo" labelWidth="150rpx">
					<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: 96%;margin: 0 auto;background-color: red;">
						<u-button text="保存" type="primary" @click="confirmSearch" color="#fd4b09"></u-button>
					</view>
				</view>
			</view>
		</u-popup> -->
		
		
	</view>
</template>

<script>
	import {
		customerTypeAllList,
		clientGetUserByRole,
		regionSelectList,
		corpsDescSubmit,
		corpsAttnUpdate
	} from "@/api/views/customer/index.js"
	import { storageDescListAll } from '@/api/OutboundTask/index.js'
	import {corpsDescDetail } from '@/api/views/sale/index.js'
	import { queryBrand } from '@/api/views/stock/index.js'
	
	import http from '@/http/api.js'
	import {corpsDescList} from '@/api/views/sale/salesOrderList.js'
	import {
		clientId,
		clientSecret
	} from '@/common/setting'
	export default {
		data() {
			return {
				// 数据绑定的对象
				form: {
					corpsAttnList:[{}], //客户联系人
					corpsAddrList:[{}] //地址信息
				},
				// 客户分类的数据
				customerTypeAllData:[],
				// 客户分类弹窗的开启
				customerTypeShow:false,
				// 多列弹窗的左侧展示的数据
				customerTypeColumns:[],
				// 多列弹窗的右侧展示的数据
				customerTypeColumnData:[],
				
				// 业务员请求到的数据
				clientGetUserByData:[],
				// 发货仓库请求到的数据
				storageDescData:[],
				// 商品价格接口数据
				queryBrandData:[],
				
				// 地理位置接口数据
				regionSelectData:[],
				// 省市区地理位置弹窗
				belongtoareaShow:false,
				
				// 地址信息当前选择的下标
				corpsAddrIndex:0,
				
				// 单列弹窗的开启和关闭
				pickerShow:false,
				// 单列弹窗的数据
				pickerColumns:[],
				// 弹窗展示的key值
				pickerKeyName:'',
				
				// 客户联系人的展开和收起
				customerContact:true,
				// 地址信息的展开和收起
				addressInformation:true,
				// 图片的展开收起
				enclosure:false,
				// 地址弹窗
				DZpopupShow:false,
				mask:false,
				// 图片集合
				fileList1:[]
				
			}
		},
		onLoad(data) {
			// 客户分类接口
			this.customerTypeAllListfun()
			// 业务员接口
			this.clientGetUserByRolefun()
			// 发货仓库接口
			this.storageDescListAllfun()
			// 商城价格接口
			this.queryBrandfun()
			// 地理位置接口
			this.regionSelectListfun()
			
			if (data.id) {
				uni.setNavigationBarTitle({
					title: '客户详情'
				})
				// 客户详情
				this.corpsDescDetailfun(data.id)
			}
		},
		methods: {
			newCategory(){
				uni.$u.route('/pages/views/product/customerType',{
					corpType:'KH'
				});
			},
			// 客户联系人新增
			contactsAddfun(){
				this.form.corpsAttnList.push({})
			},
			// 客户联系人删除
			corpsAttnUpdatefun(index,id){
				if (id) {
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					corpsAttnUpdate({id:id}).then(res=>{
						this.form.corpsAttnList.splice(index, 1)
						uni.hideLoading();
					})
				}else {
					this.form.corpsAttnList.splice(index, 1)
				}
				uni.showToast({
					title: '删除成功',
					icon: 'none',
					mask: true
				});
			},
			// 联系人删除地址删除
			contactsDelfun(type,index,id){
				uni.showModal({
					title: '提示',
					content: '是否确认删除',
					success: (rest)=> {
						if (rest.confirm == true) {
							if (type == '联系人') {
								this.corpsAttnUpdatefun(index,id)
							}else {
								this.corpsAddrUpdatefun(index,id)
							}
						}
					},
				})
			},
			// 地址信息新增
			corpsAddrfun(){
				this.form.corpsAddrList.push({})
			},
			// 地址信息删除
			corpsAddrUpdatefun(index,id){
				if (id) {
					uni.showLoading({
						title: '加载中',
						mask: true
					});
					corpsAddrUpdate().then(res=>{
						this.form.corpsAddrList.splice(index, 1)
						uni.hideLoading();
					})
				}else {
					this.form.corpsAddrList.splice(index, 1)
				}
				uni.showToast({
					title: '删除成功',
					icon: 'none',
					mask: true
				});
			},
			// 获取客户分类数据
			customerTypeAllListfun(){
				customerTypeAllList({corpType:'KH'}).then(res=>{
					this.customerTypeColumns = [res.data,res.data[0].children || []]
					for(let item of res.data) {
						if (item.children) {
							this.customerTypeColumnData.push(item.children)
						}else {
							this.customerTypeColumnData.push([])
						}
					}
				})
			},
			// 获取业务员数据
			clientGetUserByRolefun(){
				clientGetUserByRole().then(res=>{
					this.clientGetUserByData = res
				})
			},
			// 获取发货仓库数据
			storageDescListAllfun(){
				storageDescListAll().then(res=>{
					this.storageDescData = res.data
				})
			},
			// 获取商品价格
			queryBrandfun(){
				queryBrand({code: 'mall_price'}).then(res=>{
					this.queryBrandData = res.data
				})
			},
			// 获取地理位置
			regionSelectListfun(){
				regionSelectList().then(res=>{
					this.regionSelectData = res.data
				})
			},			
			// 客户分类弹窗分数据
			customerTypeChange(e) {
			    const {
			        columnIndex,
			        value,
			        values, // values为当前变化列的数组内容
			        index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
			        picker = this.$refs.customerTypeUPicker
			    } = e
			    // 当第一列值发生变化时，变化第二列(后一列)对应的选项
			    if (columnIndex === 0) {
			        // picker为选择器this实例，变化第二列对应的选项
			        picker.setColumnValues(1, this.customerTypeColumnData[index])
			    }
			},
			// 客户分类确认按钮事件
			customerTypeConfirm(e) {
				if (e.value[1]) {
					this.form.corpsTypeId = e.value[1].id
					this.form.corpsTypeName = e.value[1].title
				}else {
					this.form.corpsTypeId = e.value[0].id
					this.form.corpsTypeName = e.value[0].title
				}
			    this.customerTypeShow = false
			},
			
			
			// 省市区地理位置弹窗chenge
			belongtoareaChange(e) {
				const {
					columnIndex,
					index,
					value,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.belongtoareaUPicker
				} = e
				if (columnIndex !== 2) {
					regionSelectList({
						parentCode: value[columnIndex].code
					}).then(res => {
						if (columnIndex == 0) {
							picker.setColumnValues(columnIndex + 1, res.data[0])
							picker.setColumnValues(columnIndex + 2, res.data[1])
						} else {
							picker.setColumnValues(columnIndex + 1, res.data[0])
						}
					})
				}
			},
			// 省市区地理位置弹窗确认事件
			belongtoareaConfirm(e){
				console.log(e);
				this.form.corpsAddrList[this.corpsAddrIndex].belongtoarea = `${e.value[0].name},${e.value[1].name},${e.value[2].name}`
				this.belongtoareaShow = false
			},
			belongtoareafun(index){
				this.corpsAddrIndex = index
				this.belongtoareaShow = true
			},
			
			// 详情
			corpsDescDetailfun(id) {
				uni.showLoading({
					title: '加载中',
					mask: true
				});
				corpsDescDetail({
					id: id
				}).then(res => {
					this.form = res.data
					this.fileList1 = res.data.corpsFilesList
					
					for(let item of this.clientGetUserByData) {
						if (item.id == this.form.salesmanId) {
							this.form.salesmanName = item.name
						}
					}
					for(let item of this.storageDescData) {
						if (item.id == this.form.deliveryWarehouseId) {
							this.form.deliveryWarehouseName = item.cname
						}
					}
					
					uni.hideLoading();
				})
			},
			//提交保存
			corpsDescSubmitfun() {
				if (!this.form.cname) {
					return uni.showToast({
						title: '客户名称不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.corpsTypeName) {
					return uni.showToast({
						title: '客户分类不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.salesmanId) {
					return uni.showToast({
						title: '业务员不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.deliveryWarehouseId) {
					return uni.showToast({
						title: '发货仓库不能为空',
						icon: 'none',
						mask: true
					});
				}
				if (!this.form.priceSystem) {
					return uni.showToast({
						title: '商品价格不能为空',
						icon: 'none',
						mask: true
					});
				}
				for(let index in this.form.corpsAttnList) {
					if (!this.form.corpsAttnList[index].cname) {
						return uni.showToast({
							title: `客户联系人序号${Number(index) + 1}联系人不能为空`,
							icon: 'none',
							mask: true
						});
					}
					if (!this.form.corpsAttnList[index].tel) {
						return uni.showToast({
							title: `客户联系人序号${Number(index) + 1}电话不能为空`,
							icon: 'none',
							mask: true
						});
					}
				}
				for(let index in this.form.corpsAddrList) {
					if (!this.form.corpsAddrList[index].contacts) {
						return uni.showToast({
							title: `地址信息序号${Number(index) + 1}联系人不能为空`,
							icon: 'none',
							mask: true
						});
					}
					if (!this.form.corpsAddrList[index].tel) {
						return uni.showToast({
							title: `地址信息序号${Number(index) + 1}电话不能为空`,
							icon: 'none',
							mask: true
						});
					}
					if (!this.form.corpsAddrList[index].belongtoarea) {
						return uni.showToast({
							title: `地址信息序号${Number(index) + 1}地址不能为空`,
							icon: 'none',
							mask: true
						});
					}
					if (!this.form.corpsAddrList[index].detailedAddress) {
						return uni.showToast({
							title: `地址信息序号${Number(index) + 1}详细地址不能为空`,
							icon: 'none',
							mask: true
						});
					}
				}
				uni.showModal({
					title: '提示',
					content: '是否确认保存',
					success: (rest)=> {
						if (rest.confirm == true) {
							uni.showLoading({
								title: '加载中',
								mask: true
							});
							if(!this.form.id) {
							    this.form.checkStatus = '通过'
							}
							corpsDescSubmit({
								...this.form,
								billType: 1,
								code: this.form.cname,
								corpType: "KH",
								corpsFilesList:this.fileList1
							}).then(res => {
								console.log(res,529);
								uni.showToast({
									icon: "none",
									title: '保存成功',
									mask: true
								});
								this.corpsDescDetailfun(res.data.id)
								uni.hideLoading();
							})
						}
					}
				})
			},
			//集合筛选条件 
			// 第一项是 绑定id ,第二项是 绑定的name
			filterAll(screen) {
				this.screen = screen
				switch (screen[1]) {
					case "salesmanId":
						this.pickerColumns = [this.clientGetUserByData]
						this.pickerShow = true,
						this.pickerKeyName = 'name'
						break;
					case "deliveryWarehouseId":
						this.pickerColumns = [this.storageDescData]
						this.pickerShow = true,
						this.pickerKeyName = 'cname'
						break;
					case "priceSystem":
						this.pickerColumns = [this.queryBrandData]
						this.pickerShow = true,
						this.pickerKeyName = 'dictValue'
						break;
				}
			},
			// 弹窗复制
			pickerConfirm(e) {
				switch (this.screen[1]) {
					case "salesmanId":
						this.form.salesmanId = e.value[0].id
						this.form.salesmanName = e.value[0].name
						break;
					case "deliveryWarehouseId":
						this.form.deliveryWarehouseId = e.value[0].id
						this.form.deliveryWarehouseName = e.value[0].cname
						break;
					case "priceSystem":
						this.form.priceSystem = e.value[0].dictValue
						break;
				}
				this.pickerShow = 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>
