<template>
    <div class="ficc-activity-list-wrap">
        <div class="top-wrap">
            <el-button :type="activityStatus === 1 ? 'primary' : ''" @click="handleActivityStatusChange(1)">未开始
            </el-button>
            <el-button :type="activityStatus === 2 ? 'primary' : ''" @click="handleActivityStatusChange(2)">进行中
            </el-button>
            <el-button :type="activityStatus === 3 ? 'primary' : ''" @click="handleActivityStatusChange(3)">已结束
            </el-button>
            <el-button type="primary" style="float: right" @click="$router.push('/ficcActivitySpeaker')">主讲人配置</el-button>
            <el-button type="primary" style="float: right" @click="$router.push('/ficcActivityAdd')">添加活动</el-button>
        </div>
        <div class="content-wrap">
            <div class="select-wrap">
                <el-cascader placeholder="请选择活动类别" v-model="activeType" :options="typeList" clearable
                    :collapse-tags="true" :props="{
                        value: 'ActivityTypeId',
                        label: 'ActivityTypeName',
                        children: 'ChildList',
                        multiple: true,
                    }" style="margin-right: 30px; min-width: 310px" @change="handleTypeChange">
                </el-cascader>
                <el-date-picker v-model="timeRange" type="daterange" range-separator="至" start-placeholder="活动开始日期"
                    end-placeholder="活动结束日期" value-format="yyyy-MM-dd" @change="handleTypeChange"
                    style="margin-right: 30px">
                </el-date-picker>
                <el-select @change="handleTypeChange" v-model="publishStatus" placeholder="发布状态" clearable="">
                    <el-option label="已发布" value="1"></el-option>
                    <el-option label="未发布" value="0"></el-option>
                </el-select>
                <el-input placeholder="请输入活动标题" v-model="searchVal" style="max-width: 400px; float: right"
                    @input="handleTypeChange" clearable>
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </div>
            <div class="list-wrap">
                <el-table :data="list" border>
                    <el-table-column key="活动标题" align="center" prop="ActivityName" label="活动标题">
                        <template slot-scope="scope">
                            <span class="title" @click="handleShowDetail(scope.row)">{{
                                    scope.row.ActivityName
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="活动类型" align="center" prop="FirstActivityTypeName" label="活动类型" width="200px">
                    </el-table-column>
                    <el-table-column key="活动类别" align="center" prop="ActivityTypeName" label="活动类别" width="200px">
                    </el-table-column>
                    <el-table-column key="活动时间" align="center" prop="StartTime" label="活动时间" width="250px">
                        <template slot-scope="scope">
                            <span class="time">{{
                                    scope.row.StartTime | formatActivityTimeRange(scope.row.EndTime)
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="更新时间" align="center" prop="ModifyTime" label="更新时间" width="180px">
                        <template slot-scope="scope">
                            <span class="time">{{
                                    scope.row.ModifyTime | formatActivityTime
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="发布状态" align="center" prop="PublishStatus" label="发布状态" width="100px">
                        <template slot-scope="scope">
                            <span class="time">{{
                                    scope.row.PublishStatus === 0 ? "未发布" : "已发布"
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="操作" align="center" label="操作" width="250px">
                        <template slot-scope="scope">
                            <div v-if="activityStatus == 2">--</div>
                            <div v-else>
                                <span class="opt-btn" v-if="scope.row.PublishStatus == 0 && activityStatus == 1"
                                    @click="handlePublishActivity(scope.row)">发布</span>
                                <span class="opt-btn" @click="handleGoEditActivity(scope.row)">编辑</span>
                                <span class="opt-btn" v-if="scope.row.PublishStatus == 1 && activityStatus == 1"
                                    @click="handleUnPublishActivity(scope.row)">取消发布</span>
                                <span class="opt-btn" style="color: #ff4040"
                                    v-if="activityStatus == 1 && scope.row.PublishStatus != 1"
                                    @click="handleDelActivity(scope.row)">删除</span>
                                <!-- <template v-if="activityStatus==1 && scope.row.PublishStatus == 1">
                                    <span v-if="scope.row.QsId == 0" @click="QuanShiEventCreate(scope.row)"
                                        style="color: #4099ef; cursor: pointer">全时建会</span>
                                    <span class="opt-btn" v-else-if="scope.row.QsId >= 0"
                                        @click="quanShiEventCreateCancel(scope.row)">取消建会</span>
                                </template> -->
                            </div>
                        </template>
                    </el-table-column>
                    <div slot="empty" style="padding: 150px 0">暂无数据</div>
                </el-table>
            </div>
            <!-- 分页 -->
            <el-pagination layout="total,prev,pager,next,jumper" background :current-page="page"
                @current-change="handlePageChange" :page-size="pageSize" :total="total" class="pagination-wrap">
            </el-pagination>
        </div>

        <!-- 详情弹窗 -->
        <el-dialog v-dialogDrag :append-to-body="true" :visible.sync="showDetail" width="600px" center>
            <div slot="title">
                <img src="../../../assets/img/ficc_activity/flag.png" alt="" width="16" height="16"
                    style="vertical-align: middle" />
                <span style="vertical-align: middle">活动详情</span>
            </div>
            <div class="ficc-activity-detail-wrap">
                <table class="table-wrap">
                    <tr>
                        <td class="table-item dark-item">
                            {{ detailInfo.ActivityTypeName }}
                        </td>
                    </tr>
                    <tr>
                        <td class="table-item">活动名称：{{ detailInfo.ActivityName }}</td>
                    </tr>
                    <tr>
                        <td class="table-item">
                            活动时间：{{
                                    detailInfo.StartTime
                                    | formatActivityTimeRange(detailInfo.EndTime)
                            }}
                        </td>
                    </tr>
                    <tr v-if="detailInfo.City">
                        <td class="table-item">
                            活动地址：{{ detailInfo.City }}{{ detailInfo.Address }}
                        </td>
                    </tr>
                    <tr>
                        <td class="table-item">主讲人：{{ detailInfo.Speaker }}</td>
                    </tr>
                    <tr v-if="detailInfo.LimitPeopleNum">
                        <td class="table-item">
                            线下人数限制：{{ detailInfo.LimitPeopleNum }}
                        </td>
                    </tr>
                    <tr v-if="detailInfo.MainlandTel">
                        <td class="table-item">大陆拨入：{{ detailInfo.MainlandTel }}</td>
                    </tr>
                    <tr v-if="detailInfo.HongKongTel">
                        <td class="table-item">香港拨入：{{ detailInfo.HongKongTel }}</td>
                    </tr>
                    <tr v-if="detailInfo.TaiwanTel">
                        <td class="table-item">台湾拨入：{{ detailInfo.TaiwanTel }}</td>
                    </tr>
                    <tr v-if="detailInfo.SingaporeTel">
                        <td class="table-item">
                            新加坡拨入：{{ detailInfo.SingaporeTel }}
                        </td>
                    </tr>
                    <tr v-if="detailInfo.AmericaTel">
                        <td class="table-item">美国拨入：{{ detailInfo.AmericaTel }}</td>
                    </tr>
                    <tr v-if="detailInfo.ParticipationCode">
                        <td class="table-item">
                            拨入密码：{{ detailInfo.ParticipationCode }}
                        </td>
                    </tr>
                    <tr v-if="detailInfo.LinkParticipants">
                        <td class="table-item">
                            网络参会：{{ detailInfo.LinkParticipants }}
                        </td>
                    </tr>
                    <tr v-if="detailInfo.ReportLink">
                        <td class="table-item">相关报告：{{ detailInfo.ReportName }}</td>
                    </tr>
                    <tr>
                        <td class="table-item">主持人入会密码：{{ detailInfo.HostCode }}</td>
                    </tr>
                </table>
                <div style="text-align: center; margin: 30px 0">
                    <el-button type="primary" style="width: 150px" v-if="detailInfo.PosterList"
                        @click="handleDownLoadImg">下载活动海报</el-button>
                    <el-button type="primary" @click="showDetail = false" style="width: 150px">关闭</el-button>
                </div>
            </div>
        </el-dialog>
        <!-- 下载海报弹窗 -->
        <el-dialog v-dialogDrag :append-to-body="true" :visible.sync="showDownLoadImg" width="400px" title="下载活动海报"
            center>
            <div v-if="detailInfo.PosterList">
                <el-checkbox-group v-model="downPosterList">
                    <el-checkbox style="display: block; margin: 5px 0" v-for="item in detailInfo.PosterList"
                        :key="item.Url" :label="item">{{ item.Name }}</el-checkbox>
                </el-checkbox-group>
            </div>
            <div style="text-align: center; margin: 30px 0">
                <el-button type="primary" plain @click="showDownLoadImg = false">取消</el-button>
                <el-button type="primary" @click="downloadImg">确定</el-button>
            </div>
        </el-dialog>

        <!-- 全时建会 -->
        <el-dialog v-dialogDrag :append-to-body="true" :visible.sync="quanshiEventCreateDialog" width="500px"
            title="全时建会" center>
            <el-form :model="quanshiForm" :rules="quanshiRules" ref="quanshiForm" label-width="130px">
                <el-form-item label="会议时长(分钟)" prop="qsTime">
                    <el-input v-model="quanshiForm.qsTime"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button @click="quanshiEventCreateDialogClose()">取消</el-button>
                    <el-button type="primary" :loading="isLoading" @click="quanshiEventCreate(this)">确定</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 取消全时建会 -->
        <el-dialog v-dialogDrag :append-to-body="true" :visible.sync="quanshiEventCreateCalcelDialog" width="20%"
            title="取消建会" center>
            <h4 style="text-align:center">确定要取消该会议吗？</h4>
            <span slot="footer" class="dialog-footer">
                <el-button @click="quanshiEventCancelDialogCancel()">取消</el-button>
                <el-button type="primary" :loading="isLoading" @click="quanshiEventCancel(this)">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { ficcManageInterface } from "@/api/api";
import moment from "moment";
export default {
    name: "ficcActivityList",
    filters: {
        /**
         * 活动时间格式化
         * @param {2021-11-12T09:25:01+08:00} start 开始时间
         * @param 2021-11-12T09:25:01+08:00 end 结束时间
         * @returns 2020-06-04 15:30-16:30 星期一
         */
        formatActivityTimeRange(start, end) {
            const week = moment(start).format("dddd");
            const day = moment(start).format("YYYY-MM-DD");
            const startTime = moment(start).format("HH:mm");
            const endTime = moment(end).format("HH:mm");
            return `${day} ${startTime}-${endTime} ${week}`;
        },
        formatActivityTime(time) {
            return moment(time).format("YYYY.MM.DD HH:mm:ss");
        },
    },
    //进入前是否清除参数
    beforeRouteEnter(to, from, next) {
        if (from.path != "/ficcActivityAdd" && from.path != "/ficcActivityEdit") {
            sessionStorage.removeItem("ficcActivityList");
        }
        next();
    },
    //离开前缓存页面状态
    beforeRouteLeave(to, from, next) {
        let obj = {
            searchVal: this.searchVal,
            activityStatus: this.activityStatus,
            publishStatus: this.publishStatus,
            timeRange: this.timeRange,
            page: this.page,
            activeType: this.activeType,
        };
        sessionStorage.setItem("ficcActivityList", JSON.stringify(obj));
        next();
    },
    data() {
        return {
            quanshiForm: {
                qsTime: 60,
            },
            quanshiRules: {
                name: [
                    { required: true, message: '请输入会议时长', trigger: 'blur' },
                    { min: 30, max: 1200, message: '请输入会议时长', trigger: 'blur' }
                ],
            },
            searchVal: "",
            activityStatus: 1,
            typeList: [],
            activeType: [],
            publishStatus: "",
            timeRange: [],
            list: [],
            page: 1,
            pageSize: 10,
            total: 0,

            detailInfo: {},
            showDetail: false,
            showDownLoadImg: false,

            downPosterList: [], //需要下载的海报
            quanshiEventCreateActivityId: 0,
            quanshiEventCreateDialog: false,
            quanshiEventCreateCalcelDialog: false,
            isLoading: false
        };
    },
    created() {
        this.init();
        this.getActivityTypeList();
        this.getActivityList();
    },
    methods: {
        init() {
            let obj = JSON.parse(sessionStorage.getItem("ficcActivityList")) || {};
            this.searchVal = obj.searchVal || "";
            this.activityStatus = obj.activityStatus || 1;
            this.activeType = obj.activeType || [];
            this.publishStatus = obj.publishStatus || "";
            this.timeRange = obj.timeRange || [];
            this.page = obj.page || 1;
        },

        //编辑活动
        handleGoEditActivity(e) {
            this.$router.push({
                path: "/ficcActivityEdit",
                query: {
                    id: e.ActivityId,
                },
            });
            sessionStorage.setItem("ficcActivityDetail", JSON.stringify(e));
        },

        // 发布活动
        handlePublishActivity(e) {
            this.$confirm("确定发布该活动吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                const res = await ficcManageInterface.activityPublish({
                    ActivityId: Number(e.ActivityId),
                });
                if (res.Ret === 200) {
                    this.$message.success("发布成功");
                    this.getActivityList();
                }
            });
        },

        // 取消发布活动
        handleUnPublishActivity(e) {
            this.$confirm("确定取消发布该活动吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                const res = await ficcManageInterface.activityUnPublish({
                    ActivityId: Number(e.ActivityId),
                });
                if (res.Ret === 200) {
                    this.$message.success("取消发布成功");
                    this.getActivityList();
                }
            });
        },

        // 删除活动
        handleDelActivity(e) {
            this.$confirm("确定删除该活动吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(async () => {
                const res = await ficcManageInterface.activityDelete({
                    ActivityId: Number(e.ActivityId),
                });
                if (res.Ret === 200) {
                    this.$message.success("删除成功");
                    this.getActivityList();
                }
            });
        },

        handleShowDetail(e) {
            this.detailInfo = e;
            this.showDetail = true;
        },

        // 活动状态切换
        handleActivityStatusChange(e) {
            this.page = 1;
            this.searchVal = "";
            this.activityStatus = e;
            this.activeType = [];
            this.publishStatus = "";
            this.timeRange = [];
            this.getActivityList();
        },

        //筛选
        handleTypeChange() {
            this.page = 1;
            this.getActivityList();
        },

        handlePageChange(e) {
            this.page = e;
            this.getActivityList();
        },

        // 获取活动分类
        async getActivityTypeList() {
            const res = await ficcManageInterface.activityTypeList();
            if (res.Ret === 200) {
                this.typeList = res.Data || [];
            }
        },

        // 获取活动列表
        async getActivityList() {
            let ids = []; //选择的分类
            this.activeType.forEach((item) => {
                ids.push(item[item.length - 1]);
            });
            const res = await ficcManageInterface.activityList({
                Keyword: this.searchVal,
                ActivityTypeIds: ids.join(","),
                ActiveStatus: Number(this.activityStatus),
                PublishStatus:
                    this.publishStatus === "" ? -1 : Number(this.publishStatus),
                StartDate: (this.timeRange && this.timeRange[0]) || "",
                EndDate: (this.timeRange && this.timeRange[1]) || "",
                CurrentIndex: this.page,
                PageSize: this.pageSize,
            });
            if (res.Ret === 200) {
                this.list = res.Data.List || [];
                this.total = res.Data.Paging.Totals;
            }
        },

        // 下载活动海报
        handleDownLoadImg() {
            if (this.detailInfo.PosterList.length == 1) {
                this.downPosterList = this.detailInfo.PosterList;
                this.downloadImg();
            } else {
                this.showDownLoadImg = true;
            }
        },

        // 下载海报
        downloadImg(name, url) {
            // 方法一
            // this.downPosterList.forEach(item=>{
            //     console.log(item.Name,item.Url);
            //     const a=document.createElement('a')
            //     a.setAttribute("download",item.Name)
            //     a.style.display = "none"
            //     a.href=item.Url+'?response-content-type=application/octet-stream'
            //     document.body.appendChild(a);
            //     a.click()
            // })

            // 方法二
            this.downPosterList.forEach((item) => {
                let img = new Image();
                img.setAttribute("crossOrigin", "anonymous");
                img.src = item.Url;
                img.onload = () => {
                    let canvas = document.createElement("canvas");
                    canvas.width = img.width;
                    canvas.height = img.height;
                    let context = canvas.getContext("2d");
                    context.drawImage(img, 0, 0, img.width, img.height);
                    let dataURL = canvas.toDataURL("image/png", 1);
                    const a = document.createElement("a");
                    a.setAttribute("download", item.Name);
                    a.style.display = "none";
                    a.href = dataURL;
                    document.body.appendChild(a);
                    a.click();
                };
            });
            // let img=new Image()
            // img.setAttribute('crossOrigin', 'anonymous');
            // img.src=this.downloadUrl
            // img.onload=()=>{
            //     let canvas = document.createElement("canvas");
            // 	canvas.width = img.width;
            // 	canvas.height = img.height;
            // 	let context = canvas.getContext('2d');
            // 	context.drawImage(img, 0, 0, img.width, img.height);
            //     let dataURL = canvas.toDataURL("image/png", 1);
            //     const a=document.createElement('a')
            //     let name=''
            //     this.detailInfo.PosterList.forEach(item=>{
            //         if(item.Url==this.downloadUrl){
            //             name=item.Name
            //         }
            //     })
            //     a.setAttribute("download",name)
            //     a.style.display = "none"
            //     a.href=dataURL
            //     document.body.appendChild(a);
            //     a.click()
            // }
        },

        //全时建会
        QuanShiEventCreate(e) {
            this.quanshiEventCreateDialog = true;
            this.quanshiEventCreateActivityId = Number(e.ActivityId);
            this.quanshiForm.qsTime = 60
        },
        //建会取消
        quanshiEventCreateDialogClose() {
            this.quanshiEventCreateActivityId = 0
            this.quanshiForm.qsTime = 60
            this.quanshiEventCreateDialog = false;
        },
        //建会保存
        quanshiEventCreate(e) {
            if (Number(this.quanshiForm.qsTime) <= 0) {
                this.$message.warning("建会时长必须大于0！");
                return;
            }
            this.isLoading = true
            ficcManageInterface.quanshiEventCreate({
                ActivityId: this.quanshiEventCreateActivityId,
                Time: Number(this.quanshiForm.qsTime),
            }).then((result) => {
                console.info(result.Ret)
                if (result.Ret === 200) {
                    this.$message.success(result.Msg);
                    this.getActivityList();
                    this.quanshiEventCreateDialog = false;
                    this.isLoading = false;
                }
            });
        },
        //取消建会弹框
        quanShiEventCreateCancel(e) {
            this.quanshiEventCreateActivityId = Number(e.ActivityId);
            this.quanshiEventCreateCalcelDialog = true;
        },
        //取消建会弹框-取消按钮
        quanshiEventCancelDialogCancel() {
            this.quanshiEventCreateCalcelDialog = false;
        },
        //取消建会弹框-确定按钮
        quanshiEventCancel(obj) {
            this.isLoading = true
            ficcManageInterface.quanshiEventCancel({
                ActivityId: this.quanshiEventCreateActivityId
            }).then((result) => {
                console.info(result.Ret)
                if (result.Ret === 200) {
                    this.$message.success(result.Msg);
                    this.getActivityList();
                    this.quanshiEventCreateCalcelDialog = false;
                    this.isLoading = false;
                }
            });
        }
    },
};
</script>

<style lang="scss" scoped>
.ficc-activity-list-wrap {
    div {
        box-sizing: border-box;
    }

    .top-wrap {
        background: #ffffff;
        border: 1px solid #ececec;
        border-radius: 4px;
        padding: 20px 30px;

        .el-button {
            background-color: #ecf5ff;
            border: 1px solid #b3d8ff;
            color: #409eff;
        }

        .el-button--primary {
            background-color: #409eff;
            border: none;
            color: #ffffff;
        }
    }

    .content-wrap {
        margin-top: 20px;
        min-height: 70vh;
        background: #ffffff;
        border: 1px solid #ececec;
        box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
        border-radius: 4px;
        padding: 30px;
        padding-bottom: 65px;
        position: relative;

        .pagination-wrap {
            position: absolute;
            bottom: 24px;
            right: 30px;
        }
    }

    .list-wrap {
        margin-top: 40px;

        .title {
            color: #409eff;
            cursor: pointer;
        }

        .opt-btn {
            cursor: pointer;
            color: #409eff;
            margin: 0 5px;
        }
    }
}

.ficc-activity-detail-wrap {
    .table-wrap {
        color: #666;
        width: 100%;
        // text-align: center;
        border-top: 1px solid #dcdfe6;
        border-left: 1px solid #dcdfe6;

        .table-item {
            padding: 14px 30px;
            border-right: 1px solid #dcdfe6;
            border-bottom: 1px solid #dcdfe6;
            position: relative;
        }

        .dark-item {
            background: #f0f2f5;
            text-align: center;
        }
    }
}
</style>