<template>
    <a-modal v-model:visible="modelValue" width="800px" :title="$t('order.OrderDetails')" :closable="false">
        <div class="detail-box">
            <div class="detail-item-box">
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.OrderNum') }}</div>
                    <div class="item-content">{{ FormDataList.id }}</div>
                </div>
                <div class="detail-item">
                    <div class="item-label">{{ $t('lotCard.orderType') }}</div>
                    <div class="item-content">
                        <a-tag color="#168cff" v-if="FormDataList.tmsStatus == 1">{{ $t('order.unshipped') }}</a-tag>
                        <a-tag color="#00b42a" v-if="FormDataList.tmsStatus == 2">{{ $t('order.shipped') }}</a-tag>
                    </div>
                </div>
            </div>
            <div class="detail-item-box">
                <div class="detail-item">
                    <div class="item-label">{{ $t('lotCard.operator') }}</div>
                    <div class="item-content">{{ FormDataList.sourceName }}</div>
                </div>
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.TariffName') }}</div>
                    <div class="item-content">{{ tariffForm.label }}</div>
                </div>
            </div>
            <div class="detail-item-box">
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.BillingMode') }}</div>
                    <div class="item-content">{{ tariffForm.billingMethodName }}</div>
                </div>
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.SettlementCycle') }}</div>
                    <div class="item-content">{{ tariffForm.billingcycleName }}</div>
                </div>
            </div>
            <div class="detail-item-box">
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.CardType') }}</div>
                    <div class="item-content">{{ FormDataList.cardType }}</div>
                </div>
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.FlowPool') }}</div>
                    <div class="item-content">{{ FormDataList.isTrafficPool == 1 ? $t('lotCard.Yes') : $t('lotCard.No')
                        }}</div>
                </div>
            </div>
            <div class="detail-item-box">
                <div class="detail-item">
                    <div class="item-label">{{ $t('order.CardNum') }}</div>
                    <div class="item-content">{{ dataDetail.length<=10?dataDetail.length:tableDataList.length }}
                        <a-button type="primary" @click="showCard = true" style="margin-left:10px;"
                            v-if="userType == 1 && FormDataList.moderationStatus == 2">{{
                                $t('order.AllocationCardNumber') }}</a-button>
                    </div>
                </div>
            </div>
        </div>
        <div class="detail-table">
            <a-table :columns="columnsDetail" @page-change="evChangePage" :data="dataDetail"
                :pagination="dataDetail.length == 10 ? pagination : false" />
        </div>

        <template #footer>
            <a-button @click="cancel">{{ $t('form.Cancel') }}</a-button>
        </template>
    </a-modal>

    <!-- 分配卡号 -->
    <a-modal v-model:visible="showCard" :title="$t('order.AllocationCardNumber')"
        @cancel="closeModal(showCard, FormDataList)" @before-ok="showCard = false" :okText="$t('form.Confirm')"
        :cancelText="$t('form.Cancel')">
        <div style="display: flex;justify-content: space-between;">
            <div>
                <Upload listType="" minx="1" accept=".xlsx" :handelUpload="customRequest" :showRemoveButton="false">
                </Upload>
                <span style="color: #ccc;margin-top: 10px;display: inline-block;">请上传.xlsx文件</span>
            </div>
            <div>
                <a-button type="primary" @click="DownloadSampleFile">下载示例文件</a-button>
            </div>
        </div>
    </a-modal>
</template>

<script setup>
import { ref, onMounted, toRefs, toRef, watch } from 'vue';
import { AcquireOrdertariff, DistributionCard, ReturntheOrderCard } from '@/api/path/order'
import { Message } from '@arco-design/web-vue';
import Upload from "@/components/upload/index.vue";
import { Getdictionary } from '@/mixins/index.js'
import { downloadFile } from '@/utils/xlsx.js'
import { useI18n } from 'vue-i18n'
const { t } = useI18n();
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    FormDataList: {
        type: Object,
        default: () => ({})
    }
})
const modelValue = toRef(props, 'modelValue')
const FormDataList = toRef(props, 'FormDataList')
const emit = defineEmits(['update:modelValue', 'submit'])
const state = ref({
    tariffForm: {},
    showCard: false,
    res1: [],
    res2: [],
    res3: [],
    userType: JSON.parse(localStorage.getItem('user_login_information'))?.userType, // 1平台 2用户
})
const { tariffForm, showCard, res1, res2, res3, userType } = toRefs(state.value)
const columnsDetail = [{ title: 'ICCID', dataIndex: 'iccid' }, { title: t('order.CardStatus'), dataIndex: 'status' }, { title: t('order.CreationTime'), dataIndex: 'createdAt' }
]
// 初始数据
const tableDataList = ref([])
// 处理后的数据
const dataDetail = ref([])
const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0
})

// 分配卡号
const customRequest = (options) => {
    const formData = new FormData();
    formData.append('file', options.fileItem.file);  // 这里将文件添加到 FormDataList 中
    formData.append('orderId', FormDataList.value.id);
    DistributionCard(formData).then(res => {
        if (res.code == 200) {
            Message.success(res.message)
            if (res.data[0].length <= 10) {
                res.data[0].forEach(val => {
                    dataDetail.value.push({ iccid: val, status: val.status == 1 ? t('order.normal') : t('order.unsubscribe') })
                })
            } else {
                // 更新完整数据
                tableDataList.value = res.data[0];

                // 更新总条目数
                pagination.value.total = res.data[0].length;

                updatePageData();
            }
        }
    })
}

const cancel = () => {
    emit('update:modelValue', false)
}

const closeModal = () => {
    showCard.value = false
}

watch(() => FormDataList.value, val => {
    if (Object.keys(val).length === 0) return
    pagination.value.total = 0
    pagination.value.current = 1
    pagination.value.pageSize = 10
    AcquireOrdertariff({ id: val.trafficId }).then(res => {
        tariffForm.value = res.data
        tariffForm.value.billingcycleName = res1.value.filter(val => val.value == res.data.billingCycle)[0]?.label;
        tariffForm.value.billingMethodName = res2.value.filter(val => val.value == res.data.billingMethod)[0]?.label;
        tariffForm.value.TariffInfomr = res.data.trafficBilling + '/' + res.data.trafficBillingType
        tariffForm.value.pricingName = tariffForm.value.pricing !== '' ? tariffForm.value.pricing + '/' + res3.value.filter(val => val.value == res.data.currency)[0]?.label : '';
    })
    dataDetail.value = []
    ReturntheOrderCard({ id: val.id }).then(res => {
        console.log(res);
        if (res.data.length <= 10) {
            dataDetail.value.push(...res.data.map(val => ({ ...val, status: val.status == 1 ? t('order.normal') : t('order.unsubscribe') })))
        } else {
            // 更新完整数据
            tableDataList.value = res.data;

            // 更新总条目数
            pagination.value.total = res.data.length;

            updatePageData();
        }
    })
}, { deep: true })

const evChangePage = (page) => {
    pagination.value.current = page
    updatePageData();
}

// 更新分页数据方法
const updatePageData = () => {
    const startIndex = (pagination.value.current - 1) * pagination.value.pageSize;
    const endIndex = startIndex + pagination.value.pageSize; // 每次切 10 条
    dataDetail.value = tableDataList.value.slice(startIndex, endIndex);
};

const DownloadSampleFile = () => {
    // 下载示例文件
    downloadFile(['ICCID'], [['8968099000011939']])
}

onMounted(async () => {
    res1.value = await Getdictionary('Billingcycle')
    res2.value = await Getdictionary('billingMethod')
    res3.value = await Getdictionary('currencyType')
})
</script>
<style scoped lang="less">
.detail-box {
    .detail-item-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        .detail-item {
            //styleName: Body/Medium;
            font-family: PingFang SC;
            font-size: 14px;
            font-weight: 400;
            line-height: 22px;
            text-align: left;
            display: flex;
            align-items: center;
            min-width: 350px;

            .item-label {
                color: rgba(0, 0, 0, 0.4);
                width: 120px;
                text-align: right;
                margin-right: 10px;
            }

            .item-content {
                color: rgba(51, 51, 51, 1);
            }
        }
    }
}
</style>