<template>
	<div class="global-width">
		<div class="container">
			<!--当前位置-->
			<div class="hc-breadcrumb">
				<router-link to="/currency/trade" class="otc-index-btn">{{$t('交易大厅')}}</router-link>
				<router-link to="/currency/release" class="otc-index-btn hc-btn-active">{{$t('发布广告')}}</router-link>
				<router-link to="/order/currency" class="otc-index-btn">{{$t('订单管理')}}</router-link>
			</div>

			<div class="hc-breadcrumb trade-center-top">
				<span>{{$t('发布广告详情')}}</span>

				<div class="order-top-div2 margin-t0">
					<span class="hc-color4" @click="$router.push('/currency/ads')">{{$t('我的广告')}}</span>
				</div>
			</div>

			<div class="trade-detail-warp release-box">
				<!--左边-->
				<div class="trade-detail-left">
					<router-link to="/" class="trade-detail-left-div1">
						<div class="trade-detail-left-top">
							<img class="trade-detail-left-headimg" :src="dealerInfo.avatar" v-if="dealerInfo.avatar">
							<img class="trade-detail-left-headimg" src="../../assets/images/user-head-img.png" v-else>
						</div>
						
						<div class="trade-detail-left-top">
							<div class="trade-detail-left-nickname">{{dealerInfo.username || $t('暂无昵称')}}</div>
							
							<div class="merchants-tag">
								<img src="../../assets/images/trade/icon-authentication.png">
								<span class="hc-color">{{$t('认证商家')}}</span>
							</div>
						</div>
					</router-link>

					<div class="trade-detail-left-div2">
						<div class="trade-detail-left-div3">
							<div class="hc-color">{{$t('总成单')}}</div>
							<div class="div2-d1">{{dealerInfo.sumOfFinishedFlow || 0}}</div>
						</div>

						<div class="trade-detail-left-div4">
							<div class="hc-color">{{$t('完成率')}}</div>
							<div class="div2-d1">{{dealerInfo.finishedRate || 0}}%</div>
						</div>

						<!-- <div class="trade-detail-left-div5">
							<div class="hc-color">{{$t('30日成单')}}</div>
							<div class="div2-d1">{{dealerInfo.numberOf30DayFinishedFlow || 0}}</div>
						</div> -->
						
						<div class="trade-detail-left-div5">
							<div class="hc-color">{{$t('平均放行')}}</div>
							<div class="div2-d1">{{dealerInfo.avgReleaseMinus || 0}} {{$t('分钟')}}</div>
						</div>
					</div>

					<div class="trade-detail-explain">
						<h3>{{$t('广告说明')}}:</h3>
						<p class="hc-color">{{$t('1.订单有效期为15分钟，请您及时在有效期内付款并点击「标记付款已完成」按钮，我才可以释放数字币给您。')}}</p>
						<p class="hc-color">{{$t('2.开始交易后数字币由系统锁定托管，请安心下单。')}}</p>
					</div>
				</div>

				<!-- 右边 -->
				<div class="trade-detail-right">
					<div class="tab-title">
						<ul>
							<li :class="{'active': dealType}" @click="dealType = 1">
								<span>{{$t('我要买')}}</span>
							</li>
							<li :class="{'active': !dealType}" @click="dealType = 0">
								<span>{{$t('我要卖')}}</span>
							</li>
						</ul>
					</div>

					<div class="tab-container">
						<div class="choose-currency">
							<ul>
								<li class="active">
									<!-- <span :class="[{'buy-currency': dealType}, {'sell-currency': !dealType}]">{{currentCoin}}</span> -->
									<el-cascader v-model="currentCoin" :options="options" @change="handleChange"></el-cascader>
								</li>
								<li class="limit">{{$t('限额')}} ¥{{limitMin}}~¥{{limitMax}}</li>
							</ul>
						</div>
						
						<div class="top-price">
							<span>
								{{$t('当前单价')}}（CNY）: {{price}}
								<div class="question-box">
									<img class="fa-question" src="../../assets/images/icon-question.png">
									
									<div class="free-explanation free-explanation2">
										<p>{{$t('当前单价会因市场波动而改变，实际单价请以下单后的锁定单价为准')}}</p>
									</div>
								</div>
							</span>
							
							<div class="top-price-r hc-color1" v-if="dealType">{{$t('您需要支付手续费，交易手续费按')}}{{buyFee}}%{{$t('收取！')}}</div>
							<div class="top-price-r hc-color1" v-else>{{$t('您需要支付手续费，交易手续费按')}}{{sellFee}}%{{$t('收取！')}}</div>
						</div>

						<div class="form-box">
							<div class="form-group">
								<div class="address-form-div2">
									<label class="form-label">{{dealTypeText}}{{$t('金额')}}</label>
									
									<div class="form-control release-form">
										<el-input class="text-input" :placeholder="$t('请输入金额')" v-model="totalPrice" type="text" clearable autocomplete="off" @input="setPrice" @keyup.enter.native="openPassword">
										</el-input>
										<div class="form-control-company">CNY</div>
									</div>
								</div>
								
								<div class="address-form-div3">
									<img src="../../assets/images/trade/icon-equal.png">
								</div>
								
								<div class="address-form-div2">
									<label class="form-label">{{dealTypeText}}{{$t('数量')}}</label>
									
									<div class="form-control release-form">
										<el-input class="text-input" :placeholder="$t('请输入数量')" v-model="quantity" type="text" clearable autocomplete="off" @input="setQuantity" @keyup.enter.native="openPassword">
										</el-input>
										<div class="form-control-company">{{currentCoin}}</div>
									</div>
								</div>
							</div>
							
							<div class="form-group">
								<div class="address-form-div2">
									<label class="form-label">{{$t('最小限额')}}</label>
									
									<div class="form-control release-form">
										<el-input class="text-input" :placeholder="$t('请输入最小限额')" v-model="minPrice" type="text" clearable autocomplete="off" @keyup.enter.native="openPassword">
										</el-input>
										<div class="form-control-company">CNY</div>
									</div>
								</div>
								
								<div class="address-form-div2" style="float: right;">
									<label class="form-label">{{$t('设置单价')}}</label>
									
									<div class="form-control release-form">
										<el-input class="text-input" :placeholder="$t('请输入单价')" v-model="price" type="text" clearable autocomplete="off" @keyup.enter.native="openPassword">
										</el-input>
										<div class="form-control-company">CNY</div>
									</div>
								</div>
							</div>
							
							<div class="form-group">
								<div class="address-form-div2">
									<label class="form-label">{{$t('付款方式')}}</label>
									
									<div class="form-control">
										<div class="buy-payment">
											<div class="buy-payment-choose" :class="{'active': alipay}" v-if="hasAlipay">
												<span @click="alipay = !alipay">{{$t('支付宝')}}</span>
											</div>
											<div class="buy-payment-choose" :class="{'active': weixinpay}" v-if="hasWeixin">
												<span @click="weixinpay = !weixinpay">{{$t('微信')}}</span>
											</div>
											<div class="buy-payment-choose" :class="{'active': unionpay}" v-if="hasUnionpay">
												<span @click="unionpay = !unionpay">{{$t('银行卡')}}</span>
											</div>
											<span class="buy-payment-tips" v-if="hasPayment">
												{{$t('您还未添加收款方式')}}
												<router-link to="/user/setting">{{$t('去设置')}}</router-link>
											</span>
										</div>
									</div>
								</div>
							</div>
							
							<div class="form-group">
								<div class="address-form-div2" @click="openPassword">
									<el-button type="primary" :loading="true" v-if="loading">{{$t('提交中...')}}</el-button>
									<el-button type="primary" v-else>{{$t('立即发布')}}</el-button>
								</div>
							</div>
						</div>
					</div>

					<div class="trade-detail-right-tips">
						<h3>{{$t('当前数字货币价格为系统自动计算，实际交易价格以发起交易时的价格为准，请点击查看关于')}} <span>{{$t('浮动价格的说明')}}</span>。</h3>
						<p>1. {{$t('交易发起前，请您确认已阅读并同意卖家提出的条款，并再次确认交易内容无误后，再点击购买按钮。')}}</p>
						<p>2. {{$t('交易发起后，请您于付款期限截止前转帐至指定账户，并标记已付款完毕，逾期系统将自动取消交易。')}}</p>
						<p>3. {{$t('交易发起后，系统会自动将卖家的数字货币锁定，待卖家确认收到您的转帐后，将会释放数字货币至您的账户中。')}}</p>
						<p>4. {{$t('建议您在交易前先查看卖家信息，检视相关交易记录及评价，以减少交易纠纷。')}}</p>
						<p>5. {{$t('交易过程请使用平台的聊天系统进行沟通，平台外的对话记录将无法作为交易纠纷的依据。')}}</p>
						<p>6. {{$t('温馨提示：超过三笔取消订单，将被冻结当天下单权限。')}}</p>
						<p>7. {{$t('下单后请履行契约精神，恶意抬价或者是反悔，被投诉将冻结账户 3-14 天不等。')}}</p>
					</div>
				</div>
			</div>
		</div>
		
		<!-- 输入支付密码的弹窗 -->
		<el-dialog class="user-dialog" :title="$t('验证支付密码')" :visible.sync="showPassword" :before-close="closePassword">
			<div class="title-tips">{{$t('支付密码')}}</div>
			<div class="address-form-input">
				<el-input :placeholder="$t('请输入支付密码')" v-model="payPwd" type="password" clearable autocomplete="off" @keyup.enter.native="releaseAds">
				</el-input>
			</div>
			
			<div class="title-tips">{{$t('图形验证码')}}</div>
			<div class="address-form-input" style="display: flex;justify-content: space-between;">
				<el-input :placeholder="$t('请输入图形验证码')" v-model="imgVerifyCode" type="text" clearable autocomplete="off" @keyup.enter.native="submit">
				</el-input>
				<img class="val" :src="imagesUrl" @click="getImageCode">
			</div>
			
			<div class="title-tips">{{$t('短信验证码')}}</div>
			<div class="address-form-input">
				<el-input class="verify-input" :placeholder="$t('请输入短信验证码')" v-model="noteVerifyCode" type="text" clearable autocomplete="off" @keyup.enter.native="releaseAds">
				</el-input>
					
				<span class="get-code" v-if="isCodeSend">{{iTime + $t('s后重新获取')}}</span>
				<span class="get-code" @click="getCode" v-else>{{$t('获取验证码')}}</span>
			</div>
		
			<span slot="footer" class="dialog-footer">
				<el-button type="primary" :loading="true" v-if="loading2">{{$t('提交中...')}}</el-button>
				<el-button type="primary" @click="releaseAds" v-else>{{$t('确定')}}</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import { mapState } from 'vuex'
	let Countdown;
	export default {
		name: 'currencyRelease',
		data() {
			return {
				dealerId: '',
				dealerInfo: {}, //商家信息
				
				dealType: 1, //1买 0卖
				
				coinList: [], //所有币种列表
				currentCoin: '', //当前币种
				currentCoinID: '', //当前币种ID
				price: 0, //币种参考单价
				limitMin: 0, //最小限额
				limitMax: 0, //最大限额
				buyRange: 0, //买入价格限制
				sellRange: 0, //卖出价格限制
				buyFee: 0, //买入手续费
				sellFee: 0, //卖出手续费
				
				options: [],
				
				totalPrice: '', //金额
				quantity: '', //数量
				minPrice: '', //最小限额
				alipay: false,
				weixinpay: false,
				unionpay: false,
				payPwd: '', //支付密码
				noteVerifyCode: '', //短信验证码
				
				hasAlipay: false,
				hasWeixin: false,
				hasUnionpay: false,
				
				showPassword: false,
				iTime: 60, //验证码倒计时
				isCodeSend: false,
				loading: false,
				loading2: false,
				
				randomString: '', //图片验证码随机数
				imgVerifyCode: '', //图片验证码
				imagesUrl: '', //验证码图片地址
			}
		},
		computed: {
			...mapState('user', ['userInfoData' ,'merchantStatus']),
			dealTypeText() {
				let text = this.dealType ? this.$t('购买') : this.$t('出售');
				return text;
			},
			hasPayment() { //是否有添加支付方式
				let val = false;
				if(!this.hasAlipay && !this.hasWeixin && !this.hasUnionpay) {
					val = true;
				}
				return val;
			}
		},
		watch: {
			price(newVal) { //监听单价
				if (newVal != '' && this.totalPrice > 0) {
					this.quantity = this.common.accDiv(this.totalPrice, newVal); //数量=金额÷单价
				}
			},
		},
		methods: {
			getImageCode() { //获取图片验证码
				this.randomString = Math.floor(Math.random() * 4000 + 1000) + new Date().getTime();
				this.imagesUrl = this.common.baseURL + '/user/api/user/image/' + this.randomString;
			},
			getUserInfoData() {
				this.getAxios('/user/api/user/info')
					.then(data => {
						this.dealerId = data.data.id;
						setTimeout(() => {
							this.getDealerInfo();
						}, 300);
					})
			},
			getDealerInfo() { //商家信息
				this.postAxios('/api/market/order/business/info/' + this.dealerId)
					.then(data => {
						this.dealerInfo = data.data;
					})
			},
			getCoinList() { //获取币种列表
				this.getAxios('/api/market/fcoin/list')
					.then(data => {
						this.coinList = data.data;
			
						this.currentCoin = this.coinList[0].coinId;
						this.currentCoinID = this.coinList[0].coinId;
						this.price = this.coinList[0].price; //单价
						this.buyRange = this.coinList[0].buyRange; //买入单价范围
						this.sellRange = this.coinList[0].sellRange; //卖出单价范围
						this.buyFee = this.coinList[0].buyServiceChargeRate; //买入手续费
						this.sellFee = this.coinList[0].sellServiceChargeRate; //卖出手续费
						this.limitMin = this.coinList[0].minLimit; //总金额最低
						this.limitMax = this.coinList[0].maxLimit; //总金额最高
						
						this.coinList.forEach(item => {
							this.options.push({
								value: item.coinId,
								label: item.coinId
							})
						})
					})
			},
			getPayment() { //获取支付方式
				this.getAxios('/api/user/payment/list')
					.then(data => {
						let list = data.data;
						list.forEach(item => {
							if(item.status == 'U_P_S_NORMAL') {
								if(item.paymentType == 1) {
									this.hasWeixin = true;
								}
								if(item.paymentType == 2) {
									this.hasAlipay = true;
								}
								if(item.paymentType == 3) {
									this.hasUnionpay = true;
								}	
							}
						})
					})
			},
			
			handleChange(value) { //切换币种
				console.log(JSON.stringify(value));
				
				this.coinList.forEach(item => {
					if(item.coinId == value[0]) {
						this.currentCoin = item.coinId;
						this.currentCoinID = item.coinId;
						this.price = item.price; //单价
						this.buyRange = item.buyRange; //买入单价范围
						this.sellRange = item.sellRange; //卖出单价范围
						this.buyFee = item.buyServiceChargeRate; //买入手续费
						this.sellFee = item.sellServiceChargeRate; //卖出手续费
						this.limitMin = item.minLimit; //总金额最低
						this.limitMax = item.maxLimit; //总金额最高
					}
				})
			},
			
			setPrice() { //数量=金额÷单价
				if(this.totalPrice != '' && this.totalPrice != 0 && this.price > 0) {
					this.quantity = this.common.accDiv(this.totalPrice, this.price);
				} else if(this.totalPrice == '') {
					this.quantity = '';
				}
			},
			setQuantity() { //金额=数量×单价
				if (this.quantity != '' && this.quantity != 0 && this.price > 0) {
					this.totalPrice = this.common.accMul(this.quantity, this.price);
				} else if(this.quantity == '') {
					this.totalPrice = '';
				}
			},
			
			getCode() { //获取验证码
				if (this.isCodeSend) {
					this.$message.error(this.$t('请勿频繁获取验证码！'))
					return;
				}
				this.isCodeSend = true;
			
				this.getAxios(`/user/api/user/verify/get?verifyType=0`)
					.then(() => {
						this.$message.success(this.verifyTypeText + this.$t('验证码发送成功！'));
						this.countdownTimer();
					})
					.catch(() => {
						this.isCodeSend = false;
					});
			},
			countdownTimer() { //短信发送开始计时60s
				if (this.iTime === 0) {
					clearTimeout(Countdown);
					this.isCodeSend = false;
					this.iTime = 60;
				} else {
					Countdown = setTimeout(this.countdownTimer, 1000);
					this.iTime = this.iTime - 1;
				}
			},
			
			openPassword() { //打开密码弹框
				if(this.loading) {
					return;
				}
				if(this.merchantStatus != 'M_E_S_PASS') {
					this.$message.error(this.$t('您还不是承兑商，不能发布广告!'));
					return;
				}
				if(!this.userInfoData.initPayPwd) {
					this.$message.error(this.$t('您还未设置支付密码!'));
					return;
				}
				if(!this.price) {
					this.$message.error(this.$t('请输入单价!'));
					return;
				}
				if(!this.totalPrice) {
					this.$message.error(this.$t('请输入金额!'));
					return;
				}
				if(!this.quantity) {
					this.$message.error(this.$t('请输入数量!'));
					return;
				}
				if(!this.minPrice) {
					this.$message.error(this.$t('请输入最小限额!'));
					return;
				}
				if(this.minPrice < this.limitMin) {
					this.$message.error(this.$t('最小限额不能小于') + this.limitMin);
					return;
				}
				if (!this.alipay && !this.weixinpay && !this.unionpay) {
					this.$message.error(this.$t('请选择支付方式！'));
					return;
				}
				
				this.loading = true;
				this.showPassword = true;
			},
			closePassword() {
				this.showPassword = false;
				//清除数据
				this.payPwd = '';
				this.noteVerifyCode = '';
				this.loading = false;
				this.loading2 = false;
			},
			
			releaseAds() { //发布广告
				if(this.loading2) {
					return;
				}
				if(!this.payPwd) {
					this.$message.error('请输入支付密码!');
					return;
				}
				if (!this.imgVerifyCode) {
					this.$message.error(this.$t('请输入图片验证码！'));
					return;
				}
				if(!this.noteVerifyCode) {
					this.$message.error('请输入短信验证码!');
					return;
				}
				
				this.loading2 = true;
				
				let params = {
					buy: this.dealType ? true : false, //买or卖
					amount: this.price, //单价
					intAmount: this.dealType ? this.quantity : this.totalPrice, //买数量 卖金额
					intCoinId: this.dealType ? this.currentCoinID : 'CNY',
					outAmount: this.dealType ? this.totalPrice : this.quantity, //买金额  卖数量
					outCoinId: this.dealType ? 'CNY' : this.currentCoinID,
					minAmount: this.minPrice, //最小限额
					alipay: this.alipay,
					weixinpay: this.weixinpay,
					unionpay: this.unionpay,
					payPwd: this.payPwd,
					noteVerifyCode: this.noteVerifyCode,
					randomString: this.randomString,
					imgVerifyCode: this.imgVerifyCode,
				}
				
				this.postAxios('/api/market/order/publish', params)
					.then(() => {
						this.loading = false;
						this.loading2 = false;
						this.$message.success('广告发布成功！');
						
						setTimeout(() => {
							this.$router.push('/currency/ads');
						}, 800)
					})
					.catch(() => {
						this.loading = false;
						this.loading2 = false;
					})
			}
		},
		created() {
			this.getCoinList();
			this.getUserInfoData();
			this.getPayment();
			this.getImageCode();
		}
	}
</script>

<style scoped>
	.order-top-div2 {
		position: absolute;
		right: 0;
		top: 0;
	}
	.top-price {
		margin-bottom: 30px;
	}
	
	.release-form {
		background: #f6f6f6;
		display: flex;
		align-items: center;
		padding: 0 10px;
	}
	.release-form .text-input {
		width: auto;
		flex: 1 1 auto;
		padding: 0;
	}
</style>
