<script setup>
import { ref, reactive, onMounted } from 'vue'
import {Popup,DatetimePicker,TreeSelect,Icon as VanIcon,Toast } from 'vant'
import {apiGetPermissionList,apiGetPermissionNewestDate,apiGetCalendarEventList,apiGetDailyEventList}  from '@/api/hzyb/forexCalendar.js'
import moment from 'moment'
import BaseCalendar from './components/BaseCalendar.vue'

let baseCalendarRef = ref(null)
let currentDay = ref('') //选择的日期
function dateClick(info){
    setEventInfo(info.dateStr)
}
function eventClick(info){
    setEventInfo(info.event.startStr)
}
//事项列表
let eventList = ref([])
let showEventList = ref(false)
async function setEventInfo(date){
    if(!permissionValue.value) return Toast('请选择品种!')
    currentDay.value = date||''
    //获取当天的日历信息，若有事项，则打开弹窗
    await getEventsByDay()
    showEventList.value = Boolean(eventList.value.length)
}
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||[]
    })
}

let monthValue = ref(null)
let datePickShow = ref(false)
function changeMonth(month){
    const Month = month||new Date()
    baseCalendarRef.value?.calendarApi.gotoDate(Month)
    renderCalendar()
}

let typePickShow = ref(false)
let activeId = ref(0)
let activeIndex = ref(0)
let items = ref([]) //vant品种列表

//选择一级品种，没用到
function clickFirstHandle(index){}
//选择二级品种
function clickItemHandle({text,id}){
    //获取到品种ID
    if(permissionValue.value===id){
        typePickShow.value = false
        return 
    }
    permissionValue.value = id
    permissionName.value = text
    changePermission()
}
//获取该品种最新月份
async function changePermission(){
    if(!hasAuth.value) return 
    if(!permissionValue.value) return 
    await getPermissionNewestMonth()
}
async function getPermissionNewestMonth(){
    //获取最新月份的接口
    await apiGetPermissionNewestDate({
        chart_permission_id:Number(permissionValue.value)
    }).then(res=>{
        if(res.code!==200) return 
        monthValue.value = moment(res.data?(res.data+'-01'):new Date())._d
        changeMonth(monthValue.value)
    })
}

//权限控制
let hasAuth = ref(true)
let noAuth = ref({
    type:'',
    name:'',
    mobile:'',
    customer_info:{}
})
let permissonList = ref([])
let permissionValue = ref('') //选中的品种ID
let permissionName = ref('') //品种名称
function getPermissionList(){
    apiGetPermissionList().then(res=>{
        if(res.code===200){
            hasAuth.value = true
            permissonList.value = res.data||[]
            //将品种列表转换成vant-TreeSelect支持的格式
            items.value = permissonList.value.map(p=>{
                p.text = p.chart_permission_name
                if(p.children.length){
                    p.children = p.children.map(c=>{
                        c.text = c.chart_permission_name
                        c.id = c.chart_permission_id
                        return c
                    })
                }
                return p
            })
        }else{
            hasAuth.value = false
            noAuth.value = res.data
            //将无权限信息传到transIndex，transIndex显示无权限
            window.parent.postMessage(JSON.stringify({
                path:'/hzyb/forex/noauth',
                query:{
                   noAuth:noAuth.value
                }
            }),'*')
        }
    })
}
async function renderCalendar(){
    typePickShow.value = false
    datePickShow.value = false

    //获取当前日历的起始日期+终止日期,可能会跨月
    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',
            }
        })
        //移动端要求每天最多展示2条
        if(eventSource.events.length>2){
            eventSource.events = eventSource.events.splice(0,2)
        }
        return eventSource
    })
    eventList.forEach(es=>{
        baseCalendarRef.value?.calendarApi.addEventSource(es)
    })
    baseCalendarRef.value?.calendarApi.updateSize()
}
//跳转事项详情
function handleClickEvent(item){
    if(item.matter_type===1) return Toast("该事项未关联指标")
    const {activeStart,activeEnd} = baseCalendarRef.value?.calendarApi.view||{}
    //信息传到transIndex,在transIndex跳转
    window.parent.postMessage({
        path:'/hzyb/forex/detail',
        query:{
            startDate:moment(activeStart).format('YYYY-MM-DD'),
            endDate:moment(activeEnd).subtract(1, 'days').format('YYYY-MM-DD'),
            edbInfoId:item.edb_info_id,
            permissionId:permissionValue.value,
            permissionName:permissionName.value,
            token:localStorage.getItem('hzyb-token')||''
        }
    },'*')
    showEventList.value = false
}
onMounted(()=>{
    monthValue.value = new Date()
    getPermissionList()
})
</script>

<template>
    <div class="forex-calendar-wrap">
        <div class="calendar-header">
            <span @click.stop="datePickShow = true"><img src="@/assets/hzyb/chart/calendar.png">选择日期</span>
            <span @click.stop="typePickShow = true"><van-icon name="bars" color="#E3B377" size="16"/>其他品种</span>
        </div>
        <BaseCalendar 
            ref="baseCalendarRef"
            :markText="{date:monthValue,type:permissionName||'请选择品种'}"
            @dateClick="dateClick"
            @eventClick="eventClick"
        ></BaseCalendar>
        <!-- 选择日期 -->
        <Popup v-model:show="datePickShow" position="bottom">
            <DatetimePicker
                v-model="monthValue"
                title="选择日期"
                type="year-month"
                :formatter="(type, val)=>{
                    if (type === 'year') {
                        return `${val}年`;
                    } else if (type === 'month') {
                        return `${val}月`;
                    }
                    return val;
                }"
                @confirm="changeMonth"
                @cancel="datePickShow = false"
            />
        </Popup>
        <!-- 选择品种 -->
        <Popup v-model:show="typePickShow" position="bottom">
            <!-- <div class="select-header">
                <span class="cancel" @click="typePickShow=false">取消</span>
                <span class="ensure" @click="changeType">确认</span>
            </div> -->
            <TreeSelect
                v-model:active-id="activeId"
                v-model:main-active-index="activeIndex"
                :items="items"
                @click-nav="clickFirstHandle" 
                @click-item="clickItemHandle" 
            />
        </Popup>
        <Popup v-model:show="showEventList" position="bottom" :style="{ height: '50%' }">
            <div class="pop-wrap">
                <div class="select-header">
                    <span class="title">{{ currentDay }}{{ permissionName }}事项</span>
                    <span class="btn" @click="showEventList=false"><van-icon name="cross" size="16"/></span>
                </div>
                <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>
            </div>
        </Popup>
    </div>
</template>

<style scoped lang="scss">
.forex-calendar-wrap{
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 100%;
    position: absolute;
    left:0;
    right:0;
    top:0;
    bottom:0;
    .calendar-header{
        font-size: 16px;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height:40px;
        span{
            margin-right: 40px;
            display: flex;
            align-items: center;
            gap:5px;
            i{
                font-size: 18px !important;
            }
            img{
                width:15px;
                height:15px;
            }
        }
    }
    .pop-wrap{
        display: flex;
        flex-direction: column;
        height: 100%;
        .select-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: var(--van-picker-action-padding);
            font-size: var(--van-picker-action-font-size);
            height: var(--van-picker-toolbar-height);
            .cancel,.btn{
                color: #969799;
            }
            .ensure {
                color: #576b95;
            }
            .title{
                font-weight: bold;
            }
        }
        .event-list-wrap{
            font-size: var(--van-picker-action-font-size);
            padding: var(--van-padding-md);
            flex:1;
            overflow-y: auto;
            .event-item{
                margin-bottom: var(--van-padding-md);
                border-bottom: 1px solid #E7E7E7;
            }
        }
    }
    
    .van-tree-select {
        ::v-deep(.van-sidebar-item--select:before) {
            background-color: #E3B377;
        }

        ::v-deep(.van-tree-select__item--active) {
            color: #E3B377;
        }

        ::v-deep(.van-tree-select__selected) {
            position: absolute !important;
        }
    }
    
}
</style>
