<template>
    <div>
        <div>
            <el-table :data="pager.lists" v-loading="pager.loading">
                <el-table-column label="标题" prop="name" show-overflow-tooltip />
                <el-table-column label="日期" prop="date" show-overflow-tooltip />
                <el-table-column label="收入金额" prop="income" show-overflow-tooltip />
                <el-table-column label="支出金额" prop="expenditure" show-overflow-tooltip />
                <el-table-column label="门店应入账金额" prop="enter" show-overflow-tooltip />
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button v-perms="['store_cash_finance_flow.store_cash_finance_flow/edit']" type="primary"
                            link @click="openDetail(row)">
                            详情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="flex mt-4 justify-end">
            <pagination v-model="pager" @change="getLists" />
        </div>
        <el-dialog v-model="showDetail" title="订单详情" width="70%">
            <runWaterPop ref="runRef"></runWaterPop>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="billTable">
import { usePaging } from '@/hooks/usePaging'
import { apiDayBillLists, apiWeekBillLists, apiMonthBillLists } from '@/api/store_finance_bill'
import moment from 'moment';

let apiFun = apiDayBillLists;

const props = defineProps({
    queryParams: {
        type: Object,
        default: () => ({})
    },
    type: {
        type: String,
        default: 'day'
    }
})

if (props.type == 'day') apiFun = apiDayBillLists;
if (props.type == 'week') apiFun = apiWeekBillLists;
if (props.type == 'month') apiFun = apiMonthBillLists;

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiFun,
    params: props.queryParams
})

defineExpose({
    getLists
})

const extractWeekNumber = (str:any)=> {
    // 使用正则表达式匹配"第xxxx-xx周"中的xx，即周数
    const weekRegex = /第\d{4}-([0-9]{1,2})周/;
    const match = str.match(weekRegex);
    
    if (match) {
        // 返回匹配到的周数
        return parseInt(match[1], 10);
    } else {
        // 如果没有匹配到，返回null或其他默认值
        return null;
    }
}
const extractYear = (str: any) => {
    // 使用正则表达式匹配"第xxxx-xx周"中的xxxx，即年份
    const yearRegex = /第(\d{4})-\d{1,2}周/;
    const match = str.match(yearRegex);
    
    if (match) {
        // 返回匹配到的年份
        return parseInt(match[1], 10);
    } else {
        // 如果没有匹配到，返回null或其他默认值
        return moment(new Date()).format('YYYY');
    }
}
const convertToYYYYMMDD = (dateString:any) => {
    // 分割输入字符串获取年和月
    const year = dateString.split('年')[0];
    const month = dateString.split('年')[1].split('月')[0];
    
    // 创建Date对象，注意JavaScript的月份是从0开始的，所以需要减1
    const date = new Date(year, month - 1, 1);
    
    // 格式化日期为yyyy-mm-dd
    const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
    
    return formattedDate;
}


const runRef = ref(null);
const showDetail = ref(null);
const openDetail = async (row: any) => {
    showDetail.value = true;
    await nextTick();
    if(props.type == 'day'){
        runRef.value?.init({
            start_time: moment(row.date).format('YYYY-MM-DD') + ' 00:00:00',
            end_time: moment(row.date).format('YYYY-MM-DD') + ' 23:59:59',
        });
    }else if(props.type == 'week'){
        let t = extractWeekNumber(row.date);
        if(t){
            let year:any = extractYear(row.date);
            // 初始化日期为该年第1周的星期一（这里假设1月1日是星期四，因为2024年1月1日是星期二，但我们需要调整到最近的星期一）
            let now = new Date(year, 0, 1 - (new Date(year, 0, 1).getDay() || 7) + 1); // 这里确保了得到的是当周的星期一
            now.setDate(now.getDate() + (t - 1) * 7); // 从第1周的周一到第23周的周一需要增加(23-1)*7天 
            let end = new Date(now);
            end.setDate(end.getDate() + 6)
            runRef.value?.init({
                start_time: moment(now).format('YYYY-MM-DD') + ' 00:00:00',
                end_time: moment(end).format('YYYY-MM-DD') + ' 23:59:59',
            });
        }else runRef.value?.init({});
    } else {
        let sdate = convertToYYYYMMDD(row.date); //获取当前月
        let edate = new Date(sdate); 
        edate.setMonth(edate.getMonth()+1); //当前月份+1
        edate.setDate(edate.getDate()-1); //当前日期-1即可获得上月最后一天
        runRef.value?.init({
            start_time: moment(sdate).format('YYYY-MM-DD') + ' 00:00:00',
            end_time: moment(edate).format('YYYY-MM-DD') + ' 23:59:59',
        });
    }
}

onMounted(() => {
    getLists()
})


</script>

<style lang="scss" scoped></style>

