<template>
	<page-meta :page-style="'overflow:' + (show ? 'visible' : 'hidden')"></page-meta>
	<view>
		<view style="margin-top: 19px">
			<Segmented
				styleType="text"
				fontSize="16px"
				gap="6px"
				:current="current"
				:values="items"
				@clickItem="onClickItem"
				underLineHeight="0px"
				inActiveColor="#999999"
				activeColor="#000"
			></Segmented>
		</view>
		<view v-show="current === 0" class="bankCardList">
			<view v-for="bank in rawBankList" :key="bank.id">
				<BankCard :values="bank" :onClick="() => showDialog(bank)" />
			</view>
		</view>
		<view v-if="!rawBankList.length && current === 0" style="display: flex; justify-content: center; align-items: center">
			<Spin v-show="listLodaing" />
			<image v-show="!listLodaing" src="/static/empty.png" mode="aspectFit" style="width: 72px; height: 100px; margin-top: 64px"></image>
		</view>
		<view v-show="current === 1" class="bankCardList">
			<view v-for="bank in B1BankList" :key="bank.id">
				<BankCard :values="bank" :onClick="() => showDialog(bank)" />
			</view>
			<AddBankCard :onClick="() => showDialog()" addType="B1" :addText="$t('form.personalData.financialInformation.addBankCard_B1')" />
		</view>
		<view v-show="current === 2" class="bankCardList">
			<view v-for="bank in B2BankList" :key="bank.id">
				<BankCard :values="bank" :onClick="() => showDialog(bank)" />
			</view>
			<AddBankCard :onClick="() => showDialog()" addType="B2" :addText="$t('form.personalData.financialInformation.addBankCard_B2')" />
		</view>
		<view v-show="current === 3" class="bankCardList">
			<view v-for="bank in B3BankList" :key="bank.id">
				<BankCard :values="bank" :onClick="() => showDialog(bank)" />
			</view>
			<AddBankCard :onClick="() => showDialog()" addType="B3" :addText="$t('form.personalData.financialInformation.addBankCard_B3')" />
		</view>
		<uni-popup ref="alertDialog" :isMaskClick="false">
			<view class="detailModal">
				<uni-icons type="closeempty" size="17" class="closeIcon" @click="closeDialog"></uni-icons>
				<scroll-view :style="{ height: getType() === 'B1' ? '80vh' : '100%', paddingTop: '36px', boxSizing: 'border-box' }" scroll-y="true">
					<view class="detailContent">
						<uni-forms ref="addCardForm" :modelValue="addCardFormData" :rules="addCardFormRules">
							<uni-forms-item name="bank_no">
								<text class="uni-subtitle">{{ $t(`form.personalData.financialInformation.bankNo.label_${getType() === 'B1' ? 'B1' : 'B2'}`) }}</text>
								<uni-easyinput :disabled="getType()!='B1'&&addCardFormData.apply_status == 0 && addCardFormData.verify_email == 1" trim="both" primaryColor="#29BBE4" v-model="addCardFormData.bank_no"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="first_name">
								<text class="uni-subtitle">{{ $t('form.firstName.label') }}</text>
								<uni-easyinput trim="both" primaryColor="#29BBE4" :disabled="addCardFormData.id" v-model="addCardFormData.first_name"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="last_name">
								<text class="uni-subtitle">{{ $t('form.lastName.label') }}</text>
								<uni-easyinput trim="both" primaryColor="#29BBE4" :disabled="addCardFormData.id" v-model="addCardFormData.last_name"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="bank_name" v-show="getType() === 'B1'">
								<text class="uni-subtitle">{{ $t(`form.personalData.financialInformation.bankName.label_${getType()}`) }}</text>
								<uni-easyinput trim="both" primaryColor="#29BBE4" v-model="addCardFormData.bank_name"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="bank_sub_name" v-show="getType() === 'B1'">
								<text class="uni-subtitle">{{ $t('form.personalData.financialInformation.bankSubName.label') }}</text>
								<uni-easyinput trim="both" primaryColor="#29BBE4" v-model="addCardFormData.bank_sub_name"></uni-easyinput>
							</uni-forms-item>

							<uni-forms-item name="bank_remark" v-show="getType() === 'B1'">
								<text class="uni-subtitle">{{ $t('form.addressDetailed.label') }}</text>
								<uni-easyinput trim="both" primaryColor="#29BBE4" v-model="addCardFormData.bank_remark"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="bank_swift" v-show="getType() === 'B1'">
								<text class="uni-subtitle">SWIFT/ABA/IBAN</text>
								<uni-easyinput trim="all" primaryColor="#29BBE4" v-model="addCardFormData.bank_swift"></uni-easyinput>
							</uni-forms-item>
							<uni-forms-item name="bank_currency">
								<text class="uni-subtitle">{{ $t('form.personalData.financialInformation.bankCurrency.label') }}</text>
								<uni-data-select
									:placeholder="$t('form.pleaseSelect')"
									:emptyTips="$t('common.empty')"
									:localdata="currencyOptions"
									v-model="addCardFormData.bank_currency"
									:disabled="getType()!='B1'&&addCardFormData.apply_status == 0 && addCardFormData.verify_email == 1"
								></uni-data-select>
							</uni-forms-item>
							<uni-forms-item name="bank_img_0" v-if="needBankImg" >
								<text class="uni-subtitle">{{ $t('form.personalData.financialInformation.bankImg.label_B1') + $t('form.personalData.financialInformation.bankImg.front') }}</text>
								<view class="bankImgWrapper" >
									<uni-file-picker ref="bank_img_0" v-model="bankImg0" file-mediatype="image" mode="grid" :limit="1" @select="(e) => select(e, 'bank_img_0')" />
									<view style="max-width: 140px">
										<Progress :progress="bank_img_0_progress" :error="bank_img_0_error" />
									</view>
								</view>
							</uni-forms-item>
							<uni-forms-item name="bank_img_1" v-if="needBankImg" >
								<text class="uni-subtitle">{{ $t('form.personalData.financialInformation.bankImg.label_B1') + $t('form.personalData.financialInformation.bankImg.back') }}</text>
								<view class="bankImgWrapper" >
									<uni-file-picker ref="bank_img_1" v-model="bankImg1" file-mediatype="image" mode="grid" :limit="1" @select="(e) => select(e, 'bank_img_1')" />
									<view style="max-width: 140px">
										<Progress :progress="bank_img_1_progress" :error="bank_img_1_error" />
									</view>
								</view>
							</uni-forms-item>
						</uni-forms>
					</view>
					<view class="btnsWrapper" style="padding: 0 29px 42px">
						<button v-show="addCardFormData.id && !(getType()!='B1'&&addCardFormData.apply_status == 0 && addCardFormData.verify_email == 1)" class="primaryButton delBtn" :disabled="delBtnLoading" @click="handleDeleteBank">
							<image v-show="delBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
							{{ $t('common.delete') }}
						</button>
						<button v-show="!(getType()!='B1'&&addCardFormData.apply_status == 0 && addCardFormData.verify_email == 1)" class="primaryButton" :disabled="bank_img_0_progress !== 100 || bank_img_1_progress !== 100 || submitBtnLoading" @click="handleAddBank">
							<image v-show="submitBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
							{{ $t('form.submit') }}
						</button>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import BankCard from './components/bankCard/index.vue';
import AddBankCard from './components/addBankCard/index.vue';
import Segmented from '@/pages/components/segmented/index.vue';
import { getBankList } from '@/services/user.ts';
import { saveBank } from '@/services/user/completeInfo.ts';
import { getDictByCode, getImgPath, imgUpload } from '@/services/common.ts';
export default {
	name: 'FinancialInformation',
	data() {
		return {
			show: true,
			current: 0,
			items: [
				this.$t('common.allAccounts'),
				this.$t('form.bankAccount.label'),
				this.$t('form.personalData.financialInformation.digitalCurrency.label'),
				this.$t('common.alipay')
			],
			bankImg0: {
				// url: ''
			},
			bankImg1: {
				// url: ''
			},
			imgBaseUrl: '',
			bank_img_0_progress: 100,
			bank_img_1_progress: 100,
			bank_img_0_error: false,
			bank_img_1_error: false,
			rawBankList: [],
			B1BankList: [],
			B2BankList: [],
			B3BankList: [],
			currencyOptions: [],
			addCardFormData: {},
			addCardFormRules: {
				bank_no: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.pleaseEnter')
						}
					]
				},
				first_name: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.pleaseEnter')
						}
					]
				},
				last_name: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.pleaseEnter')
						}
					]
				},
				bank_name: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.pleaseEnter')
						}
					]
				},
				bank_sub_name: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.pleaseEnter')
						}
					]
				},
				bank_currency: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.pleaseSelect')
						}
					]
				},
				bank_img_0: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.personalData.financialInformation.bankImg.required')
						}
					]
				},
				bank_img_1: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.personalData.financialInformation.bankImg.required')
						}
					]
				}
			},
			currentBank: {},
			listLodaing: false,
			submitBtnLoading: false,
			delBtnLoading: false
		};
	},
	computed: {
		needBankImg() {
			if (this.addCardFormData && this.addCardFormData.bank_currency === 'CNY' && this.getType() === 'B1') {
				return true
			}
			return false
		}
	},
	methods: {
		async getImgPathData() {
			const res = await getImgPath();
			if (res && res.code === 0) {
				this.imgBaseUrl = res.data;
			}
		},
		onClickItem(e) {
			if (this.current != e.currentIndex) {
				this.current = e.currentIndex;
			}
		},
		showDialog(bank = {}) {
			console.log(bank)
			this.addCardFormData = { ...bank };
			this.currentBank = { ...bank };
			this.bankImg0 = bank.bank_img_0 ? ({url: this.imgBaseUrl + bank.bank_img_0}) : {}
			this.bankImg1 = bank.bank_img_1 ? ({url: this.imgBaseUrl + bank.bank_img_1}) : {}
			this.show = false;
			this.$refs.alertDialog.open();
		},
		closeDialog() {
			this.show = true;
			this.$refs.alertDialog.close();
		},
		getType() {
			if (this.current === 1) {
				return 'B1';
			} else if (this.current === 2) {
				return 'B2';
			} else if (this.current === 3) {
				return 'B3';
			} else {
				return this.currentBank?.bank_standby_1;
			}
		},
		filterB1BankList(bankList) {
			this.B1BankList = bankList.filter((bank) => bank.bank_standby_1 === 'B1');
		},
		filterB2BankList(bankList) {
			this.B2BankList = bankList.filter((bank) => bank.bank_standby_1 === 'B2');
		},
		filterB3BankList(bankList) {
			this.B3BankList = bankList.filter((bank) => bank.bank_standby_1 === 'B3');
		},
		async getBankListData() {
			this.listLodaing = true;
			const res = await getBankList();
			if (res && res.code === 0) {
				this.rawBankList = res.data
				this.filterB1BankList(this.rawBankList);
				this.filterB2BankList(this.rawBankList);
				this.filterB3BankList(res.data);
			}
			this.listLodaing = false;
		},
		async getCurrency() {
			const res = await getDictByCode('currency_type');
			if (res && res.code === 0) {
				this.currencyOptions = res.data?.map((item) => ({
					text: item.fun_item_text,
					value: item.fun_item_code
				}));
			}
		},
		async handleDeleteBank() {
			uni.showModal({
				content: this.$t('modal.deleteBankCardContent'),
				confirmColor: '#4DC0E5',
				success: async (res) => {
					if (res.confirm) {
						this.delBtnLoading = true;
						const res = await saveBank({
							bank: [],
							del_bank_id_arr: [this.currentBank.id]
						});
						this.delBtnLoading = false;
						this.closeDialog();
						if (res && res.code === 0) {
							this.$nextTick(() => {								
								this.$cusModal.showModal({
									type: 'message',
									status: 'success',
									contentText: this.$t('common.success.action'),
									onClose() {
										this.getBankListData();
										this.currentBank = {};
									}
								});
							})
						} else {
							this.$nextTick(() => {
								this.$cusModal.showModal({
									type: 'message',
									status: 'warning',
									contentText: res.msg ?? this.$t('common.error.sysError')
								});
							})
						}
					}
				}
			});
		},
		async handleAddBank() {
			const calidateFields =
				this.getType() === 'B1'
					? (
						this.addCardFormData.bank_currency=='CNY'?
						['bank_no', 'first_name', 'last_name', 'bank_name', 'bank_sub_name', 'bank_remark', 'bank_swift', 'bank_currency','bank_img_0','bank_img_1']:
						['bank_no', 'first_name', 'last_name', 'bank_name', 'bank_sub_name', 'bank_remark', 'bank_swift', 'bank_currency']
					)
					: ['bank_no', 'first_name', 'last_name', 'bank_currency'];
			this.$refs.addCardForm.validateField(calidateFields).then(async (fields) => {
				fields.bank_standby_1 = this.getType();
				let params = {
					bank: [
						{
							id: this.currentBank.id ?? ''
						}
					]
				};
				Object.keys(fields).forEach((key) => {
					if (fields[key] !== this.currentBank[key]) {
						params.bank[0][key] = {
							nv: fields[key] ?? '',
							ov: this.currentBank[key] ?? '',
							edit_power: 1,
							bank_no: fields.bank_no
						};
					}
				});
				this.submitBtnLoading = true;
				const res = await saveBank(params);
				this.submitBtnLoading = false;
				if (res && res.code === 0) {
					this.closeDialog();
					this.getBankListData();
					const type = this.getType();
					this.currentBank = {};
					// 0需要审核，1审核通过，请邮箱验证，2审核通过
					if (type === 'B1') {
						uni.navigateTo({
							url: `/pages/user/financialInformation/saveBankResult/index?resCode=${res.data}&type=${type}`
						});
					} else {
						uni.navigateTo({
							url: `/pages/user/financialInformation/saveBankResult/index?resCode=${res.data}&type=${type}&wa=${fields.bank_no}&currency=${
								fields.bank_currency
							}`
						});
					}
				} else {
					this.closeDialog();
					this.$nextTick(() => {
						this.$cusModal.showModal({
							type: 'message',
							status: 'warning',
							contentText: res.msg ?? this.$t('common.error.sysError')
						});
					})
				}
			});
		},
		async select(e, field) {
			this[`${field}_progress`] = 0;
			this[`${field}_error`] = false;
			let step = 1;
			const timer = setInterval(() => {
				if (this[`${field}_progress`] > 85) {
					step = 0.1;
				} else if (this[`${field}_progress`] > 35) {
					step = 0.8;
				} else if (this[`${field}_progress`] > 15) {
					step = 0.4;
				}
				if (this[`${field}_progress`] + step > 98) {
					clearInterval(timer);
					return;
				}
				this[`${field}_progress`] += step;
			}, 34);
			this.$refs[field].files[0].progress = 100;
			const res = await imgUpload(e);
			if (res && res.code === 0) {
				this[`${field}_progress`] = 100;
				this.addCardFormData[field] = res.data?.imgNameList?.[0];
				uni.showToast({
					icon: 'none',
					title: this.$t('common.success.uploadSuccess')
				});
			} else {
				this[`${field}_error`] = true;
				this.$cusModal.showModal({
					type: 'message',
					status: 'warning',
					contentText: res.msg ?? this.$t('common.error.uploadError')
				});
			}
		}
	},
	async created() {
		await this.getImgPathData();
		this.getBankListData();
		this.getCurrency();
	},
	components: {
		Segmented,
		BankCard,
		AddBankCard
	}
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
