<template>
    <div class="layout-container">
        <!-- 菜单栏 -->
        <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset"
            is_add_button="新增" @addForm="edit" />

        <!-- 表格 -->
        <div class="layout-container">
            <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
                @selection-change="handleSelectionChange">
                <el-table-column prop="adSourceId" label="广告源ID" />
                <el-table-column prop="name" label="广告源名称" />
                <el-table-column prop="type" label="广告源类型" />
                <el-table-column prop="placementName" label="广告位名称" />
                <el-table-column prop="placementId" label="广告位ID" />
                <el-table-column prop="mix_format" label="混合类型">
                    <template #default="scope">
                        {{ scope.row.mix_format }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="scope">
                        <div class="button">
                            <el-button class="button-item" type="primary" style="margin-bottom: 5px;"
                                @click="edit(scope.row)">
                                编辑
                            </el-button>
                            <el-popconfirm placement="left" title="确认删除该数据?" @confirm="removeItem(scope.row)">
                                <template #reference>
                                    <el-button class="button-item" style="margin-bottom: 5px;"
                                        type="danger">删除</el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </template>
                </el-table-column>
            </Table>
        </div>

        <!-- 操作弹窗 -->
        <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
            <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="120px" style="margin-right:30px;">
                <el-row :gutter="5">
                    <el-col :span="10">
                        <el-form-item required label="广告源名称" prop="name">
                            <el-input v-model="formEdit.name" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="2"></el-col>
                    <el-col :span="10">
                        <el-form-item required label="广告位" prop="placementId">
                            <el-select v-model="formEdit.placementId">
                                <el-option v-for="item in placementListData" :value="item.placementId"
                                    :label="item.placementName" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="5">
                    <el-col :span="10">
                        <el-form-item required label="广告源类型" prop="type">
                            <el-select v-model="formEdit.type">
                                <el-option :value="2" label="常规广告源" />
                                <el-option :value="10" label="兜底广告源" />
                                <el-option :value="12" label="客户端竞价广告源" />
                                <el-option :value="13" label="服务端竞价广告源" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2"></el-col>
                    <el-col :span="10">
                        <el-form-item required label="混合类型" prop="mix_format">
                            <el-select v-model="formEdit.mix_format">
                                <el-option :value="-1" label="非混合类型" />
                                <el-option :value="0" label="混合native类型" />
                                <el-option :value="1" label="混合rewarded_video类型" />
                                <el-option :value="2" label="混合banner类型" />
                                <el-option :value="3" label="混合interstitial类型" />
                                <el-option :value="4" label="混合splash类型" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- <el-row :gutter="5">
                    <el-col :span="10" v-if="formEdit.appId">

                    </el-col>
                    <el-col :span="2" v-if="formEdit.appId"></el-col>
                    <el-col :span="10">

                    </el-col>
                </el-row> -->
            </el-form>
        </Layer>
    </div>
</template>

<script setup>
import { onBeforeMount, ref, reactive } from "vue";
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import { useGetDictList } from '@/hooks/useGetDictList.js'
import { useStore } from 'vuex'
import { placementList, adSourceList, adSourceAddOne, adSourceUpdateOne, adSourceDeleteOne } from "@/api/formworkErection";
import Layer from "@/components/layer/index.vue";
import { ElMessage } from "element-plus";

const store = useStore()
const { dictData, loadDictData, getOptions, getDictionaryName } = useGetDictList();
const form = ref(null);
const tableData = ref([]);

// 分页参数, 供table使用
const page = reactive({
    pageNum: 1,
    pageSize: 20,
    total: 0,
});

const formSearch = ref({
    limit: 20,// 当前页数量(查询量)
    page: 1,// 当前页码
    name: null,//名称
    placementId: null,//广告位id
});

const dynamicFormItems = ref([])

onBeforeMount(() => {
    settingData()
    getList();
    getPlacementList()
});

// 获取缓存数据设置筛选数据
const settingData = () => {
    loadDictData().then(() => {
        dynamicFormItems.value = [
            {
                label: '广告源ID',
                prop: 'nickName',
                type: 'input',
                needEnterEvent: true
            },
            {
                label: '广告位名称',
                prop: 'channelType',
                type: 'select',
                options: [
                    {
                        label: "全部",
                        value: null,
                    },
                    {
                        label: "正常",
                        value: 0,
                    },
                    {
                        label: "锁定",
                        value: 1,
                    }
                ]
            },
            {
                label: '应用名称',
                prop: 'loginType',
                type: 'select',
                options: [
                    {
                        label: "全部",
                        value: null,
                    },
                    {
                        label: "账号密码",
                        value: 0,
                    },
                    {
                        label: "微信",
                        value: 1,
                    }
                ]
            },
        ]
    })
}

// 分页数据
const getList = async () => {
    let res = await adSourceList({ ...formSearch.value });
    tableData.value = res.data;
    page.total = res.pageMeta.total;
};

const changeTableData = (type) => {
    formSearch.value.page = type ? 1 : page.pageNum;
    formSearch.value.limit = page.pageSize;
    // 分页切换
    getList();
};

// 搜索
const handleFormSubmitted = (formData) => {
    // console.log("接收到子组件传递的数据", formData);
    formSearch.value.page = page.pageNum;
    formSearch.value.limit = page.pageSize;
    getList();
};

// 表单重置
const handleFormReset = () => {
    formSearch.value = {
        limit: 20,// 当前页数量(查询量)
        page: 1,// 当前页码
        name: null,//名称
        placementId: null,//广告位id
    };
    page.pageNum = 1
    page.pageSize = 20
    page.total = 0
    getList();
};

// 选择监听器
const handleSelectionChange = (val) => {
    context.emit("selection-change", val)
}


// 获取广告位列表
const placementListData = ref([])
const getPlacementList = async () => {
    let res = await placementList({
        limit: 999,
        page: 1,
    })
    placementListData.value = res.data

}

// 弹窗
const layer = ref({
    show: false,
    title: "新增广告渠道",
    showButton: true,
    width: '50vw',
    edit: false,
});

const formEdit = ref({
    adSourceId: undefined,
    mix_format: '',//混合类型
    name: '', //广告源名称
    network_id: '1210971759',//Taku广告平台账号ID
    placementId: '',//广告位id
    type: '',//广告源类型
})

const edit = (row) => {
    ruleForm.value?.resetFields()
    if (row) {
        formEdit.value = row
        layer.value.edit = true;
        layer.value.title = '编辑广告源'
    } else {
        formEdit.value = {
            adSourceId: undefined,
            mix_format: '',//混合类型
            name: '', //广告源名称
            network_id: '1210971759',//Taku广告平台账号ID
            placementId: '',//广告位id
            type: '',//广告源类型
        }
        layer.value.edit = false;
        layer.value.title = '新增广告源'
    }
    layer.value.show = true
}

const ruleForm = ref(null);

const rules = reactive({
    name: [
        { required: true, message: "请输入广告源名称", trigger: "blur" },
    ],
    placementId: [
        { required: true, message: "请选择广告位", trigger: "change" },
    ],
    type: [
        { required: true, message: "请选择广告源类型", trigger: "change" },
    ],
    mix_format: [
        { required: true, message: "请选择混合类型", trigger: "change" },
    ],
});

const submit = async (formEl) => {
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            // 提交内容
            console.log('提交内容', formEdit.value)

            // 编辑
            if (layer.value.edit) {
                await adSourceUpdateOne({ ...formEdit.value }).then((res) => {
                    ElMessage.success('保存成功')
                    getList();
                })
            } else {
                await adSourceAddOne({ ...formEdit.value }).then((res) => {
                    ElMessage.success('新增成功');
                    getList()
                })
            }

            layer.value.show = false
        } else {
            console.log("error submit!", fields);
        }
    });
};


// 删除
const removeItem = async (row) => {
    console.log('删除', row)
    await adSourceDeleteOne({ adSourceId: row.adSourceId }).then((res) => {
        ElMessage.success("删除成功");
        handleFormSubmitted();
    });
}



</script>

<style scoped lang="scss">
.layout-container {
    .button {
        display: flex;
        flex-direction: column;

        .button-item {
            margin: 4px;
        }
    }
}
</style>