<template>
    <hc-sys navBarUi='data-table-nav-bar'>
        <template #navBar>
            <hc-nav-back-bar ui='data-table-nav-bar' :title="treeNode.title"/>
        </template>
        <uni-collapse class="mb-4" v-model="appUserValue" v-if="appUserList.length">
            <uni-collapse-item title="填过数据的用户" >
                <view class="hc-table-avatar-content">
                    <hc-img v-for="item in appUserList" class="avatar-img" :src="item.avatar??avatarPng" :width="35" :height="35"/>
                </view>
            </uni-collapse-item>
        </uni-collapse>

        <!--表单列表-->
        <template v-if="listItemData.length > 0">
            <uni-card v-for="(item, index) in listItemData" padding="0">
                <template v-slot:title>
                    <view class="card-slot-title">{{item.nodeName}}</view>
                </template>
                <view slot="actions" class="card-actions">
                    <template v-if="item.isBussShow !== 2">
                        <view class="card-actions-item border" style="color: #EE5B20" @click="toEditTable(item, index)">
                            <text class="i-ri-edit-2-fill icon"/>
                            <text class="card-actions-item-text">填写</text>
                        </view>
                    </template>
                    <template v-if="(item.isCopeTab === 2 || item.isCopeTab === 3) && item.isBussShow !== 2">
                        <view class="card-actions-item" style="color: #f56c6c" @click="toDelClick(item)">
                            <text class="i-ri-delete-bin-2-fill icon"/>
                            <text class="card-actions-item-text">删除</text>
                        </view>
                    </template>
                    <template v-if="item.isLinkTable !== 1">
                        <view class="card-actions-item" style="color: #4095e5" @click="toCopyClick(item)">
                            <text class="i-ri-file-copy-2-fill icon"/>
                            <text class="card-actions-item-text">复制</text>
                        </view>
                    </template>
                    <template v-if="item.isBussShow === 1">
                        <view class="card-actions-item" style="color: #999999" @click="toShowHideClick(item)">
                            <text class="i-ri-eye-off-fill icon"/>
                            <text class="card-actions-item-text">隐藏</text>
                        </view>
                    </template>
                    <template v-if="item.isBussShow !== 1">
                        <view class="card-actions-item" style="color: #544e80" @click="toShowHideClick(item)">
                            <text class="i-ri-eye-fill icon"/>
                            <text class="card-actions-item-text">显示</text>
                        </view>
                    </template>
                </view>
            </uni-card>
        </template>
        <view v-else class="uni-pt-16" style="text-align: center;">暂无表单</view>

        <!--底部操作栏-->
        <HcTabbarBlock :height="77"/>
        <hc-tabbars>
            <view class="hc-data-table-tabbar">
                <view class="item"
                      :style="nodeStatus !== '3' && nodeStatus !== '1' ? 'color: #E99D43;' : 'color: #999999;'"
                      @click="toReportPage"
                >
                    <view class="item-icon">
                        <text class="i-ri-send-plane-fill"/>
                    </view>
                    <view class="item-name">上报</view>
                </view>
                <view class="item" :style="nodeStatus === '1' ? 'color: #999999;' : ''" @click="bussPdfsClick">
                    <view class="item-icon">
                        <text class="i-ri-eye-fill"/>
                    </view>
                    <view class="item-name">预览</view>
                </view>
                <view class="item" :style="nodeStatus !== '3' ? 'color: #999999;' : ''" @click="abolishOneClick">
                    <view class="item-icon">
                        <text class="i-ri-delete-bin-5-line"/>
                    </view>
                    <view class="item-name">废除</view>
                </view>
            </view>
        </hc-tabbars>
    </hc-sys>
</template>

<script setup>
import {ref} from "vue";
import {onLoad, onShow} from '@dcloudio/uni-app'
import {useAppStore} from "@/store";
import wbsApi from '~api/data-fill/wbs';
import {getArrValue} from "js-fast-way";
import avatarPng from "@/static/image/avatar.png";
import {errorToast, successToast, toPdfPreview} from "@/utils/tools";
import { eVisaTaskCheck } from '~api/other/index'
import api from '~api/api';

const store = useAppStore()

//初始变量
const contractInfo = ref(store.contractInfo);
const projectId = ref(store.projectId);
const contractId = ref(store.contractId);
const treeNode = ref({})

const appUserValue = ref(['0'])

onLoad((option) => {
    if (option.node) {
        treeNode.value = JSON.parse(decodeURIComponent(option.node));
    }
})

onShow(() => {
    getTableDataAll();
})

//获取相关数据
const getTableDataAll = () => {
    searchNodeAllTable()
    queryNodeStatus()
}

//获取列表数据
const listItemData = ref([])
const appUserList = ref([])
const searchNodeAllTable = async () => {
    const info = treeNode.value
    const { data } = await wbsApi.searchNodeAllTable({
        projectId: projectId.value,
        contractId: contractId.value,
        primaryKeyId: info['primaryKeyId'],
        type: contractInfo.value?.contractType ?? '',
    })
    const res = getArrValue(data)
    listItemData.value = res
    //获取用户列表
    const userMap = new Map();
    res.forEach((item) => {
        const userList = getArrValue(item?.appUserList)
        userList.forEach(user => {
            userMap.set(user.id,user);
        })
    })
    appUserList.value = [...userMap.values()]
}

//当前节点状态, 1 未填报，2待上报，3已上报
const nodeStatus = ref('1');
const queryNodeStatus = async () => {
    const info = treeNode.value, type = Number(contractInfo.value?.contractType ?? '')
    let url = `blade-business/informationWriteQuery/${type === 1?'queryNodeStatus': 'queryNodeStatus-jl'}`;
    //查询节点状态
    const { error, code, data } = await api.post({
        url: url,
        params: {
            primaryKeyId: info['primaryKeyId'] ?? '',
            classify: type,
        }
    })
    if (!error && code === 200) {
        nodeStatus.value = data ?? '1'
    } else {
        nodeStatus.value = '1'
    }
}

//填写表单
const toEditTable = (item) => {
    const pkeyId = item.pkeyId ? item.pkeyId + '': ''
    if(!pkeyId){
        errorToast('pkeyId为空');
        return
    } else if (item.isBussShow === 2) {
        errorToast('此表单当前状态不可填写');
        return
    }
    const info = treeNode.value, type = Number(contractInfo.value?.contractType ?? '')
    uni.navigateTo({
        url: '/pages/data-fill/editTable?node=' + encodeURIComponent(JSON.stringify({
            projectId: projectId.value,
            contractId: contractId.value,
            status: nodeStatus.value,
            treeId:  info['primaryKeyId'],
            pkeyId: pkeyId,
            classify: type,
            title: item.nodeName,
            isBussShow: item.isBussShow,
            isTabPdf: item.isTabPdf,
            pdfUrl: item.pdfUrl,
            tabFileType: item.tabFileType,
        }))
    });
}

//删除本表
const toDelClick = async (item) => {
    const pkeyId = item.pkeyId ? item.pkeyId + '': ''
    const type = Number(contractInfo.value?.contractType ?? '')
    if(!pkeyId){
        errorToast('pkeyId为空');
        return
    } else if(nodeStatus.value === '3'){
        errorToast('已上报的资料，不允许删除');
        return
    }
    uni.showLoading({title: '删除中...', mask: true});
    const { error, code, msg } = await wbsApi.removeBussTabInfo({
        pkeyid: pkeyId,
        classify: type,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        getTableDataAll();
        successToast('删除成功');
    } else {
        errorToast('删除失败：' + msg);
    }
}

//复制本表
const toCopyClick = async (item) => {
    const pkeyId = item.pkeyId ? item.pkeyId + '': ''
    if(nodeStatus.value === '3'){
        errorToast('已上报的资料，不允许复制');
        return
    } else if(!pkeyId){
        errorToast('pkeyId为空');
        return
    }
    uni.showLoading({title: '复制中...', mask: true});
    const { error, code, msg } = await wbsApi.copeBussTab({
        pkeyId: pkeyId,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        getTableDataAll();
        successToast('复制成功');
    } else {
        errorToast('复制失败：' + msg);
    }
}

//隐藏本表
const toShowHideClick = async ({ pkeyId, isBussShow }) => {
    const pkey_id = pkeyId ? pkeyId + '': ''
    if(!pkey_id){
        errorToast('pkeyId为空');
        return
    } else if(nodeStatus.value === '3'){
        errorToast('已上报的资料，不允许隐藏或显示');
        return
    }
    uni.showLoading({title: '操作请求中...', mask: true});
    const bussShow = isBussShow === 2 ? 1 : 2 //状态(1显示 2隐藏)
    const { error, code, msg } = await wbsApi.showBussTab({
        pkeyId: pkey_id,
        status: bussShow,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        getTableDataAll();
        successToast('操作成功');
    } else {
        errorToast('操作失败：' + msg);
    }
}

//上报
const toReportPage = async () => {
    if(nodeStatus.value === '3'){
        errorToast('已上报,无法重复上报');
        return
    } else if(nodeStatus.value === '1'){
        errorToast('请填写保存后再进行上报');
        return
    }
    const rows = listItemData.value
    if (rows.length <= 0) {
        errorToast('暂无相关数据');
        return
    }
    uni.showLoading({title: '准备相关的数据中...', mask: true});
    const {contractIdRelation, primaryKeyId } = treeNode.value;
    const type = Number(contractInfo.value?.contractType ?? '')
    const { error, code, msg, data } = await eVisaTaskCheck({
        projectId: projectId.value,
        contractId: type === 2 ? contractIdRelation : contractId.value,
    })
    //处理数据
    if (!error && code === 200 && data === true) {
        let newArr = []
        for (let i = 0; i < rows.length; i++) {
            newArr.push(rows[i]['isTypePrivatePid'])
        }
        //请求文件题名
        const { data } = await wbsApi.queryDocumentTitle({
            primaryKeyId: primaryKeyId,
            classify: type,
        })
        uni.hideLoading();
        //路由跳转
        uni.navigateTo({
            url: '/pages/report/report',
            events:{
                finish: function(data) {
                    getTableDataAll();
                }
            },
            success: function(res){
                res.eventChannel.emit('reportProps', {
                    type: "wbs",
                    ids: primaryKeyId,
                    taskName: data ?? '',
                    typeData: newArr,
                    projectId: projectId.value,
                    contractId: type === 2 ? contractIdRelation : contractId.value,
                    url: 'informationWriteQuery/taskOne',
                    addition: {
                        classify: type,
                        contractIdRelation: contractIdRelation,
                    },
                })
            }
        });
    } else {
        uni.hideLoading();
        errorToast(msg);
    }
}

//预览
const bussPdfsClick = async () => {
    if(nodeStatus.value === '1'){
        errorToast('请先填报后再进行预览');
        return
    }
    uni.showLoading({title: '获取数据中...', mask: true});
    const {contractIdRelation, primaryKeyId } = treeNode.value;
    const type = Number(contractInfo.value?.contractType ?? '')
    const { error, code, msg, data } = await wbsApi.getBussPdfs({
        nodeId: primaryKeyId ?? '',
        classify: type,
        projectId: projectId.value,
        contractId: type === 2 ? contractIdRelation : contractId.value,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        toPdfPreview(data)
    } else {
        errorToast('获取PDF失败：' + msg);
    }
}

//废除 = 客户端中的撤回上报流程
const abolishOneClick = () => {
    if(nodeStatus.value !== '3'){
        errorToast('只有上报后才能废除上报');
        return
    }
    uni.showModal({
        title: '废除上报',
        content: '请谨慎考虑后，是否确定废除',
        success: (res) => {
            if (res.confirm) {
                abolishOneSave()
            }
        }
    });
}

//撤回上报的请求
const abolishOneSave = async () => {
    uni.showLoading({title: '操作请求中...', mask: true});
    const info = treeNode.value, type = Number(contractInfo.value?.contractType ?? '')
    const { error, code, msg } = await wbsApi.abolishOne({
        primaryKeyId: info['primaryKeyId'],
        classify: type,
    })
    uni.hideLoading();
    if (!error && code === 200) {
        getTableDataAll();
        successToast('废除成功');
    } else {
        errorToast('废除失败：' + msg);
    }
}
</script>

<style lang="scss" scoped>
page {
    background: #FAFBFE;
}
@import "@/style/data-fill/data-table.scss";
</style>

<style lang="scss">
page {
    height: auto;
}
</style>
