<template>
    <view class="fb-data-list">
        <ZPaging :fixed="false" ref="paging" v-model="dataSource" @query="loadMore">
            <template v-slot:top>
                <FBFilterBar v-model="searchData" :showBatch="!!selectionActions?.length" :queryFields="queryFields"
                    :switchBatch="switchBatch" :batch="batch">
                </FBFilterBar>
            </template>
            <FBGap />
            <view class="fb-data-list-container">
                <view class="fb-data-list-item" v-for="(item, index) in dataSource" :key="index">
                    <view v-if="batch" class="fb-data-list-item-checkbox" @click="selectItem(index)">
                        <uv-icon v-if="selected?.[index]" name="checkbox-checked" custom-prefix="fb-icon" size="22"
                            color="#1456F0"></uv-icon>
                        <uv-icon v-else name="checkbox-unchecked" custom-prefix="fb-icon" size="22"
                            color="#999"></uv-icon>
                    </view>
                    <view v-else class="fb-data-list-item-padding" />
                    <view class="fb-data-list-item-info" @click="selectItem(index)">
                        <view class="fb-data-list-item-header">
                            <view class="fb-data-list-item-title">
                                <FBListField class="field-item" v-for="(field, fi) in titleFields" :key="fi"
                                    :fieldInfo="field" :itemValue="item" />
                            </view>
                            <view class="fb-data-list-item-status">
                                <FBListField class="field-item" v-for="(field, fi) in statusFields" :key="fi"
                                    :fieldInfo="field" :itemValue="item" />
                            </view>
                        </view>
                        <view class="fb-data-list-item-content">
                            <FBListField class="field-item" v-for="(field, fi) in contentFields" :key="fi"
                                :fieldInfo="field" :itemValue="item" />
                        </view>
                    </view>
                    <view v-if="!batch && item.___FB_RECORD_ACTIONS?.length" class="fb-data-list-item-actions"
                        @click="showRecordAction(index)">
                        <uv-icon name="more-dot-fill" color="#444" size="22"></uv-icon>
                    </view>
                    <view v-else class="fb-data-list-item-padding" />
                    <uv-action-sheet v-if="item.___FB_RECORD_ACTIONS?.length" :ref="el => setRef(el, index)"
                        @select="ab => doRecordAction(item, ab)" :actions="item.___FB_RECORD_ACTIONS" cancelText="取消" />
                </view>
            </view>
            <FBButtonBar hide-placeholder v-if="batch" :actions="selectionActions"></FBButtonBar>
            <FBButtonBar hide-placeholder v-else :actions="actions"></FBButtonBar>
        </ZPaging>
    </view>
</template>

<script setup lang="ts">
import { computed, defineProps, onMounted, ref, watch } from 'vue'
import { Debounce } from 'fastball-mobile-common';
import ZPaging from 'z-paging/components/z-paging/z-paging.vue';

import type { ActionInfo, Data } from '../../types/basic';
import type { ListProps } from '../../types/components/list';
import { doApiAction } from '../../commons/api/component';

import FBButtonBar from '../commons/fb-button-bar.vue'
import FBGap from '../commons/fb-gap.vue';
import FBFilterBar from './filter-bar.vue';
import FBListField from './fb-list-field.vue';
import { doAction, filterVisibled } from '../../commons/utils/action';

interface ActionButton {
    name?: string;
    action: ActionInfo;
}

interface ListRecord extends Data {
    ___FB_RECORD_ACTIONS?: ActionButton[];
}

const { componentKey, fields, queryFields, input, onDataLoad, actions, selectionActions, recordActions } = defineProps<ListProps>()

const paging = ref()
const searchData = ref<any>({})
const actionSheetRefs = ref<{ [key: number]: any }>({})
const dataSource = ref<Data[]>()
const selected = ref<{ [key: number]: boolean }>()
const batch = ref(false)

const setRef = (el: any, index: number) => {
    actionSheetRefs.value[index] = el
}

const selectItem = (index: number) => {
    if (!batch.value) {
        return;
    }
    const currentSelected = selected.value || {}
    selected.value = { ...currentSelected, [index]: !currentSelected[index] }
    console.log(index, currentSelected, selected.value)
}

const switchBatch = () => {
    batch.value = !batch.value
    if (!batch.value) {
        selected.value = []
    }
}

const showRecordAction = (index: number) => {
    actionSheetRefs.value?.[index]?.open();
}

const doRecordAction = (record: ListRecord, actionButton: ActionButton) => {
    if (!actionButton) {
        console.error('can not happen')
        return;
    }
    doAction({
        ...actionButton.action,
        data: record,
        closePopupOnSuccess: true,
        callback: () => {
            fetchListData()
        }
    })
}

const titleFields = computed(() => {
    return fields.filter(field => field.position === 'Title' && field.display === 'Show')
})

const statusFields = computed(() => {
    return fields.filter(field => field.position === 'Status' && field.display === 'Show')
})

const contentFields = computed(() => {
    return fields.filter(field => field.position === 'Content' && field.display === 'Show')
})

const fetchListData = async (current: number, pageSize: number) => {
    const search = searchData.value
    console.log(search)
    const result = await doApiAction({ componentKey, type: 'API', actionKey: 'loadData', needArrayWrapper: false, data: [{ search, current, pageSize }, input] })
    const { data, total } = result
    if (onDataLoad) {
        onDataLoad(data);
    }
    data.forEach((record: Data) => {
        const recordActionAvailableFlags = record.recordActionAvailableFlags as Record<string, boolean>
        const recordActionButtons = recordActions?.filter(filterVisibled)
            .filter(action => !recordActionAvailableFlags || recordActionAvailableFlags[action.actionKey] !== false)
            .map(action => ({ name: action.actionName, action }))
        record.___FB_RECORD_ACTIONS = recordActionButtons
    });
    paging.value.completeByTotal(data, total)
}

const loadMore = async (current: number, pageSize: number) => {
    console.log(current, 'loadMore')
    await fetchListData(current, pageSize)
}

const reloadData = () => {
    paging.value.reload()
}

onMounted(async () => {
    await fetchListData(1, 10)
})

watch(searchData, Debounce(reloadData), { deep: true });
</script>

<style lang="less" scoped>
.fb-data-list {
    height: 100%;
    background-color: #F4F5F9;

    .fb-data-list-container {
        display: flex;
        row-gap: 10px;
        flex-direction: column;

        .fb-data-list-item {
            background-color: #fff;
            display: flex;

            .fb-data-list-item-info {
                flex: 1;
                padding: 20px 0px 20px 0px;

                .fb-data-list-item-header {
                    display: flex;
                    align-items: center;
                    margin-bottom: 10px;

                    .fb-data-list-item-title {
                        margin-right: 15px;
                    }

                    .fb-data-list-item-status {
                        display: flex;
                        column-gap: 10px;
                    }
                }
            }

            .fb-data-list-item-checkbox {
                display: flex;
                justify-items: center;
                padding: 20px;
            }

            .fb-data-list-item-padding {
                width: 20px;
            }

            .fb-data-list-item-actions {
                display: flex;
                justify-items: center;
                padding: 20px;
            }
        }
    }
}
</style>