<template>
	<view>
		<!-- tabs栏 -->
		<view class=" mart10 marb20 alijus" v-if="showItem">
			<view class="font16 fcor333 paddtop5 paddbotm5  margle20  marRight20"
				v-for="(item,index) in listData" @click="switchid(index)"
				:class="[showItem.platformType == item.platformType ? 'fcor089 borbtom fontwig6' : ' borb ']"
				:key="index">
				{{item.platformTypeName}}
			</view>
		</view>
		<template v-if="showItem&&showItem.platformPeriod">
			<view class="marb20 fotct pd-main font15" :class="{'fcorred':showItem.platformPeriod.status==3,'green':showItem.platformPeriod.status==1,'yellow':showItem.platformPeriod.status==2}"  >
				{{showItem.platformPeriod | filterStatus}}
			</view>
		</template>
		<view class="width100 line1"></view>


		<view class="form-gorup  backcorfff font15" style="padding-bottom: 60px;" v-if="showItem">

			<!-- 开通银联分期 -->
			<view class="dis-flex pd-main bor-botm1 flex-sp">
				<view class="  fontwig6   flex-s0">开通银联分期:
				</view>
				<switch disabled :checked="periodData.openUnionpay" @change="switch1Change" />
			</view>
			
			<!-- 注册资本 -->
			<view class="dis-flex pd-main bor-botm1 flex-sp">
				<view class="  fontwig6   flex-s0">注册资本:
				</view>
				<input type="text" class=" flex-1 fotrt"  v-model.trim="periodData.authCapital" placeholder-class="corf6 font15 fotrt"
					 placeholder="请输入注册资本">
			</view>
			
			<!-- 银联贴息方式，可多选 -->
			<view class=" pd-main bor-botm1 ">
				<view class=" fontwig6 marb10 ">银联贴息方式(可多选):
				</view>
				<!-- <checkbox-group @change="checkBoxChange">
					<view class="dis-flex flex-sp flex-wrap">
						<label v-for="(item,index) in unionpayFeePaidList" class=" marb5">
							<checkbox :value="item.id+''" :checked="item.isSelect" :disabled="!isShowMethodToUpdate" />{{item.name}}
						</label>
					</view>
				</checkbox-group> -->
				
				<radio-group @change="checkBoxChange">
					<view class="dis-flex flex-sp flex-wrap ">
						<label v-for="(item,index) in unionpayFeePaidList" class="marb5">
							<radio :value="item.id+''" :checked="item.isSelect" />{{item.name}}
						</label>
					</view>
				</radio-group>
				
			</view>
			<!-- 银联分期费率 -->
			<view class=" pd-main bor-botm1 ">
				<view class=" fontwig6 marb10 ">银联分期费率(1类银行):<text class="fn">范围(0~1)最多保留3位小数</text>
				</view>
				<view class="dis-flex flex-center marb10" v-for="(item,index) in periodData.unionpayRate1" :key="index">
					<view class="paddtright10">{{item.periodNum}}期</view>
					<input class="rate" type="digit"  v-model.trim="item.rate" :disabled="!isShowMethodToUpdate" placeholder-class="corf6 font15" 
						placeholder="请输入费率">
					<!-- <view v-else class="corf6 font15 rate">{{item.rate}}</view> -->
				</view>
			</view>
			<view class=" pd-main bor-botm1 ">
				<view class=" fontwig6 marb10 ">银联分期费率(2类银行):<text class="fn ">范围(0~1)最多保留3位小数</text>
				</view>
				<view class="dis-flex flex-center marb10" v-for="(item,index) in periodData.unionpayRate2" :key="index">
					<view class=" paddtright10">{{item.periodNum}}期</view>
					
					<input class="rate" type="digit"  v-model.trim="item.rate" :disabled="!isShowMethodToUpdate" placeholder-class="corf6 font15" 
						placeholder="请输入费率">
					<!-- <view v-else class="corf6 font15 rate">{{item.rate}}</view> -->
				</view>
			</view>

			<!-- 协议图片 -->
			<view class=" pd-main bor-botm1 ">
				<view class="dis-flex">
					<view class=" fontwig6 marb10 ">协议照片:</view>
					<!-- <view class="flex-1">
						<view class="dis-flex flex-center"><image class="iconw40 height40p marRight10" mode="aspectFill" v-for="(item,index) in imgExampleValue" :key="index" :src="imgUrl+item" @click="previewImage(index,imgExampleValue)"></image></view>
						<view class="corf6 font13 fotct">(示例照片)</view>
					</view> -->
				</view>
				
				<view class="imageUploadContainer flex-1">
					<view class="imageUploadList">
						<template v-if="periodData.agreementPics!=''">
							<view class="imageItem" v-for="(item,index) in imgValue" :key="index">
								<image :src="imgUrl+item" mode="aspectFill" @click="previewImage(index,imgValue)"
									:data-index="index"></image>
								<view v-if="isShowMethodToUpdate" class="imageDel" @click="deleteImage(item)">x</view>
							</view>
						</template>
						<view  v-if="isShowMethodToUpdate" class="imageUpload" @click="upload">+</view>
					</view>
				</view>
			</view>





			<view class="footer-btn" v-if="isShowMethodToUpdate" >
				<button class="backcor89 fcorfff" @click="apply">保存</button>
			</view>
		</view>


	</view>
</template>

<script>
	import {
		getDictionaryByCodeType,
		apply,
		getMerPlatformPeriodDetail,

		updateFeePaid,
	} from '@/Utils/Api.js';

	let app = getApp();
	export default {
		data() {
			return {
				reqUrl: app.globalData.url, //请求地址
				imgUrl: app.globalData.imgUrl, //图片访问地址
				merNo: '', //商户号
				platformPeriodIndex: 0,//平台类型下标
				listData:[],
				showItem:null,

				periodData: {
					merNo: '', //商户号
					platformPeriodType: '', //平台类型   1：零零购
					openUnionpay: true, //开通银联分期 true：是 false：否
					unionpayFeePaid: '', // 银联贴息方式 ‘1,2,3’
					unionpayRate1: [], //银联分期费率（1类银行）
					unionpayRate2: [], //银联分期费率（2类银行）
					agreementPics: '', // 协议照片（多张）
					authCapital:'',//注册资本
				},
				periodNumList:[],//分期数列表
				
				
				unionpayFeePaidList: [ //支持多选
					{
						id: 1,
						name: '商户贴息',
						isSelect: false
					},
					{
						id: 2,
						name: '用户贴息',
						isSelect: false
					},
					{
						id: 3,
						name: '商户用户各一半',
						isSelect: false
					},
				],
				imgValue: [], //协议照片
				imgExampleValue: ["/merchant/62/1694595101306.jpeg", "/merchant/62/1694595101306.jpeg"], //协议示例照片

			}
		},
		onLoad(option) {
			this.merNo = option.merNo;
			this.periodData.merNo = option.merNo;

			this.getDictionaryByCodeType(); //查询分期树

		},
		computed:{
			/* 是否展示提供修改的按钮 */
			isShowMethodToUpdate(){
				if(this.showItem){
					return !this.showItem.platformPeriod||(this.showItem.platformPeriod&&this.showItem.platformPeriod.status==3)
				}else{
					return false
				}
				
			},
		},
		filters:{
			/* 状态 0：不可用  1：正常  2： 审核中   3：审核驳回 */
			filterStatus(type){
				switch (type.status) {
					case 1:
						return '正常';
					case 2:
						return '审核中';
					case 3:
						return '审核驳回:'+type.suggestionReject;
					default:
						return '未知';
				}
			},
			
		},
		methods: {
			/* 平台类型change切换 */
			switchid(index) {
				this.platformPeriodIndex = index;
				this.showItem = this.listData[this.platformPeriodIndex];
				this.periodData.platformPeriodType = this.showItem.platformType;
				
				if(this.showItem.platformPeriod){
					this.periodData.openUnionpay = this.showItem.platformPeriod.openUnionpay;
					this.periodData.unionpayFeePaid = this.showItem.platformPeriod.unionpayFeePaid;
					this.periodData.unionpayRate1 =this.handleUnionpayRate(this.showItem.unionpayRate1);
					this.periodData.unionpayRate2 = this.handleUnionpayRate(this.showItem.unionpayRate2);
					this.periodData.agreementPics = this.showItem.platformPeriod.agreementPics;
					this.periodData.authCapital = this.showItem.platformPeriod.authCapital;
					this.imgValue =this.periodData.agreementPics.split(',');
				}else{
					this.periodData.openUnionpay = true;
					this.periodData.unionpayFeePaid = "";
					this.periodData.unionpayRate1 = this.handleUnionpayRate(this.periodNumList);
					this.periodData.unionpayRate2 =this.handleUnionpayRate(this.periodNumList);
					this.periodData.agreementPics =  "";
					this.periodData.authCapital ="";
					this.imgValue =[];
				}
					
					
				
				this.unionpayFeePaidList.forEach(item => {
					item.isSelect = false;
					if(this.periodData.unionpayFeePaid==item.id){
						item.isSelect = true;
					}
				})
				
			},
			handleUnionpayRate(arr){
				let result = arr.map((item)=>{
					let rate =  item.rate===''? '' : item.rate ;
					return {"periodNum": item.periodNum,"rate":rate};
				})
				return result
			},
			/* 开通银联分期切换 */
			switch1Change(e) {
				this.periodData.openUnionpay = e.detail.value;
				
			},

			/* 贴息方式change */
			checkBoxChange(e) {
				
				console.log(e.detail.value)
				
				this.periodData.unionpayFeePaid = e.detail.value;
				
				// let selectArr = e.detail.value;
				// this.periodData.unionpayFeePaid = selectArr.join(',');
			},
			/* 点击申请分期 */
			apply() {
				if (!this.isVertify()) return;			
				
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				apply(this.periodData).then(res => {
					uni.hideLoading();
					if (res.return_code == '000000') {
						uni.showToast({
							title: res.return_data,
							duration: 2000,
							icon: 'none'
						})
						this.getMerPlatformPeriodDetail(false)
					} else {
						uni.showToast({
							title: res.return_msg,
							duration: 2000,
							icon: 'none'
						})
					}
				})


			},
			isVertify() {
				if (this.periodData.platformPeriodType === '') {
					uni.showToast({
						title: '请选择平台类型',
						icon: 'none'
					})
					return false
				}
				if (this.periodData.unionpayFeePaid === '') {
					uni.showToast({
						title: '请选择银联贴息方式',
						icon: 'none'
					})
					return false
				}
				
				if(this.periodData.authCapital == ''){
					uni.showToast({
						title: '请输入注册资本',
						icon: 'none'
					})
					return false
				}
				
				
				
				// var reg = /^(([0-9]|[1][0-9])([.][0-9]{1,2})|([0-9]|1[0-9]|20))$/;
				/*  0-1:最多保留三位小数 */
				let reg = /^((0+(\.\d{0,3})?)|1(\.0{0,3})?)$/;

				let unionpayRate1Bool = this.periodData.unionpayRate1.every((item) => {
					if (!reg.test(item.rate)) {
						item.rate = ''
					}
					return reg.test(item.rate)
				})
				let unionpayRate2Bool = this.periodData.unionpayRate2.every((item) => {

					if (!reg.test(item.rate)) {
						item.rate = ''
					}

					return reg.test(item.rate)
				})
				if (!unionpayRate1Bool) {
					uni.showToast({
						title: '银联分期费率(1类银行)费率未填写完整',
						icon: 'none'
					})
					return false
				}
				if (!unionpayRate2Bool) {
					uni.showToast({
						title: '银联分期费率(2类银行)费率未填写完整',
						icon: 'none'
					})
					return false
				}

				if (this.imgValue.length == 0) {
					uni.showToast({
						title: '请上传协议照片',
						icon: 'none'
					})
					return false
				} else {
					this.periodData.agreementPics = this.imgValue.join(",");
				}

				return true;
			},

			/* 查询分期详情 */
			getMerPlatformPeriodDetail(bool=true) {
				let params = {
					merNo: this.merNo
				}
				if(bool){
					uni.showLoading({
						title: '加载中',
						mask: true
					})
				}
				

				getMerPlatformPeriodDetail(params).then(res => {
					if(bool){
						uni.hideLoading();
					}
					
					if (res.return_code == '000000') {
	
						this.listData = res.return_data;
						if(this.listData.length>0){
							this.switchid(this.platformPeriodIndex);
						}
						
					} else {
						uni.showToast({
							title: res.return_msg,
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},
			
			/* 查询分期数 */
			getDictionaryByCodeType() {
				let params = {
					codeType: 'PERIOD_NUMBER'
				}
				getDictionaryByCodeType(params).then(res => {
					if (res.return_code == '000000') {
						res.return_data.sort((item1, item2) => {
							return item1.codeValue - item2.codeValue
						})	
						//分期列表
						this.periodNumList = res.return_data.map(item=>{
							return {"periodNum": item.codeValue,"rate": ""};
						});
						
						this.getMerPlatformPeriodDetail(); //查询分期详情

					} else {
						uni.showToast({
							title: res.return_msg,
							duration: 2000,
							icon: 'none'
						})
					}
				})
			},

			//上传图片
			upload() {
				let that = this;
				uni.chooseImage({
					count: 1,
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'],
					success: function(res) {
						const tempFilePaths = res.tempFilePaths;
						that.uploadFile(tempFilePaths[0]);
					},
					error: function(e) {
						console.log(e);
					}
				});
			},
			//上传
			uploadFile(imgURL) {
				const that = this;
				uni.showLoading({
					title: "加载中...",
					mask: true,
				})
				uni.uploadFile({
					url: that.reqUrl + '/fileUpload/uploadfile',
					filePath: imgURL,
					header: {
						"Authorization": app.globalData.token
					},
					name: 'files',
					success: function(uploadFileRes) {
						uni.hideLoading()
						that.getImgSignedUrl(JSON.parse(uploadFileRes.data).return_data[0]);
					},
					fail: function(err) {
						uni.hideLoading()
						uni.showToast({
							title: err,
							icon: 'none'
						})
					}
				});
			},
			//查看临时图片路径
			getImgSignedUrl(item1) {
				this.imgValue.push(item1);
			},
			// 删除图片
			deleteImage(data) {
				let arr = this.imgValue.filter((item) => item != data);
				this.imgValue = arr;
			},
			// 预览
			previewImage(index,list) {
				let arr = list.map(item=>{
					return this.imgUrl+item
				})
				uni.previewImage({
					current: index,
					indicator: "number",
					loop: "true",
					urls:arr
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	
	.yellow{
		color:#f3a73f;
	}
	.green{
		color: #18bc37;
	}
	
	.borbtom {
		border-bottom: 3px solid #089bf5;
	}

	.borb {
		border-bottom: 3px solid transparent;
	}

	i {
		border: solid #000000;
		border-width: 0 2px 2px 0;
		display: inline-block;
		padding: 4px;
		margin-left: 10px;
		vertical-align: 3px;
	}

	.fn {
		font-weight: normal;
		font-size: 12px;
		color: #3c3c3c;
	}

	.down {
		-webkit-transform: rotate(45deg);
	}

	/* 表单 */
	.form-gorup {
		padding: 20rpx;
		margin-bottom: 20rpx;
		border-radius: 20rpx;

		.rate {
			height: 20px;
			line-height: 20px;
			border-radius: 10px;
			border: 1px solid #089bf5;
			padding: 5px 5px;
			width:50%;
		}
		
	}

	.flex-wrap {
		flex-wrap: wrap;
	}

	/* 底部按钮 */
	.footer-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 99;
		display: flex;
		justify-content: center;
		align-items: center;

		button {
			margin: 0 20px;
			border-radius: 25px;
			flex: 1;
			height: 50px;
			line-height: 50px;
		}
	}


	/* 上传图片 */
	/* 图片 */
	.imageUploadContainer {
		padding: 10upx 5upx;
		margin: 10upx 5upx;
	}


	.imageUploadList {
		display: flex;
		flex-wrap: wrap;
	}

	.imageItem,
	.imageUpload {
		width: 200upx;
		height: 200upx;
		margin: 30upx 15upx 30upx;
	}

	.imageDel {
		position: relative;
		left: 180upx;
		bottom: 225upx;
		background-color: rgba(0, 0, 0, 0.5);
		width: 36upx;
		text-align: center;
		line-height: 35upx;
		border-radius: 17upx;
		color: white;
		font-size: 30upx;
		padding-bottom: 2upx;
	}

	.imageItem image {
		width: 200upx;
		height: 200upx;
		border-radius: 8upx;
	}

	.imageUpload {
		line-height: 200upx;
		text-align: center;
		font-size: 150upx;
		color: #D9D9D9;
		border: 1px solid #D9D9D9;
		border-radius: 8upx;
	}
</style>