<template>
	<NavBar />
	<view class="container">
		<view class="title">
			<PageTitle :title="$t('menu.activity')" />
		</view>
		<Spin v-show="loading" />
		<view class="content" v-if="detail" >
			<view class="news-title" >{{detail.title}}</view>
			<view class="news-content" v-html="detail.content"></view>
		</view>
		<view style="margin-top: 100upx;" v-if="contentType == 1 && detail" >
			<button class="primaryButton" @click="goldIn(detail.activity_id)">
				{{ $t('activity.activityGoldIn') }}
			</button>
		</view>
		<uni-forms v-if="contentType == 2 && participateData" ref="postRef" :modelValue="form" :rules="rules" style="margin-top: 16px;">
			<uni-forms-item>
			  <text class="uni-subtitle">{{ $t('activity.presentedMinPay') }}</text>
			  <uni-easyinput type="number" primaryColor="#29BBE4" :value="participateData.min_amount" disabled :clearable="false"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="mt4_server">
				<text class="uni-subtitle">{{ $t('form.mtServer.label') }}</text>
				<uni-data-select
					:disabled="participateData.code == -1"
					:placeholder="$t('form.pleaseSelect')"
					:emptyTips="$t('common.empty')"
					:localdata="mtServerOptions"
					v-model="form.mt4_server"
					@change="getMtLoginData"
					:clear="false"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="mt4_login">
				<text class="uni-subtitle">{{ $t('form.mtAccount.label') }}</text>
				<uni-data-select
					:disabled="participateData.code == -1"
					:placeholder="$t('form.pleaseSelect')"
					:emptyTips="$t('common.empty')"
					:localdata="mtLoginOptions"
					v-model="form.mt4_login"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item name="apply_amount">
				<text class="uni-subtitle">{{ $t('form.amount.label') }}</text>
				<uni-easyinput type="number" primaryColor="#29BBE4" v-model="form.apply_amount" :disabled="participateData.code == -1"></uni-easyinput>
			</uni-forms-item>
			<button class="primaryButton" type="button" v-if="participateData.code == 0" :disabled="nextBtnLoading" @click="save">
				<image v-show="nextBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
				{{ $t('form.submit') }}
			</button>
		</uni-forms>
		<view style="margin-top: 40upx;text-align: center;" v-if="detail && detail.activity_accessory" >
			<uni-link color="#1DC0E4" :href="baseUrl + detail.activity_accessory" :text="$t('activity.doc')"></uni-link>
		</view>
	</view>
</template>

<script>
import { getActivityDetail, participateSave, getNewActivityDetail } from '@/services/activity';
import { getFilePath, getCustomerMtLoginList, getMtServers } from '@/services/common';
import { UserLanguage } from '@/utils/const';
// #ifndef H5
import * as cheerio from 'cheerio';
// #endif

export default {
	data() {
		return {
			contentId: undefined,
			contentType: undefined,
			detail: undefined,
			loading: false,
			baseUrl: '',
			participateData: null,
			form: {
				apply_amount: undefined,
				mt4_server: undefined,
				mt4_login: undefined,
				act_id: undefined
			},
			rules: {
				apply_amount: {
					rules: [
						{ required: true, errorMessage: " ", format: 'number' },
						{ minimum: 0, errorMessage: " " }
					]
				},
				mt4_server: { 
					rules: [
						{ required: true, errorMessage: " " },
					]
				},
				mt4_login: { 
					rules: [
						{ required: true, errorMessage: " " },
					]
				}
			},
			mtServerOptions: [],
			mtLoginOptions: [],
			nextBtnLoading: false
		}
	},
	methods: {
		goldIn(actId) {
			uni.navigateTo({
				url:'/pages/capital/deposit/index?actId=' + actId
			})
		},
		handleImages(htmlContent) {
		  // #ifdef H5
		  var parser = new DOMParser();
		  var doc = parser.parseFromString(htmlContent, 'text/html');
		  var images = doc.getElementsByTagName('img');
		  Array.from(images).forEach(function(img) {
			var width = img.getAttribute("width");
			if (!isNaN(parseFloat(width)) && parseFloat(width) > 200) {
			  img.setAttribute('width', '100%');
			  img.setAttribute('height', 'auto');
			}
		  });
		  return doc.documentElement.innerHTML;
		  // #endif
		  
		  // #ifndef H5
		  const $ = cheerio.load(htmlContent);
		  const images = $('img')
		  Array.from(images).forEach(function(img) {
			  var width = $(img).attr('width')
			  if (!isNaN(parseFloat(width)) && parseFloat(width) > 200) {
				  $(img).attr('width', '100%');
				  $(img).attr('height', 'auto');
			  }
		  })
		  return $.html();
		  // #endif
		},
		async getMtLoginData(serverId) {
			this.mtLoginOptions = []
			this.form.mt4_login = undefined
			const res = await getCustomerMtLoginList({ mt4_server: serverId });
			if (res && res.code === 0) {
				this.mtLoginOptions = res.data?.map((mtAccount) => ({text: mtAccount.mt4_login,value: mtAccount.mt4_login}))
			}
		},
		loadParticipate(activity_id) {
			getNewActivityDetail({id: activity_id}).then(resp => {
				this.participateData = resp.data
				this.rules.apply_amount.rules[1].minimum = Number(resp.data.min_amount)
				this.form.mt4_server = resp.data.mt_server
				this.form.mt4_login = resp.data.mt_login
				this.form.apply_amount = resp.data.apply_amount
			})
		},
		save() {
			this.$refs.postRef.validate((err,formData) => {
				if (!err) {
					this.nextBtnLoading = true;
					participateSave(this.form).then(resp => {
						if (resp.code == 0) {
							this.participateData.code = -1
							this.$nextTick(() => {
								this.$cusModal.showModal({
									type: 'message',
									status: 'success',
									contentText: this.$t('common.success.action')
								});
							})
						} else {
							this.$nextTick(() => {
								this.$cusModal.showModal({
									type: 'message',
									status: 'warning',
									contentText: resp.msg ?? this.$t('common.error.sysError')
								});
							})
						}
						this.nextBtnLoading = false;
					})
				}
			})
		}
	},
	created() {
		getFilePath().then(resp => {
			this.baseUrl = resp.data
		})
	},
	onLoad(options) {
		const {contentId, contentType} = options
		this.contentId = contentId
		this.contentType = contentType
		this.loading = true
		getActivityDetail({contentId, contentType}).then(resp => {
			if (resp.code == 0) {
				if (this.contentType == 2) {
					this.loadParticipate(resp.data.activity_id)
					this.form.act_id = resp.data.activity_id
					getMtServers({ qcc_language: UserLanguage, server_type: 'live' }).then(resp => {
						this.mtServerOptions = resp.data?.map((item) => ({
							text: item.server_name,
							value: item.id
						}))
					})
					
				}
				if (resp.data.content) {
					resp.data.content = this.handleImages(resp.data.content)
				}
				this.detail = resp.data
			}
			this.loading = false
		}).catch(() => {
			this.loading = false
		})
	}
}
</script>

<style lang="scss" scoped>
@import './detail.scss';
</style>
<style>
	.news-content {
		width: 100%;
		overflow-y: auto;
		word-wrap: break-word;
	}
</style>