<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 }}
                        <template v-if="!show">
                            <a-button type="primary"  @click="showCard = true" style="margin-left:10px;"
                            v-if="userType == 1 && FormDataList.moderationStatus == 2">{{
                                $t('order.AllocationCardNumber') }}</a-button>
                        </template>
                    </div>
                </div>
            </div>
        </div>
        <div class="detail-table" v-if="!show">
            <a-table :columns="columnsDetail" :data="dataDetail" />
        </div>

        <div class="progress" v-if="show">
            <div class="title">{{ schedule }}</div>
            <!-- <div class="cusrte">
                <a-progress type="circle" :percent="(schedule / 100)" size="large" />
            </div> -->
        </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')" unmount-on-close>
        <div style="display: flex;justify-content: space-between;">
            <div>
                <Upload listType="" minx="1" accept=".xlsx" :handelUpload="customRequest" :showRemoveButton="false" v-if="showCard">
                </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, GuideCardProgress } 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用户
    show: false,
    schedule: 0, // 进度
    ids: null
})

const { tariffForm, showCard, res1, res2, res3, userType, show, schedule, ids } = toRefs(state.value)
const columnsDetail = [
    { title: 'ICCID', dataIndex: 'iccid' },
    { title: t('order.CardStatus'), dataIndex: 'status' },
    { title: t('order.CreationTime'), dataIndex: 'createdAt' }
]

const dataDetail = ref([])
let timer;

// 分配卡号并开始进度监控
const customRequest = async (options) => {
    const formData = new FormData();
    formData.append('file', options.fileItem.file); // 文件
    formData.append('orderId', FormDataList.value.id);

    const res = await DistributionCard(formData);
    if (res.code === 200) {
        Message.success(res.message);
        showCard.value = false;
        
        const progressRes = await GuideCardProgress({ id: FormDataList.value.id });
        handleProgressResponse(progressRes);
    }
}

// 关闭弹窗
const cancel = () => emit('update:modelValue', false);
const closeModal = () => showCard.value = false;

// 监听 FormDataList 的变化
watch(() => FormDataList.value, val => {
    if (Object.keys(val).length === 0) return;

    ids.value = val.id;
    fetchTariffData(val.trafficId);
    fetchOrderCardData(val.id);
}, { immediate: true });

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

// 获取和处理订单资费数据
const fetchTariffData = async (trafficId) => {
    const res = await AcquireOrdertariff({ id: trafficId });
    tariffForm.value = res.data;
    tariffForm.value.billingcycleName = res1.value.find(item => item.value === res.data.billingCycle)?.label;
    tariffForm.value.billingMethodName = res2.value.find(item => item.value === res.data.billingMethod)?.label;
    tariffForm.value.TariffInfomr = `${res.data.trafficBilling}/${res.data.trafficBillingType}`;
    tariffForm.value.pricingName = res.data.pricing ? `${res.data.pricing}/${res3.value.find(item => item.value === res.data.currency)?.label}` : '';
}

// 获取和处理订单卡信息
const fetchOrderCardData = async (orderId) => {
    const res = await ReturntheOrderCard({ id: orderId });
    dataDetail.value = res.data?.map(item => ({
        ...item, status: item.status === 1 ? t('order.normal') : t('order.unsubscribe')
    })) || [];
}

// 处理导卡进度响应
const handleProgressResponse = (progressRes) => {
    if (progressRes.code === 200) {
        show.value = progressRes.data !== 0 && progressRes.data !== 100;
        schedule.value = progressRes.data;
        if (progressRes.data === 100) {
            clearInterval(timer);
            getICCIDDetaile();
        } else {
            startProgressMonitor(progressRes.data);
        }
    }
}

// 启动定时器监控导卡进度
function startProgressMonitor(initialProgress) {
    if (timer) clearInterval(timer);

    timer = setInterval(async () => {
        const progressRes = await GuideCardProgress({ id: FormDataList.value.id });
        if (progressRes.code === 200) {
            show.value = progressRes.data !== 0 && progressRes.data !== 100;
            if (progressRes.data === 100) {
                clearInterval(timer);
                getICCIDDetaile();
            }
            schedule.value = progressRes.data;
        }
    }, 5000); // 每10秒检查一次
}

// 获取 ICCID 详情
const getICCIDDetaile = () => {
    ReturntheOrderCard({ id: ids.value }).then(res => {
        dataDetail.value = res.data?.map(item => ({
            ...item, status: item.status === 1 ? t('order.normal') : t('order.unsubscribe')
        })) || [];
    });
}

// 监听导卡进度
watch(() => modelValue.value, (val) => {
    if (val) {
        CardProgress();
    } else {
        clearInterval(timer);
    }
}, { immediate: true });

// 卡进度检查
const CardProgress = async () => {
    const res = await GuideCardProgress({ id: FormDataList.value.id });
    handleProgressResponse(res);
}

onMounted(async () => {
    res1.value = await Getdictionary('Billingcycle');
    res2.value = await Getdictionary('billingMethod');
    res3.value = await Getdictionary('currencyType');
});

</script>
<style scoped lang="less">
.progress {
    margin: 30px auto;
    display: flex;
    justify-content: center;
    .title{
        text-align: center;
        font-size: 16px;
    }
}

.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>