<template>
    <div class="hc-layout-box">
        <HcTabsSimple :datas="sbTableData" :cur="sbTableKey" @tabClick="sbTableClick">
            <template #tab-key1>
                <TableCard v-if="sbTableKey === 'key1'" :projectId="projectId" :contractId="contractId" :contractList="projectInfo['contractInfoList']" :tableKey="sbTableKey"
                           @rowTaskName="rowTaskName" @signRules="setSignRulesClick" @batchApproval="batchApprovalTaskClick"/>
            </template>
            <template #tab-key2>
                <TableCard v-if="sbTableKey === 'key2'" :projectId="projectId" :contractId="contractId" :contractList="projectInfo['contractInfoList']" :tableKey="sbTableKey"
                           @rowTaskName="rowTaskName" @signRules="setSignRulesClick" @batchApproval="batchApprovalTaskClick"/>
            </template>
            <template #tab-key3>
                <TableCard v-if="sbTableKey === 'key3'" :projectId="projectId" :contractId="contractId" :contractList="projectInfo['contractInfoList']" :tableKey="sbTableKey"
                           @rowTaskName="rowTaskName" @signRules="setSignRulesClick" @batchApproval="batchApprovalTaskClick"/>
            </template>
        </HcTabsSimple>

        <!--任务审核-->
        <el-dialog v-model="showTaskReviewModal" width="80vw" class="hc-modal-border hc-modal-table" draggable destroy-on-close>
            <template #header="{ titleId, titleClass }">
                <div class="hc-card-header flex items-center">
                    <div :id="titleId" :class="titleClass">任务审核 【已开启电签】</div>
                    <div class="ml-6 font-bold text-main" v-if="taskReviewType === '1'">任务名称：{{taskReviewInfo.taskName}}</div>
                </div>
            </template>
            <div class="hc-card-body-flex">
                <div class="flex-iframe" v-if="batchPdfUrl">
                    <embed :src="batchPdfUrl" width='100%' height='100%' type="application/pdf"/>
                    <!--iframe allow="display-capture" width='100%' height='100%' frameborder='1' :src="batchPdfUrl"></iframe-->
                </div>
                <div class="flex-iframe hc-no-table-form" v-else>
                    <div class="table-form-no">
                        <img :src="notableform" alt=""/>
                        <div class="desc">暂无 PDF 数据</div>
                    </div>
                </div>
                <div class="flex-table" :class="sbTableKey === 'key1'?'':'vh'">
                    <div class="data-table taskReviewData" v-if="taskReviewType==='1'">
                        <HcTable :column="taskReviewColumns" :datas="taskReviewData" @row-click="rowTaskReviewClick"/>
                    </div>
                    <div class="data-table checkedRowsRef" v-if="taskReviewType==='2'">
                        <HcTable :column="checkedRowsColumns" :datas="checkedRowsRef" @row-click="rowTaskReviewClick"/>
                    </div>
                    <div class="radio-group-box" v-if="sbTableKey === 'key1'">
                        <span class="label">审批操作：</span>
                        <el-radio-group v-model="taskReviewForm.flag">
                            <el-radio label="OK">同意</el-radio>
                            <el-radio label="NO">废除任务</el-radio>
                        </el-radio-group>
                    </div>
                    <div class="textarea-box" v-if="sbTableKey === 'key1'">
                        <el-input type="textarea" v-model="taskReviewForm.comment" placeholder="请输入审核意见" :autosize="{ minRows: 3, maxRows: 5 }"/>
                    </div>
                </div>
            </div>
            <template #footer v-if="sbTableKey === 'key1'">
                <div class="dialog-footer">
                    <el-button size="large" @click="showTaskReviewModal = false">取消</el-button>
                    <el-button type="primary" hc-btn :loading="SMSAuthLoading" @click="ConfirmApprovalClick">确认审批</el-button>
                </div>
            </template>
        </el-dialog>

        <!--设置重签规则-->
        <el-dialog v-model="showSetSignRulesModal" title="设置重签规则" width="38rem" class="hc-modal-border" draggable destroy-on-close>
            <div class="text-orange mb-10">
                <span class="mr-4">提示：设置默认时长，在任务被废除需要重签的时候，规定的重签上报时间提示时间段内，系统提示用户重签信息，但是超过处理时间，系统可默认自动授权重签</span>
                <el-checkbox v-model="setPactVal" label="Option 1" size="large">
                    <span class="text-main">《授权系统自动电签协议》</span>
                </el-checkbox>
            </div>
            <div class="obj-item-cell">
                <div class="label">默认处理时间（时）</div>
                <HcCounter v-model:value="formReport.date" @update:modelValue="dateUpdateValue"/>
            </div>
            <div class="obj-item-cell">
                <div class="label">开启系统自动电签</div>
                <el-switch v-model="formReport.active" />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="showSetSignRulesModal = false">取消</el-button>
                    <el-button type="primary" hc-btn>保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!--短信认证-->
        <HcSmsAuth :show="SMSAuthShow" :loading="SMSAuthLoading" @cancel="SMSAuthCancel" @confirm="SMSAuthConfirm"/>
    </div>
</template>

<script setup>
import {ref, onMounted} from "vue";
import {useAppStore} from "~src/store";
import {useRouter, useRoute} from 'vue-router'
import TableCard from './components/TableCard.vue';
import notableform from '~src/assets/view/notableform.svg';
import {getObjValue, getArrValue, isString} from "vue-utils-plus"
import {checkFlowUserIsExistPfxFile} from "~api/other"
import tasksApi from '~api/tasks/data';
import dayjs from "dayjs"


//初始变量
const router = useRouter()
const useRoutes = useRoute()
const useAppState = useAppStore()

//路由参数
const routerQuery = useRoutes?.query;
const activeName = routerQuery?.active || 'key1'

//全局变量
const projectId = ref(useAppState.getProjectId);
const contractId = ref(useAppState.getContractId);
const projectInfo = ref(useAppState.getProjectInfo);

//渲染完成
onMounted(() => {
    checkSmsCode()
})

//类型处理
const sbTableKey = ref(activeName)
const sbTableData = ref([
    {icon: 'time', label: '待办任务', key: 'key1'},
    {icon: 'calendar-check', label: '已办任务', key: 'key2'},
    {icon: 'user-shared', label: '我发起的', key: 'key3'},
])
const sbTableClick = (key) => {
    sbTableKey.value = key
    router.push({
        path: useRoutes.path,
        query: {active: key}
    })
}

//审批页详情
const showTaskReviewModal = ref(false)
const taskReviewType = ref('1')
const taskReviewInfo = ref({})
const taskReviewData = ref([])
const batchPdfUrl = ref('')
const taskReviewForm = ref({flag: 'OK', comment: ''})
const taskReviewColumns = ref([
    {key:'fileName', name: '文件名称'}
])
//任务审核
const rowTaskName = async (row) => {
    if (row.formDataId) {
        taskReviewInfo.value = row
        const { error, code, data } = await tasksApi.queryApprovalParameter({
            parallelProcessInstanceId: row['parallelProcessInstanceId'],
            formDataId: row.formDataId,
            approvalType: row.approvalType,
        })
        if (!error && code === 200) {
              const approvalFileList = getArrValue(data['approvalFileList'])
             if(approvalFileList[approvalFileList.length-1].fileName===''){
                 approvalFileList.pop()
             }
            taskReviewData.value = approvalFileList
            if (approvalFileList.length > 0) {
                batchPdfUrl.value = approvalFileList[0].fileUrl
            }
            taskReviewType.value = '1'
            showTaskReviewModal.value = true
        } else {
            taskReviewData.value = []
            batchPdfUrl.value = ''
        }
    } else {
        taskReviewInfo.value = {}
        taskReviewData.value = []
        batchPdfUrl.value = ''
        window?.$message?.warning('此数据异常')
    }
}

//批量审批
const checkedRowsColumns = ref([
    {key:'taskName', name: '任务名称'}
])
const checkedRowsRef = ref([])

const batchApprovalTaskClick = (rows) => {
    taskReviewType.value = '2'
    showTaskReviewModal.value = true
    checkedRowsRef.value = rows
    let taskids=[]
    rows.forEach((item)=>{
        taskids.push(item.formDataId)
    })
    taskids=taskids.join()
    queryTaskInfo(rows[0],taskids)
}

//行被点击
const rowTaskReviewClick = async ({row}) => {
    const type = taskReviewType.value
    if (type === '1') {
        batchPdfUrl.value = row.fileUrl
    } else if (row['hc_batchPdfUrl']) {
        batchPdfUrl.value = row['hc_batchPdfUrl']
    } else {
        queryTaskInfo(row)
    }
}

//获取PDF数据
const queryTaskInfo = async (row,taskids) => {
    const { error, code, data } = await tasksApi.queryTaskInfo({
        // formDataId: row['formDataId'] || '',
        formDataId:taskids&&taskids.length>0?taskids:row['formDataId'] ,
        approvalType: row['approvalType']
    })
    //处理数据
    if (!error && code === 200) {
        // const approvalFileList = getArrValue(data['approvalFileList'])
        // if (approvalFileList.length > 0) {
        //     batchPdfUrl.value = approvalFileList[0].fileUrl
        //     row['hc_batchPdfUrl'] = approvalFileList[0].fileUrl
        // } else {
        //     batchPdfUrl.value = ''
        //     row['hc_batchPdfUrl'] = ''
        //     window?.$message?.warning('PDF获取异常')
        // }
        const alldata=getArrValue(data)
        let approvalFileList=[]
        alldata.forEach((item)=>{
           let innerfilist =item?.approvalFileList
           innerfilist.forEach((item1)=>{
               approvalFileList.push(item1)
           })
        })
        if (approvalFileList.length > 0) {
            batchPdfUrl.value = approvalFileList[0].fileUrl
            row['hc_batchPdfUrl'] = approvalFileList[0].fileUrl
        } else {
            batchPdfUrl.value = ''
            row['hc_batchPdfUrl'] = ''
            window?.$message?.warning('PDF获取异常')
        }
    } else {
        batchPdfUrl.value = ''
        row['hc_batchPdfUrl'] = ''
        window?.$message?.warning(data.msg || 'PDF异常')
    }
}

//确认审批
const ConfirmApprovalClick = async () => {
    const formData = taskReviewForm.value
    if (formData.flag === 'NO' && !formData.comment) {
        window?.$message?.warning('请先输入审核意见')
    } else {
        SMSAuthLoading.value = true
        const {error, code, msg, data} = await checkFlowUserIsExistPfxFile({},false)
        //判断数据
        SMSAuthLoading.value = false
        if (!error && code === 200 && data === true) {
            const ShowAuth = isCheckSmsCodeTime()
            SMSAuthShow.value = ShowAuth
            //免短信验证
            if (!ShowAuth) {
                SMSAuthConfirm()
            }
        } else {
            window.$message?.warning(msg)
        }
    }
}

//短信验证有效期
const smsCodeTime = ref('')
const checkSmsCode = async () => {
    const {error, code, data} = await tasksApi.checkSmsCode()
    //处理数据
    if (!error && code === 200) {
        smsCodeTime.value = isString(data) ? data : '';
    } else {
        smsCodeTime.value = '';
    }
}

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

//短信验证
const SMSAuthLoading = ref(false)
const SMSAuthShow = ref(false)
const SMSAuthConfirm = () => {
    const type = taskReviewType.value
    if (type === '1') {
        saveCompleteApprovalTask()
    } else {
        batchCompleteApprovalTask()
    }
    checkSmsCode()
}
const SMSAuthCancel = () => {
    SMSAuthShow.value = false
}

//单个审批
const saveCompleteApprovalTask = async () => {
    const DataInfo = taskReviewInfo.value
    SMSAuthLoading.value = true
    const {error, code} = await tasksApi.saveCompleteApprovalTask({
        ...taskReviewForm.value,
        taskId: DataInfo['taskId'] || '',
        parallelProcessInstanceId: DataInfo['parallelProcessInstanceId'] || '',
        formDataId: DataInfo['formDataId'] || '',
        approvalType: DataInfo['approvalType']
    },false)
    //处理数据
    SMSAuthLoading.value = false
    if (!error && code === 200) {
        SMSAuthShow.value = false
        showTaskReviewModal.value = false
        window?.$message?.success('审批成功')
        setTimeout(() => {
            window?.location?.reload()  //刷新页面
        }, 3000)
    } else {
        window?.$message?.warning('审批异常')
    }
}

//批量审批
const batchCompleteApprovalTask = async() => {
    const rows = checkedRowsRef.value
    SMSAuthLoading.value = true
    let taskIds = rowsToId(rows,'taskId')
    let approvalType = rowsToId(rows,'approvalType')
    let formDataId = rowsToId(rows,'formDataId')
    let parallelProcessInstanceIds = rowsToId(rows,'parallelProcessInstanceId')
    const {error, code} = await tasksApi.batchCompleteApprovalTask({
        ...taskReviewForm.value,
        taskIds,
        approvalType,
        formDataId,
        parallelProcessInstanceIds
    },false)
    //处理数据
    SMSAuthLoading.value = false
    if (!error && code === 200) {
        SMSAuthShow.value = false
        showTaskReviewModal.value = false
        window?.$message?.success('审批成功')
        setTimeout(() => {
            window?.location?.reload()  //刷新页面
        }, 3000)
    } else {
        window?.$message?.warning('审批出错')
    }
}

//拼接ID
const rowsToId = (rows,key) => {
    return rows.map((obj) => {
        return obj[key];
    }).join(",")
}

//设置重签规则
const showSetSignRulesModal = ref(false)
const setPactVal = ref(true)
const formReport = ref({date: 1, active: true})
const setSignRulesClick = () => {
    showSetSignRulesModal.value = true
}
const dateUpdateValue = (val) => {
    formReport.value.date = val
}
</script>

<style lang="scss" scoped>
@import '../../styles/tasks/hc-data.scss';
</style>
