<template>
    <el-dialog v-model="showDialog" title="选择产品" width="30%" :before-close="handleClose">
        <div class="select">
            <el-select v-if="status" v-model="beforeCode" @change="beforeChange">
                <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.code" />
            </el-select>

            <el-select v-else v-model="afterCode" @change="afterChange">
                <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.code" />
            </el-select>

        </div>
        <template #footer>
            <el-button type="primary" @click="onConfirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang='ts'>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

const props = defineProps({
    // select 数据源
    options: {
        type: Object,
        default: []
    }
})
const showDialog = ref(false)
const status = ref(true) // 判断是哪个选择产品
const type = ref()
const beforeCode = ref() //  第一个选择产品
const afterCode = ref() // 第二个选择产品

const emits = defineEmits(['codeChange', 'initCode'])

const afterChange = (value: string) => {
    type.value = 'after'
    afterCode.value = value
}
const beforeChange = (value: string) => {
    type.value = 'before'
    beforeCode.value = value
}

const onConfirm = () => {
    if (type.value === 'after') {
        if (!afterCode.value) return ElMessage({ type: 'warning', message: '产品不能为空' })
        if (afterCode.value === beforeCode.value) return ElMessage({ type: 'warning', message: '不能选择相同产品' })
        emits('codeChange', 'after', afterCode.value)
        showDialog.value = false
    } else if (type.value === 'before') {
        if (!beforeCode.value) return ElMessage({ type: 'warning', message: '产品不能为空' })
        if (afterCode.value === beforeCode.value) return ElMessage({ type: 'warning', message: '不能选择相同产品' })
        emits('codeChange', 'before', beforeCode.value)
        showDialog.value = false
    }
}

const handleClose = () => {
    showDialog.value = false
}

defineExpose({
    showDialog,
    status,
    type,
    afterCode,
    beforeCode
})
</script>
 
<style lang = "scss" scoped>
.select {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    :deep(.el-dialog__body) {
        display: flex;
        justify-content: center;
        align-items: center;
    }
}
</style>