<template>
    <!--资费 弹框 -->
    <a-modal :title="typeIndex == 1 ? $t('form.Add') : $t('form.Edit')" v-model:visible="modelValue"
        @onCancel="resetForm" centered :maskClosable="false" :footer="null" width="700px" :closable="false">
        <a-form ref="formRef" :rules="rules" :model="formState" @submit="handleSubmit">
            <div class="formTitle">{{ $t('tariffManagement.BasicInformation') }}</div>
            <a-form-item :label="$t('tariffManagement.source')" field="source">
                <a-select v-model="formState.source">
                    <a-option v-for=" item in sourceList" :key="item.id" :value="item.value">{{
                        item.label
                    }}
                    </a-option>
                </a-select>
            </a-form-item>
            <template v-if="formState.source">
                <a-form-item :label="$t('tariffManagement.simDataPlanId')" field="simDataPlanId">
                    <a-select v-model="formState.simDataPlanId" :disabled="typeIndex!==1">
                        <a-option v-for=" (item, index) in planList" :key="item.id" :value="item.id">{{ $t('tariffManagement.DataPackage') }} {{
                            item.productName
                        }}
                        </a-option>
                    </a-select>
                </a-form-item>
            </template>
            <a-form-item :label="$t('tariffManagement.label')" field="label">
                <a-input v-model="formState.label" />
            </a-form-item>
            <a-form-item :label="$t('tariffManagement.userId')" field="userId">
                <a-select v-model="formState.userId">
                    <a-option v-for=" item in userIdList" :key="item.id" :value="item.id">{{
                        item.name
                    }}
                    </a-option>
                </a-select>
            </a-form-item>
            <a-form-item :label="$t('tariffManagement.billingMethod')" field="billingMethod">
                <a-select v-model="formState.billingMethod">
                    <a-option v-for=" item in methodList" :key="item.id" :value="item.value">{{
                        item.label
                    }}
                    </a-option>
                </a-select>
            </a-form-item>
            <a-form-item :label="$t('tariffManagement.currency')" field="currency">
                <a-select v-model="formState.currency">
                    <a-option v-for=" item in currency" :key="item.id" :value="item.value">{{
                        item.label
                    }}
                    </a-option>
                </a-select>
            </a-form-item>
            <div class="formTitle">{{ $t('tariffManagement.BillingInformation') }}</div>
            <a-form-item field="billingCycle" :label="$t('tariffManagement.billingCycle')" required>
                <a-radio-group v-model="formState.billingCycle" :options="billingCycleData">
                </a-radio-group>
            </a-form-item>
            <a-form-item field="" :label="$t('tariffManagement.pricing')" required>
                <a-input v-model="formState.pricing" v-if="formState.billingMethod == 2">
                    <template #append>
                        {{ formState.currency === '0' ? $t('setting.yuan') : $t('setting.USD') }}
                    </template>
                </a-input>
                <a-input v-model="formState.trafficBilling" v-if="formState.billingMethod == 1"></a-input>
                <a-select v-model="formState.trafficBillingType" style="width: 80px; margin:0 8px;"
                    v-if="formState.billingMethod == 1">
                    <a-option value="MB">MB</a-option>
                </a-select>
                <a-input v-model="formState.trafficBillingAmount" v-if="formState.billingMethod == 1">
                    <template #append>
                        {{ formState.currency === '0' ? $t('setting.yuan') : $t('setting.USD') }}
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item field="endDate" :label="$t('tariffManagement.cycleBuy')">
                <a-date-picker v-model="formState.endDate" style="width: 100%;" />
            </a-form-item>
            <a-form-item :label="$t('tariffManagement.MRCName')" field="mrcAmount">
                <a-input v-model="formState.mrcAmount">
                    <template #append>
                        {{ formState.currency === '0' ? $t('setting.yuan') : $t('setting.USD')}}
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item :label="$t('tariffManagement.networkName')" field="networkAccessFee">
                <a-input v-model="formState.networkAccessFee">
                    <template #append>
                        {{ formState.currency === '0' ? $t('setting.yuan') : $t('setting.USD') }}
                    </template>
                </a-input>
            </a-form-item>
            <a-form-item>
                <a-button type="primary" html-type="submit" style="margin-right: 10px;">{{
                    $t('form.Confirm')
                }}
                </a-button>
                <a-button @click="resetForm">{{ $t('form.Cancel') }}</a-button>
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script setup>
import { ref, onMounted, toRefs, toRef, watch } from 'vue';
import { getDataPlanList } from "@/api/path/lotCard.api"
import { getSTSInfoList } from '@/api/path/system.api'
import { updateTariff, addTariff } from "@/api/path/tariffManagement.api"
import { Getdictionary } from '@/mixins/index.js'
import { Message } from '@arco-design/web-vue'
import {useI18n} from 'vue-i18n'
const {t} = useI18n();
const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    typeIndex: {
        type: Number,
        default: null
    },
    FormDataList: {
        type: Object,
        default: () => { }
    }
})

const modelValue = toRef(props, 'modelValue')
const typeIndex = toRef(props, 'typeIndex')
const FormDataList = toRef(props, 'FormDataList')
const emit = defineEmits(['update:modelValue', 'submit'])

const state = ref({
    formState: {
        // 资费名称（必填）
        "label": "",
        // 流量包ID（必填）
        "simDataPlanId": null,
        // 用户ID（必填）
        "userId": null,
        // 来源（必填）
        "source": "",
        // 计费周期（必填）
        "billingCycle": "",
        // 计费方式（必填）
        "billingMethod": "1",
        // 价格（必填）
        "pricing": "",
        // 币种（必填）
        "currency": "usb",
        // 流量资费计费
        "trafficBilling": '',
        // 流量资费计费类型
        "trafficBillingType": 'MB',
        // 流量资费计费金
        "trafficBillingAmount": '',
        // MRC金额
        "mrcAmount": '',
        // 网络接入费
        "networkAccessFee": '',
        "endDate":''
    },
    sourceList: [],
    userIdList: [],
    methodList: [],
    currency: [],
    billingCycleData: [],
    planList: [],
    formRef: null

})

const { formState, sourceList, userIdList, methodList, currency, billingCycleData, planList, formRef } = toRefs(state.value)

const rules = {
    label: [{ required: true, trigger: 'change', }],
    simDataPlanId: [{ required: true, trigger: 'change', }],
    userId: [{ required: true, trigger: 'change', }],
    source: [{ required: true, trigger: 'change', }],
    billingCycle: [{ required: true, trigger: 'change', }],
    billingMethod: [{ required: true, trigger: 'change', }],
    currency: [{ required: true, trigger: 'change', }],
    trafficBilling: [{ required: true, trigger: 'change', }],
    trafficBillingType: [{ required: true, trigger: 'change', }],
    trafficBillingAmount: [{ required: true, trigger: 'change', }],
    mrcAmount: [{ required: true, trigger: 'change', }],
    networkAccessFee: [{ required: true, trigger: 'change', }],
    endDate: [{ required: true, trigger: 'change', }],
};


// 提交
const handleSubmit = ({ values, errors }) => {
    formRef.value.validate(async (errors) => {
        if (!errors) {
            const formVal = JSON.parse(JSON.stringify(values))
            delete formVal.settlementCycleMap
            formVal.userId = Number(values.userId)
            formVal.simDataPlanId = String(values.simDataPlanId)
            formVal.simDataPlanId = String(values.simDataPlanId)
            formVal.pricing = Number(values.pricing)


            if (typeIndex.value === 2) {
                const { code, data } = await updateTariff(formVal)

                if (code == 200) {
                    Message.success({
                        content: t('setting.editSuccess'),
                        duration: 2000,
                    })
                    emit('update:modelValue', false)
                    emit('submit', true)
                    resetForm()
                }
            } else {
                const { code, data } = await addTariff(formVal)
                if (code == 200) {
                    Message.success({
                        content: t('setting.addSuccess'),
                        duration: 2000,
                    })
                    emit('update:modelValue', false)
                    emit('submit', true)
                    resetForm()
                }
            }
        }
    });
}

// 取消
const resetForm = () => {
    emit('update:modelValue', false)
    Object.keys(formState.value).forEach(key => {
        formState.value[key] = ''
    })
    delete formState.value.id
    FormDataList.value = {}

}

const handleDataPlan = async () => {
    const param = {
        current: 1,
        size: 999,
        source: formState.value.source
    }
    getDataPlanList(param).then(res => {
        planList.value = res.data.records || []
    })
}

// 获取id数组
const handleModelId = async () => {
    const param = {
        current: 1,
        size: 999,
    }
    getSTSInfoList(param).then(res => {
        userIdList.value = (res.data.records || [])
    })
}

const handleDictValue = async () => {
    sourceList.value = await Getdictionary('source')
    methodList.value = await Getdictionary('billingMethod')
    currency.value = await Getdictionary('currencyType')
    billingCycleData.value = await Getdictionary('Billingcycle')
}

watch(() => modelValue.value, val => {
    if (val) {
        handleDictValue()
        handleModelId()
        formState.value.billingMethod = '1'
        formState.value.trafficBillingType = 'MB'
    }
})

watch(() => formState.value.billingMethod, val => {
    if (val == 2) {
        formState.value.trafficBillingType = ''
        formState.value.trafficBilling = ''
        formState.value.trafficBillingAmount = ''
    }else{
        formState.value.pricing = ''
    }
})

watch(
    () => formState.value.source,
    (newValue, oldValue) => {

        if (newValue != oldValue) {
            handleDataPlan()
        }
    },
    { immediate: true,deep:true }
);


watch(() => FormDataList.value, val => {
    if (!val.id) return
    Object.keys(formState.value).forEach(key => {
        if (val[key]) {
            formState.value[key] = key === 'userId' ? Number(val[key]) : val[key];
        }
    })
    formState.value.id = val.id
},{deep:true})
</script>
<style scoped></style>