<template>
    <hc-sys id="app-sys" class="h-full hc-app-task-detail" :isNavBar="false">
        <view id="task-detail-content" class="task-detail-content">
            <view class="task-name-box">
                <view class="name-bar">{{taskInfo.taskName}}</view>
                <view class="arrow-bar">
                    <zb-tooltip placement="bottom-end" ref="tooltipRef">
                        <uni-icons type="bottom" size="22"/>
                        <template #content>
                            <view class="task-item" v-for="item in taskList" @click="taskClick(item)">{{item.taskName}}</view>
                        </template>
                    </zb-tooltip>
                </view>
            </view>
            <view class="task-report-info">
                <view>上报人：{{taskInfo.reportUserName}}</view>
                <view>{{taskInfo.startTime}}</view>
            </view>
            <view class="task-pdf-list-bar">
                <zb-tooltip placement="bottom-end" ref="tooltipRef1">
                    <view class="task-pdf-info">
                        <view class="file-name">{{taskFileInfo.fileName}}</view>
                        <view class="file-num">共{{taskFileInfo.fileNum}}张表格</view>
                    </view>
                    <template #content>
                        <view class="task-item" v-for="item in taskInfo.approvalFileList" @click="taskFileClick(item)">{{item.fileName}}</view>
                    </template>
                </zb-tooltip>
            </view>
        </view>
        <!--pdf区域-->
        <hc-pdf :ui="webViewStyle" :src="taskFileInfo?.fileUrl" v-if="taskFileInfo?.fileUrl"/>
        <uv-empty icon="/static/image/list.png" marginTop="24" v-else/>
        <!--底部操作栏-->
        <template v-if="isTaskAuth">
            <HcTabbarBlock :height="77"/>
            <hc-tabbars id="action-bar">
                <button type="primary" class="action-bar-btn" @click="approveClick">
                    <text>审</text>
                    <text class="ml-10">批</text>
                </button>
            </hc-tabbars>
        </template>
        <view id="action-bar" v-else></view>

        <!-- 普通弹窗 -->
        <uni-popup ref="popupRef" class="hc-popup" type="bottom">
            <view class="task-popup-content">
                <template v-if="popupType === 1">
                    <view class="title">请选择审批是否通过？</view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c1" @click="agreeClick">同意签字审批</button>
                    </view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c2" @click="cancelTaskClick">废除任务</button>
                    </view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c3" @click="cancelApproval">取消审批</button>
                    </view>
                </template>

                <template v-if="popupType === 2">
                    <view class="title">请输入验证码验证是否为本人操作授权</view>
                    <view class="popup-code-bar">
                        <view class="btn-tel-code-bar">
                            <view class="btn-tel">{{userInfo.phone}}</view>
                            <view class="btn-code">
                                <button type="primary" :disabled="isCodeDisabled" class="popup-btn code" size="mini" @click="getCodeClick">
                                    {{ isCodeDisabled ? `倒计时${currentCodeTime}s` : '发送验证码' }}
                                </button>
                            </view>
                        </view>
                        <view class="code-input-bar">
                            <input class="code-input" v-model="smsCode" placeholder="请输入验证码"/>
                        </view>
                    </view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c4" @click="confirmApproval">确认审批</button>
                    </view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c3" @click="cancelClick">取消操作</button>
                    </view>
                </template>

                <template v-if="popupType === 3">
                    <view class="popup-argument-bar">
                        <textarea class="argument-input" v-model="argument" :maxlength="-1" placeholder="请输入废除任务的理由"/>
                    </view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c1" @click="confirmRepeal">确认废除</button>
                    </view>
                    <view class="popup-btn-bar">
                        <button type="primary" class="popup-btn c3" @click="cancelClick">取消操作</button>
                    </view>
                </template>
            </view>
        </uni-popup>
    </hc-sys>
</template>

<script setup>
import {ref, nextTick, getCurrentInstance} from "vue";
import {onLoad, onReady} from '@dcloudio/uni-app'
import {arrToKey, getArrValue, getObjValue, isString} from "js-fast-way";
import {errorToast, querySelect, successToast} from "@/utils/tools";
import {checkFlowUserIsExistPfxFile, saveSmsTimeout, sendNotice} from "~api/other/index";
import mainApi from '~api/tasks/data';
import {useAppStore} from "@/store";
import dayjs from "dayjs";

//初始变量
const store = useAppStore()
const instance = getCurrentInstance().proxy
const userInfo = ref(store.userInfo);
const taskList = ref([])
const taskInfo = ref({})
const isTaskAuth = ref(false)

//页面传参数据
let eventChannel = null;
const getEventChannel = async () => {
    await nextTick();
    eventChannel = instance.getOpenerEventChannel();
    eventChannel.on('data', ({rows, isTask}) => {
        const res = getArrValue(rows);
        if (res.length > 0) {
            taskInfo.value = res[0]
        }
        taskList.value = res
        isTaskAuth.value = !!isTask
    })
}

onLoad(() => {
    getDataApi()
})

//渲染完成
onReady(() => {
    setWebViewStyle()
})

//获取数据
const getDataApi = async () => {
    uni.showLoading({title: '获取数据中...', mask: true});
    await getEventChannel()
    await getTaskInfo()
    checkSmsCode().then()
    uni.hideLoading();
}

//设置webview样式
const webViewStyle = ref({})
const setWebViewStyle = async () => {
    const appSys = await querySelect(instance,'app-sys')
    const appSysHeight = appSys.height
    //顶部
    const contentBar = await querySelect(instance,'task-detail-content')
    const contentBarHeight = contentBar?.height ?? 48
    // #ifdef H5
    webViewStyle.value.top = contentBarHeight + 'px'
    // #endif
    // #ifdef APP-PLUS
    const {statusBarHeight} = uni.getSystemInfoSync()
    webViewStyle.value.top = statusBarHeight + 45 + contentBarHeight
    // #endif
    //底部
    const actionBar = await querySelect(instance,'action-bar')
    const actionBarHeight = actionBar?.height ?? 80
    webViewStyle.value.height = (appSysHeight - contentBarHeight - actionBarHeight - 2) + 'px'
}

//切换任务
const tooltipRef = ref(null)
const taskClick = (item) => {
    taskInfo.value = item
    taskFileInfo.value = item.approvalFileList[0]
    tooltipRef.value?.close()
}

//切换PDF
const tooltipRef1 = ref(null)
const taskFileInfo = ref({})
const taskFileClick = (item) => {
    taskFileInfo.value = item
    tooltipRef1.value?.close()
}

//获取任务详情
const getTaskInfo = async () => {
    const rows = taskList.value
    if (rows.length <= 0) return false
    //处理详情数据
    for (let i = 0; i < rows.length; i++) {
        const res = await queryApprovalParameter(rows[i])
        rows[i].approvalFileList = res.approvalFileList
    }
    taskInfo.value = getObjValue(rows[0])
    taskFileInfo.value = getObjValue(rows[0].approvalFileList[0])
    taskList.value = rows
}

//获取审批详情
const queryApprovalParameter = async ({parallelProcessInstanceId, formDataId, approvalType}) => {
    const { data } = await mainApi.queryApprovalParameter({
        parallelProcessInstanceId: parallelProcessInstanceId ?? '',
        formDataId: formDataId ?? '',
        approvalType: approvalType ?? ''
    })
    const res = getObjValue(data)
    const list = getArrValue(res.approvalFileList)
    for (let i = 0; i < list.length; i++) {
        list[i].fileNum = await queryPDFnumApi(list[i]?.fileUrl)
    }
    res.approvalFileList = list
    return getObjValue(data)
}

//查询PDF数量
const queryPDFnumApi = async (pdfUrl) => {
    const { data } = await mainApi.queryPDFnum({
        url: pdfUrl
    })
    return data ? data : 0
}

//审批弹窗
const popupRef = ref(null)
const popupType = ref(1)
const approveClick = () => {
    popupType.value = 1
    popupRef.value?.open()
}

//短信验证有效期
const smsCodeTime = ref('')
const checkSmsCode = async () => {
    const {data} = await mainApi.checkSmsCode()
    smsCodeTime.value = isString(data) ? data : '';
}

//验证短信有效期
const isCheckSmsCodeTime = () => {
    const smsTime = smsCodeTime.value;
    if (!smsTime) return true
    const toDayTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    return dayjs(smsTime).isBefore(toDayTime)
}

//同意审批短信验证
const smsCode = ref('')
const agreeClick = async () => {
    const showAuth = isCheckSmsCodeTime()
    if (showAuth) {
        smsCode.value = ''
        popupType.value = 2
    } else {
        const {error, code, msg, data} = await checkFlowUserIsExistPfxFile()
        if (!error && code === 200 && data === true) {
            const showAuth = isCheckSmsCodeTime()
            if (showAuth) {
                smsCode.value = ''
                popupType.value = 2
            } else {
                batchTaskApproval('ok').then()
            }
        } else {
            errorToast(msg)
            cancelApproval()
        }
    }
}

//验证码倒计时
const totalTime = 60    //总时间，单位秒
const isCodeDisabled = ref(false)   //是否开启倒计时
const recordingCodeTime = ref(0)    //记录时间变量
const currentCodeTime = ref(0)      //显示时间变量

//获取短信验证码
const resCode = ref('')
const getCodeClick = async () => {
    const {phone} = userInfo.value
    if (!phone) {
        errorToast('您的手机号是空的，无法获取验证码')
        return false
    }
    const { error, code, msg } = await sendNotice({
        phone: phone
    })
    //处理数据
    if (!error && code === 200 && msg) {
        resCode.value = msg
        //把显示时间设为总时间
        currentCodeTime.value = totalTime
        //开始倒计时
        isCodeDisabled.value = true
        //执行倒计时
        checkingTime()
        successToast('发送成功')
    } else {
        resCode.value = ''
        errorToast(msg)
    }
}

//倒计时
const checkingTime = () => {
    //判断是否开启
    if (isCodeDisabled.value) {
        //判断显示时间是否已到0，判断记录时间是否已到总时间
        if (currentCodeTime.value > 0 && recordingCodeTime.value <= totalTime) {
            //记录时间增加 1
            recordingCodeTime.value++
            //显示时间，用总时间 - 记录时间
            currentCodeTime.value = totalTime - recordingCodeTime.value
            //1秒钟后，再次执行本方法
            setTimeout(() => {
                checkingTime()
            }, 1000)
        } else {
            //时间已完成，还原相关变量
            isCodeDisabled.value = false		//关闭倒计时
            recordingCodeTime.value = 0         //记录时间为0
            currentCodeTime.value = totalTime	//显示时间为总时间
        }
    } else {
        //倒计时未开启，初始化默认变量
        isCodeDisabled.value = false
        recordingCodeTime.value = 0
        currentCodeTime.value = totalTime
    }
}

//确认审批
const confirmApproval = () => {
    if (!resCode.value) {
        errorToast('请先获取验证码')
        return false
    } else if (!smsCode.value) {
        errorToast('请先输入验证码')
        return false
    } else if (resCode.value !== smsCode.value) {
        errorToast('验证码错误')
        return false
    }
    //验证码过期时间
    saveSmsTimeout({code: resCode.value})
    //处理数据
    batchTaskApproval('ok')
    checkSmsCode()
}

//批量审批
const batchTaskApproval = async (type) => {
    let res = {}, t = type === 'ok' ? '审批' : '废除';
    uni.showLoading({title: '提交审批中...', mask: true});
    if (type === 'ok') {
        res = await batchCompleteApprovalTaskApi({
            flag: 'OK',
            comment: 'OK',
        })
    } else {
        res = await batchCompleteApprovalTaskApi({
            flag: 'NO',
            comment: argument.value,
        })
    }
    //处理数据
    uni.hideLoading();
    const {error, code, msg} = res
    if (!error && code === 200) {
        successToast(`${t}成功`)
        cancelApproval()
        eventChannel.emit('finish');
        setTimeout(() => {
            uni.navigateBack()
        }, 3000)
    } else {
        errorToast(`${t}失败：${msg}`)
    }
}

//批量审批
const batchCompleteApprovalTaskApi = async (obj = {}) => {
    const rows = taskList.value
    let taskIds = arrToKey(rows, 'taskId', ',')
    let approvalType = arrToKey(rows, 'approvalType', ',')
    let formDataId = arrToKey(rows, 'formDataId', ',')
    let parallelProcessInstanceIds = arrToKey(rows, 'parallelProcessInstanceId', ',')
    return await mainApi.batchCompleteApprovalTask({
        ...obj,
        taskIds,
        approvalType,
        formDataId,
        parallelProcessInstanceIds
    })
}

//废除任务并输入理由
const argument = ref('')
const cancelTaskClick = () => {
    argument.value = ''
    popupType.value = 3
}

//确认废除
const confirmRepeal = () => {
    if (!argument.value) {
        errorToast('请先填写废除理由')
        return false
    }
    batchTaskApproval('no')
}

//取消审批
const cancelApproval = () => {
    popupType.value = 1
    popupRef.value?.close()
}

//取消操作
const cancelClick = () => {
    popupType.value = 1
    smsCode.value = ''
    argument.value = ''
}
</script>

<style lang="scss">
@import "@/style/task/detail.scss";
</style>

