<template>
    <div class="approval-list-container">
        <!-- 状态切换标签页 -->
        <van-tabs v-model:active="activeTab" @change="handleTabChange">
            <van-tab title="待处理"></van-tab>
            <van-tab title="已处理"></van-tab>
        </van-tabs>
        <!-- 搜索表单 -->
        <van-form @submit="handleSearch">
            <van-search v-model="searchParams.searchStr" placeholder="请输入搜索内容" />
        </van-form>

        <van-dialog v-model:show="showVerificationDialog" title="输入核销码" @confirm="handleVerification">
            <van-field v-model="verificationCode" placeholder="请输入核销码" />
        </van-dialog>

        <!-- 审批列表 -->
        <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad"
            class="approval-list">
            <van-cell v-for="item in list" :key="item.approvalId" :title="`审批单号：${item.approvalId}`" clickable
                @click="handleCellClick(item.approvalId)">
                <template #label>
                    <div v-for="goods in item.goodsList" :key="goods.approvalGoodsId">
                        商品名称：{{ goods.goodsName }}
                    </div>
                    <div>申领人：{{ item.applyUserName }}</div>
                    <div>核销码：{{ item.code }}</div>
                    <div>申请时间：{{ item.createTime }}</div>
                    <van-tag :type="statusTagType(item.status)">
                        {{ statusMap[item.status] }}
                    </van-tag>
                </template>
            </van-cell>
        </van-list>

        <!-- 悬浮核销码按钮 -->
        <van-button type="primary" @click="showVerificationDialog = true" class="floating-verification-btn">
            <van-icon name="plus" style="font-size: 20px;" />
            <!-- <span>核销码</span> -->
        </van-button>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onUnmounted } from 'vue'
import { debounce } from 'lodash-es'
import { showDialog, showToast } from 'vant'
import { checkApprovalCodeApi, getApprovalAssetListApi } from '@/common/apis/approval'
import type { SearchReturnApprovalAssetQuery, ReturnApprovalAssetDTO } from '@/common/apis/approval/type'
import type { PickerConfirmEventParams } from 'vant/es';
import { useApprovalStore } from '@/pinia/stores/approval';
import { useWxStore } from '@/pinia/stores/wx';

const router = useRouter();
const wxStore = useWxStore();

// 搜索参数
const activeTab = ref(0);
const searchParams = reactive<SearchReturnApprovalAssetQuery>({
    corpid: wxStore.corpid,
    handleStatus: activeTab.value,
    approvalType: 1,
    code: '',
    codeCheck: 1,
    searchStr: '',
    pageNum: 1,
    pageSize: 10,
})

// 状态选择相关
const showStatusPicker = ref(false)
const statusOptions = [
    { text: '全部', value: undefined },
    { text: '待审核', value: 1 },
    { text: '已通过', value: 2 },
    { text: '已驳回', value: 3 },
]

const statusMap: { [key: number]: string } = {
    1: '待审核',
    2: '已通过',
    3: '已驳回',
    4: '开柜中'
}

const statusText = ref('')

// 时间选择相关
const showDatePicker = ref(false)
const dateRangeText = ref('')

// 核销码相关
const showVerificationDialog = ref(false)
const verificationCode = ref('')

// 列表相关
const list = ref<ReturnApprovalAssetDTO[]>([])
const loading = ref(false)
const finished = ref(false)

const handleCellClick = (approvalId: number) => {
    const approvalStore = useApprovalStore()
    const currentItem = list.value.find(item => item.approvalId === approvalId)
    if (currentItem) {
        approvalStore.setCurrentApproval(currentItem);
    }
    router.push(`/approval/handleApply/${approvalId}`);
}

// 处理核销码提交
const handleVerification = async () => {
    if (!verificationCode.value) {
        showDialog({ message: '请输入核销码' })
        return
    }
    try {
        const params = {
            corpid: wxStore.corpid,
            approvalType: 1,
            code: verificationCode.value
        }
        await checkApprovalCodeApi(params)
        showDialog({ message: '核销成功' })
        showVerificationDialog.value = false
        verificationCode.value = ''
        // 刷新列表
        handleSearch()
    } catch (error) {
        console.error('核销失败', error)
        showDialog({ message: '核销失败' })
    }
}

// 状态标签类型
const statusTagType = (status: number) => {
    switch (status) {
        case 1: return 'warning'
        case 2: return 'success'
        case 3: return 'danger'
        default: return 'default'
    }
}

// 处理状态选择
const onStatusConfirm = (e: PickerConfirmEventParams) => {
    const { selectedOptions } = e;
    searchParams.status = selectedOptions[0]?.value ? Number(selectedOptions[0]?.value) : undefined;
    showStatusPicker.value = false;
    // 确保赋值给 statusText 的是字符串类型
    statusText.value = String(selectedOptions[0]?.text || '');
}

// 处理时间选择
const onDateConfirm = (values: Date[]) => {
    const [start, end] = values
    searchParams.startTime = start.toISOString().split('T')[0]
    searchParams.endTime = end.toISOString().split('T')[0]
    dateRangeText.value = `${searchParams.startTime} 至 ${searchParams.endTime}`
    showDatePicker.value = false
}

// 标签页切换处理
const handleTabChange = (tabIndex: number) => {
    searchParams.handleStatus = tabIndex;
    handleSearch();
};

// 搜索处理
const handleSearch = () => {
    list.value = [];
    searchParams.pageNum = 1;
    finished.value = false;
    onLoad();
}

const debouncedHandleSearch = debounce(() => {
    handleSearch();
}, 500);

// 重置表单
const handleReset = () => {
    Object.assign(searchParams, {
        pageNum: 1,
        pageSize: 10,
        approvalId: undefined,
        orderId: undefined,
        goodsId: undefined,
        status: undefined,
        startTime: undefined,
        endTime: undefined
    })
    statusText.value = ''
    dateRangeText.value = ''
    handleSearch()
}

// 加载数据
const onLoad = async () => {
    try {
        searchParams.corpid = wxStore.corpid;
        const { data } = await getApprovalAssetListApi(searchParams)
        // 根据approvalId去重后再添加新数据
        const existingIds = new Set(list.value.map(item => item.approvalId));
        const newItems = data.rows.filter(item => !existingIds.has(item.approvalId));
        list.value.push(...newItems);
        loading.value = false

        if (list.value.length >= data.total) {
            finished.value = true
        } else {
            searchParams.pageNum++
        }
    } catch (error) {
        console.error('获取审批列表失败', error)
        finished.value = true
    }
}

// 监听搜索字符串变化触发搜索
watch(() => searchParams.searchStr, (newVal) => {
    debouncedHandleSearch();
});

onUnmounted(() => {
    debouncedHandleSearch.cancel();
});
</script>

<style lang="scss" scoped>
.approval-list-container {
    padding: 12px;
}

.approval-list {
    margin-top: 12px;
}

.van-cell__title {
    font-size: 14px;
    color: #333;
}

.van-cell__label {
    margin-top: 8px;
    color: #666;
    font-size: 12px;
}

.btn-group {
    display: flex;
    width: 100%;
    gap: 12px;
    margin: 8px 0;
    background-color: #ffffff;
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
    padding: 16px;
}

.floating-verification-btn {
    position: fixed;
    bottom: 80px;
    right: 20px;
    border-radius: 50%;
    width: 56px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    padding: 0;
}
</style>