<template>
    <div class="app-container calendar-list-container">

        <!-- 查询和其他操作 -->
        <div class="filter-container">
            <el-input clearable class="filter-item" style="width: 200px;" placeholder="标题"
                v-model="listQuery.title"></el-input>
            <el-date-picker
            class="filter-item"
            value-format="yyyy-MM-dd"
            v-model="listQuery.createTime"
            type="date"
            placeholder="创建日期">
            </el-date-picker>
            <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
            <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-edit">添加</el-button>

        </div>

        <!-- 查询结果 -->
        <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit
            highlight-current-row>
            <el-table-column type="index" label="序号" header-align="center" align="center">
            </el-table-column>

            <el-table-column align="center" min-width="100px" label="标题" prop="title">
            </el-table-column>
            
            <el-table-column align="center" min-width="80px" label="类型" prop="typeName">
            </el-table-column>
            <el-table-column align="center" min-width="80px" label="积分" prop="integral">
            </el-table-column>
            <el-table-column align="center" min-width="100px" label="截止日期" prop="deadline">
            </el-table-column>
            <el-table-column align="center" min-width="100px" label="创建日期" prop="createTime">
            </el-table-column>
            <el-table-column align="center" min-width="80px" label="状态" prop="statusName">
            </el-table-column>
            <el-table-column align="center" label="操作" width="240px" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.status == 0" type="success" size="small"
                        @click="changeState(scope.row.id, 1)">开启</el-button>
                    <el-button v-if="scope.row.status == 1" type="warning" size="small"
                        @click="changeState(scope.row.id, 0)">关闭</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row.id, -1)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="listQuery.page" :page-sizes="[10, 20, 30, 50]" :page-size="listQuery.limit"
                layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
        <!-- 添加或修改对话框 -->
        <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="65%">
            <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width:750px;margin-left:50px;'>
                <el-form-item label="标题" prop="title">
                    <el-input v-model="dataForm.title" style="width: 100%"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="dataForm.type" placeholder="请选择" style="width: 100%" @change="changeType">
                        <el-option :key="item.value" v-for="item in typeList" :label="item.name" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 800px" label="图片" prop="media">
                    <el-tooltip content="建议图片宽高比120*80" placement="top-start">
                        <el-upload :action="fileImgUrl" list-type="picture-card" :file-list="dataForm.mediaFiles" :limit="1"
                            :on-success="handleGallerySucess" :on-exceed="handleExceed" :before-upload="uploadBannerImg"
                            :on-remove="handleRemove">
                            <i class="el-icon-plus"></i>
                        </el-upload>
                    </el-tooltip>
                    
                </el-form-item>
                <el-form-item label="积分" prop="integral">
                    <el-input-number style="width: 100%" :min="0" :step="1" v-model="dataForm.integral"></el-input-number>
                </el-form-item>
                <el-form-item label="截止日期" prop="deadline">
                    <el-date-picker value-format="yyyy-MM-dd" v-model="dataForm.deadline" type="date" placeholder="请选择结束时间" style="width: 100%">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="参与人">
                    <el-select v-model="dataForm.participants" multiple filterable placeholder="请选择" style="width: 100%">
                        <el-option :key="item.loginId" v-for="item in participantsList" :label="item.userName+'_'+item.deptName" :value="item.loginId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="内容" prop="content">
                    <el-input type="textarea" :rows="4" style="width: 100%" v-model="dataForm.content"></el-input>
                </el-form-item>
                <el-form-item label="问题类型" prop="questions">
                    <el-select v-model="qesType" placeholder="请选择" style="width: 84%">
                        <el-option :key="item.value" v-for="item in qesTypeList" :label="item.name" :value="item.value">
                        </el-option>
                    </el-select>
                    <el-button type="success" @click="addquest">添加问题</el-button>
                </el-form-item>
                <div style="margin: 50px 0;" v-for="(item,index) in dataForm.questions" :key="index">
                    <el-form-item v-if="item.type=='SCQ'" :label="'问题'+(index+1)+'(单选)'">
                        <el-input v-model="item.description" style="width: 67%"></el-input>
                        <el-button type="primary" @click="additem(index)">添加选项</el-button>
                        <el-button type="danger" @click="delectquest(index)">删除问题</el-button>
                    </el-form-item>
                    <el-form-item v-if="item.type=='MCQ'" :label="'问题'+(index+1)+'(多选)'">
                        <el-input v-model="item.description" style="width: 67%"></el-input>
                        <el-button type="primary" @click="additem(index)">添加选项</el-button>
                        <el-button type="danger" @click="delectquest(index)">删除问题</el-button>
                    </el-form-item>
                    <el-form-item v-if="item.type=='SAQ'" :label="'问题'+(index+1)+'(问答)'">
                        <el-input v-model="item.description" style="width: 84%"></el-input>
                        <el-button type="danger" @click="delectquest(index)">删除问题</el-button>
                    </el-form-item>
                    <div v-for="(val,childindex) in item.options" :key="childindex">
                        <el-form-item :label="'选项'+(childindex+1)">
                            <el-input v-model="val.name" style="width: 84%"></el-input>
                            <el-button type="danger" @click="delectitem(index,childindex)">删除选项</el-button>
                        </el-form-item>
                    </div>
                   
                </div>
               
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData">确定</el-button>
                <el-button v-else type="primary" @click="updateData">确定</el-button>
            </div>
        </el-dialog>

    </div>
</template>
  
<style>
.demo-table-expand {
    font-size: 0;
}

.demo-table-expand label {
    width: 200px;
    color: #99a9bf;
}

.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
}
</style>
  
<script>
import { create, update, getList, changeState, getDetailInfo } from "@/api/postManage";
import { allUserList } from "@/api/public";
import waves from "@/directive/waves"; // 水波纹指令
import Tinymce from '@/components/Tinymce'

export default {
    name: 'getList',
    components: { Tinymce },
    directives: { waves },
    data() {
        return {
            fileImgUrl: this.upLoadUrl,
            qesType:'',
            qesTypeList:[
                {
                    value:'SCQ',
                    name:'单选'
                },
                {
                    value:'MCQ',
                    name:'多选'
                },
                {
                    value:'SAQ',
                    name:'问答'
                },
            ],
            typeList:[
                {
                    value:4,
                    name:'投票'
                },
                {
                    value:5,
                    name:'问卷调查'
                }
            ],
            participantsList: [],
            list: [
                {
                    title:'问卷调查标题',
                    type:5,
                    typeName:'问卷调查',
                    integral:500,
                    deadline:'2023-11-08',
                    participants: ["13564541778","13651932750","18616396637","13817835530"],
                    content: '2222',
                    questions: [
                        {
                            description: "测试—问题1",
                            type: "SCQ",
                            options:[
                                {
                                    name: "A"
                                },
                                {
                                    name: "B"
                                },
                                {
                                    name: "C"
                                },
                                {
                                    name: "D"
                                }
                            ]
                            
                        },
                        {
                            type: "MCQ",
                            description: "测试—问题2",
                            options: [
                                {
                                    name: "A"
                                },
                                {
                                    name: "B"
                                },
                                {
                                    name: "C"
                                },
                                {
                                    name: "D"
                                }
                            ]
                        },
                        {
                            type: "SAQ",
                            description: "测试—问题3",
                            options: []
                        }
                    ],
                },
                {
                    title:'投票标题',
                    type:4,
                    typeName:'投票',
                    integral:500,
                    deadline:'2023-11-08',
                    participants: ["13564541778","13651932750"],
                    content: '2222',
                    questions: [
                        {
                            description: "测试—问题1",
                            type: "SCQ",
                            options:[
                                {
                                    name: "A"
                                },
                                {
                                    name: "B"
                                },
                                {
                                    name: "C"
                                },
                                {
                                    name: "D"
                                }
                            ]
                            
                        },
                        {
                            type: "MCQ",
                            description: "测试—问题2",
                            options: [
                                {
                                    name: "A"
                                },
                                {
                                    name: "B"
                                },
                                {
                                    name: "C"
                                },
                                {
                                    name: "D"
                                }
                            ]
                        },
                    ],
                },
            ],
            total: 0,
            listLoading: false,
            listQuery: {
                page: 1,
                limit: 10,
                title: '',
                createTime: '',
            },
            dataForm: {
                title: '',
                type: '',
                media: '',
                mediaFiles: [],
                integral: '',
                deadline: '',
                participants: [],
                content: '',
                questions: [],
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: "编辑",
                create: "创建",
            },
            rules: {
                title: [{ required: true, message: "请填写标题", trigger: "blur" }],
                type: [{ required: true, message: "请选择类型", trigger: "blur" }],
                media: [{ required: true, message: "图片不能为空", trigger: "blur" }],
                integral: [{ required: true, message: "请填写积分", trigger: "blur" }],
                deadline: [{ required: true, message: "请选择截止日期", trigger: "blur" }],
                content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
                questions: [{ required: true, message: "请添加至少一个问题", trigger: "blur" }],
            },
        }
    },
    created() {
        this.getAllUserList(); 
        this.getList();
    },
    methods: {
        handleRemove(file, fileList) {
            console.log(file, fileList);
            let mediaFiles = [];
            for (let i in fileList) {
                let response = fileList[i].response;
                let url = response.data.url;
                mediaFiles.push(url);
                this.dataForm.media = mediaFiles.join(",");
            }
        },
        uploadBannerImg(file) {
            const isJPGs = file.type === "image/jpeg";
            console.log(isJPGs);
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件！，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        handleGallerySucess(res, file, fileList) {
            this.dataForm.media = ""; // 清空画廊图片数组

            let mediaFiles = [];
            for (let i in fileList) {
                let response = fileList[i].response;
                if (response.errno && response.errno != "0") {
                    this.$message.error("该图片上传失败,已被移除,请重新上传!");
                    // 上传失败移除该 file 对象
                    fileList.splice(i, 1);
                } else {
                    let url = response.data.url;
                    mediaFiles.push(url);
                }
            }

            this.dataForm.media = mediaFiles.join(",");
        },
        //改变类型
        changeType(val){
            if(val==5){
                this.qesTypeList = [
                    {
                        value:'SCQ',
                        name:'单选'
                    },
                    {
                        value:'MCQ',
                        name:'多选'
                    },
                    {
                        value:'SAQ',
                        name:'问答'
                    },
                ];
            }
            if(val==4){
                this.qesTypeList = [
                    {
                        value:'SCQ',
                        name:'单选'
                    },
                    {
                        value:'MCQ',
                        name:'多选'
                    },
                ];
            }
        },
        //添加问题
        addquest(){
            let tempArray = this.dataForm.questions;
            if(this.qesType){
                var temp0 = {
                    type: this.qesType,
                    description: '',
                    options:[],
                };
                tempArray.push(temp0);
                this.dataForm.questions = tempArray;
            }else{
                this.$message.error('请选择问题类型');
            }
            this.qesType = '';
        },
        //删除问题
        delectquest(index){
            let qusetion = this.dataForm.questions;
            qusetion.splice(index, 1);
            this.dataForm.questions = qusetion;
        },
        //添加选项
        additem(index){
            console.log(index);
            let qusetion = this.dataForm.questions;
            let options = qusetion[index].options;
            options.push({ name:''});
            this.dataForm.questions = qusetion;
        },
         //删除选项
        delectitem(index,childindex){
            console.log(index,childindex);
            let qusetion = this.dataForm.questions;
            let options = qusetion[index].options;
            options.splice(childindex, 1);
            this.dataForm.questions = qusetion;
        },
        resetForm() {
            this.dataForm = {
                title: '',
                type: '',
                media: '',
                mediaFiles: [],
                integral: '',
                deadline: '',
                participants: [],
                content: '',
                questions: [],
            };
        },
        handleCreate() {

            this.resetForm();
            this.dialogFormVisible = true;
            this.dialogStatus = "create";
            this.$nextTick(() => {
                this.$refs["dataForm"].clearValidate();
            });
        },
        //验证是否为空的函数
        ifnone_data() {
            let stati_top = 200;
            let qusetion = this.dataForm.questions;
            for (let i = 0; i < qusetion.length; i++) {
            if (qusetion[i].description == '') { 
                stati_top = '请填写问题'; break; 
            }
            if (qusetion[i].type != 'SAQ') {
                if (qusetion[i].options.length == 0) { 
                    stati_top = '请添加选项'; break; 
                }
                for (let j = 0; j < qusetion[i].options.length; j++) {
                    if (qusetion[i].options[j].name == '') { 
                        stati_top = '请填写选项'; break; 
                    }
                }
            }

            }
            return stati_top;
        },
        createData() {
            this.$refs["dataForm"].validate((valid) => {
                let ifnone_data = this.ifnone_data();
                if (valid&&ifnone_data==200) {
                    console.log(this.dataForm);
                    create(this.dataForm)
                            .then((response) => {
                                this.getList();
                                this.dialogFormVisible = false;
                                this.$notify({
                                    title: "成功",
                                    message: "创建成功",
                                    type: "success",
                                    duration: 2000,
                                });
                                this.getList();
                            })
                            .catch(() => { });
                }else{
                    this.$message.error(ifnone_data);
                }
            });
        },
        handleUpdate(row) {
            getDetailInfo({postId:row.id}).then(response => {
                this.dataForm = response.data.data;
                this.dataForm.questions = response.data.data.data;
                if (this.dataForm.media) {
                    let mediaFiles = this.dataForm.media.split(",");
                    this.dataForm.mediaFiles = [];
                    for (let i in mediaFiles) {
                        let url = mediaFiles[i];
                        let name = "image_" + i;

                        this.dataForm.mediaFiles.push({
                            name: name,
                            url: url,
                            response: { error: "0", data: { url: url } },
                        });
                    }
                }
                this.dialogStatus = 'update'
                this.dialogFormVisible = true
                this.$nextTick(() => {
                    this.$refs["dataForm"].clearValidate();
                });
            }).catch(() => {})
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    update(this.dataForm).then(() => {
                            this.dialogFormVisible = false
                            this.$notify({
                                title: '成功',
                                message: '更新成功',
                                type: 'success',
                                duration: 2000
                            })
                            this.getList()
                        })

                }

            })
        },
        changeState(postId, index) {
            changeState({ postId: postId, status: index }).then(response => {
                this.$notify({
                    title: '成功',
                    message: '状态修改成功',
                    type: 'success',
                    duration: 2000
                })
                this.getList()
            })
        },
        handleDelete(postId, index) {
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                changeState({ postId: postId, status: index }).then(response => {
                    this.$notify({
                        title: '成功',
                        message: '删除成功',
                        type: 'success',
                        duration: 2000
                    })
                    this.getList();
                })
            }).catch(() => {})

        },
        getAllUserList() {
            allUserList().then(response => {
                this.participantsList = response.data.data;
            }).catch(() => {});
        },
        getList() {
            this.listLoading = true
            getList(this.listQuery).then(response => {
                this.list = response.data.data.items
                this.total = response.data.data.total
                this.listLoading = false
            }).catch(() => {})
        },
       

        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleSizeChange(val) {
            this.listQuery.limit = val
            this.getList()
        },
        handleCurrentChange(val) {
            this.listQuery.page = val
            this.getList()
        },

        
    }
}
</script>
<style>
.ad-avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.ad-avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.ad-avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.ad-avatar {
    display: block;
}
</style>
  