<template>
    <div class="approval-list-container">
        <!-- 搜索表单 -->
        <van-form @submit="handleSearch">
            <van-field v-model="searchParams.approvalId" label="审批单号" type="number" placeholder="请输入审批单号" />

            <van-field v-model="searchParams.orderId" label="订单编号" type="number" placeholder="请输入订单编号" />

            <van-field v-model="searchParams.goodsId" label="商品ID" type="number" placeholder="请输入商品ID" />

            <van-field name="status" label="审批状态" readonly clickable v-model="statusText" placeholder="请选择状态"
                @click="showStatusPicker = true" />
            <van-popup v-model:show="showStatusPicker" position="bottom">
                <van-picker :columns="statusOptions" @confirm="onStatusConfirm" @cancel="showStatusPicker = false" />
            </van-popup>

            <!-- <van-field
        readonly
        clickable
        name="date"
        :value="dateRangeText"
        label="申请时间"
        placeholder="选择时间范围"
        @click="showDatePicker = true"
      />
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-datetime-picker
          type="daterange"
          @confirm="onDateConfirm"
          @cancel="showDatePicker = false"
        />
      </van-popup> -->

            <div style="margin: 16px;">
                <van-button block type="primary" native-type="submit">搜索</van-button>
                <van-button block plain type="primary" style="margin-top: 10px;" @click="handleReset">重置</van-button>
            </div>
        </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';

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

// 搜索参数
const searchParams = reactive<SearchApiReturnApprovalQuery>({
    corpid: wxStore.corpid,
    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);
    }
    if (currentItem?.approvalType == 1) {
        router.push(`/approval/handleApply/${approvalId}`);
    } else {
        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 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
    onLoad()
}

// 重置表单
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 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>