<script setup>
import { ficcManageInterface,customInterence } from "@/api/api";
import { onBeforeRouteLeave, useRouter } from "vue-router"
import { ref, computed } from 'vue'
import { ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import moment from "moment";
/**
 * 活动时间格式化
 * @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 星期一
 */
function 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}`;
}
function formatTimeRange(time){
    return moment(time).format("YYYY.MM.DD HH:mm:ss");
}
//离开前缓存页面状态
onBeforeRouteLeave((to, from, next)=>{
    let obj = {
        searchVal: searchVal.value,
        activityStatus: activityStatus.value,
        publishStatus: publishStatus.value,
        timeRange: timeRange.value,
        page: page.value,
        activeType: activeType.value,
    };
    sessionStorage.setItem("ficcActivityList", JSON.stringify(obj));
    next();
})

let searchVal=ref("")
let activityStatus=ref(1)
let typeList=ref([])
let activeType=ref( )
let publishStatus=ref("")
let timeRange=ref([])
let list=ref([])
let page=ref(1)
let pageSize=ref(10)
let total=ref(0)

let detailInfo=ref({})
let showDetail=ref(false)
let showChooseSellerDialog=ref(false)
let sellerList=ref([])
let ShareSellerId=ref('')

let Role = computed(()=>localStorage.getItem('Role'))
let AdminId = computed(()=>localStorage.getItem('AdminId'))

function init() {
    let obj = JSON.parse(sessionStorage.getItem("ficcActivityList")) || {};
    searchVal.value = obj.searchVal || "";
    activityStatus.value = obj.activityStatus || 1;
    activeType.value = obj.activeType || [];
    publishStatus.value = obj.publishStatus || "";
    timeRange.value = obj.timeRange || [];
    page.value = obj.page || 1;
}
init()
// 获取活动分类
async function getActivityTypeList() {
    const res = await ficcManageInterface.activityTypeList();
    if (res.Ret === 200) {
        typeList.value = res.Data || [];
    }
}
getActivityTypeList()

// 获取到会列表
async function getAttendList() {
    let ids = []; //选择的分类
    activeType.value.forEach((item) => {
        ids.push(item[item.length - 1]);
    });
    const res = await ficcManageInterface.quanshiAttendList({
        Keyword: searchVal.value,
        ActivityTypeIds: ids.join(","),
        StartDate: timeRange.value?.[0]|| "",
        EndDate: timeRange.value?.[1] || "",
        CurrentIndex: page.value,
        PageSize: pageSize.value,
    });
    if (res.Ret === 200) {
        list.value = res.Data.List || [];
        total.value = res.Data.Paging.Totals;
    }
}
getAttendList()
function handleShowDetail(e) {
    detailInfo.value = e;
    showDetail.value = true;
}
// 活动状态切换
function handleActivityStatusChange(e) {
    page.value = 1;
    searchVal.value = "";
    activityStatus.value = e;
    activeType.value = [];
    publishStatus.value = "";
    timeRange.value = [];
    getAttendList();
}
//筛选
function handleTypeChange() {
    page.value = 1;
    getAttendList();
}
function handlePageChange(e) {
    page.value = e;
    getAttendList();
}
function handleChooseSeller(data){
    detailInfo.value = data
    ShareSellerId.value = data.ShareSellerId?data.ShareSellerId:''
    showChooseSellerDialog.value = true
    customInterence.saleslist({SellerType:1}).then(res=>{
        if(res.Ret!==200) return
        sellerList.value = res.Data.List||[]
    })
}
function chooseSeller(){
    const {QsId} = detailInfo.value
    if(!ShareSellerId.value){
        ElMessage.warning('请选择销售')
        return
    }
    ficcManageInterface.qs_shareSeller({
        QsId,SellerId:Number(ShareSellerId.value)
    }).then(res=>{
        if(res.Ret!==200) return 
        ElMessage.success('分享销售成功')
        getAttendList()
        showChooseSellerDialog.value = false
    })
}
const router = useRouter()
function quanShiEventDetail(e) {
    const { href } = router.resolve({
        path: '/attendDetail',
        query: {
            id: e.QsId,
        }
    });
    window.open(href, '_blank');
}
</script>
<template>
    <div class="ficc-activity-list-wrap">
        <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-input placeholder="请输入活动标题" v-model="searchVal" style="max-width: 400px; float: right"
                    :prefix-icon="Search"
                    @input="handleTypeChange" clearable>
                </el-input>
            </div>
            <div class="list-wrap">
                <el-table :data="list" border>
                    <el-table-column key="活动标题" align="center" prop="ActivityName" label="活动标题">
                        <template #default="scope">
                            <span class="title" @click="handleShowDetail(scope.row)">{{
                                    scope.row.ActivityName
                            }}</span>
                        </template>
                    </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 #default="scope">
                            <span class="time">{{
                                    formatActivityTimeRange(scope.row.StartTime,scope.row.EndTime)
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="开始时间" align="center" prop="EventStartTime" label="开始时间" width="180px">
                        <template #default="scope">
                            <span class="time">{{
                                    scope.row.QsStatus == 2?formatTimeRange(scope.row.EventStartTime):''
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="持续时长" align="center" prop="RealTime" label="持续时长" width="180px">
                        <template #default="scope">
                              <span class="time">
                                {{scope.row.QsStatus == 2?(scope.row.RealTime+'分钟'):''}}
                              </span>
                        </template>
                    </el-table-column>
                    <el-table-column key="出现方数" align="center" prop="People" label="出现方数" width="180px">
                         <template #default="scope">
                              <span class="time">{{
                                   scope.row.QsStatus == 2?scope.row.People:''
                            }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column key="操作" align="center" label="操作" width="250px">
                        <template #default="{row}">
                            <!-- <span v-if="scope.row.QsStatus==2" @click="quanShiEventDetail(scope.row)"
                                style="color: #4099ef; cursor: pointer">到会详情</span> -->
                            <!-- 管理员：到会详情 分享/被分享人（ -->
                            <template v-if="Role.includes('admin')">
                              <el-link :underline="false" type="primary" @click="quanShiEventDetail(row)">到会详情</el-link>
                              <el-link :underline="false" type="primary" style="margin-left: 6px;" @click="handleChooseSeller(row)" v-if="!row.ShareSellerId">分享</el-link>
                              <span v-else style="font-size: 12px;margin-left: 6px;">
                                被分享人（{{ row.ShareSellerName }}）
                              </span>
                            </template>
                            <!-- 非管理员：到会详情 -->
                            <template v-else>
                              <el-link :underline="false" type="primary" v-if="AdminId==row.ShareSellerId" 
                                @click="quanShiEventDetail(row)">到会详情</el-link>
                            </template>
                        </template>
                    </el-table-column>
                    <template #empty>
                        <div style="padding: 150px 0">暂无数据</div>
                    </template>
                    
                </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 :append-to-body="true" v-model="showDetail" width="600px" center>
            <template #header>
                <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>
            </template>
            <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">
                            活动时间：{{
                                    formatActivityTimeRange(detailInfo.StartTime,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 :append-to-body="true" v-model="showChooseSellerDialog" 
          :title="detailInfo.ShareSellerId?'分享记录':'分享活动'" width="600px" center>
            <div class="ficc-activity-detail-wrap">
              <div class="select-seller" style="display:flex;align-items:center;justify-content: center;">
                <p style="margin-right:10px;">选择销售</p>
                <el-select style="width:80%;" v-model="ShareSellerId" 
                  :disabled="Boolean(detailInfo.ShareSellerId)"
                  placeholder="请选择销售">
                  <el-option v-for="item in sellerList" :key="item.AdminId" 
                    :label="item.RealName"
                    :value="item.AdminId"
                  />
                </el-select>
              </div>
              <div style="text-align: center; margin: 30px 0" v-if="!detailInfo.ShareSellerId">
                <el-button @click="showChooseSellerDialog = false" style="width: 150px">取消</el-button>
                <el-button  type="primary" @click="chooseSeller" style="width: 150px">确定</el-button>
              </div>
              <div style="text-align: center; margin: 30px 0" v-else>
                <el-button  type="primary" @click="showChooseSellerDialog = false" style="width: 150px">知道了</el-button>
              </div>
            </div>
        </el-dialog>
    </div>
</template>

<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>