<template>
	<view class="apply-wrap flex flex_column">
		<view class="login-form">
			<u-form :model="form" label-width="180rpx" :error-type="['toast']" ref="uForm">
				<u-form-item label="门头照片" required prop="storeImage">
					<u-upload 
					@on-success="uploadStorePhoto" 
					@on-remove="removeStorePhoto" 
					:file-list="storePhotoList" 
					:action="action" 
					:max-size="2 * 1024 * 1024" 
					:width="200"
					:height="150"
					upload-text="上传门头照片"
					max-count="1"></u-upload>
				</u-form-item>
				<u-form-item label="营业执照">
					<u-upload
					@on-success="uploadYyzzPhoto" 
					@on-remove="removeYyzzPhoto" 
					:file-list="yyzzPhotoList" 
					:action="action" 
					:max-size="2 * 1024 * 1024" 
					:width="200"
					:height="150"
					upload-text="上传营业执照"
					max-count="1"></u-upload>
				</u-form-item>
				<u-form-item label="门店名称" required prop="storeName">
					<u-input v-model="form.storeName" :maxlength="30" placeholder="请输入门店名称(最多30个字符)"/>
				</u-form-item>
				<u-form-item label="所在地区" required prop="label">
					<u-input v-model="form.label" placeholder="请选择省市区" :disabled="true" @click="openAddress"/>
					<Address ref="applyAddress" :isJrMini="true" @onConfirm="areaConfirm"></Address>
				</u-form-item>
				<u-form-item label="详细地址" required prop="addrDetail">
					<u-input v-model="form.addrDetail" :maxlength="100" placeholder="请输入详细地址(最多100个字符)"/>
				</u-form-item>
				<u-form-item label="联系人姓名" required prop="contactName">
					<u-input v-model="form.contactName" :maxlength="20" placeholder="请输入联系人姓名(最多20个字符)"/>
				</u-form-item>
				<u-form-item label="联系人手机">
					{{form.contactPhone}}
				</u-form-item>
				<u-form-item label="关联客户" required prop="customerSn">
					<u-input v-model="form.customerName" type="select" placeholder="请输入选择关联客户" @click="chooseCustome" />
				</u-form-item>
				<u-form-item label="结算方式" required prop="settleType">
					<u-input v-model="form.settleTypeDictValue" placeholder="请输入选择结算方式" type="select" @click="settleStyleModal = true" />
					<u-picker v-model="settleStyleModal" @confirm="settleStyleChange" :range="settleStyleList" range-key="dispName" mode="selector"></u-picker>
				</u-form-item>
				<u-form-item label="授信金额" v-if="form.settleType == 'CREDIT'" required prop="creditLimit">
					<u-input :clearable="false" type="digit" :min="100" :maxlength="8" @blur="numberToFixed('creditLimit',2,999999)" v-model.trim="form.creditLimit" placeholder="请输入大于100的数字，最多两位小数"/>
				</u-form-item>
			</u-form>
		</view>
		<view class="form-btn-con flex justify_center">
			<u-button class="form-btn" shape="circle" :loading="loading" type="info" :custom-style="{ background: '#066cff', color: '#fff',width:'350rpx' }" @click="formSubmit">审核通过</u-button>
		</view>
	</view>
</template>

<script>
	import Address from '@/components/address.vue'
	import { xprhStoreApplyDetail, xprhStoreApplyAudit } from '@/api/approveStore'
	import { clzConfirm, numberToFixed } from '@/libs/tools';
	const baseUrl = getApp().globalData.baseUrl
	export default{
		components: {
			Address,
		},
		data(){
			return{
				loading: false,
				theme: '',
				form: {
					storeName: '', // 门店名称
					contactPhone: '', //  联系手机
					contactName: '', //  联系人
					label: '',
					addrProvince: undefined, //  省
					addrProvinceName: '',
					addrCity: undefined, // 市
					addrCityName: '',
					addrDistrict: undefined, // 区
					addrDistrictName: '',
					addrDetail: '', //  详细地址
					storeImage: '', // 门头照片
					licenseImage: '', // 营业执照
					settleType: undefined, //  结算方式
					settleTypeDictValue: undefined,
					customerSn: undefined, //  关联客户
					customerName: undefined,
					creditLimit: '', //  授信额度
					delearSn: undefined,
					applySn: undefined,
					auditStatus: 'PASS' // 通过
				},
				rules: {
					storeImage:[{ required: true, message: '请选择门头照片', trigger: 'change' }],
					storeName: [{ required: true, message: '请输入门店名称', trigger: 'change' }],
					contactMobile: [{ required: false, pattern: /^\d{30}$/, message: '请输入正确的手机号', trigger: 'change' }],
					label: [{ required: true, message: '请选择地区', trigger: 'change' }],
					addrDetail: [{ required: true, message: '请输入详细地址', trigger: 'change' }],
					contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'change' }],
					settleType: [{ required: true, message: '请选择收结算方式', trigger: 'change' }],
					customerSn: [{ required: true, message: '请选择关联客户', trigger: 'change' }],
					// creditLimit: [{ required: true, message: '请输入授信金额', trigger: 'change' }],
				},
				areaIdArr: [],  //  省市区id数组
				labelArr: [],
				action: baseUrl + 'upload',
				storePhotoList: [],
				yyzzPhotoList: [],
				settleStyleModal: false,
				settleStyleList: []
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			const _this = this
			this.applySn = options.sn
			this.getDetail()
			this.settleStyleList = this.$store.state.vuex_shelfSettleType
			
			// 选择关联客户
			uni.$on("addCustome",function(data){
				_this.form.customerSn = data.customerSn
				_this.form.customerName = data.customerName
			})
		},
		onUnload() {
			uni.$off("addCustome")
		},
		methods: {
			// 小数点后两位
			numberToFixed: function (key, num, max) {
				let val = this.form[key]
				let ret = numberToFixed(val, num, max)
				this.$nextTick(() => {
					this.form[key] = ret < 100 ? 100 : ret
				})
			},
			//  获取详细
			getDetail () {
			  xprhStoreApplyDetail({ sn: this.applySn }).then(res => {
			    if (res.status == 200) {
			      this.form = Object.assign(this.form, res.data)
			      this.storePhotoList = this.form.storeImage ? [{url:this.form.storeImage}] : []
			      this.yyzzPhotoList = this.form.licenseImage ? [{url:this.form.licenseImage}] : [],
				  this.form.addrDetail = this.form.addrDetail || ''
				  if(this.form.addrProvinceName&&this.form.addrCityName&&this.form.addrDistrictName){
					  this.labelArr = [this.form.addrProvinceName,this.form.addrCityName,this.form.addrDistrictName]
					  this.areaIdArr = [this.form.addrProvince,this.form.addrCity,this.form.addrDistrict]
					  this.form.label = this.labelArr.join('-')
				  }else{
					  this.labelArr = []
					  this.areaIdArr = []
					  this.form.label = ''
				  }
			      this.form.auditStatus = 'PASS' // 通过
			    } else {
			      this.$refs.ruleForm.resetFields()
			    }
			  })
			},
			// 上传门店图片成功
			uploadStorePhoto(res){
				this.form.storeImage = res.data
			},
			// 删除门店图片
			removeStorePhoto(index){
				this.form.storeImage = ''
			},
			// 上传营业执照图片成功
			uploadYyzzPhoto(res){
				this.form.licenseImage = res.data
			},
			// 删除营业执照图片
			removeYyzzPhoto(index){
				this.form.licenseImage = ''
			},
			// 收款方式  change
			settleStyleChange(ind){
				this.form.settleType = this.settleStyleList[ind].code || undefined
				this.form.settleTypeDictValue = this.settleStyleList[ind].dispName || undefined
				this.form.creditLimit = ''
			},
			// 选择关联客户
			chooseCustome(){
				uni.navigateTo({
					url: "/pages/sales/chooseCustomer?backPage=authPass"
				})
			},
			//  表单提交
			formSubmit(){
				const _this = this
				this.$refs.uForm.validate(valid => {
					if (valid) {
						if((_this.form.creditLimit >= 100 && _this.form.settleType == 'CREDIT') || _this.form.settleType !== 'CREDIT'){
							clzConfirm({
							  title: '提示',
							  content: '审核通过后，即可成为认证门店,确认审核通过吗？',
							  success: function(res) {
							  	if (res.confirm || res.index == 0) {
								  _this.submitData()
							  	}
							  }
							})
						}else{
							uni.showToast({
								icon: 'none',
								title: '请输入授信金额'
							})
						}
					} else {
						console.log('验证失败');
					}
				});
			},
			submitData(){
				let obj = this.form
				obj.addrProvince = this.areaIdArr[0]  //  省id
				obj.addrCity = this.areaIdArr[1]  //  市id
				obj.addrDistrict = this.areaIdArr[2]  //  区id
				obj.addrProvinceName = this.labelArr[0]  //  省
				obj.addrCityName = this.labelArr[1]  //  市
				obj.addrDistrictName = this.labelArr[2]  //  区
				this.loading = true
				//  申请试用
				xprhStoreApplyAudit(obj).then(res => {
					console.log(res)
					if(res.status == 200){
						 uni.navigateBack()
						 uni.$emit("updateAuthState")
					}
					uni.showToast({icon: 'none',title: res.message})
					this.loading = false
				})
			},
			//  选择省区市
			areaConfirm(e) {
				console.log('已选择的省市区', e)
				this.labelArr = e.labelArr
				this.areaIdArr = [ e.provinceCode, e.cityCode, e.areaCode ]
				this.form.label = e.label
			},
			openAddress(){
				//  省市区  回显     参数为省市区id数组
				this.$refs.applyAddress.open(this.areaIdArr)
			},
		}
	}
</script>
<style scoped lang="scss">
	.apply-wrap{
		width:100%;
		height: 100vh;
		background-color: #fff;
		.login-form{
			padding: 0.7rem 1.5rem;
			flex-grow: 1;
			overflow: auto;
		}
		.form-btn-con{
			padding: 1rem;
		}
	}
</style>
