<!-- 资费管理 -->
<template>
    <div class="container">
        <div class="head-title">
            <span>{{ route.meta.title }} </span>
            <span class="head-title-right">
                <a-button class="m-r-10" type="primary" @click="dictShowModel(1, null)">{{ $t('form.Add') }}</a-button>
            </span>
        </div>
        <!-- 搜索条件区 -->
        <div class="search-section">
            <a-form :model="searchForm" layout="inline">
                <a-form-item field="sim_data_plan_id" :label="$t('tariffManagement.simDataPlanId')">
                    <a-input v-model="searchForm.sim_data_plan_id"
                        :placeholder="$t('lotCard.please') + $t('tariffManagement.simDataPlanId')" allow-clear />
                </a-form-item>
                <a-form-item>
                    <a-space>
                        <a-button type="primary" @click="handleSearch">{{ $t('form.Search') }}</a-button>
                        <a-button @click="resetSearch">{{ $t('form.Reset') }}</a-button>
                    </a-space>
                </a-form-item>
            </a-form>
        </div>

        <div class="audit-btn">
            <a-button type="text" @click="dictShowModel(1, null)">
                <template #icon>
                    <icon-plus-circle />
                </template>
                <template #default>{{ $t('form.Add') }}</template>
            </a-button>
        </div>

        <a-table row-key="id" :data="dataSource" :columns="columns" :pagination="pagination"
            :row-selection="rowSelection" v-model:selectedKeys="selectedKeys" :scroll="{ x: 'auto' }">
            <template #id="{ record }">
                <!-- 修改 -->
                <a class="a-link" href="javascript:;" style="margin-right: 1rem" @click="dictShowModel(2, record)">{{
                    $t('form.Edit') }}</a>
                <!-- 删除 -->
                <a-popconfirm :content="$t('form.Delete')" :ok-text="$t('form.Confirm')"
                    :cancel-text="$t('form.Cancel')" @ok="handleDel(record.id)">
                    <a class="a-link" href="javascript:;" style="margin-right: 1rem">{{ $t('form.Delete')
                        }}</a>
                </a-popconfirm>
            </template>

        </a-table>


        <!-- 弹框 -->
        <a-modal :title="typeCurrent == 1 ? $t('form.Add') : $t('form.Edit')" v-model:visible="visible"
            @onCancel="resetForm" centered :maskClosable="false" :footer="null">
            <a-form ref="formRef" :rules="rules" :model="formState" @submit="handleSubmit">
                <a-form-item :label="$t('tariffManagement.simDataPlanId')" field="sim_data_plan_id">
                    <a-input v-model="formState.sim_data_plan_id" />
                </a-form-item>
                <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="user_id">
                    <a-input v-model="formState.user_id" />
                </a-form-item>
                <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>
                <a-form-item :label="$t('tariffManagement.trafficType')" field="traffic_type">
                    <a-select v-model="formState.traffic_type">
                        <a-option v-for=" item in trafficList" :key="item.id" :value="item.value">{{ item.label
                            }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item :label="$t('tariffManagement.billingType')" field="billing_type">
                    <a-select v-model="formState.billing_type">
                        <a-option v-for=" item in typeList" :key="item.id" :value="item.value">{{ item.label
                            }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item :label="$t('tariffManagement.bagSize')" field="bag_size">
                    <a-input v-model="formState.bag_size" />
                </a-form-item>
                <a-form-item :label="$t('tariffManagement.billingCycle')" field="billing_cycle">
                    <a-select v-model="formState.billing_cycle">
                        <a-option v-for=" item in cycleist" :key="item.id" :value="item.value">{{ item.label
                            }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item :label="$t('tariffManagement.billingMethod')" field="billing_method">
                    <a-select v-model="formState.billing_method">
                        <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.settlementCycle')" field="settlement_cycle">
                    <a-select v-model="formState.settlement_cycle">
                        <a-option v-for=" item in settlementCycleList" :key="item.id" :value="item.value">{{ item.label
                            }}</a-option>
                    </a-select>
                </a-form-item>
                <a-form-item :label="$t('tariffManagement.pricing')" field="pricing">
                    <a-input v-model="formState.pricing" />
                </a-form-item>
                <a-form-item :label="$t('tariffManagement.currency')" field="currency">
                    <a-input v-model="formState.currency" />
                </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>
    </div>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, nextTick } from "vue";
import { useRoute } from "vue-router";
import { columns } from "./config";
import { Message, Notification } from '@arco-design/web-vue'
import { deleteTariff, updateTariff, addTariff, tariffList } from "@/api/path/tariffManagement.api"
import { enum_dict } from "@/hooks/enum";
import { useSystemStore } from '@/store/modules/systemStore'


const { proxy } = getCurrentInstance()
const formRef = ref()
const searchForm = ref({
    "sim_data_plan_id": "",
});



const dataSource = ref([]);
const route = useRoute();
const pagination = ref({
    total: 0,
    pageSize: 10,
    current: 1,
})




const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
});
const selectedKeys = ref([])



const intData = async () => {
    const param = {
        current: pagination.value.current,
        size: pagination.value.pageSize,
        ...searchForm.value,
    }
    const { data } = await tariffList(param)
    dataSource.value = (data.records || []).map((item, index) => {
        const sourceName = sourceList.value.find(val => val.value == item.source)?.label
        const trafficTypeName = trafficList.value.find(val => val.value == item.traffic_type)?.label
        const billingTypeName = typeList.value.find(val => val.value == item.billing_type)?.label
        const billingCycleName = cycleist.value.find(val => val.value == item.billing_cycle)?.label
        // const methodName = methodList.value.find(val => val.value == item.billing_method)?.label
        const settlementCycleName = settlementCycleList.value.find(val => val.value == item.settlement_cycle)?.label
        return {
            ...item,
            sourceName,
            trafficTypeName,
            billingTypeName,
            billingCycleName,
            settlementCycleName,
            feeCode: "NR0" + (index + 1),
            status: "正常"
        }
    })
    pagination.value.total = data.total
}




// 删除
const handleDel = async (id) => {
    const { code } = await deleteTariff({ id })
    if (code == 200) {
        Message.success({
            content: "删除成功！",
            duration: 2000,
        })
        intData()
    }
};

//

const handleSearch = () => {
    intData()
}
const resetSearch = () => {
    proxy.$refs.formRef.resetFields()
    intData()
}




// -------------------弹窗数据------------------------------------
const visible = ref(false);
const typeCurrent = ref(null);
const sourceList = ref([])
const trafficList = ref([])
const cycleist = ref([])
const typeList = ref([])
const methodList = ref([])
const settlementCycleList = ref([])

const formState = ref({
    id: "",
    // 资费名称（必填）
    "label": "",
    // 流量包ID（必填）
    "sim_data_plan_id": "",
    // 用户ID（必填）
    "user_id": 0,
    // 来源（必填）
    "source": "",
    // 流量类型（必填）
    "traffic_type": "",
    // 计费类型（必填）
    "billing_type": "",
    // 流量包Size（必填）
    "bag_size": "",
    // 计费周期（必填）
    "billing_cycle": "",
    // 计费方式（必填）
    "billing_method": "",
    // 结算周期（必填）
    "settlement_cycle": "",
    // 价格（必填）
    "pricing": "",
    // 币种（必填）
    "currency": ""

});

const rules = {
    label: [{ required: true, trigger: 'change', }],
    sim_data_plan_id: [{ required: true, trigger: 'change', }],
    user_id: [{ required: true, trigger: 'change', }],
    source: [{ required: true, trigger: 'change', }],
    traffic_type: [{ required: true, trigger: 'change', }],
    billing_type: [{ required: true, trigger: 'change', }],
    bag_size: [{ required: true, trigger: 'change', }],
    billing_cycle: [{ required: true, trigger: 'change', }],
    billing_method: [{ required: true, trigger: 'change', }],
    settlement_cycle: [{ required: true, trigger: 'change', }],
    pricing: [{ required: true, trigger: 'change', }],
    currency: [{ required: true, trigger: 'change', }],
};


// 提交
const handleSubmit = ({ values, errors }) => {
    formRef.value.validate(async (errors) => {
        if (!errors) {
            values.user_id = Number(values.user_id)
            if (formState.value.id) {
                const { code, data } = await updateTariff(values)

                if (code == 200) {
                    Message.success({
                        content: "修改成功！",
                        duration: 2000,
                    })
                    visible.value = false;
                    intData()
                }
            } else {
                const { code, data } = await addTariff(values)
                if (code == 200) {
                    Message.success({
                        content: "添加成功！",
                        duration: 2000,
                    })
                    visible.value = false;
                    intData()
                }
            }
        }
    });

}
// 弹框
const dictShowModel = (type, data) => {
    typeCurrent.value = type;
    visible.value = true;
    // 编辑
    if (type == 2) {
        Object.assign(formState.value, data);
    }
}
// 取消
const resetForm = () => {
    visible.value = false;
    formRef.value.resetFields();
}

// --------------------------------------------------------
// 获取字典
const handleDictValue = () => {
    const dictList = JSON.parse(window.localStorage.getItem('dictList')) ?? []
    sourceList.value = dictList.filter((item) => item.type_key == enum_dict.SOURCE)
    trafficList.value = dictList.filter((item) => item.type_key == enum_dict.TRAFFI_CTYPE)
    cycleist.value = dictList.filter((item) => item.type_key == enum_dict.BILLING_CYCLE)
    typeList.value = dictList.filter((item) => item.type_key == enum_dict.BILLING_TYPE)
    methodList.value = dictList.filter((item) => item.type_key == enum_dict.BILLING_METHOD)
    settlementCycleList.value = dictList.filter((item) => item.type_key == enum_dict.SETTLEMENT_CYCLE)
}


onMounted(() => {
    handleDictValue()
    intData()
})



</script>

<style scoped lang="less">
.head-title-right {
    .m-r-10 {
        margin-right: 10px;
    }

}

.search-section {
    margin-top: 20px;
    margin-bottom: 20px;
}

.container {
    .head-title {
        display: flex;
        justify-content: space-between;
    }

    .form-row {
        display: flex;

        .form-row-col {
            width: 25%;
            display: flex;
            align-items: center;

            .form-row-label {
                width: 120px;
                text-align: right;
            }
        }
    }
}

.audit-btn {
    margin-bottom: 10px;
}
</style>