<template>
    <app-view class="mine-invoice">
        <template #header>
            <app-navbar title="发票信息" />
        </template>
        <RadioGroup class="mine-invoice__container" v-model="checkedRow" v-if="dataList.length">
            <ul class="list">
                <li class="list-item" v-for="(item, index) in dataList" :key="index">
                    <div class="list-item__checkbox" @click="onChange(item)" v-if="showRadio">
                        <Radio :name="item" checked-color="#ee0a24" />
                    </div>
                    <div class="list-item__info" @click="onChange(item)">
                        <div class="list-item__info-name">
                            <Tag size="medium">{{ getReceiptTypeName(item.receipttype) }}</Tag>
                            <span>{{ item.username }}</span>
                            <Tag type="danger" round v-if="item.isdefault">默认</Tag>
                        </div>
                    </div>
                    <div class="list-item__button">
                        <Button icon="edit" @click="onEdit(item)" />
                    </div>
                </li>
            </ul>
        </RadioGroup>
        <Empty v-else />
        <template #footer>
            <div class="g-form__footer">
                <Button type="primary" @click="onEdit" round block>新增发票</Button>
            </div>
            <component ref="componentRef" v-bind="{ selectedRow }" :is="componentMap.get(componentId)"
                @closed="closeComponent" v-if="componentId" />
        </template>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, defineAsyncComponent, PropType } from 'vue'
import { RadioGroup, Radio, Button, Tag, Empty } from 'vant'
import { getReceiptTypeName } from '@/constants/receipt'
import { useComponent } from '@/hooks/component'
import { useRequest } from '@/hooks/request'
import { queryWrUserReceiptInfo } from '@/services/api/user'

const componentMap = new Map<string, unknown>([
    ['edit', defineAsyncComponent(() => import('./components/edit/index.vue'))],
])

const props = defineProps({
    // 是否显示单选按钮
    showRadio: {
        type: Boolean,
        default: false
    },
    checked: {
        type: Object as PropType<Model.WrUserReceiptInfoRsp>,
    }
})

const emit = defineEmits(['change'])
const { dataList, run } = useRequest(queryWrUserReceiptInfo)
const { componentRef, componentId, openComponent, closeComponent } = useComponent(() => run())
const checkedRow = shallowRef(props.checked)
const selectedRow = shallowRef()

// 选择发票
const onChange = (item: Model.WrUserReceiptInfoRsp) => {
    checkedRow.value = item
    emit('change', item)
}

const onEdit = (item?: Model.WrUserReceiptInfoRsp) => {
    selectedRow.value = item
    openComponent('edit')
}
</script>

<style lang="less">
@import './index.less';
</style>