<template>
	<view class="flex flex-col mb-5">
		<cl-text :pt="{ className: 'text-lg font-bold' }">{{ t("手机登录") }}</cl-text>
		<cl-text :pt="{ className: 'text-sm mt-2' }" color="info">{{
			t("未注册的手机号登录成功后将自动注册")
		}}</cl-text>
	</view>

	<view class="flex flex-col">
		<view class="mb-3 flex flex-row">
			<cl-input
				v-model="form.phone"
				prefix-icon="device-fill"
				:placeholder="t('请输入手机号')"
				:border="false"
				:pt="{
					className: parseClass([
						'!h-[90rpx] flex-1 !rounded-xl !px-4',
						[isDark, '!bg-surface-70', '!bg-white']
					]),
					prefixIcon: {
						className: 'mr-1'
					}
				}"
			></cl-input>
		</view>

		<view class="relative flex flex-row items-center mb-5">
			<cl-input
				v-model="form.smsCode"
				:clearable="false"
				type="number"
				prefix-icon="shield-check-fill"
				:placeholder="t('请输入验证码')"
				:maxlength="4"
				:border="false"
				:pt="{
					className: parseClass([
						'!h-[90rpx] flex-1 !rounded-xl !px-4',
						[isDark, '!bg-surface-70', '!bg-white']
					]),
					prefixIcon: {
						className: 'mr-1'
					}
				}"
			>
			</cl-input>

			<view class="absolute right-0">
				<sms-btn
					:ref="refs.set('smsBtn')"
					:phone="form.phone"
					@success="showCode = true"
				></sms-btn>
			</view>
		</view>

		<cl-button
			:pt="{
				className: '!h-[90rpx] !rounded-xl'
			}"
			:loading="loading"
			:disabled="disabled"
			@tap="toLogin"
		>
			{{ t("登录") }}
		</cl-button>
	</view>
</template>

<script setup lang="ts">
import { t } from "@/locale";
import { computed, inject, ref, type PropType } from "vue";
import type { LoginForm } from "../../types";
import SmsBtn from "@/components/sms-btn.uvue";
import { isDark, parseClass, request, useRefs, type Response } from "@/cool";
import { useUi } from "@/uni_modules/cool-ui";

const props = defineProps({
	form: {
		type: Object as PropType<LoginForm>,
		default: () => ({})
	}
});

const emit = defineEmits(["success"]);

const ui = useUi();
const refs = useRefs();

// 是否同意
const isAgree = inject("isAgree") as () => boolean;

// 是否显示验证码
const showCode = ref(false);

// 是否加载中
const loading = ref(false);

// 是否禁用
const disabled = computed(() => {
	return props.form.phone == "" || props.form.smsCode == "";
});

// 登录
async function toLogin() {
	if (!isAgree()) {
		return;
	}

	const { phone, smsCode } = props.form;

	loading.value = true;

	await request({
		url: "/app/user/login/phone",
		method: "POST",
		data: {
			phone,
			smsCode
		}
	})
		.then((res) => {
			emit("success", res);
		})
		.catch((err) => {
			ui.showToast({
				message: (err as Response).message!
			});
		});

	loading.value = false;
}
</script>
