<template>
    <hc-sys class="hc-report-page" :isNavBar="false">
        <uni-collapse class="mt-1">
            <uni-collapse-item :title="item.roleName" title-border="show" :open="item.open" v-for="item in dataList">
                <template v-if="item.signPfxFileList.length > 0">
                    <uni-list-item title-border="show" v-for="items in item.signPfxFileList">
                        <template v-slot:header>
                            <checkbox @click.stop="items.select = !items.select" :checked="items.select"/>
                            <text>{{items.certificateUserName}}</text>
                        </template>
                    </uni-list-item>
                </template>
                <view class="h-50 text-gray text-center p-5" v-else>无数据</view>
            </uni-collapse-item>
        </uni-collapse>

        <!--底部操作栏-->
        <HcTabbarBlock :height="77"/>
        <hc-tabbars>
            <button type="primary" class="action-bar-btn" @click="submitClick">确认选择</button>
        </hc-tabbars>
    </hc-sys>
</template>

<script setup>
import {ref, nextTick, getCurrentInstance} from "vue";
import {onLoad} from '@dcloudio/uni-app'
import {checkFlowUser, checkFlowUserQuery} from '~api/other/index'
import {getArrValue, getObjValue} from "js-fast-way";
import {errorToast} from "@/utils/tools";
import flowApi from '~api/tasks/flow'

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

//渲染完成
onLoad(() => {
    getEventChannel();
})

//页面传参数据
let eventChannel = null;
const getEventChannel = async () => {
    await nextTick();
    eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('flowUserData', (data) => {
        props.value = getObjValue(data);
        queryAllRoleList().then()
    })
}

//获取数据
const dataList = ref([])
const queryAllRoleList = async () => {
    uni.showLoading({title: '获取数据中...', mask: true});
    const { projectId, contractId, selectedData } = props.value
    const { data } = await flowApi.queryAllRoleList({
        projectId: projectId,
        contractId: contractId,
    })
    console.log(data)
    const res = getArrValue(data)
    const selected_data = getArrValue(selectedData)
    res.forEach((item)=>{
        item.signPfxFileList.forEach((item2)=>{
            selected_data.forEach((selected)=>{
                if(item2.certificateUserId === selected.userId){
                    item2.select = true;    //勾选
                    item.open = true;       //展开
                }
            })
        })
    })
    dataList.value = res
    uni.hideLoading();
}

//确认提交
const submitClick = async () => {
    const checks = await getChecks();
    if (checks.length <= 0) {
        errorToast('请先选择人员')
        return;
    }
    uni.showLoading({title: '效验数据中...', mask: true});
    let {type, typeData} = props.value, flowJson = {}
    //判断类型
    if (type === 'first') {
        flowJson['firstId'] = typeData
    } else if (type === 'log') {
        flowJson['theLogPrimaryKeyId'] = typeData
    } else if (type === 'wbs') {
        flowJson['privatePKeyId'] = typeData
    } else if (type === 'query') {
        flowJson['privatePKeyId'] = typeData
    }
    //封装数据
    let customFlowUserList = [], newUserId= [];
    checks.forEach(item => {
        customFlowUserList.push({
            userId: item.certificateUserId,
            userName: item.certificateUserName,
        })
        newUserId.push(item.certificateUserId)
    })
    //效验人员
    if (type === 'first' || type === 'log' || type === 'wbs') {
        getCheckCustomFlowUserIsEVisaPermissions(flowJson, customFlowUserList, newUserId).then()
    } else if (type === 'query') {
        getCheckCustomFlowUserIsEVisaPermissionsQuery(flowJson, customFlowUserList, newUserId).then()
    } else {
        uni.hideLoading();
        eventChannel.emit('flowUserList', customFlowUserList);
        uni.navigateBack()
    }
}

//检查所选的流程环节处理人是否具有审批权限（三大填报页、日志列表的批量上报、首件列表的批量上报）
const getCheckCustomFlowUserIsEVisaPermissions = async (flowJson, newUser, newUserId) => {
    const { projectId, contractId } = props.value
    const { error, code, data, msg } = await checkFlowUser({
        projectId: projectId,
        contractId: contractId,
        customFlowUserList: newUserId,
        ...flowJson,
    })
    //处理数据
    uni.hideLoading();
    if (!error && code === 200 && data === true) {
        eventChannel.emit('flowUserList', newUser);
        uni.navigateBack()
    } else {
        errorToast(msg)
    }
}

//资料查询页面
const getCheckCustomFlowUserIsEVisaPermissionsQuery = async (flowJson, newUser, newUserId) => {
    const { projectId, contractId } = props.value
    const { error, code, data, msg } = await checkFlowUserQuery({
        projectId: projectId,
        contractId: contractId,
        customFlowUserList: newUserId,
        ...flowJson,
    })
    //处理数据
    uni.hideLoading();
    if (!error && code === 200 && data === true) {
        eventChannel.emit('flowUserList', newUser);
        uni.navigateBack()
    } else {
        errorToast(msg)
    }
}

//获取选中的用户
const getChecks = async () => {
    let res = [], arr = dataList.value;
    for (let i = 0; i < arr.length; i++) {
        const signList = arr[i].signPfxFileList;
        for (let j = 0; j < signList.length; j++) {
            if(signList[j].select){
                res.push(signList[j])
            }
        }
    }
    return res;
}
</script>

<style lang="scss">
@import "@/style/report/tasks-user.scss";
</style>
