<template>
	<div class="index">
		<el-dialog v-model="dialogTableVisible" :title="formData?.id ? '编辑账号' : '创建账号'" width="600" @closed="close">
			<el-form :model="formData" label-width="auto" :rules="formRule" ref="formRef">
				<el-form-item label="企业类型" prop="companyType">
					<el-select v-model="formData.companyType" placeholder="请选择企业类型" clearable>
						<el-option v-for="item of COMPANYTYPE_CONST" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
				</el-form-item>
				<el-form-item label="企业名称" prop="companyName">
					<el-input v-model="formData.companyName" placeholder="企业名称需唯一" />
				</el-form-item>
				<el-form-item label="手机号码" prop="phone">
					<el-input v-model="formData.phone" placeholder="请输入手机号码" />
				</el-form-item>
				<el-form-item label="账号名称" prop="accountName">
					<el-input v-model="formData.accountName" placeholder="无则默认为手机号" />
				</el-form-item>
				<el-form-item label="子账号最大数量" prop="accountLimit">
					<el-input-number v-model="formData.accountLimit" :min="0" />
				</el-form-item>
				<el-form-item label="账号类型" prop="accountType">
					<el-select v-model="formData.accountType" placeholder="请选择账号类型" clearable>
						<el-option v-for="item of ACCOUNTTYPE_CONST" :key="item.value" :label="item.label" :value="item.value" />
					</el-select>
					<el-row v-if="formData.accountType === 1" style="margin-top: 10px; padding: 10px; border: 1px solid #e7e7e7; border-radius: 5px">
						<el-col :span="12" v-for="(item, index) in PERMISSIONS" :key="item.value">
							<el-switch v-model="formData.permissions[index]" :active-text="item.label" :active-value="item.value" :inactive-value="0" />
						</el-col>
					</el-row>
				</el-form-item>
				<el-form-item label="账号有效期" prop="daterange">
					<el-date-picker
						v-model="formData.daterange"
						type="daterange"
						unlink-panels
						range-separator="-"
						value-format="YYYY-MM-DD"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
					/>
				</el-form-item>
			</el-form>

			<template #footer>
				<div class="dialog-footer">
					<el-button @click="close">取消</el-button>
					<el-button type="primary" @click="submit()"> 确认 </el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="loginIndex">
import { onMounted, reactive, ref } from 'vue';
import { NextLoading } from '/@/utils/loading';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { createTenant, updateTenant } from '/@/api/tenant';
import { COMPANYTYPE_CONST, ACCOUNTTYPE_CONST, PERMISSIONS } from './constant';

const emit = defineEmits(['close']);
const formRef = ref<FormInstance>();
const formData = reactive({
	id: undefined,
	companyType: '',
	companyName: '',
	phone: '',
	accountName: '',
	accountLimit: 0,
	accountType: '',
	daterange: [],
	permissions: [...PERMISSIONS.map(() => 1)],
});
const oldPhone = ref('');

const validatePhone = (rule: any, value: any, callback: any) => {
	const phoneRegex = /^1[3456789]\d{9}$/;
	if (!value) {
		callback(new Error('必须填写手机号码'));
	} else if (!phoneRegex.test(value)) {
		callback(new Error('请输入有效的手机号'));
	} else {
		callback();
	}
};

const formRule = reactive({
	companyType: [{ required: true, message: '必须填写企业类型', trigger: 'change' }],
	companyName: [{ required: true, message: '必须填写企业名称', trigger: 'blur' }],
	phone: [{ validator: validatePhone, required: true, message: '必须填写手机号码', trigger: 'blur' }],
	accountType: [{ required: true, message: '必须填写账号类型', trigger: 'change' }],
	daterange: [{ required: true, message: '必须填写有效期', trigger: 'change' }],
	accountLimit: [{ required: true, message: '必须填写子账号最大数量', trigger: 'blur' }],
});

const dialogTableVisible = ref(false);

function open(data) {
	dialogTableVisible.value = true;
	if (data) {
		oldPhone.value = data.phone;
		Object.assign(formData, { ...data, daterange: [data.validStart, data.validEnd], permissions: data.permissions.map((item) => item.enabled) });
	}
}
function close() {
	dialogTableVisible.value = false;
	formData.id = undefined;
	formData.companyType = '';
	formData.companyName = '';
	formData.phone = '';
	formData.accountName = '';
	formData.accountType = '';
	formData.accountLimit = 0;
	formData.daterange = [];
	emit('close');
}
async function submit() {
	console.log('output >>>>> formData', formData);
	await formRef.value?.validate();
	const permissions = formData.permissions.map((item, index) => ({
		name: PERMISSIONS[index].name,
		enabled: item,
	}));
	const params = {
		id: formData?.id || undefined,
		companyType: formData.companyType,
		companyName: formData.companyName,
		accountName: formData.accountName || formData.phone,
		accountType: formData.accountType,
		phone: formData.phone,
		validStart: formData.daterange[0],
		validEnd: formData.daterange[1],
		accountLimit: formData.accountLimit,
		permissions: permissions,
	};
	console.log('output >>>>> params', params);
	if (formData.id) {
		updateTenant(params).then((res) => {
			if (res.code === 200) {
				if(oldPhone.value !== formData.phone) {
					ElMessage.success('租户手机号已更新，如需使用新手机号作为子账号登录，请手动修改默认子账号!');
				} else {
					ElMessage.success('操作成功');
				}
				close();
			} else {
				ElMessage.error(res.msg || '操作失败');
			}
		});
		return;
	} else {
		createTenant(params).then((res) => {
			if (res.code === 200) {
				ElMessage.success('操作成功');
				close();
			} else {
				ElMessage.error(res.msg || '操作失败');
			}
		});
	}
}

// 页面加载时
onMounted(() => {
	NextLoading.done();
});

defineExpose({
	open,
	close,
});
</script>

<style scoped lang="scss"></style>
