<template>
    <hc-sys id="app-sys" class="hc-ledger-page" :isNavBar="false">
        <view id="nav-bar" class="bg-white hc-tab-bar">
            <scroll-view scroll-x class="nav" scroll-with-animation :scroll-left="scrollLeft">
                <template v-for="(item, index) in tabList" :key="index">
                    <view class="cu-item" :class="item.primaryKeyId === tabKey?'text-blue cur':''" @click="tabSelect(item, index)">
                        {{item.title}}
                    </view>
                </template>
            </scroll-view>
        </view>
        <view id="date-bar" class="hc-calendar-bar">
            <uni-calendar insert :showMonth="false" :selected="calendarSelected" @change="calendarChange" @monthSwitch="calendarSwitch" />
        </view>

        <!--内容区域-->
        <view class="hc-content-bar hc-zindex" :style="[bottomStyle, contentStyle]">
            <view class="arrow-bar" @click="isCollapseUnfold">
                <text class="i-ri-arrow-down-double-line icon" v-if="isCollapse"/>
                <text class="i-ri-arrow-up-double-line icon" v-else/>
            </view>
            <scroll-view class="h-full" scroll-y>
                <view v-for="(item, index) in timeFormData" :key="index" class="time-form-item">
                    <view class="time">{{index+1}}、{{item.recordTime}}</view>
                    <view class="name">{{item.createUserName}}</view>
                    <view>
                        <text class="text-blue" @click="handleTableQuery(item)">查看</text>
                        <template v-if="!(item.status === 1 || item.status === 2)">
                            <text class="ml-2 text-orange" @click="toReportPage(item)">上报</text>
                        </template>
                        <template v-if="(item.status === 1 || item.status === 2)">
                            <text class="ml-2 text-red" v-if="userInfo.user_id == item.createUser" @click.stop="handleAbolish(item)">废除</text>
                            <text class="ml-2"  style="color: #d1d1d1;" v-else>废除</text>
                        </template>
                    </view>
                </view>
            </scroll-view>
        </view>

        <!--底部操作栏-->
        <HcTabbarBlock :height="80"/>
        <hc-tabbars id="tab-bar">
            <button type="primary" @click="fillReport">立即填报</button>
        </hc-tabbars>
    </hc-sys>
</template>

<script setup>
import {ref, getCurrentInstance} from "vue";
import {onLoad, onReady} from '@dcloudio/uni-app'
import mainApi from '~api/ledger/index';
import {useAppStore} from "@/store";
import {deepClone, getArrValue, isString} from "js-fast-way";
import {errorToast, querySelect, showModal, successToast, toPdfPreview} from "@/utils/tools";
import dayjs from "dayjs";

//初始变量
const store = useAppStore()
const instance = getCurrentInstance().proxy
const contractInfo = ref(store.contractInfo);
const userInfo = ref(store.userInfo);
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);

//页面启动完成
onLoad(() => {
    fullDate.value = dayjs().format('YYYY-MM-DD')
    fullYear.value = dayjs().format('YYYY')
    getDataApi()
})

onReady(() => {
    setContentStyle()
})

//设置样式
const bottomStyle = ref({})     // 距离底部
const setContentStyle = async () => {
    const {height: appHeight } = await querySelect(instance, 'app-sys')
    const {height: navHeight } = await querySelect(instance, 'nav-bar')
    const {height: dateHeight } = await querySelect(instance, 'date-bar')
    const {height: tabHeight } = await querySelect(instance, 'tab-bar')
    bottomStyle.value = { bottom: tabHeight + 'px' }

    // 展开高度
    const unfold_height = appHeight - tabHeight
    // #ifdef H5
    unfoldHeight.value = { height: (unfold_height - (navHeight * 4)) + 'px' }
    // #endif
    // #ifdef APP-PLUS
    unfoldHeight.value = { height: (unfold_height - (navHeight * 7)) + 'px' }
    // #endif
    contentStyle.value = deepClone(unfoldHeight.value)

    //收起高度
    const collapse_height = appHeight - dateHeight - tabHeight
    // #ifdef H5
    collapseHeight.value = { height: (collapse_height - navHeight)+ 'px' }
    // #endif
    // #ifdef APP-PLUS
    collapseHeight.value = { height: (collapse_height - (navHeight * 3.5)) + 'px' }
    // #endif
}


//获取接口数据
const getDataApi= async () => {
    await queryLogList()
    queryLogTimeTreeList().then()
    getSubmitLogDateList().then()
}

//获取tab数据
const tabList = ref([])
const tabItem = ref({})
const queryLogList = async () => {
    const { data } = await mainApi.queryLogList({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    const dataArr = getArrValue(data)
    if (dataArr.length > 0) {
        tabList.value = dataArr
        tabItem.value = dataArr[0]
        tabKey.value = dataArr[0]?.primaryKeyId
    } else {
        tabList.value = []
        tabItem.value = {}
        tabKey.value = ''
    }
}

//tab切换
const tabKey = ref('')
const scrollLeft = ref(0)
const tabSelect = async (item, index) => {
    tabItem.value = item
    tabKey.value = item?.primaryKeyId
    scrollLeft.value = (index - 1) * 60
    uni.showLoading({title: '获取数据中...', mask: true});
    await queryLogTimeTreeList()
    await getSubmitLogDateList()
    uni.hideLoading()
}

//日历变量
const calendarSelected = ref([])
const getSubmitLogDateList = async () => {
    if (fullYear.value && tabKey.value) {
        const { data } = await mainApi.getSubmitLogDateList({
            projectId: projectId.value,
            contractId: contractId.value,
            primaryKeyId: tabKey.value,
            year: fullYear.value,
        })
        //处理数据
        let newArr = [], res = getArrValue(data)
        res.forEach((item)=>{
            newArr.push({ date: item })
        })
        calendarSelected.value = newArr
    } else {
        calendarSelected.value = []
    }
}

//切换年月
const fullYear = ref('')
const calendarSwitch = ({year}) => {
    if (year !== fullYear.value) {
        fullYear.value = year
        getSubmitLogDateList()
    }
}

//选择日期
const fullDate = ref('')
const calendarChange = ({fulldate, year}) => {
    if (fulldate !== fullDate.value) {
        fullDate.value = fulldate
        queryLogTimeTreeList()
    }
    if (year !== fullYear.value) {
        fullYear.value = year
        getSubmitLogDateList()
    }
}

//获取填报记录
const timeFormData = ref([])
const queryLogTimeTreeList = async () => {
    const { data } = await mainApi.queryLogTimeTreeList({
        contractId: contractId.value,
        nodePrimaryKeyId: tabKey.value,
        time: fullDate.value,
    })
    timeFormData.value = getArrValue(data)
}

//查看
const handleTableQuery = async (item) => {
    if (item.pdfUrl) {
        toPdfPreview(item.pdfUrl).then()
        return false
    }
    uni.showLoading({title: '获取pdf文件中...', mask: true});
    const {excelId, primaryKeyId} = tabItem.value
    const { error, code, data } = await mainApi.getBussPdfInfo({
        contractId: contractId.value,
        pkeyId: excelId,
        nodePrimaryKeyId: primaryKeyId,
        recordTime: fullDate.value,
        theLogId: ""
    })
    const resData = isString(data) ? data ?? '' : ''
    uni.hideLoading();
    if (!error && code === 200 && resData) {
        toPdfPreview(resData).then()
    } else {
        errorToast('暂无PDF，无法预览')
    }
}

//上报
const toReportPage = ({createUser, recordTime}) => {
    const {primaryKeyId, title} = tabItem.value, {real_name} = userInfo.value
    //路由跳转
    uni.navigateTo({
        url: '/pages/report/report',
        events:{
            finish: (data) => {
                queryLogTimeTreeList();
            }
        },
        success:(res) => {
            res.eventChannel.emit('reportProps', {
                type: "log",
                typeData: primaryKeyId,
                projectId: projectId.value,
                contractId: contractId.value,
                taskName: `${recordTime} ${title} ${real_name}`,
                url: 'contractLog/startTaskTheLog',
                addition: {
                    nodePrimaryKeyId: primaryKeyId,
                    recordTime: recordTime,
                    userId: createUser,
                },
            })
        }
    });
}

//废除
const handleAbolish = async (item) => {
    const res = await showModal({
        title: '废除上报',
        content: '请谨慎考虑后，是否确定废除',
    })
    if (!res) return
    uni.showLoading({title: '废除上报中...', mask: true});
    const {primaryKeyId} = tabItem.value
    const { error, code } = await mainApi.theLogOneAbolish({
        projectId: projectId.value,
        contractId: contractId.value,
        nodePrimaryKeyId: primaryKeyId,
        recordTime: item.recordTime
    })
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('废除成功')
        queryLogTimeTreeList().then()
    } else {
        errorToast('废除失败')
    }
}

//展开收缩
const collapseHeight = ref({})  // 收起高度
const unfoldHeight = ref({})    // 展开高度
const isCollapse = ref(true)    // 是否展开
const contentStyle = ref({})    // 设置高度
const isCollapseUnfold = () => {
    if (isCollapse.value) {
        contentStyle.value = deepClone(collapseHeight.value)
        isCollapse.value = false
    } else {
        contentStyle.value = deepClone(unfoldHeight.value)
        isCollapse.value = true
    }
}

//立即填报
const fillReport = () => {
    const {excelId, primaryKeyId, title, nodeType} = tabItem.value
    const {real_name} = userInfo.value
    uni.navigateTo({
        url: '/pages/ledger/editTable?node=' + encodeURIComponent(JSON.stringify({
            projectId: projectId.value ?? '',
            contractId: contractId.value ?? '',
            excelId:  excelId ?? '',
            pkeyId: primaryKeyId ?? '',
            title: title ?? '',
            date: fullDate.value ?? '',
            nodeType: nodeType,
            taskName: `${fullDate.value} ${title} ${real_name}`,
        }))
    });
}
</script>

<style lang="scss" scoped>
page {
    background: #EFEFF4;
    height: 100%;
}
</style>

<style lang="scss">
@import "@/style/ledger/index.scss";
</style>
