<template>
    <div class="agent_page">
        <div class="title">{{ ptitle }}</div>
        <div class="query adfacjb">
            <div class="left">
                <el-button type="primary" icon="el-icon-plus" @click="handleAddChannel" v-hasPermi="['core:channelmanage:save']">添加渠道</el-button>
            </div>
        </div>
        <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无渠道" max-height="578px" style="margin-top: 24px;">
            <el-table-column label="序号" width="50">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="渠道类型" prop="channelType">
                <template #default="{ row }">{{ channel_type.find(c=>c.value==row.channelType)?.label||'' }}</template>
            </el-table-column>
            <el-table-column label="邀请二维码" prop="inviteCode">
                <template #default="{ row }">
                    <img :src="row.inviteCode" v-if="row.inviteCode" style="width: 100px;height: 100px;cursor: pointer;" @click="showBigImg(row.inviteCode)">
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createDate"></el-table-column>
            <el-table-column label="备注" prop="remark"></el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button link type="text" size="mini" @click="handleCreateCode(scope.row)" v-hasPermi="['core:channelmanage:gen']" v-if="scope.row.channelType==='scan'&&!scope.row.inviteCode">生成二维码</el-button>
                    <el-button link type="text" size="mini" @click="handleEdit(scope.row)" v-hasPermi="['core:channelmanage:update']">编辑</el-button>
                    <el-button link type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['core:channelmanage:delete']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-row style="display: flex;justify-content: center;">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryParams.page"
                :page-sizes="[5, 10, 20, 50]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                v-show="total > 0">
            </el-pagination>
        </el-row>
        <el-dialog width="40%" :visible.sync="show" :title="title" @close="cancel">
            <el-form ref="modelRef" :model="modelForm" :rules="modelRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="渠道类型" prop="channelType">
                    <el-select v-model="modelForm.channelType" placeholder="请选择渠道类型">
                        <el-option :label="item.label" :value="item.value" v-for="item in channel_type" :key="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="modelForm.remark" placeholder="备注"></el-input>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">保 存</el-button>
                <el-button @click="cancel" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
        <el-dialog width="30%" :visible.sync="bigShow" title="邀请二维码" @close="bigShow=false">
            <img :src="bigImg" style="width: 100%;height: auto;">
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button type="primary" @click="downloadImg">下载</el-button>
                <el-button @click="bigShow=false" style="margin-right: 5%;">关 闭</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="">
    import { ref, getCurrentInstance, onMounted } from 'vue'
    import { getChannelList,publishChannelConfirm,updateChannelPublish,getChannelInfo,deleteChannel,createChannelCode } from '@/api/agent/index.js';
    const { proxy } = getCurrentInstance();
    const { channel_type } = proxy.useDict("channel_type");
    const queryParams = ref({
        page:1,
        limit:10,
    })
    const ptitle = proxy.$route.meta.title;
    const dataList = ref([])
    const loading = ref(false)
    const total = ref(0)
    const show = ref(false)
    const title = ref('添加渠道类型')
    const bigShow = ref(false)
    const bigImg = ref('')
    const modelForm = ref({
        id:'',
        channelType:'',
        remark:''
    })
    const modelRules = ref({
        channelType: [
            { required: true, message: '请选择渠道类型', trigger: 'change' },
        ]
    })
    const buttonLoading = ref(false)
    const modelRef = ref(null)

    const handleAddChannel = () => {
        reset();
        title.value = "添加渠道类型";
        show.value = true;
    }

    const reset = () => {
        modelForm.value = {
            id:'',
            channelType:'',
            remark:''
        };
        proxy.resetForm("modelRef");
    }

    const submitForm = () => {
        proxy.$refs.modelRef.validate((valid) => {
            if (valid) {
                buttonLoading.value = true;
                if(modelForm.value.id){
                    updateChannelPublish(modelForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        show.value = false;
                        getList();
                    })
                }else{
                    publishChannelConfirm(modelForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        show.value = false;
                        getList();
                    })
                }
            } else {
                return false;
            }
        });
    }
    const cancel = () => {
        show.value = false;
        reset();
    }

    const getList = async () => {
        let query = {...queryParams.value};
        loading.value = true;
        const res = await getChannelList(query);
        dataList.value = res.data.list;
        total.value = res.data.total;
        loading.value = false;
    }
    const handleSizeChange = (e)=>{
        queryParams.value.limit = e;
        getList();
    }
    const handleCurrentChange = (e)=>{
        queryParams.value.page = e;
        getList();
    }

    const handleEdit = (row) => {
        reset();
        getChannelInfo(row.id).then(response => {
            modelForm.value = response.data;
            title.value = "编辑渠道类型";
            show.value = true;
        });
    }
    async function handleDelete(row) {
        await proxy?.$modal.confirm('确认删除吗？').finally(() => loading.value = false);
        let res = await deleteChannel([row.id]);
        if (res.code === 0) proxy?.$modal.msgSuccess("删除成功");
        else return proxy?.$modal.msgError(res.msg);
        await getList();
    }   

    async function handleCreateCode(row) {
        await proxy?.$modal.confirm('确认生成邀请二维码吗？').finally(() => loading.value = false);
        let res = await createChannelCode(row.id);
        if (res.code === 0) proxy?.$modal.msgSuccess("生成成功");
        else return proxy?.$modal.msgError(res.msg);
        await getList();
    }

    const showBigImg = imgurl => {
        bigImg.value = imgurl;
        bigShow.value = true;
    }

    const downloadImg = () => {
        const a = document.createElement('a');
        a.href = bigImg.value;
        a.download = '邀请二维码';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        proxy?.$modal.msgSuccess("下载成功");
        bigShow.value = false;
    }

    onMounted(()=>{
        getList();
    })

</script>

<style scoped lang="scss">
    .agent_page{
        padding: 20px;
        box-sizing: border-box;
        .title{
            font-family: PingFang-SC, PingFang-SC;
            font-weight: bold;
            font-size: 16px;
            color: #111111;
            line-height: 16px;
        }
        .query{
            margin-top: 24px;
        }
    }

    
    :v-deep .el-dialog__wrapper{
        background: rgba(0,0,0,.3) !important;
    }
    ::v-deep .el-dialog__title{
        font-weight: bold !important;
    }
    ::v-deep .el-dialog{
        margin-top: 15vh !important;
    }
    ::v-deep .el-drawer__header span{
        font-weight: bold;
        font-size: 16px;
        color: #1D2129;
        line-height: 22px;
    }
</style>