<template>
    <div class="account-cost-list">
        <el-card class="!border-none mb-4" shadow="never">
            <div class="flex flex-wrap">
                <div class="w-1/2 md:w-1/3">
                    <div class="leading-10">当前筛选天数</div>
                    <div class="text-4xl">{{ pager.extend.days_count ?? 0 }}</div>
                </div>
                <div class="w-1/2 md:w-1/3">
                    <div class="leading-10">累计账户消耗 (元)</div>
                    <div class="text-4xl">¥{{ pager.extend.total_amount ?? '0.00' }}</div>
                </div>
            </div>
        </el-card>

        <el-card class="!border-none" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="日期范围">
                    <daterange-picker
                        v-model:startTime="queryParams.start_date"
                        v-model:endTime="queryParams.end_date"
                    />
                </el-form-item>
                <el-form-item label="自媒体渠道">
                    <el-select
                        v-model="queryParams.media_channel_code"
                        placeholder="筛选全部渠道"
                        clearable
                        filterable
                        class="account-cost-channel-select w-[220px]"
                    >
                        <el-option label="全部" value="" />
                        <el-option-group
                            v-for="g in mediaChannelGroups"
                            :key="g.group_name"
                            :label="g.group_name"
                        >
                            <el-option
                                v-for="ch in g.channels"
                                :key="ch.channel_code"
                                :label="ch.channel_name"
                                :value="ch.channel_code"
                            >
                                <div class="channel-opt-row">
                                    <span class="opt-name">{{ ch.channel_name }}</span>
                                </div>
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
                <el-form-item label="部门">
                    <el-tree-select
                        v-model="queryParams.dept_id"
                        :data="deptOptions"
                        node-key="id"
                        :props="treeProps"
                        :default-expand-all="true"
                        check-strictly
                        placeholder="筛选全部部门"
                        clearable
                        filterable
                        class="w-[220px]"
                    />
                </el-form-item>
                <el-form-item class="w-[280px]" label="备注/维护人">
                    <el-input
                        v-model="queryParams.remark"
                        placeholder="备注 / 创建人 / 修改人"
                        clearable
                        @keyup.enter="resetPage"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <el-card class="!border-none mt-4" shadow="never">
            <div>
                <el-button v-perms="['finance.account_cost/add']" type="primary" @click="handleAdd">
                    <template #icon>
                        <icon name="el-icon-Plus" />
                    </template>
                    新增
                </el-button>
            </div>

            <el-table class="mt-4" size="large" v-loading="pager.loading" :data="pager.lists">
                <el-table-column label="日期" prop="cost_date" min-width="120" />
                <el-table-column label="自媒体渠道" min-width="160">
                    <template #default="{ row }">
                        <span v-if="getChannelGroupLabel(row.media_channel_code)">
                            <el-tag size="small" class="mr-1">{{ getChannelGroupLabel(row.media_channel_code) }}</el-tag>
                            {{ row.media_channel_name }}
                        </span>
                        <span v-else>{{ row.media_channel_name }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="部门" prop="dept_name" min-width="140" />
                <el-table-column label="账户消耗" min-width="120">
                    <template #default="{ row }">¥{{ row.amount }}</template>
                </el-table-column>
                <el-table-column label="备注" prop="remark" min-width="260" show-overflow-tooltip />
                <el-table-column label="创建人" prop="creator_name" min-width="100" />
                <el-table-column label="最后修改人" prop="updater_name" min-width="100" />
                <el-table-column label="更新时间" prop="update_time" min-width="180" />
                <el-table-column label="操作" width="160" fixed="right">
                    <template #default="{ row }">
                        <el-button
                            v-perms="['finance.account_cost/edit']"
                            type="primary"
                            link
                            @click="handleEdit(row)"
                        >
                            编辑
                        </el-button>
                        <el-button
                            v-perms="['finance.account_cost/delete']"
                            type="danger"
                            link
                            @click="handleDelete(row.id)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="flex justify-end mt-4">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>

        <edit-popup
            v-if="showEdit"
            ref="editRef"
            :media-channel-groups="mediaChannelGroups"
            :dept-options="deptOptions"
            :default-media-channel-code="defaultMediaChannelCode"
            @success="getLists"
            @close="showEdit = false"
        />
    </div>
</template>

<script lang="ts" setup name="accountCostList">
import { accountCostDelete, accountCostLists } from '@/api/finance'
import { usePaging } from '@/hooks/usePaging'
import feedback from '@/utils/feedback'

import EditPopup from './edit.vue'

interface MediaChannelGroup {
    group_name: string
    channels: { channel_code: string; channel_name: string }[]
}

interface MediaChannelOption {
    code: string
    name: string
}

interface DeptOption {
    id: number
    name: string
    children?: DeptOption[]
}

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const showEdit = ref(false)

const queryParams = reactive({
    start_date: '',
    end_date: '',
    media_channel_code: '',
    dept_id: '',
    remark: '',
})

const { pager, getLists, resetPage } = usePaging({
    fetchFun: accountCostLists,
    params: queryParams,
})

const mediaChannelOptionsFlat = computed<MediaChannelOption[]>(() => {
    const options = pager.extend.media_channel_options
    if (!Array.isArray(options)) return []

    return options.map((item: Record<string, any>) => ({
        code: String(item.code || ''),
        name: String(item.name || ''),
    }))
})

const mediaChannelGroups = computed<MediaChannelGroup[]>(() => {
    const groups = pager.extend.media_channel_groups
    if (Array.isArray(groups) && groups.length > 0) {
        return groups as MediaChannelGroup[]
    }
    const flat = mediaChannelOptionsFlat.value
    if (!flat.length) {
        return []
    }
    return [
        {
            group_name: '渠道',
            channels: flat.map(item => ({
                channel_code: item.code,
                channel_name: item.name,
            })),
        },
    ]
})

const deptOptions = computed<DeptOption[]>(() => {
    const options = pager.extend.dept_options
    return Array.isArray(options) ? options : []
})

const defaultMediaChannelCode = computed(() => String(pager.extend.default_media_channel_code || ''))

const getChannelGroupLabel = (channelCode: string): string => {
    if (!channelCode) return ''
    for (const group of mediaChannelGroups.value) {
        const channel = group.channels.find(ch => ch.channel_code === channelCode)
        if (channel) {
            return group.group_name
        }
    }
    return ''
}

const treeProps = {
    value: 'id',
    label: 'name',
    children: 'children',
}

const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
}

const handleEdit = async (row: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.getDetail(row)
}

const handleDelete = async (id: number) => {
    await feedback.confirm('确定要删除这条账户消耗记录吗？')
    await accountCostDelete({ id })
    getLists()
}

const handleReset = () => {
    queryParams.start_date = ''
    queryParams.end_date = ''
    queryParams.media_channel_code = ''
    queryParams.dept_id = ''
    queryParams.remark = ''
    resetPage()
}

getLists()
</script>

<style scoped lang="scss">
.account-cost-channel-select {
    :deep(.channel-opt-row) {
        display: flex;
        align-items: center;
        width: 100%;
        min-width: 0;
        padding-right: 4px;
    }
    :deep(.opt-name) {
        flex: 1;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}
</style>
