<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" v-model="listQuery.createTime" type="datetime" placeholder="创建时间">
            </el-date-picker> -->
            <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="100px" label="福利开始结束时间">
                <template slot-scope="props">
                   {{ props.row.startTime }}~{{ props.row.endTime }}
                </template>
            </el-table-column>
            <el-table-column align="center" min-width="80px" label="创建人" prop="creater">
            </el-table-column>
            <el-table-column align="center" min-width="150px" 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.welfareId, 1)">开启</el-button>
                    <el-button v-if="scope.row.status == 1" type="warning" size="small"
                        @click="changeState(scope.row.welfareId, 0)">关闭</el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row.welfareId, -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="70%">
            <el-form :rules="rules" ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" style='width:700px;margin-left:50px;'>
                <el-form-item label="福利名称" prop="title">
                    <el-input v-model="dataForm.title" style="width: 350px"></el-input>
                </el-form-item>
                <el-form-item style="width: 800px" label="福利图片" prop="imgUrl">
                    <el-tooltip content="建议图片宽高比260*200" placement="top-start">
                        <el-upload :action="fileImgUrl" list-type="picture-card" :file-list="dataForm.images" :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="startTime">
                    <el-date-picker value-format="yyyy-MM-dd" :picker-options="setDisabled" v-model="dataForm.startTime" type="date" placeholder="请选择开始时间" style="width: 350px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="结束日期" prop="endTime">
                    <el-date-picker value-format="yyyy-MM-dd" :picker-options="setDisabled" v-model="dataForm.endTime" type="date" placeholder="请选择结束时间" style="width: 350px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="参与人">
                    <el-select v-model="dataForm.participants" multiple filterable placeholder="请选择" style="width: 350px">
                        <el-option :key="item.loginId" v-for="item in participantsList" :label="item.userName" :value="item.loginId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item style="width: 800px" label="内容" prop="content">
                    <tinymce v-model="dataForm.content" ref="tinymce"></tinymce>
                </el-form-item>
            </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 { createItem, updateItem, welfareList, welfareState } from "@/api/welfareManage";
import { allUserList } from "@/api/public";
import waves from "@/directive/waves"; // 水波纹指令
import Tinymce from '@/components/Tinymce'

export default {
    name: 'welfareList',
    components: { Tinymce },
    directives: { waves },
    data() {
        return {
            setDisabled: {
                disabledDate(time) {
                    // return time.getTime() > Date.now();  // 可选历史天、可选当前天、不可选未来天
                    // return time.getTime() > Date.now() - 8.64e7;  // 可选历史天、不可选当前天、不可选未来天
                    // return time.getTime() < Date.now() - 8.64e7;  // 不可选历史天、可选当前天、可选未来天
                    return time.getTime() < Date.now(); // 不可选历史天、不可选当前天、可选未来天
                },
            },
            participantsList: [],
            list: [],
            total: 0,
            listLoading: false,
            listQuery: {
                page: 1,
                limit: 10,
                title: '',
                createTime: '',
            },
            dataForm: {
                title: '',
                imgUrl: '',
                startTime: '',
                endTime: '',
                participants: [],
                content: '',
                images: [],
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: "编辑",
                create: "创建",
            },
            rules: {
                title: [{ required: true, message: "请填写福利名称", trigger: "blur" }],
                imgUrl: [{ required: true, message: "图片不能为空", trigger: "blur" }],
                startTime: [
                    { required: true, message: "请选择福利开始时间", trigger: "change" },
                    { validator: this.checkStartTime, trigger: 'change' }
                ],
                endTime: [
                    { required: true, message: "请选择福利结束时间", trigger: "change" },
                    { validator: this.checkEndTime, trigger: 'change' }
                ],
                content: [{ required: true, message: "内容不能为空", trigger: "blur" }],
            },
            fileImgUrl: this.upLoadUrl,
        }
    },
    created() {
        this.getAllUserList(); 
        this.getList();
    },
    methods: {
        //校验开始时间
        checkStartTime(rule, value, callback) {
            if (!value) {
                callback(new Error("请选择福利开始时间！"));
            } else {
                if (this.dataForm.endTime && Date.parse(value)  > Date.parse(this.dataForm.endTime)) {
                    callback(new Error("福利开始时间必须小于等于福利结束时间！"))
                    this.dataForm.startTime = '';
                } else {
                    callback();
                }
            }
        },
        //校验结束时间
        checkEndTime(rule, value, callback) {
            if (!value) {
                callback(new Error("请选择福利结束时间！"));
            } else {
                if (!this.dataForm.startTime) {
                    callback(new Error("请选择福利开始时间！"))
                    this.dataForm.endTime = '';
                } else if (Date.parse(this.dataForm.startTime) > Date.parse(value)) {
                    callback(new Error("福利结束时间必须大于等于福利开始时间！"))
                    this.dataForm.endTime = '';
                } else {
                    callback();
                }
            }
        },
        handleRemove(file, fileList) {
            console.log(file, fileList);
            let images = [];
            for (let i in fileList) {
                let response = fileList[i].response;
                let url = response.data.url;
                images.push(url);
                this.dataForm.imgUrl = images.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.imgUrl = ""; // 清空画廊图片数组

            let images = [];
            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;
                    images.push(url);
                }
            }

            this.dataForm.imgUrl = images.join(",");
        },
        resetForm() {
            this.dataForm = {
                title: '',
                imgUrl: '',
                startTime: '',
                endTime: '',
                participants: [],
                content: '',
                images: [],
            };
        },
        handleCreate() {

            this.resetForm();
            this.dialogFormVisible = true;
            this.dialogStatus = "create";
            this.$nextTick(() => {
                this.$refs.tinymce.setContent("");
                this.$refs["dataForm"].clearValidate();
            });
        },
        createData() {
            this.$refs["dataForm"].validate((valid) => {
                if (valid) {
                    console.log(this.dataForm);
                    createItem(this.dataForm)
                            .then((response) => {
                                this.getList();
                                this.dialogFormVisible = false;
                                this.$notify({
                                    title: "成功",
                                    message: "创建成功",
                                    type: "success",
                                    duration: 2000,
                                });
                                this.getList();
                            })
                            .catch(() => { });
                }
            });
        },
        handleUpdate(row) {
            this.dataForm = Object.assign({}, row);
            let content = this.dataForm.content;
            if (this.dataForm.imgUrl) {
                let images = this.dataForm.imgUrl.split(",");
                this.dataForm.images = [];
                for (let i in images) {
                    let url = images[i];
                    let name = "image_" + i;

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

                }

            })
        },
        changeState(welfareId, index) {
            welfareState({ welfareId: welfareId, status: index }).then(response => {
                this.$notify({
                    title: '成功',
                    message: '福利状态修改成功',
                    type: 'success',
                    duration: 2000
                })
                this.getList()
            })
        },
        handleDelete(welfareId, index) {
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                welfareState({ welfareId: welfareId, 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
            welfareList(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>
  