<template>
    <div class="agent_page adffc">
        <div class="ap_title">{{ title }}</div>
        <el-form :model="queryParams" ref="queryRef" label-width="118px" style="margin-top: 20px;">
          <el-row>
            <el-col :span="8" style="padding-right: 20px;">
                <el-form-item label="用户昵称/手机号">
                    <el-input v-model="queryParams.keyword" placeholder="请输入用户昵称/手机号" style="width: 100%;"></el-input>
                </el-form-item>
            </el-col>
            <el-col :span="8" style="padding-right: 20px;">
                <el-form-item label="时间周期">
                    <el-date-picker
                        v-model="queryParams.startEndTime"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间">
                    </el-date-picker>
                </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8" style="padding-right: 20px;">
                <el-form-item label="渠道类型">
                    <el-select v-model="queryParams.channelType" placeholder="请选择渠道类型" clearable style="width: 100%">
                        <el-option v-for="item in channel_type" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8" style="padding-right: 20px;">
                <el-form-item label="用户标签">
                    <el-select v-model="queryParams.userBrief" placeholder="请选择用户标签" clearable style="width: 100%">
                        <el-option v-for="item in user_brief" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item>
                <div style="margin-left: -118px;">
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    <el-button type="primary" @click="getList">查询</el-button>
                    <el-button type="primary" @click="handleGive" v-hasPermi="['core:wechatuser:give']">赠送</el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="dataList" border @selection-change="handleSelectionChange" cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无小程序用户" max-height="578px" style="margin-top: 5px;">
            <el-table-column
                type="selection"
                width="55">
            </el-table-column>
            <el-table-column label="序号" width="50">
                <template #default="scope">
                    {{ scope.$index + 1 }}
                </template>
            </el-table-column>
            <el-table-column label="用户昵称" prop="realName"></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="mobile"></el-table-column>
            <el-table-column label="注册编号" prop="registerId" width="180"></el-table-column>
            <el-table-column label="用户类型" prop="xx">
                <template #default="{ row }">{{ typeCfg[row.type] }}</template>
            </el-table-column>
            <el-table-column label="注册渠道" prop="channelName"></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="createDate"></el-table-column>
            <!-- <el-table-column label="最近登录时间" prop="xx"></el-table-column> -->
            <el-table-column label="操作" width="150">
                <template #default="scope">
                    <el-button link type="text" size="mini" @click="handleReview(scope.row)">查看</el-button>
                    <el-button link type="text" size="mini" @click="handleTag(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="更改用户标签" @close="cancel">
            <el-form ref="tagRef" :model="tagForm" :rules="tagRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="用户标签" prop="userBrief">
                    <el-select v-model="tagForm.userBrief" placeholder="请选择用户标签类型" clearable style="width: 100%;">
                        <el-option v-for="item in user_brief" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </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="giveShow" title="赠送" @close="cancelGive">
            <el-form ref="giveRef" :model="giveForm" :rules="giveRules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="赠送类型" prop="type">
                    <el-radio-group v-model="giveForm.type">
                        <el-radio :label="1">个人版</el-radio>
                        <el-radio :label="2">团队版</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="赠送次数" prop="orderCount">
                    <el-input-number v-model="giveForm.orderCount" :min="1" :max="9999999" label="请输入赠送次数" style="width: 100%;"></el-input-number>
                </el-form-item>
            </el-form>
            <div class="demo-drawer__footer" style="display: flex;justify-content: end;">
                <el-button :loading="buttonLoadingGive" type="primary" @click="submitFormGive">保 存</el-button>
                <el-button @click="cancelGive" style="margin-right: 5%;">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="">
    import { ref, getCurrentInstance, onMounted } from 'vue'
    import { 
        getWechatUserList,updateBrief,saveBatch
    } from '@/api/agent/indexTwo.js'
    const { proxy } = getCurrentInstance();
    const { channel_type,user_brief } = proxy.useDict("channel_type","user_brief");
    const title = proxy.$route.meta.title;
    const queryParams = ref({
        page:1,
        limit:10,
        channelType:'',
        userBrief:'',
        keyword:'',
        startEndTime:'',
        beginTime:'',
        endTime:''
    })
    const typeCfg = ref({
        1:'个人版',
        2:'团队版',
        0:'团队PRO版',
        3:'高级',
        4:'中级',
        5:'初级',
    })
    const dataList = ref([])
    const total = ref(0)
    const loading = ref(false)
    const show = ref(false)
    const buttonLoading = ref(false)
    const tagForm = ref({
        id:'',
        userBrief:''
    })
    const tagRules = ref({
        userBrief:[{ required: true, message: '请选择用户标签', trigger: 'change' }],
    })
    const multipleSelection = ref([])
    const giveRef = ref(null)
    const giveShow = ref(false)
    const giveForm = ref({
        userIds:[],
        type:1,
        orderCount:1
    })
    const giveRules = ref({
        type:[{ required: true, message: '请选择赠送类型', trigger: 'change' }],
        orderCount:[{ required: true, message: '请输入赠送次数', trigger: 'blur' }],
    })
    const buttonLoadingGive = ref(false)

    const handleSelectionChange = (val) => {
        multipleSelection.value = val;
    }
    
    const resetQuery = () => {
        // 重置表单字段
        proxy.$refs.queryRef.resetFields();
        // 重置查询参数到初始状态
        queryParams.value = {
            page:1,            // 重置页码为1
            limit:10,          // 重置每页显示数量为10
            channelType:'',    // 清空渠道类型筛选
            keyword:'',        // 清空关键字搜索
            startEndTime:'',   // 清空时间范围选择
            beginTime:'',      // 清空开始时间
            endTime:''        // 清空结束时间
        }
        // 重新获取数据列表
        getList();
    }

    const handleGive = () => {
        if(multipleSelection.value.length === 0) return proxy.$message.warning('请选择需要赠送的用户！')
        giveForm.value.userIds = multipleSelection.value.map(item => item.id);
        giveShow.value = true;
    }

    const getList = async () => {
        let query = JSON.parse(JSON.stringify(queryParams.value));
        if(query.startEndTime && query.startEndTime.length > 0) {
            query.beginTime = proxy.parseTime(new Date(query.startEndTime[0]), '{yy}-{mm}-{dd} {hh}:{ii}:{ss}')
            query.endTime = proxy.parseTime(new Date(query.startEndTime[1]), '{yy}-{mm}-{dd} {hh}:{ii}:{ss}')
        }
        loading.value = true;
        delete query.startEndTime;
        const res = await getWechatUserList(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 handleReview = (row) => {
        proxy.$router.push({
            path:'/wechatUserDetail',
            query:{
                id:row.id
            }
        })
    }
    const handleTag = (row) => {
        tagForm.value.id = row.id;
        tagForm.value.userBrief = row.userBrief;
        show.value = true;
    }

    const reset = () => {
        tagForm.value = {
            id:'',
            userBrief:''
        };
        proxy.resetForm("tagRef");
    }

    const submitForm = () => {
        proxy.$refs.tagRef.validate((valid) => {
            if (valid) {
                buttonLoading.value = true;
                updateBrief(tagForm.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 submitFormGive = () => {
        proxy.$refs.giveRef.validate((valid) => {
            if (valid) {
                buttonLoadingGive.value = true;
                saveBatch(giveForm.value).then((res)=>{
                    if(res.code!==0) return proxy.$message.error(res.msg);
                    proxy.$message.success('赠送成功！');
                    buttonLoadingGive.value = false;
                    giveShow.value = false;
                    getList();
                })
            } else {
                return false;
            }
        });
    }
    const cancelGive = () => {
        giveShow.value = false;
        giveForm.value = {
            userIds:[],
            type:1,
            orderCount:1
        };
        proxy.resetForm("giveRef");
    }

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

<style scoped lang="scss">
    :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: 20vh !important;
    }
    ::v-deep .el-drawer__header span{
        font-weight: bold;
        font-size: 16px;
        color: #1D2129;
        line-height: 22px;
    }

    .agent_page{
        padding: 24px 16px;
    }
</style>