<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="150px" label="开始日期" prop="startTime"/>
            <el-table-column align="center" min-width="150px" label="结束日期" prop="endTime"/>

            <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 == 3" type="success" size="small"
                        @click="changeState(scope.row.actId, 2)">开启</el-button>
                    <el-button v-if="scope.row.status == 2" type="warning" size="small"
                        @click="changeState(scope.row.actId, 3)">关闭</el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope.row.actId, -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="110px" style='width:700px; margin-left:50px;'>
                <el-form-item label="活动类型" prop="type">
                    <el-select :disabled="dialogStatus == 'update'?true:false" v-model="dataForm.type" filterable placeholder="请选择" style="width: 350px"
                        value-key="value"  @change="clickType">
                        <el-option :key="item.dictValue" v-for="item in typeList" :label="item.dictLabel"
                            :value="item.dictValue">
                        </el-option>
                    </el-select>
                </el-form-item>
                <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="开始日期" prop="startCron">
                <el-input v-model="dataForm.startCron" placeholder="请输入cron执行表达式" style="width: 350px">
                    <template slot="append">
                    <el-button type="primary" :disabled="dialogStatus == 'update'?true:false" @click="handleShowCronStart">
                        生成表达式
                        <i class="el-icon-time el-icon--right"></i>
                    </el-button>
                    </template>
                </el-input>
                </el-form-item>
                <el-form-item label="结束日期" prop="endCron">
                    <el-input v-model="dataForm.endCron" placeholder="请输入cron执行表达式" style="width: 350px">
                        <template slot="append">
                            <el-button type="primary" :disabled="dialogStatus == 'update'?true:false" @click="handleShowCronEnd">
                                生成表达式
                                <i class="el-icon-time el-icon--right"></i>
                            </el-button>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="dataForm.type=='3' || dataForm.type=='5'"  label="关联奖池" prop="prizePoolId">
                    <el-select :disabled="dialogStatus == 'update'?true:false" v-model="dataForm.prizePoolId" clearable placeholder="请选择奖池" class="filter-item" style="width: 350px">
                        <el-option :key="item.id" v-for="item in poolList" :label="item.title" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-else label="关联兑换卷" prop="relationCoupon">
                    <el-radio-group :disabled="dialogStatus == 'update'?true:false" v-model="dataForm.relationCoupon">
                        <el-radio :label="'0'">否</el-radio>
                        <el-radio :label="'1'">是</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item v-if="(dataForm.type!='3' && dataForm.type!='5') && dataForm.relationCoupon=='1'"  label="兑换券" prop="couponIds">
                    <el-select :disabled="dialogStatus == 'update'?true:false" v-model="dataForm.couponIds" clearable multiple collapse-tags placeholder="请选择兑换券" class="filter-item" style="width: 350px">
                        <el-option :key="item.id" v-for="item in couponsList" :label="item.couponName" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="dataForm.type=='3' || dataForm.type=='5'" label="抽奖次数">
                    <el-input-number :disabled="dialogStatus == 'update'?true:false" style="width: 350px" :min="0" :step="1" v-model="dataForm.prizeNum"></el-input-number>
                </el-form-item>
                <el-form-item v-if="dataForm.type=='3' || dataForm.type=='5'" label="兑换积分">
                    <el-input-number :disabled="dialogStatus == 'update'?true:false" style="width: 350px" :min="0" :step="1" v-model="dataForm.expenseIntegral"></el-input-number>
                </el-form-item>
                <el-form-item v-if="dataForm.type=='5'" label="开奖日期" prop="winningTimeCron">
                <el-input v-model="dataForm.winningTimeCron" placeholder="请输入cron执行表达式" style="width: 350px">
                    <template slot="append">
                    <el-button type="primary" :disabled="dialogStatus == 'update'?true:false" @click="handleShowCronDrawStart">
                        生成表达式
                        <i class="el-icon-time el-icon--right"></i>
                    </el-button>
                    </template>
                </el-input>
                </el-form-item>
                <el-form-item v-if="dataForm.relationCoupon=='1' || dataForm.type=='3' || dataForm.type=='5'" label="兑换截至时间" prop="couponEndTime">
                    <el-date-picker
                    :disabled="dialogStatus == 'update'?true:false"
                    format="yyyy-MM-dd HH:mm:ss"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    type="datetime" v-model="dataForm.couponEndTime"
                    placeholder="请选择兑换截至时间"
                    style="width: 350px">
                    </el-date-picker>
                </el-form-item>
                <el-form-item  v-if="dataForm.type=='1'  || dataForm.type=='4'" label="活动连接" prop="activityUrl">
                    <el-input v-model="dataForm.activityUrl" style="width: 350px"></el-input>
                </el-form-item>
                <el-form-item label="参与人">
                    <el-select :disabled="dialogStatus == 'update'?true:false" 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>
        <el-dialog title="开始日期Cron表达式生成器" :visible.sync="openCronStart" append-to-body destroy-on-close class="scrollbar">
            <crontab @hide="openCronStart=false" @fill="crontabFillStart" :expression="expressionStart"></crontab>
        </el-dialog>
        <el-dialog title="结束日期Cron表达式生成器" :visible.sync="openCronEnd" append-to-body destroy-on-close class="scrollbar">
            <crontab @hide="openCronEnd=false" @fill="crontabFillEnd" :expression="expressionEnd"></crontab>
        </el-dialog>
        <el-dialog title="开奖日期Cron表达式生成器" :visible.sync="openCronDrawStart" append-to-body destroy-on-close class="scrollbar">
            <crontab @hide="openCronDrawStart=false" @fill="crontabFillDrawStart" :expression="expressionDrawStart"></crontab>
        </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, activityList, activityState } from "@/api/activityManage";
import Crontab from '@/components/Crontab'
import { allUserList,dataTypeList,couponsList,prizePoolList,drawPoolList } from "@/api/public";
import waves from "@/directive/waves"; // 水波纹指令
import Tinymce from '@/components/Tinymce'

export default {
    components: { Tinymce,Crontab },
    directives: { waves },
    data() {
        return {
            poolList:[],
            couponsList:[],
             // 是否显示Cron表达式弹出层
            openCronStart: false,
            openCronEnd: false,
            openCronDrawStart: false,
            // 传入的表达式
            expressionStart: "",
            expressionEnd: "",
            expressionDrawStart: "",
            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: {
                type:'',
                title: '',
                imgUrl: '',
                activityUrl: '',
                winningTimeCron: '',
                startCron: '',
                endCron: '',
                couponEndTime:'',
                prizePoolId:'',
                relationCoupon:'0',
                couponIds:[],
                prizeNum:undefined,
                expenseIntegral:undefined,
                participants: [],
                content: '',
                images: [],
            },
            dialogFormVisible: false,
            dialogStatus: '',
            textMap: {
                update: "编辑",
                create: "创建",
            },
            rules: {
                type: [{ required: true, message: "请选择活动类型", trigger: "blur" }],
                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" }],
                winningTimeCron: [
                    { required: true, message: "cron执行表达式不能为空", trigger: "blur" }
                ],
                startCron: [
                    { required: true, message: "cron执行表达式不能为空", trigger: "blur" }
                ],
                endCron: [
                    { required: true, message: "cron执行表达式不能为空", trigger: "blur" }
                ],
                couponEndTime:[
                    { required: true, message: "请选择兑换截止日期", trigger: "blur" }
                ],
                prizePoolId: [
                    { required: true, message: "请选择奖池", trigger: "blur" }
                ],
                relationCoupon: [
                    { required: true, message: "请选择是否关联兑换卷", trigger: "blur" }
                ],
                couponIds: [
                    { required: true, message: "请关联兑换券", trigger: "blur" }
                ],
                prizeNum: [
                    { required: true, message: "请设置抽奖次数", trigger: "blur" }
                ],
                expenseIntegral: [
                    { required: true, message: "请设置兑换积分", trigger: "blur" }
                ],
                activityUrl: [
                    { required: true, message: "请填写活动连接", trigger: "blur" }
                ],

            },
            fileImgUrl: this.upLoadUrl,
            typeList:[],
        }
    },
    created() {
        this.getCouponsList();
        this.getTypeList();
        this.getAllUserList();
        this.getList();
    },
    methods: {
        clickType(){
            this.dataForm.title = undefined;
            this.dataForm.imgUrl = undefined;
            this.dataForm.activityUrl = undefined;
            this.dataForm.winningTimeCron = undefined;
            this.dataForm.startCron = undefined;
            this.dataForm.endCron = undefined;

            this.dataForm.couponEndTime = undefined;
            this.dataForm.prizePoolId = undefined;
            this.dataForm.relationCoupon = '0';
            this.dataForm.couponIds = [];
            this.dataForm.prizeNum = undefined;
            this.dataForm.expenseIntegral = undefined,
            this.dataForm.participants = [];
            this.dataForm.content = undefined;
            this.dataForm.images = [];
            if(this.dataForm.type == '3'){
                this.getPrizePoolList();
            }
            if(this.dataForm.type == '5'){
                this.getDrawPoolList();
            }
        },
        getDrawPoolList() {
            drawPoolList({}).then(response => {
                this.poolList = response.data.data;
            }).catch(() => { });
        },
        getPrizePoolList() {
            prizePoolList({}).then(response => {
                this.poolList = response.data.data;
            }).catch(() => { });
        },
        getCouponsList() {
            couponsList({}).then(response => {
                this.couponsList = response.data.data;
            }).catch(() => { });
        },
        getTypeList(){
            dataTypeList({dictType:'act_type'}).then(response => {
                this.typeList = response.data.data;
            }).catch(() => {});
        },
          /** cron表达式按钮操作 */
        handleShowCronDrawStart() {
            this.expressionDrawStart = this.dataForm.winningTimeCron;
            this.openCronDrawStart = true;
        },
        handleShowCronStart() {
            this.expressionStart = this.dataForm.startCron;
            this.openCronStart = true;
        },
        handleShowCronEnd() {
            this.expressionEnd = this.dataForm.endCron;
            this.openCronEnd = true;
        },
        /** 确定后回传值 */
        crontabFillDrawStart(value) {
            this.dataForm.winningTimeCron = value;
        },
        crontabFillStart(value) {
            this.dataForm.startCron = value;
        },
        crontabFillEnd(value) {
            this.dataForm.endCron = value;
        },
        //校验开始时间
        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 = {
                type:'',
                title: '',
                imgUrl: '',
                activityUrl: '',
                winningTimeCron: '',
                startCron: '',
                endCron: '',
                couponEndTime:'',
                prizePoolId:'',
                relationCoupon:'0',
                couponIds:[],
                prizeNum:'',
                expenseIntegral:undefined,
                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) {
            if(row.type == '3'){
                this.getPrizePoolList();
            }
            if(row.type == '5'){
                this.getDrawPoolList();
            }
            this.dataForm = Object.assign({}, row);
            if(this.dataForm.couponIds==null){
                this.dataForm.couponIds = [];
            }
            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(actId, index) {
            activityState({ actId: actId, status: index }).then(response => {
                this.$notify({
                    title: '成功',
                    message: '活动状态修改成功',
                    type: 'success',
                    duration: 2000
                })
                this.getList()
            })
        },
        handleDelete(actId, index) {
            this.$confirm('确认删除吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                activityState({ actId: actId, 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
            activityList(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>
