<template>
    <el-drawer v-model="drawerVisible" size="100%" :with-header="false" direction="btt">
        <div class="drawer_wrap">
            <div class="header">
                <div class="left">
                    <div class="return" @click="drawerVisible = false">
                        <el-icon size="26" color="#555">
                            <Back />
                        </el-icon>
                    </div>
                    <div class="user_info">
                        <el-image :src="userInfo.headImg" fit="cover"
                            style="width: 40px; height: 40px; border-radius: 50%;background-color: #efefef;">
                            <template #error>
                                <el-icon style="font-size: 40px; color: #ccc;">
                                    <user />
                                </el-icon>
                            </template>
                        </el-image>
                        <el-text>{{ userInfo.nickName }}/{{ userInfo.phone }}</el-text>
                    </div>
                </div>
                <div class="right">
                    <!-- <el-button type="danger" @click="dialogVisible = true">取酒</el-button> -->
                    <el-button type="primary" @click="dialogVisible = true">新增存酒</el-button>
                </div>
            </div>
            <div class="pay_wrap">
                <div class="tab">
                    <el-table :data="list" height="100%" border stripe>
                        <el-table-column label="记录" prop="name"></el-table-column>
                        <el-table-column label="数量" prop="num"></el-table-column>
                        <el-table-column label="到期时间" prop="expTime"></el-table-column>
                        <el-table-column label="操作" width="250">
                            <template #default="{ row }">
                                <el-button type="primary" @click="viewRecord(row)">查看记录</el-button>
                                <el-button type="danger" :disabled="isExpired(row.expTime) || row.num <= 0"
                                    @click="takeWineDialogVisible = true; maxTakeNum = row.num; takeWineForm.id = row.id;">
                                    <span v-if="isExpired(row.expTime) || row.status == 2">已过期</span>
                                    <span v-else-if="row.num <= 0">已取完</span>
                                    <span v-else>取酒</span>
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
    </el-drawer>
    <el-dialog v-model="dialogVisible" title="新增存酒" width="350px" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="form" :rules="rules" label-width="100px" label-position="left">
            <el-form-item label="选择酒品">
                <el-select v-model="form.shopStorageGoodId" placeholder="请选择存酒商品" style="width: 180px;">
                    <el-option v-for="item in storageGoodList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="存酒数量">
                <el-input-number v-model="form.num" :min="1"></el-input-number>
            </el-form-item>
            <el-form-item label="存酒有效期">
                <el-input-number v-model="form.expDay" :min="1"></el-input-number>
                <span style="margin-left: 8px;">天</span>
            </el-form-item>
        </el-form>
        <div class="dialog-footer">
            <div class="btn">
                <el-button style="width: 100%;" @click="dialogVisible = false">取 消</el-button>
            </div>
            <div class="btn">
                <el-button style="width: 100%;" type="primary" :loading="confirmLoading" @click="confirmHandle">确
                    定</el-button>
            </div>
        </div>
    </el-dialog>
    <!-- 取酒对话框,只选择数量即可，不可超过存酒的数量 -->
    <el-dialog v-model="takeWineDialogVisible" title="取酒" width="350px" :close-on-click-modal="false" destroy-on-close>
        <el-form :model="takeWineForm" :rules="takeWineRules" label-width="100px" label-position="left">
            <el-form-item label="取酒数量">
                <el-input-number v-model="takeWineForm.num" :min="1" :max="maxTakeNum"></el-input-number>
            </el-form-item>
        </el-form>
        <div class="dialog-footer">
            <div class="btn">
                <el-button style="width: 100%;" @click="takeWineDialogVisible = false">取 消</el-button>
            </div>
            <div class="btn">
                <el-button style="width: 100%;" type="primary" :loading="takeWineConfirmLoading"
                    @click="confirmTakeWineHandle">确 定</el-button>
            </div>
        </div>
    </el-dialog>
    <!-- 存取酒记录弹窗 -->
    <el-dialog title="记录" width="600px" v-model="showRecordDialogVisible">
        <el-table :data="recordList" border stripe>
            <el-table-column label="记录" prop="content"></el-table-column>
            <el-table-column label="操作时间" prop="time"></el-table-column>
        </el-table>
    </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from 'element-plus'
import { shopStoragePost, storageGoodGet, shopStorageGet, shopStoragePut, shopStorageRecord } from '@/api/product_new'

const props = defineProps({
    userInfo: {
        type: Object,
        default: () => ({})
    }
})

const drawerVisible = ref(false);
const dialogVisible = ref(false);

const list = ref([]);

// 获取存酒记录
async function shopStorageGetAjax() {
    try {
        const res = await shopStorageGet({
            key: '',
            phone: props.userInfo.phone,
            page: 1,
            size: 999,
        });
        list.value = res.records || [];
    } catch (error) {
        console.error('获取存酒列表失败:', error);
    }
}

const form = ref({
    userId: '',
    shopStorageGoodId: '', // 存酒商品ID
    num: 1, // 存酒数量
    expDay: 1, // 存酒有效期，单位天默认1天
})

const rules = {
    shopStorageGoodId: [{ required: true, message: '请选择存酒商品', trigger: 'change' }],
    num: [{ required: true, message: '请输入存酒数量', trigger: 'change' }],
    expDay: [{ required: true, message: '请输入存酒有效期', trigger: 'change' }],
}

// 确认存酒
const confirmLoading = ref(false);
async function confirmHandle() {
    try {
        confirmLoading.value = true;
        form.value.userId = props.userInfo.userId;
        await shopStoragePost(form.value);
        ElMessage.success('存酒成功');
        dialogVisible.value = false;
        shopStorageGetAjax(); // 刷新存酒商品列表
    } catch (error) {
        console.error('存酒失败:', error);
    } finally {
        confirmLoading.value = false;
    }
}

// 获取存酒商品列表
const storageGoodList = ref([]);
async function storageGoodGetAjax() {
    try {
        const res = await storageGoodGet({
            page: 1,
            size: 999,
        });
        storageGoodList.value = res.records || [];
    } catch (error) {
        console.error('获取存酒商品列表失败:', error);
    }
}

const takeWineDialogVisible = ref(false);
const takeWineForm = ref({
    id: '', // 存酒记录ID
    num: 1,
})
const takeWineRules = {
    num: [{ required: true, message: '请输入取酒数量', trigger: 'change' }],
}
const maxTakeNum = ref(1);
const takeWineConfirmLoading = ref(false);

function confirmTakeWineHandle() {
    shopStoragePutAjax();
}

// 存酒取酒 num 必需 正数为存酒反之为取酒
async function shopStoragePutAjax() {
    try {
        takeWineConfirmLoading.value = true;
        await shopStoragePut({
            id: takeWineForm.value.id,
            num: -takeWineForm.value.num, // 取酒数量为负数
        });
        ElMessage.success('取酒成功');
        takeWineDialogVisible.value = false;
        shopStorageGetAjax(); // 刷新存酒记录列表
    } catch (error) {
        console.error('取酒失败:', error);
    } finally {
        takeWineConfirmLoading.value = false;
    }
}

function init() {
    drawerVisible.value = false;
    dialogVisible.value = false;
    takeWineDialogVisible.value = false;
    form.value = {
        userId: '',
        shopStorageGoodId: '',
        num: 1,
        expDay: 1,
    };
    takeWineForm.value = {
        id: '',
        num: 1,
    };
    maxTakeNum.value = 1;
    list.value = [];
}

function isExpired(expTime) {
    if (!expTime) return false;
    const now = new Date();
    const expDate = new Date(expTime);
    return expDate < now;
}

// 查看记录
const showRecordDialogVisible = ref(false);
const recordList = ref([]);
async function viewRecord(row) {
    try {
        showRecordDialogVisible.value = true;
        const res = await shopStorageRecord({
            id: row.id,
            page: 1,
            size: 999,
        });
        recordList.value = res || [];
    } catch (error) {
        console.error('获取存取酒记录失败:', error);
    }
}

function show() {
    init();
    drawerVisible.value = true;
    // 刷新列表数据
    storageGoodGetAjax();
    shopStorageGetAjax();
}

defineExpose({
    show,
    init,
});

// 初始化



onMounted(() => {
    storageGoodGetAjax();
    shopStorageGetAjax();
})
</script>

<style scoped lang="scss">
.drawer_wrap {
    width: 100%;
    height: 100%;
    display: flex;
    padding: var(--el-font-size-base) 0;
    flex-direction: column;
    gap: var(--el-font-size-base);

    .header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 var(--el-font-size-base);
        background-color: #fff;
        padding: var(--el-font-size-base);
        border-radius: var(--el-font-size-base);

        .left {
            display: flex;
            align-items: center;
            gap: var(--el-font-size-base);

            .return {
                cursor: pointer;
                border-radius: 4px;
                transition: background-color 0.3s;
                padding: 10px 8px 4px;

                &:hover {
                    background-color: rgba(0, 0, 0, 0.1);
                }
            }

            .user_info {
                display: flex;
                align-items: center;
                gap: var(--el-font-size-base);
            }
        }
    }

    .pay_wrap {
        flex: 1;
        background: #fff;
        border-radius: var(--el-font-size-base);

        .tab {
            height: 100%;
            padding: var(--el-font-size-base);
        }
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: var(--el-font-size-base);

    .btn {
        flex: 1;
    }
}
</style>