<script lang="ts" setup>
/**
 * @Name: EditDrawer.vue
 * @Description: 价格审批（供货）- 编辑抽屉
 * @Author: xinyan
 */

import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { Close, Finished, Select } from '@element-plus/icons-vue';
import { useResponse } from '/@/utils/useResponse';
import * as api from '../api';
import { getCountryOptions, getCurrencyCodeOptions } from '/@/views/price-approval/api';
import { useCountryInfoStore } from '/@/stores/countryInfo';
import SelectDrawer from '/@/views/price-approval/components/SelectDrawer.vue';

const countryOptions = ref([]);
const btnLoading = ref(false);

const editOpen = defineModel({ default: false });

const editDrawer = <Ref>useTemplateRef('editDrawer');

const currencyCodeOptions = ref([]);

const props: any = defineProps({
	rowData: Object,
});
const { rowData } = props;

const emit = defineEmits(['refresh']);

const countryInfoStore = useCountryInfoStore();
const country = countryInfoStore.Countries.find((c) => c.code === rowData.country_code);

const isShow = ref(false);
const costType = ref('');

interface RuleForm {
	sku: string;
	weight: string;
	platform: string;
	country_code: string;
	currency_code: string;
	estimated_cost: string;
	price_show: string;
	price_daily: string;
	price_min: string;
	final_cost: string;
	sales_mode: string;
	cost: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
	sku: rowData.sku,
	weight: rowData.weight,
	platform: rowData.platform,
	country_code: country ? country.name : rowData.country_code,
	currency_code: rowData.currency_code,
	estimated_cost: rowData.estimated_cost,
	price_show: rowData.price_show,
	price_daily: rowData.price_daily,
	price_min: rowData.price_min,
	final_cost: rowData.final_cost,
	sales_mode: rowData.sales_mode,
	cost: rowData.cost,
});

const rules = reactive<FormRules<RuleForm>>({
	sku: [{ required: true, message: '请输入SKU', trigger: 'blur' }],
	platform: [{ required: true, message: '请输入平台', trigger: 'blur' }],
	country_code: [{ required: true, message: '请输入国家', trigger: 'blur' }],
	currency_code: [{ required: true, message: '请选择货币代码', trigger: 'change' }],
	estimated_cost: [{ required: true, message: '请输入预估成本', trigger: 'blur' }],
});

onBeforeMount(() => {
	fetchCurrencyCodeOptions();
});

async function fetchCurrencyCodeOptions() {
	const res = await useResponse(getCurrencyCodeOptions);
	currencyCodeOptions.value = res.data.currency_code;
}

const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			try {
				const res = await useResponse(api.updateRow, { id: rowData?.id, ...ruleForm }, btnLoading);
				if (res && res.code == 2000) {
					editOpen.value = false;
					ElMessage.success({ message: '编辑成功', plain: true, icon: 'Operation' });
					emit('refresh');
				}
			} catch (error) {
				console.error('Error==>', error);
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};

onBeforeMount(() => {
	fetchCountryOptions();
});

async function fetchCountryOptions() {
	const res = await useResponse(getCountryOptions);
	countryOptions.value = res.data.country_code;
}

function showSelectDrawer(type: string) {
	costType.value = type;
	isShow.value = true;
}

function getCheckId(id: any) {
	ruleForm.cost = id.value;
}

function closeDrawer() {
	editDrawer.value.handleClose();
}
</script>

<template>
	<div class="drawer-container">
		<el-drawer
			ref="editDrawer"
			v-model="editOpen"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			:title="`审批查看（直销） - 编辑 `"
			size="30%"
		>
			<el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" class="mx-2.5 mt-7" label-position="top" label-width="auto" status-icon>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item class="font-medium" label="SKU" prop="sku">
							<el-input v-model="ruleForm.sku" placeholder="请输入SKU" />
						</el-form-item>
						<el-form-item class="font-medium" label="平 台" prop="platform">
							<el-input v-model="ruleForm.platform" placeholder="请输入平台"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="货币代码" prop="currency_code">
							<el-select v-model="ruleForm.currency_code" placeholder="请选择货币代码">
								<el-option v-for="item in currencyCodeOptions" :label="item" :value="item" />
							</el-select>
						</el-form-item>
						<el-form-item class="font-medium" label="展示价格(外币)" prop="price_show">
							<el-input v-model="ruleForm.price_show" placeholder="请输入展示价格(外币)"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="最低售价(外币)" prop="price_min">
							<el-input v-model="ruleForm.price_min" placeholder="请输入最低售价(外币)"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="销售模式" prop="sales_mode">
							<el-select v-model="ruleForm.sales_mode" clearable placeholder="请选择销售模式">
								<el-option label="线上" value="线上"></el-option>
								<el-option label="线下" value="线下"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item class="font-medium" label="重量(KG)" prop="weight">
							<el-input v-model="ruleForm.weight" placeholder="请输入重量"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="国 家" prop="country_code">
							<el-select v-model="ruleForm.country_code" placeholder="请选择国家">
								<el-option v-for="item in countryOptions" :key="item" :label="item" :value="item"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item class="font-medium" label="预估硬件成本" prop="estimated_cost">
							<el-input v-model="ruleForm.estimated_cost" placeholder="请输入预估硬件成本"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="日常活动售价(外币)" prop="price_daily">
							<el-input v-model="ruleForm.price_daily" placeholder="请输入展示价格(外币)"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="尾程费用(外币)" prop="final_cost">
							<el-input v-model="ruleForm.final_cost" placeholder="请输入尾程费用(外币)"></el-input>
						</el-form-item>
						<el-form-item class="font-medium" label="成本" prop="cost">
							<el-button v-if="!ruleForm.cost" :icon="Select" class="w-full" plain type="primary" @click="showSelectDrawer"> 选 择 </el-button>
							<div v-else class="flex flex-1">
								<el-input v-model="ruleForm.cost" :disabled="true">
									<template #prepend>
										<i class="bi bi-cash-coin" style="color: #67c23a"></i>
									</template>
									<template #append>
										<el-button style="color: #e6a23c" @click="showSelectDrawer('supply')"> 重新选择</el-button>
									</template>
								</el-input>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
				<el-form-item>
					<el-divider />
					<div class="flex flex-1 justify-end">
						<el-button :icon="Close" @click="closeDrawer">取 消</el-button>
						<el-button :icon="Finished" :loading="btnLoading" type="primary" @click="submitForm(ruleFormRef)"> 确 定 </el-button>
					</div>
				</el-form-item>
			</el-form>
		</el-drawer>
	</div>
	<SelectDrawer v-if="isShow" v-model="isShow" :title="costType ==='supply' ? '供货' : '直销'" :rowData="rowData" @sendCheckId="getCheckId" />
</template>

<style scoped>
.drawer-container :deep(.el-drawer__header) {
	border-bottom: none;
	font-weight: 500;
}

.drawer-container :deep(.el-drawer__title) {
	font-size: 18px;
}
</style>
