<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-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <van-cell v-for="item in list" :key="item.approvalId" :title="`审批单号：${item.approvalId}`" clickable
                @click="handleCellClick(item.approvalId)">
                <template #label>
                    <div>商品名称：{{ item.goodsName }}</div>
                    <div>申请时间：{{ item.createTime }}</div>
                    <van-tag :type="statusTagType(item.status)">
                        {{ statusMap[item.status] }}
                    </van-tag>
                </template>
            </van-cell>
        </van-list>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { getApprovalListApi } from '@/common/apis/approval'
import type { SearchApiReturnApprovalQuery, ReturnApprovalEntity } from '@/common/apis/approval/type'
import type { PickerConfirmEventParams } from 'vant/es';
import { useApprovalStore } from '@/pinia/stores/approval';
import { useWxStore } from '@/pinia/stores/wx';
import { debounce } from 'lodash-es';

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

// 搜索参数
const activeTab = ref(0);
const searchParams = reactive<SearchApiReturnApprovalQuery>({
    corpid: wxStore.corpid,
    approvalType: 0,
    handleStatus: activeTab.value,
    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: '已驳回'
}

const statusText = ref('')

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

// 列表相关
const list = ref<ReturnApprovalEntity[]>([])
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/handle/${approvalId}`);
}

// 状态标签类型
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 handleTabChange = (tabIndex: number) => {
    searchParams.handleStatus = tabIndex;
    handleSearch();
};

// 处理时间选择
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 handleSearch = () => {
    list.value = [];
    searchParams.pageNum = 1;
    finished.value = false;
    onLoad();
}
const debouncedHandleSearch = debounce(() => {
    handleSearch();
}, 500);

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

onUnmounted(() => {
    debouncedHandleSearch.cancel();
});

// 重置表单
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 getApprovalListApi(searchParams)
        list.value.push(...data.rows)
        loading.value = false

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

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

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

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