<template>
    <hc-sys class="hc-ledger-copy-time" :isNavBar="false">
        <hc-breadcrumb :data="breadcrumbData" @change="breadcrumbChange" v-if="breadcrumbData.length > 0"/>

        <!--所有记录-->
        <CopyUserList v-if="viewType==='all'" v-model="selectedLogTime" :data="allLogTime"/>

        <!--按日期选择  年份-->
        <CopyLogCollapse v-if="viewType === 'date'" v-model="logYear" :data="yearDateList" @action="yearDateAction">
            <template #default="{item, index}">
                <CopyUserList v-if="item.logs.length > 0" v-model="selectedLogTime" :data="item.logs"/>
            </template>
        </CopyLogCollapse>

        <!--按日期选择  月份-->
        <CopyLogCollapse v-if="viewType === 'month'" text="日期" v-model="logMonth" :data="monthDateList" @action="monthDateAction">
            <template #default="{item, index}">
                <CopyUserList v-if="item.logs.length > 0" v-model="selectedLogTime" :data="item.logs"/>
            </template>
        </CopyLogCollapse>

        <!--按日期选择  日期-->
        <CopyLogCollapse v-if="viewType === 'day'" :action="false" v-model="logDay" :data="dayDateList">
            <template #default="{item, index}">
                <CopyUserList v-if="item.logs.length > 0" v-model="selectedLogTime" :data="item.logs"/>
            </template>
        </CopyLogCollapse>

        <!--底部操作栏-->
        <HcTabbarBlock :height="70"/>
        <hc-tabbars class="hc-operation-bar">
            <view class="selected-bar" @click="selectedShow" v-if="selectedLogTime.length > 0">
                <text class="label">已选择：{{selectedLogTime.length}}条记录</text>
                <text class="icon i-ri-arrow-up-s-line"/>
            </view>
            <view class="selected-bar" v-else>
                <text class="text">请先在上方勾选要复制的记录</text>
            </view>
            <view class="btn-bar">
                <button class="cu-btn blue" @click="confirmClick">确认复制</button>
            </view>
        </hc-tabbars>

        <!-- 普通弹窗 -->
        <hc-popup bg="#E9EAEC" title="已选择" ref="popupRef" @confirm="popupConfirm">
            <view class="popup-selected-log-time" v-for="(item, index) in selectedLogTime" :key="index">
                <view class="content-bar">
                    <view class="avatar">{{ getUserName(getSelectedVal(item, 'createUserName')) }}</view>
                    <view class="content">
                        <view class="name">{{ getSelectedVal(item, 'createUserName') }}</view>
                        <view class="text">{{ getSelectedVal(item, 'recordTime') }}</view>
                    </view>
                </view>
                <button class="cu-btn" @click="removeSelected(index)">移除</button>
            </view>
        </hc-popup>
    </hc-sys>
</template>

<script setup>
import {ref, nextTick, getCurrentInstance} from "vue";
import {onLoad} from '@dcloudio/uni-app'
import {arrKeyValue, getArrValue} from "js-fast-way";
import CopyUserList from "./components/user-list.vue";
import CopyLogCollapse from "./components/log-collapse.vue";
import mainApi from '~api/ledger/index';
import {getUserName} from "@/utils/utils";
import {errorToast, showModal, successToast} from "@/utils/tools";

//初始变量
const pageNode = ref({})
const instance = getCurrentInstance().proxy

//页面传参数据
let eventChannel = null;
const getEventChannel = async () => {
    await nextTick();
    eventChannel = instance.getOpenerEventChannel();
}

//视图类型
const viewType = ref('all')

onLoad((option) => {
    breadcrumbData.value = [
        {name: '按日期选择', key: 'date'},
        {name: '全部记录'},
    ]
    viewType.value = 'all'
    if (option.node) {
        getEventChannel()
        const res = JSON.parse(decodeURIComponent(option.node));
        uni.setNavigationBarTitle({title: '复制任意时间表格及内容'})
        console.log(res)
        pageNode.value = res
        queryReportLogTimeTree()
    }
})

//面包屑
const breadcrumbData = ref([])
const breadcrumbChange = ({key}) => {
    if (key === 'date') {
        setLogYear()
        viewType.value = 'date'
    } else if (key === 'year') {
        breadcrumbData.value = []
        viewType.value = 'date'
    } else if (key === 'month') {
        const year = breadcrumbData.value[0]
        breadcrumbData.value = [
            {name: year.name, key: 'year', value: year.value},
            {name: '月份记录'},
        ]
        viewType.value = 'month'
    }
}

//获取当前合同段下本日志节点的填报资料日期树
const logTimeTree = ref([])
const queryReportLogTimeTree = async () => {
    uni.showLoading({title: '获取数据中...', mask: true});
    const { contractId, pkeyId } = pageNode.value
    const { data } = await mainApi.queryReportLogTimeTree({
        contractId: contractId,
        nodePrimaryKeyId: pkeyId,
    })
    let res = getArrValue(data), newArr = [];
    for (let i = 0; i < res.length; i++) {
        const logs = await queryLogTimeTreeList(res[i].hierarchy);
        for (let j = 0; j < logs.length; j++) {
            newArr.push(logs[j])
        }
    }
    logTimeTree.value = res
    allLogTime.value = newArr
    uni.hideLoading();
}

//获取填报记录
const allLogTime = ref([])
const queryLogTimeTreeList = async (time) => {
    const { contractId, pkeyId } = pageNode.value
    const { data } = await mainApi.queryLogTimeTreeList({
        contractId: contractId,
        nodePrimaryKeyId: pkeyId,
        time: time,
    })
    const res = getArrValue(data)
    for (let i = 0; i < res.length; i++) {
        const {createUserName} = res[i]
        res[i].avatarName = getUserName(createUserName ?? '')
    }
    return res
}

const getLogTimeList = async (item) => {
    const logs = getArrValue(item.logs)
    if (logs.length <= 0) {
        return await queryLogTimeTreeList(item.hierarchy)
    } else {
        return logs
    }
}

//年份折叠面板
const logYear = ref('')
const yearDateList = ref([])
const setLogYear = async () => {
    uni.showLoading({title: '获取数据中...', mask: true});
    breadcrumbData.value = []
    const arr = logTimeTree.value
    for (let i = 0; i < arr.length; i++) {
        arr[i].logs = await getLogTimeList(arr[i])
    }
    yearDateList.value = arr
    uni.hideLoading();
}
const yearDateAction = async ({ name, hierarchy, treeList}) => {
    uni.showLoading({title: '获取数据中...', mask: true});
    const arr = getArrValue(treeList)
    for (let i = 0; i < arr.length; i++) {
        arr[i].logs = await getLogTimeList(arr[i])
    }
    breadcrumbData.value = [
        {name: name, key: 'year', value: hierarchy},
        {name: '月份记录'},
    ]
    logMonth.value = ''
    monthDateList.value = arr
    viewType.value = 'month'
    uni.hideLoading();
}

//月份折叠面板
const logMonth = ref('')
const monthDateList = ref([])
const monthDateAction = async ({ name, hierarchy, treeList}) => {
    uni.showLoading({title: '获取数据中...', mask: true});
    const year = breadcrumbData.value[0]
    const arr = getArrValue(treeList)
    for (let i = 0; i < arr.length; i++) {
        arr[i].logs = await getLogTimeList(arr[i])
    }
    breadcrumbData.value = [
        {name: year.name, key: 'year', value: year.value},
        {name: name, key: 'month', value: hierarchy},
        {name: '日期记录'},
    ]
    logDay.value = ''
    dayDateList.value = arr
    viewType.value = 'day'
    uni.hideLoading();
}

//日期折叠面板
const logDay = ref('')
const dayDateList = ref([])

//底部弹窗
const popupRef = ref(null)
const selectedShow = () => {
    popupRef.value?.setTitle(`已选择(${selectedLogTime.value.length})`)
    popupRef.value?.open()
}
const getSelectedVal = (val, name) => {
    return arrKeyValue(allLogTime.value,'id', name, val)
}
const removeSelected = (index) => {
    selectedLogTime.value.splice(index, 1)
    const leng = selectedLogTime.value.length;
    popupRef.value?.setTitle(`已选择(${leng})`)
    if (leng <= 0 ) popupRef.value?.close()
}
const popupConfirm = () => {
    popupRef.value?.close()
}

//确认复制
const selectedLogTime = ref([])

const confirmClick = async () => {
    const arr = selectedLogTime.value;
    if (arr.length <= 0) {
        errorToast('请先选择要复制的记录');
        return
    }
    //确认提示框
    const res = await showModal({
        title: '复制提醒',
        content: '复制后将覆盖原有记录，是否继续？',
    })
    if (!res) return
    //发起复制请求
    uni.showLoading({title: '复制数据中...', mask: true});
    const { contractId, pkeyId, date } = pageNode.value
    const { error, code } = await mainApi.copyTheLogBusinessData({
        contractId: contractId,
        nodePrimaryKeyId: pkeyId,
        currentTime: date,
        theLogId: arr.join(','),
    })
    //处理数据
    uni.hideLoading();
    if (!error && code === 200) {
        successToast('复制成功');
        eventChannel.emit('finish');
        setTimeout(() => {
            uni.navigateBack()
        }, 2000)
    } else {
        errorToast('复制失败，请稍后再试');
    }
}
</script>

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

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