<template>
    <div class="agent_page">
        <div class="ap_title">{{ title }}</div>
        <div class="add adf">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增活动</el-button>
        </div>
        <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无广告" max-height="578px" style="margin-top: 18px;">
            <el-table-column label="序号" width="50">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="活动名称" prop="eventName"></el-table-column>
            <el-table-column label="问卷类型" prop="queType">
                <template #default="{ row }">{{ queTypeDict[row.queType]||'' }}</template>
            </el-table-column>
            <el-table-column label="优惠类型" prop="discountMode">
                <template #default="{ row }">{{ discountModeDict[row.discountMode]||'' }}</template>
            </el-table-column>
            <el-table-column label="优惠价格" prop="title">
                <template #default="{ row }">{{ row.discountValue||0 }}{{ row.discountMode==1?'%':'元' }}</template>
            </el-table-column>
            <el-table-column label="活动开始时间" prop="beginAt"></el-table-column>
            <el-table-column label="活动结束时间" prop="endAt"></el-table-column>
            <el-table-column label="对应用户标签" prop="userBrief">
                <template #default="{ row }">{{ user_brief.find(u=>u.value==row.userBrief)?.label||'' }}</template>
            </el-table-column>
            <el-table-column label="上架状态" prop="enable">
                <template #default="{ row }">
                    <el-switch v-model="row.enable" active-color="#33A7A7" inactive-color="#B9C0C8" @change="e=>statusChange(e,row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="活动说明" prop="remark" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" prop="createDate" width="160"></el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button link type="text" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link type="text" size="mini" @click="handleDelete(scope.row)">删除</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="dialogTitle" @close="cancel">
            <el-form ref="goodActivityRef" :model="goodActivityForm" :rules="goodActivityRules" label-width="120px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="活动名称" prop="eventName">
                    <el-input v-model="goodActivityForm.eventName" placeholder="请输入活动名称"></el-input>
                </el-form-item>
                <el-form-item label="问卷类型" prop="queType">
                    <el-select v-model="goodActivityForm.queType" placeholder="请选择问卷类型" style="width:100%">
                        <el-option label="初级" :value="5"></el-option>
                        <el-option label="中级" :value="4"></el-option>
                        <el-option label="高级" :value="3"></el-option>
                        <el-option label="基础版" :value="1"></el-option>
                        <el-option label="专业版" :value="2"></el-option>
                        <el-option label="专家版" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠类型" prop="discountMode">
                    <el-select v-model="goodActivityForm.discountMode" placeholder="请选择优惠类型" style="width:100%">
                        <el-option label="折扣" :value="1"></el-option>
                        <el-option label="抵扣" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="优惠值" prop="discountValue" v-if="goodActivityForm.discountMode===0||goodActivityForm.discountMode===1">
                    <div v-if="goodActivityForm.discountMode===1" class="adfac">
                        <span>实际价格的</span><el-input style="margin: 0 10px;flex: 1;" type="number" max="100" min="0" v-model="goodActivityForm.discountValue" placeholder="请输入优惠值"></el-input><span>%</span>
                    </div>
                    <div v-else-if="goodActivityForm.discountMode===0" class="adfac">
                        <span>在实际价格上减去</span><el-input style="margin: 0 10px;flex: 1;" type="number" v-model="goodActivityForm.discountValue" placeholder="请输入优惠值"></el-input><span>元</span>
                    </div>
                </el-form-item>
                <el-form-item label="活动开始时间" prop="beginAt">
                    <el-date-picker style="width: 100%;" @change="e=>handleChangeDate(e,'beginAt')"
                        v-model="goodActivityForm.beginAt"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm"
                        placeholder="请选择活动开始时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="活动结束时间" prop="endAt">
                    <el-date-picker style="width: 100%;" @change="e=>handleChangeDate(e,'endAt')"
                        v-model="goodActivityForm.endAt"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm"
                        placeholder="请选择活动结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="对应用户标签" prop="userBrief">
                    <el-select v-model="goodActivityForm.userBrief" placeholder="请选择对应用户标签" style="width:100%">
                        <el-option v-for="item in user_brief" :value="item.value" :label="item.label" :key="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="活动说明" prop="remark">
                    <el-input type="textarea" :rows="3" v-model="goodActivityForm.remark" placeholder="请输入活动说明"></el-input>
                </el-form-item>
                <el-form-item label="活动状态" prop="enable">
                    <el-radio-group v-model="goodActivityForm.enable">
                        <el-radio :label="1">上架</el-radio>
                        <el-radio :label="0">下架</el-radio>
                    </el-radio-group>
                </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>
    </div>
</template>

<script setup name="">
    import { ref, getCurrentInstance, onMounted } from 'vue'
    const { proxy } = getCurrentInstance();
    const { user_brief } = proxy.useDict("user_brief");
    import {
        getGoodActivityList,
        addGoodActivity,
        updateGoodActivity,
        getGoodActivityInfo,
        deleteGoodActivity
    } from '@/api/agent/indexTwo.js'
    const title = proxy.$route.meta.title;
    const fileList = ref([]);
    const queryParams = ref({
        page:1,
        limit:10
    })
    const queTypeDict = ref({
        '1': '基础版',
        '2': '专业版',
        0:'专家版',
        3:'高级',
        4:'中级',
        5:'初级',
    })
    const discountModeDict = ref({
        '1': '折扣',
        '0': '抵扣'
    })
    const dataList = ref([])
    const total = ref(0)
    const loading = ref(false)
    const buttonLoading = ref(false)
    const show = ref(false)
    const dialogTitle = ref('新增商品活动')
    const goodActivityRef = ref(null)
    const goodActivityForm = ref({
        id:'',
        eventName:'',
        queType:'',
        discountMode:'',
        discountValue:0,
        beginAt:'',
        endAt:'',
        userBrief:'',
        remark:'',
        enable:1
    })
    const goodActivityRules = ref({
        eventName: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        queType: [
            { required: true, message: '请选择问卷类型', trigger: 'change' }
        ],
        discountMode: [
            { required: true, message: '请选择优惠类型', trigger: 'change' }
        ],
        discountValue: [
            { required: true, message: '请输入优惠值', trigger: 'blur' },
        ],
        beginAt: [
            { required: true, message: '请选择活动开始时间', trigger: 'change' }
        ],
        endAt: [
            { required: true, message: '请选择活动结束时间', trigger: 'change' }
        ],
        userBrief: [
            { required: true, message: '请选择对应用户标签', trigger: 'change' }
        ],
        remark: [
            { required: true, message: '请输入活动说明', trigger: 'blur' }
        ]
    })

    const getList = async () => {
        let query = {...queryParams.value};
        loading.value = true;
        const res = await getGoodActivityList(query);
        dataList.value = res.data.list;
        dataList.value.forEach(item=>{
            item.enable = item.enable==1?true:false;
        })
        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 reset = () => {
        goodActivityForm.value = {
            id:'',
            eventName:'',
            queType:'',
            discountMode:'',
            discountValue:0,
            beginAt:'',
            endAt:'',
            userBrief:'',
            remark:'',
            enable:1
        };
        fileList.value = [];
        proxy.resetForm("goodActivityRef");
    }
    const handleAdd = () => {
        reset();
        dialogTitle.value = "新增商品活动";
        show.value = true;
    }
    const handleEdit = (row) => {
        reset();
        getGoodActivityInfo(row.id).then(response => {
            goodActivityForm.value = response.data;
            goodActivityForm.value.queType = Number(goodActivityForm.value.queType);
            dialogTitle.value = "编辑商品活动";
            show.value = true;
        });
    }

    const submitForm = () => {
        proxy.$refs.goodActivityRef.validate((valid) => {
            if (valid) {
                buttonLoading.value = true;
                if(goodActivityForm.value.id){
                    updateGoodActivity(goodActivityForm.value).then((res)=>{
                        if(res.code!==0) return proxy.$message.error(res.msg);
                        buttonLoading.value = false;
                        show.value = false;
                        getList();
                    })
                }else{
                    addGoodActivity(goodActivityForm.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();
    }
    async function handleDelete(row) {
        await proxy?.$modal.confirm(`确认删除商品活动【${row.eventName}】吗？`).finally(() => loading.value = false);
        let res = await deleteGoodActivity([row.id]);
        if (res.code === 0) proxy?.$modal.msgSuccess("删除成功");
        else return proxy?.$modal.msgError(res.msg);
        await getList();
    }

    function statusChange(e,row) {
        let data = JSON.parse(JSON.stringify(row));
        data.enable = data.enable?1:0;
        updateGoodActivity(data).then((res)=>{
            if(res.code!==0) return proxy.$message.error(res.msg);
            getList();
        })
    }

    function handleChangeDate (e,key) {
        goodActivityForm.value[key] = proxy.parseTime(new Date(e), '{yy}-{mm}-{dd} {hh}:{ii}');
    }

    onMounted(()=>{
        getList();
    })
</script>

<style scoped lang="scss">
    .agent_page{
        padding: 24px 16px;

        .add{
            margin-top: -10px;
            justify-content: flex-end;
        }
    }
</style>