<template>
    <div class="page">
        <div class="top adfacjb">
            <div class="t_l">
                <p>问卷管理</p>
                <p class="tip">创建和管理PERILL评估问卷</p>
            </div>
            <div class="t_r">
                <el-button type="primary" icon="el-icon-plus" @click="show=true" v-hasPermi="['core:questionnaire:create']">新增问卷</el-button>
            </div>
        </div>
        <div class="query adfacjb">
            <el-input placeholder="搜索问卷" prefix-icon="el-icon-search" v-model="queryParams.title" style="width: calc(100% - 424px);" @keyup.enter.native="getList"></el-input>
            <el-select v-model="queryParams.type" placeholder="全部类型" style="width: 400px;" @change="getList">
                <el-option label="初级" :value="1"></el-option>
                <el-option label="中级" :value="2"></el-option>
                <el-option label="高级" :value="3"></el-option>
            </el-select>
        </div>
        <div class="list">
            <el-table :data="dataList" border cell-class-name="vertical-top-cell" v-loading="loading" empty-text="暂无问卷" max-height="578px">
                <el-table-column label="序号" width="50">
                    <template #default="scope">
                        {{ scope.$index + 1 }}
                    </template>
                </el-table-column>
                <el-table-column label="问卷标题" prop="title"></el-table-column>
                <!-- <el-table-column label="创建人" prop="title"></el-table-column> -->
                <el-table-column label="问卷类型" prop="type">
                    <template #default="scope">
                        {{ typecfg[scope.row.type]||'' }}
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createDate"></el-table-column>
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button link type="text" size="mini" @click="handleRelease(scope.row)" v-hasPermi="['core:questionnaire:publish']">发布问卷</el-button>
                        <el-button link type="text" size="mini" @click="handleDetail(scope.row)" v-hasPermi="['core:questionnairedetail:info']">详情</el-button>
                        <el-button link type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['core:questionnaire: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>
        </div>
        <el-dialog width="50%" :visible.sync="show" title="新增问卷" @close="cancel">
            <el-form ref="wjRef" :model="form" :rules="rules" label-width="100px" style="width: 90%;margin: 0 auto;">
                <el-form-item label="问卷标题" prop="title">
                    <el-input v-model="form.title" placeholder="请输入问卷标题"></el-input>
                </el-form-item>
                <el-form-item label="问卷类型" prop="type">
                    <el-select v-model="form.type" placeholder="请选择问卷类型" style="width: 100%;">
                        <el-option label="初级" :value="1"></el-option>
                        <el-option label="中级" :value="2"></el-option>
                        <el-option label="高级" :value="3"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                </el-form-item>
                <el-form-item label="上传文件" prop="file">
                    <el-upload
                        :action="uploadUrl"
                        :headers="uploadHeaders"
                        :on-success="uploadFileSuccess"
                        :before-upload="beforeAvatarUpload"
                        :on-remove="removeFile"
                        :limit="1"
                        :file-list="fileList">
                        <el-button size="small" type="primary">上传附件</el-button>
                    </el-upload>
                </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 Cookies from "js-cookie"
    import { ref, getCurrentInstance, onMounted } from 'vue'
    const { proxy } = getCurrentInstance();
    const uploadUrl = `${window.SITE_CONFIG["apiURL"]}/sys/oss/uploadFile`
    const uploadHeaders = {token:Cookies.get("token")};
    import { getQuestionnaireList, addQuestionnaire, deleteQuestionnaire } from '@/api/agent/index.js'
    
    const queryParams = ref({
        page:1,
        limit:10,
        title: '',
        type: ''
    })
    const typecfg = {
        1: '初级',
        2: '中级',
        3: '高级'
    }
    const dataList = ref([])
    const total = ref(0)
    const loading = ref(false)
    const show = ref(false)
    const fileList = ref([])
    const wjRef = ref(null)
    const buttonLoading = ref(false)
    const form = ref({
        id:'',
        title: '',
        type: '',
        remark: '',
        file: ''
    })
    const rules = ref({
        title:[{required:true,message:'请输入问卷标题',trigger:'blur'}],
        type:[{required:true,message:'请选择问卷类型',trigger:'change'}],
        file:[{required:true,message:'请上传附件',trigger:'change'}]
    })

    const uploadFileSuccess = (e) => {
        form.value.file = e.data
            if(e.data){
                fileList.value = [{name:e.data.split('/')[e.data.split('/').length-1],url:e.data}]
            }
    }
    const beforeAvatarUpload = (e) => {
        let type = e.name.split('.')[e.name.split('.').length-1];
        let isExcel = e.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
        if(type.toLowerCase() !== 'xlsx' && type.toLowerCase() !== 'xls' && !isExcel){
            proxy?.$modal.msgError('请上传xlsx或xls格式的Excel文件！');
            return false;
        }
    }
    const removeFile = (file) => {
        form.value.file = ''
        fileList.value = []
    }

    const submitForm = () => {
        proxy.$refs.wjRef.validate(async valid => {
            if (valid) {
                buttonLoading.value = true;
                const res = await addQuestionnaire(form.value);
                if (res.code === 0) {
                    proxy?.$modal.msgSuccess('新增成功！');
                    buttonLoading.value = false;
                    show.value = false;
                    getList();
                } else {
                    buttonLoading.value = false;
                }
            } else return false;
        })
    }

    const cancel = () => {
        show.value = false;
        form.value = {
            id:'',
            title: '',
            type: '',
            remark: '',
            file: ''
        }
        fileList.value = [];
        proxy?.$refs.wjRef.resetFields();
    }

    const getList = async () => {
        let query = {...queryParams.value};
        loading.value = true;
        const res = await getQuestionnaireList(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 handleRelease = row => {
        proxy.$router.push({path:'/agentQuestionnairePublish',query:{id:row.id,title:row.title,type:typecfg[row.type]}});
    }
    const handleDetail = row => {
        proxy.$router.push({path:'/agentQuestionnaireDetail',query:{id:row.id,title:row.title,type:typecfg[row.type]}});
    }
    const handleDelete = async row => {
        await proxy?.$modal.confirm('确认删除问卷【' + row.title + '】吗？').finally(() => loading.value = false);
        let res = await deleteQuestionnaire(row.id);
        if (res.code === 0) proxy?.$modal.msgSuccess("删除成功");
        else return proxy?.$modal.msgError(res.msg);
        await getList();
    }

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

<style scoped lang="scss">
    
    .page{
        padding: 28px 20px;
        background: #FAFAFA;
        
        .top{
            .t_l{
                p{
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: bold;
                    font-size: 16px;
                    color: #252525;
                    line-height: 16px;
                    &.tip{
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        font-size: 14px;
                        color: #6B7280;
                        line-height: 14px;
                        margin-top: 16px;
                    }

                }
            }
        }

        .query{
            width: 100%;
            padding: 16px 20px;
            box-sizing: border-box;
            background: #FFFFFF;
            border-radius: 6px;
            border: 1px solid #F3F4F6;
            margin-top: 16px;
        }
        
        .list{
            width: 100%;
            height: calc(100vh - 204px);
            background: #FFFFFF;
            overflow-y: auto;
            margin-top: 12px;
        }
    }
</style>