<script setup>
import { useStore } from "vuex";
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from "vue-router";
import { ElMessage,ElMessageBox } from 'element-plus'
import moment from 'moment'
import BaseCalendar from './components/BaseCalendar.vue'
import {apiGetPermissionList,apiGetCalendarEventList,apiGetDailyEventList,apiGetPermissionNewestDate} from '@/api/forexCalendar.js'

//权限控制
const store = useStore();
let hasAuth = ref(true)
let noAuth = ref({
    type:'',
    name:'',
    mobile:'',
    customer_info:{}
})

//日历点击
let showEventList = ref(false) //控制事项列表弹窗
let currentDay = ref('') //选择的日期
//日历点击事件
function dateClick(info){
    setEventInfo(info.dateStr)
}
function eventClick(info){
    //直接打开弹窗
    setEventInfo(info.event.startStr)
}
async function setEventInfo(date){
    if(!permissionValue.value) return ElMessage.warning("请选择品种")
    currentDay.value = date||''
    //获取当天的日历信息，若有事项，则打开弹窗
    await getEventsByDay()
    if(eventList.value.length) showEventList.value = true
}
//事项列表
let eventList = ref([
    {
        title:'我是自定义事项', //事件名称
        start:'2024-03-26',//日期,默认是全天事件
        textColor:'#000',//字体颜色
        backgroundColor:'#ffc0cb',//背景色
        borderColor:'#ffc0cb',//边框色
        
        isTextBold:false,
        matter_type:1,

    },
    {
        title:'我是某个关联指标', //事件名称
        start:'2024-03-26',//日期,默认是全天事件
        textColor:'#000',//字体颜色
        backgroundColor:'#ffc0cb',//背景色
        borderColor:'#ffc0cb',//边框色
        
        isTextBold:false,
        matter_type:2,
    }
])
async function getEventsByDay(){
    await apiGetDailyEventList({
        chart_permission_id:Number(permissionValue.value),
        matter_date:currentDay.value
    }).then(res=>{
        if(res.code!==200){
            eventList.value=[]
            return 
        }
        eventList.value = res.data||[]
    })
}
const router = useRouter()
//跳转事项详情
function handleClickEvent(event){
    if(event.matter_type===1) return ElMessage("该事项未关联指标")
    const {activeStart,activeEnd} = baseCalendarRef.value?.calendarApi.view||{}

    router.push({
        path:'/forexCalendar/detail',
        query:{
            startDate:moment(activeStart).format('YYYY-MM-DD'),
            endDate:moment(activeEnd).subtract(1, 'days').format('YYYY-MM-DD'),
            edbInfoId:event.edb_info_id,
            permissionId:permissionValue.value,
            permissionName:permissionName.value
        }
    })
    showEventList.value = false
}

let baseCalendarRef  = ref(null) //日历api
let monthValue = ref('') //选中的月份
function changeMonth(month){
    const Month = month||new Date()
    baseCalendarRef.value?.calendarApi.gotoDate(Month)
    renderCalendar()
}
let permissionValue = ref('') //选中的品种ID
let permissonList = ref([]) //品种列表
let cascaderRef = ref(null) //品种cascader
let permissionName = ref('') //品种名称
function getPermissionList(){
    apiGetPermissionList().then(res=>{
        if(res.code===200){
            hasAuth.value = true
            permissonList.value = res.data
            /* permissionValue.value = permissonList.value[0]?.children[0]?.chart_permission_id
            changePermission() */
        }else{
            hasAuth.value = false
            noAuth.value = res.data
        }
    })
}
async function changePermission(){
    if(!hasAuth.value) return 
    if(!permissionValue.value) return 
    getPermissionName()
    await getPermissionNewestMonth()
    //renderCalendar()
}
async function getPermissionNewestMonth(){
    //获取最新月份的接口
    await apiGetPermissionNewestDate({
        chart_permission_id:Number(permissionValue.value)
    }).then(res=>{
        if(res.code!==200) return 
        monthValue.value = res.data||moment(new Date()).format('YYYY-MM')
        changeMonth(monthValue.value)
    })
}
function getPermissionName(){
    const node = cascaderRef.value?.getCheckedNodes(true)[0]
    permissionName.value = node.label
}
//加载日历表
async function renderCalendar(){
    //获取当前日历的起始日期+终止日期,可能会跨月
    const {activeStart,activeEnd} = baseCalendarRef.value?.calendarApi.view||{}
    const res = await apiGetCalendarEventList({
        chart_permission_id:Number(permissionValue.value),
        start_date:moment(activeStart).format('YYYY-MM-DD'),
        end_date:moment(activeEnd).subtract(1, 'days').format('YYYY-MM-DD'), //activeEnd到最后一天的24：00会被认为是第二天，所以取前一天
    })
    if(res.code!==200) return 
    const allEventSource = baseCalendarRef.value?.calendarApi.getEventSources()||[]
    //先清空所有eventSource，再添加
    allEventSource.forEach(es=>es.remove())
    //将日历表每天的事件作为一个eventSource
    const eventList = (res.data?res.data:[]).map(dailyEvents=>{
        const eventSource = { id:dailyEvents.Date,events:[]}
        eventSource.events = dailyEvents.matters.map(e=>{
            return {
                ...e,
                start:e.matter_date,
                title:e.title,
                textColor:e.font_color||'#000',
                backgroundColor:e.filling_color||'#fff',
                borderColor:e.filling_color||'#fff',
            }
        })
        return eventSource
    })
    eventList.forEach(es=>{
        baseCalendarRef.value?.calendarApi.addEventSource(es)
    })
}
const handleApply=()=>{
    if(store.state.userInfo.is_bind===0){
        ElMessageBox({
            title:`温馨提示`,
            message:'为了优化您的用户体验，<br>请登录后查看更多信息！',
            dangerouslyUseHTMLString: true,
            center: true,
            confirmButtonText:'去登录',
            confirmButtonClass:'self-elmessage-confirm-btn',
            showCancelButton:true,
            cancelButtonText:'取消',
            cancelButtonClass:'self-elmessage-cancel-btn'
        }).then(res=>{
            wx.miniProgram.reLaunch({url:'/pages/login'})
        }).catch(()=>{})
        return
    }
    if(noAuth.value.customer_info.has_apply){
        const htmlStr=`<p>您已提交过申请，请耐心等待</p>`
        ElMessageBox({
            title:`事件日历`,
            message:htmlStr,
            center: true,
            dangerouslyUseHTMLString: true,
            confirmButtonText:'知道了',
            confirmButtonClass:'self-elmessage-confirm-btn'
        })
    }else{
        if (!noAuth.value.customer_info.status || noAuth.value.customer_info.status != '流失'|| noAuth.value.customer_info.status != '关闭') {
            console.log('跳转申请页');
            router.push({
                path:'/apply/permission',
                query:{
                    source:11,
                    fromPage:'事件日历'
                }
            })
        }else{
            apiApplyPermission({
                company_name:noAuth.value.customer_info.company_name,
                real_name:noAuth.value.customer_info.name,
                source:11,
                from_page:'事件日历'
            }).then(res=>{
                console.log('主动申请成功');
                const htmlStr=`<p>申请已提交</p><p>请等待销售人员与您联系</p>`
                ElMessageBox({
                    title:`事件日历`,
                    message:htmlStr,
                    center: true,
                    dangerouslyUseHTMLString: true,
                    confirmButtonText:'知道了',
                    confirmButtonClass:'self-elmessage-confirm-btn'
                })
            })
        }
    }
}
onMounted(()=>{
    monthValue.value = moment(new Date()).format('YYYY-MM')
    getPermissionList()
})
</script>

<template>
    <div class="forex-calendar-wrap" v-if="hasAuth">
        <div class="calendar-header">
            <el-cascader :options="permissonList" 
                ref="cascaderRef"
                placeholder="请选择品种"
                v-model="permissionValue"
                :props="{
                    expandTrigger:'hover',
                    emitPath:false,
                    value:'chart_permission_id',
                    label:'chart_permission_name'
                }"
                style="min-width:210px;"
                @change="changePermission"
            ></el-cascader>
            <el-date-picker v-model="monthValue" type="month" value-format="YYYY-MM" @change="changeMonth" :clearable="false" ></el-date-picker>
        </div>
        <BaseCalendar
            ref="baseCalendarRef"
            :markText="{date:monthValue,type:permissionName||'请选择品种'}"
            @dateClick="dateClick"
            @eventClick="eventClick"
        ></BaseCalendar>
    </div>
    <div class="no-auth" v-else>
        <img :src="$store.state.globalImgUrls.activityNoAuth" alt="">
        <p style="font-size:16px;margin-bottom: 0;">您暂无权限查看事件日历</p>
        <template v-if="noAuth.type=='contact'">
            <p style="font-size:16px;margin-top: 5px;margin-bottom: 62px;">若想查看，可以联系对口销售--{{noAuth.name}}：<span style="color:#F3A52F">{{noAuth.mobile}}</span></p>
        </template>
        <template v-else>
            <p style="font-size:16px;margin-top: 5px;margin-bottom: 62px;">若想参加可以申请开通</p>
            <div class="global-main-btn btn" @click="handleApply" style="margin-bottom: 20px;">立即申请</div>
        </template>
    </div>
    <!-- 事项详情弹窗 -->
    <el-dialog
        v-model="showEventList"
        :title="`${currentDay}${permissionName}事项`"
        :width="550"
        :close-on-click-modal="false"
        append-to-body
        class="event-list-dialog"
    >
        <div class="event-list-wrap">
           <ul class="event-list">
            <li class="event-item" v-for="(item,index) in eventList" :key="index" @click="handleClickEvent(item)">
                {{item.title}}
            </li>
           </ul>
        </div>
    </el-dialog>
</template>

<style scoped lang="scss">
.forex-calendar-wrap{
    min-height: 700px;
    display: flex;
    flex-direction: column;
    .calendar-header{
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;
    }
}
.no-auth{
    text-align: center;
    img{
        width: 400px;
    }
    .btn{
        width: 218px;
        margin-left: auto;
        margin-right: auto;
    }
}
.event-list-dialog{
    .event-list-wrap{
        min-height: 300px;
        .event-list{
            padding:0 15px;
            .event-item{
                margin-bottom: 35px;
                cursor: pointer;
            }
        }
    }
}
</style>
