<template>
    <div class="hc-layout-box">
        <HcTabsSimple :no-drop-shadow="showTaskReviewModal" :cur="sbTableKey" :datas="sbTableData" @tab-click="sbTableClick">
            <template #tab-key1>
                <TableCard
                    v-if="sbTableKey === 'key1'" :contract-id="contractId"
                    :contract-list="contractList"
                    :project-id="projectId" :table-key="sbTableKey"
                    :select-contrac-id="selectContracId" @batch-approval="batchApprovalTaskClick"
                    @row-task-name="rowTaskName"
                    @sign-rules="setSignRulesClick"
                    @changeselect-contrac-id="changeselectContracId"
                />
            </template>
            <template #tab-key2>
                <TableCard
                    v-if="sbTableKey === 'key2'" :contract-id="contractId"
                    :contract-list="contractList"
                    :project-id="projectId" :table-key="sbTableKey"
                    :select-contrac-id="selectContracId" @batch-approval="batchApprovalTaskClick"
                    @row-task-name="rowTaskName"
                    @sign-rules="setSignRulesClick"
                    @changeselect-contrac-id="changeselectContracId"
                />
            </template>
            <template #tab-key3>
                <TableCard
                    v-if="sbTableKey === 'key3'" :contract-id="contractId"
                    :contract-list="contractList"
                    :project-id="projectId" :table-key="sbTableKey"
                    :select-contrac-id="selectContracId" @batch-approval="batchApprovalTaskClick"
                    @row-task-name="rowTaskName"
                    @sign-rules="setSignRulesClick"
                    @changeselect-contrac-id="changeselectContracId"
                />
            </template>
        </HcTabsSimple>

        <!-- 任务审核 -->
        <hc-new-dialog v-model="showTaskReviewModal" is-table widths="80vw">
            <template #header="{ titleId, titleClass }">
                <div class="hc-card-header flex items-center">
                    <div :id="titleId" :class="titleClass">任务审核 【已开启电签】</div>
                    <div v-if="taskReviewType === '1'" class="ml-6 font-bold text-main">
                        任务名称：{{ taskReviewInfo.taskName }}
                    </div>
                </div>
            </template>
            <div class="hc-card-body-flex">
                <div v-if="batchPdfUrl" class="flex-iframe">
                    <hc-pdf :src="batchPdfUrl" />
                </div>
                <div v-else class="flex-iframe hc-no-table-form">
                    <div class="table-form-no">
                        <img :src="notableform" alt="">
                        <div class="desc">暂无 PDF 数据</div>
                    </div>
                </div>
                <div :class="sbTableKey === 'key1' ? '' : 'vh'" class="flex-table">
                    <div v-if="taskReviewType === '1'" class="data-table taskReviewData">
                        <HcTable :column="taskReviewColumns" :datas="taskReviewData" is-new :index-style="{ width: 60 }" @row-click="rowTaskReviewClick" />
                    </div>
                    <div v-if="taskReviewType === '2'" class="data-table checkedRowsRef">
                        <HcTable :column="checkedRowsColumns" :datas="checkedRowsRef" is-new :index-style="{ width: 60 }" @row-click="rowTaskReviewClick" />
                    </div>
                    <div v-if="sbTableKey === 'key1'" class="radio-group-box">
                        <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 v-if="sbTableKey === 'key1'" class="textarea-box">
                        <el-input
                            v-model="taskReviewForm.comment" :autosize="{ minRows: 3, maxRows: 5 }"
                            placeholder="请输入审核意见"
                            type="textarea"
                        />
                    </div>
                </div>
            </div>
            <template v-if="sbTableKey === 'key1'" #footer>
                <div class="dialog-footer">
                    <el-button size="large" @click="showTaskReviewModal = false">取消</el-button>
                    <el-button :loading="SMSAuthLoading" hc-btn type="primary" @click="ConfirmApprovalClick">
                        确认审批
                    </el-button>
                </div>
            </template>
        </hc-new-dialog>

        <!-- 设置重签规则 -->
        <hc-new-dialog v-model="showSetSignRulesModal" title="设置重签规则" widths="38rem">
            <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="formReport.date" @update:model-value="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 hc-btn type="primary">保存</el-button>
                </div>
            </template>
        </hc-new-dialog>

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

<script setup>
import { onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { useRoute, useRouter } from 'vue-router'
import TableCard from './components/TableCard.vue'
import notableform from '~src/assets/view/notableform.svg'
import { checkFlowUserIsExistPfxFile, getContractInfo } from '~api/other'
import { arrToKey, getArrValue, isString } from 'js-fast-way'
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()
    getContractInfoList()
})
//合同段信息
const contractList = ref([])

const getContractInfoList = async ()=>{
    const { error, code, data } = await getContractInfo({
            pid: projectId.value,
     })
     if (!error && code === 200) {
        contractList.value = getArrValue(data)
     } else {
        contractList.value = []
     }
}
//类型处理
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.length > 0 && 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({
            projectId:projectId.value,
        }, 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['id'] || '',
        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 = arrToKey(rows, 'id', ',')
    let approvalType = arrToKey(rows, 'approvalType', ',')
    let formDataId = arrToKey(rows, 'formDataId', ',')
    let parallelProcessInstanceIds = arrToKey(rows, 'parallelProcessInstanceId', ',')
    const { error, code, msg } = await tasksApi.batchCompleteApprovalTask({
        ...taskReviewForm.value,
        taskIds,
        approvalType,
        formDataId,
        parallelProcessInstanceIds,
        projectId:projectId.value,
        contractId:contractId.value,
    }, 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(msg)
    }
}

//设置重签规则
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
}
const selectContracId = ref(useAppState.getContractId)
const changeselectContracId = (val)=>{
    selectContracId.value = val
}
</script>

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