<template>
    <div>
        <div class="search">
            <Search :SearchForm="SetMealSearchForm" @query="initData" @reset="reset"></Search>
        </div>

        <div class="addSetMeal">
            <a-button type="primary" @click="visible = true; Edit = true; Type = true">新增套餐</a-button>
            <a-button @click="breakFlos">返回</a-button>
        </div>

        <div class="table">
            <a-table row-key="id" :data="tableData" :columns="columnsTarrit" :pagination="pagination"
                :scroll="{ x: 'auto' }" @page-change="evChangePage">
                <template #status="{ record }">
                    <a-tag :color="record.status == 1 ? '#7bc616' : '#86909c'">{{ record.status == 1 ? '上架' : '下架'
                        }}</a-tag>
                </template>
                <template #options="{ record }">
                    <a-space>
                        <a-button type="text" @click="SetUpPackage(record)">修改</a-button>
                        <a-button type="text" @click="unmount(record)">{{ record.status == 1 ? '下架' : '上架' }}</a-button>
                        <a-popconfirm content="是否要删除该资费商品?" @ok="handelDeleteTariff(record)">
                            <a-button type="text">删除</a-button>
                        </a-popconfirm>
                    </a-space>
                </template>
            </a-table>
        </div>


        <a-modal v-model:visible="visible" width="600px" @cancel="handelCancel" :title="Edit ? '新增套餐计划商品' : '编辑套餐计划商品'">
            <div class="Form">
                <a-form ref="formRef" :rules="rules" :model="Form">
                    <a-form-item label="套餐名称" field="label" validate-trigger="input">
                        <a-input placeholder="请输入套餐名称" v-model="Form.label"></a-input>
                    </a-form-item>
                    <div class="title">套餐名称将在终端用户的充值也中展示，建议不超过10个字</div>
                    <a-form-item label="充值类型" field="type" validate-trigger="input">
                        <a-select v-model="Form.type" placeholder="请选择充值类型">
                            <a-option v-for="item in puyType" :value="item.value" :key="item.value">{{ item.label
                                }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="充值周期" field="period" validate-trigger="input">
                        <a-input v-model="Form.period"></a-input>
                        <a-select v-model="Form.timeUnit" style="width: 140px; margin:0 8px;">
                            <a-option v-for="item in cyciy" :value="item.value" :key="item.value">{{ item.label
                                }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label="充值售价" field="price" validate-trigger="input">
                        <a-input v-model="Form.price"></a-input>
                        <a-select v-model="Form.currency" style="width: 140px; margin:0 8px;">
                            <a-option v-for="item in Currency" :value="item.value" :key="item.value">{{ item.label
                                }}</a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item :label="Edit ? '充值绑定资费' : '默认绑定资费'" field="trafficId" validate-trigger="blur">
                        <a-select v-model="Form.trafficId">
                            <a-option v-for="item in tariffListData" :value="item.id" :key="item.id">{{ item.label
                                }}</a-option>
                        </a-select>
                    </a-form-item>
                    <div class="title">若更改绑定资费后已充值的用户仍使用之前的资费请谨慎操作!!</div>
                    <a-form-item label="流量大小" field="Flow" validate-trigger="change" v-if="Form.type == 2">
                        <a-input v-model="Form.flow"></a-input>
                        <a-select v-model="Form.flowUnit" style="width: 140px; margin:0 8px;">
                            <a-option value="KB">KB</a-option>
                            <a-option value="MB">MB</a-option>
                            <a-option value="GB">GB</a-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
            <template #footer>
                <a-button @click="handelCancel">取消</a-button>
                <a-button type="primary" @click="handleSubmit">确定</a-button>
            </template>
        </a-modal>
    </div>
</template>

<script setup>
import { defineEmits, defineProps, toRefs, ref, onMounted } from 'vue';
import { CheckTariffPackages } from '@/api/path/tariffManagement.api'
import { Getdictionary, tableFunction, filterDict } from '@/mixins/index.js'
import Search from '@/components/Search/index.vue'
import { columnsTarrit } from '../config'
import { tariffList, addTariffPackage, UpdateTariffTtems, DeleteTariffItems } from "@/api/path/tariffManagement.api"
import { Message, Modal } from '@arco-design/web-vue';
const props = defineProps({
    list: Object
})

const emits = defineEmits(['break'])

const state = ref({
    pagination: {
        total: 0,
        pageSize: 10,
        current: 1,
        simTerminalId: null
    },
    visible: false,
    puyType: [],
    cyciy: [],
    Currency: [],
    tariffListData: [],
    billingMethodList: [],
    Form: {
        label: '',
        type: "",
        period: "",
        timeUnit: "",
        price: "",
        currency: "",
        trafficId: "",
        flow: "",
        flowUnit: "MB",
        id: "",
    },
    formRef: null,
    Edit: true,
    Type: true
})
const { pagination, visible, puyType, Currency, cyciy, tariffListData, Form, formRef, billingMethodList, Edit, Type } = toRefs(state.value)

const rules = {
    label: [{ required: true, message: '套餐名称不能为空' }, {
        validator: (value, cb) => {
            if (value.length > 10) {
                cb('套餐名称最多10个字符');
            } else {
                cb();
            }
        }
    }],
    type: [{ required: true, message: '请选择充值类型' }],
    period: [{ required: true, message: '请填写充值周期' }, {
        validator: (value, cb) => {
            const pattern = /^[1-9]\d*$/
            if (!pattern.test(value)) {
                cb('请输入整数')
            } else {
                cb()
            }
        }
    }],
    price: [
        { required: true, message: '请填写充值售价' },
        {
            validator: (value, cb) => {
                // 修改正则表达式，使其支持最多两位小数
                const pattern = /^\d+(\.\d{1,2})?$/;
                if (!pattern.test(value)) {
                    cb('请输入合法的数字，最多支持两位小数');
                } else {
                    cb();
                }
            }
        }
    ],
    trafficId: [{ required: true, message: '请选择充值绑定资费' }]
}

const processData = (data) => {
    return (data.records || []).map((item, index) => {
        return {
            ...item,
            priceName: item.price + item.currency,
            typeName: item.type == 1 ? '服务时长' : "购买流量",
            profitPrice: item.billingMethod == 1 ? '---' : item.profitPrice + item.currency,
            billingMethod: filterDict(billingMethodList.value, item.billingMethod),
            costPrice: item.billingMethod == 1? item.trafficBilling+item.trafficBillingType+'/'+ item.trafficBillingAmount +item.trafficCurrency  : item.costPrice + item.trafficCurrency,
            oldPrice: item.billingMethod == 1 ? item.oldTrafficBilling+item.oldTrafficBillingType+'/'+ item.oldTrafficBillingAmount +item.trafficCurrency : item.oldPrice + item.trafficCurrency,
        }
    })
}

const { tableData, evChangePage, initData, reset } = tableFunction(pagination.value, CheckTariffPackages, processData)


const handleSubmit = () => {
    formRef.value.validate(async (errors) => {
        if (!errors) {
            const FormList = {
                ...Form.value,
                type: Number(Form.value.type),
                period: Number(Form.value.period),
                simTerminalId: pagination.value.simTerminalId
            }
            if (Edit.value) {
                delete FormList.id
            }
            let res = Type.value ? await addTariffPackage(FormList) : await UpdateTariffTtems(FormList)
            if (res.code === 200) {
                initData()
                Message.success(Type.value ? '添加成功' : '修改成功')
                visible.value = false
                handelCancel()
            }
        }
    })
}

const handelCancel = () => {
    Form.value.label = ""
    Form.value.type = puyType.value[0]?.value
    Form.value.period = ""
    Form.value.timeUnit = cyciy.value[0]?.value
    Form.value.price = ""
    Form.value.currency = Currency.value[0]?.value
    Form.value.trafficId = null
    Edit.value = true
    visible.value = false

}


const unmount = async (record) => {
    Modal.info({
        title: `确定要${record.status == 1 ? '下架' : '上架'}吗?`,
        content: '',
        onOk: async () => {
            const FormList = {
                ...record,
                type: Number(Form.value.type),
                period: Number(Form.value.period),
                simTerminalId: pagination.value.simTerminalId
            }
            let res = await UpdateTariffTtems(FormList)
            if (res.code === 200) {
                Message.success(`${record.status == 1 ? '下架' : '上架'}成功`)
                initData()
            }
        }
    });
}

const handelDeleteTariff = async (record) => {
    let res = await DeleteTariffItems({ id: record.id })
    if (res.code === 200) {
        Message.success('删除成功')
        initData()
    }
}

const SetUpPackage = async (record) => {
    Object.keys(Form.value).forEach(key => {
        Form.value[key] = record[key]
    })
    Form.value.price = record.price.split('/')[0];
    Form.value.type = String(Form.value.type)
    visible.value = true
    Edit.value = false
    Type.value = false
}

const breakFlos = () => {
    emits('break', true)
}

onMounted(async () => {
    let dict = await Getdictionary(['RechargeType', 'PuyCycle', 'currencyType', 'billingMethod'])
    puyType.value = dict[0]
    Form.value.type = puyType.value[0]?.value
    cyciy.value = dict[1]
    Form.value.timeUnit = cyciy.value[0]?.value
    Currency.value = dict[2]
    Form.value.currency = Currency.value[0]?.value
    billingMethodList.value = dict[3]
    let res = await tariffList({ current: 1, size: 99999, source: props.list.source, userId: props.list.userId })
    if (res.code === 200) {
        tariffListData.value = (res.data.records || []).map(item => {
            return {
                ...item,
                value: item.id,
                label: item.label + '---' + item.userName
            }
        })
    }
    pagination.value.simTerminalId = props.list.id
    initData()
})
</script>

<style scoped lang='less'>
.search,
.table {
    margin-top: 20px;
}

.addSetMeal {
    display: flex;
    justify-content: space-between;
}

.title {
    font-size: 14px;
    color: #ccc;
    margin-left: 120px;
    margin-top: -15px;
    margin-bottom: 10px;
}
</style>