<template>
	<view class="bg-[var(--page-bg-color)] min-h-[100vh] overflow-hidden form-edit" :style="themeColor()">
		<u-form labelPosition="left" :model="formData" errorType='toast' :rules="rules" ref="formRef"
			labelWidth="160rpx">
			<view class="sidebar-margin card-template mt-[var(--top-m)] py-[20rpx]">
				<u-form-item :label="t('name')" prop="name" borderBottom required>
					<u-input v-model="formData.name" :placeholder="t('namePlaceholder')" ></u-input>
				</u-form-item>
			</view>
		</u-form>
		<view v-if="hasPermission('erp_product_unit_add')" class="w-full footer">
			<view class="py-[var(--top-m)] px-[var(--sidebar-m)] footer w-full fixed bottom-0 left-0 right-0 box-border">
				<button hover-class="none" class="!bg-[var(--primary-color)] text-[#fff] h-[80rpx] leading-[80rpx] rounded-[100rpx] text-[26rpx] font-500" 
				@click="handSave" :disabled="loading" :class="{'opacity-50': loading}">{{t('save')}}</button>
			</view>
		</view>
		<!-- 上级分类 -->
		<u-action-sheet class="" :actions="pidList" :show="pidSheetShow" :closeOnClickOverlay="true"
		    :safeAreaInsetBottom="true"
		    @close="pidSheetShow = false" @select="updateSex"></u-action-sheet>
			
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted } from 'vue'
	import { t } from '@/locale'
	import { onLoad } from '@dcloudio/uni-app';
	import { getProductUnitInfo, addProductUnit, editProductUnit } from '@/addon/erp/api/product';
	import { redirect } from '@/utils/common';
	import useMemberStore from '@/stores/member'
	import usePermission from '@/utils/usePermission'
	const { hasPermission } = usePermission()	
	const memberStore = useMemberStore()
	
	const formRef: any = ref(null)
	const loading = ref(false)
	
	// 页面加载
	onLoad((option: any) => {
		if(option.id){
			getInfo(option.id);
		}
		
	})
	
	
	const rules = reactive({
		name: {
			type: 'string',
			required: true,
			message: t('namePlaceholder'),
			trigger: ['blur', 'change'],
		}
	});
	const formData = ref({
		id: 0,
		name: '',
	})
	
	const getInfo = (id: number) => {
		getProductUnitInfo(id).then((res: any) => {
			formData.value = res.data;
		}).catch(err => {
			// 如果是4001，没有绑定企业账号，强制跳转绑定
			if(err.code == 4001){
				redirect({ url: '/addon/erp/pages/member/bind' })
			}
		})
	}
	
	// 保存
	const handSave = async() => {
		formRef.value.validate().then(() => {
		    if (loading.value) return
		    loading.value = true
			const save = formData.value.id ? editProductUnit : addProductUnit;
		    save(formData.value).then((res: any) => {
				if(res.code == 1){
					redirect({ url: '/addon/erp/pages/product/unit/list' })
				}
		    }).catch((err) => {
				// 如果是4001，没有绑定企业账号，强制跳转绑定
				if(err.code == 4001){
					redirect({ url: '/addon/erp/pages/member/bind' })
				}
		        loading.value = false
		    })
		})
	}
</script>

<style>
</style>