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

        <!-- 任务审核 -->
        <hc-dialog v-model="showTaskReviewModal" ui="hc-modal-border hc-modal-table" is-table widths="98vw">
            <template #header="{ titleId, titleClass }">
                <div class="hc-card-header flex items-center">
                    <div :id="titleId" :class="titleClass">任务审核 【已开启电签】</div>
                    <div v-if="taskReviewType === '1'" class="text-main ml-6 font-bold">任务名称：{{ taskReviewInfo.taskName }}</div>
                </div>
            </template>
            <div class="hc-card-body-flex">
                <div v-if="batchPdfUrl" class="flex-iframe">
                    <!-- <HcPdf :src="batchPdfUrl" @change="changeSealStrategy" /> -->
                    <template v-if="sbTableKey === 'key1'">
                        <HcSignPdf v-if="pdfItem.pdfUrl" :batch="isBatch" :dom="pdfItem.hcSignImageArr" :sign="logoName" :src="pdfItem.pdfUrl" @change="pdfChange" />
                    </template>
                    <hc-pdfs v-else :src="pdfItem.pdfUrl" />
                </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">
                    <el-button v-if="sbTableKey === 'key1' && !isBatch && isShowDqBtn" class="mb-4" hc-btn type="warning" @click="BatchClick(true)">批量电签</el-button>
                    <el-button v-if="sbTableKey === 'key1' && isBatch && isShowDqBtn" class="mb-4" hc-btn type="warning" @click="BatchClick(false)">取消批量签名/章</el-button>
                    <div v-if="taskReviewType === '1'" class="data-table taskReviewData">
                        <HcTable :column="taskReviewColumns" :datas="taskReviewData" :index-style="{ width: 60 }" is-new @row-click="rowTaskReviewClick" />
                    </div>
                    <div v-if="taskReviewType === '2'" class="data-table checkedRowsRef">
                        <HcTable :column="checkedRowsColumns" :datas="checkedRowsRef" :index-style="{ width: 60 }" is-new @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 value="OK">同意</el-radio>
                            <el-radio value="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-dialog>

        <!-- 设置重签规则 -->
        <el-dialog v-model="showSetSignRulesModal" ui="hc-modal-border" title="设置重签规则" width="38rem">
            <div class="mb-10 text-orange">
                <span class="mr-4">提示：设置默认时长，在任务被废除需要重签的时候，规定的重签上报时间提示时间段内，系统提示用户重签信息，但是超过处理时间，系统可默认自动授权重签</span>
                <el-checkbox v-model="setPactVal" value="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>
        </el-dialog>

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

<script setup>
import { nextTick, 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 { getContractInfo } from '~api/other'
import { arrToKey, getArrValue, isString } from 'js-fast-way'
import HcSignPdf from './components/hc-pdf1.vue'
import tasksApi from '~api/tasks/data'
import dayjs from 'dayjs'
import userApi from '~api/userInfo/index'

//初始变量
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()
})

//pdf

//合同段信息
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 pdfItem = ref({})
const pdfIndex = ref(-1)
const logoName = ref('')
//获取用户信息
const queryCurrentUserData = async () => {
    const { error, code, data } = await userApi.queryCurrentUserData()
    if (!error && code === 200) {
        logoName.value = data?.signatureUrl || ''
    } else {
        logoName.value = ''
    }
}
const pdfDataClick = (item, index) => {
    pdfItem.value = {}
    pdfIndex.value = index
    nextTick(() => {
        pdfItem.value = item
    })
}
const signArr = ref([])
//签章数据改变
const pdfChange = (data) => {
    console.log('签章数据', data)
    // pdfData.value[pdfIndex.value].hcSignImageArr = data
    if (taskReviewType.value === '2') {
        checkedRowsRef.value.forEach((ele) => {
            if (ele.id === pdfIndex.value) {
                ele.hcSignImageArr = data
            }
        })
    } else {
        signArr.value = data
    }
}
const isBatch = ref(false)
const BatchClick = (val) => {
    isBatch.value = val
}
const isShowDqBtn = ref(true)
//任务审核
const rowTaskName = async (row) => {
    // if (row.id && row.type !== 2) {
    if (row.type !== 2) {
        isShowDqBtn.value = true
    } else {
        isShowDqBtn.value = false
    }
    taskReviewInfo.value = row
    const { error, code, data } = await tasksApi.queryTaskInfo({
        taskIds: row.id,
        type: row.type,
    })
    if (!error && code === 200) {
        const approvalFileList = getArrValue(data)
        taskReviewData.value = approvalFileList
        if (approvalFileList.length > 0) {
            batchPdfUrl.value = approvalFileList[0].pdfUrl
            if (sbTableKey.value === 'key1' && row.type !== 2) {
                queryCurrentUserData()
            } else {
                logoName.value = ''
            }
            pdfItem.value.pdfUrl = approvalFileList[0].pdfUrl


        }
        taskReviewType.value = '1'
        showTaskReviewModal.value = true
        isBatch.value = false


    } 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 taskId = ref([])
const batchApprovalTaskClick = (rows) => {
    //不同任务类型不能一起批量审批
    let types = arrToKey(rows, 'type', ',').split(',')
    let newTypes = Array.from(new Set(types))
    if (newTypes.length > 1) {
        window.$message.warning('不同任务类型不能一起批量审批')
    } else {
        taskReviewType.value = '2'
        showTaskReviewModal.value = true
        isBatch.value = false


        checkedRowsRef.value = rows
        let taskids = []
        rows.forEach((item) => {
            taskids.push(item.id)
        })
        taskids = taskids.join()
        queryTaskInfo(rows[0], taskids)

    }


}

//行被点击
const rowTaskReviewClick = async ({ row }) => {
    console.log(row, 'rpw')
    const type = taskReviewType.value
    if (type === '1') {
        batchPdfUrl.value = row.pdfUrl
    } else if (row['hc_batchPdfUrl']) {
        batchPdfUrl.value = row['hc_batchPdfUrl']
    } else {
        queryTaskInfo(row)
    }
    pdfDataClick(row, row.id)
}
//默认点击


//获取PDF数据
const queryTaskInfo = async (row, taskids) => {
    taskId.value = taskids && taskids.length > 0 ? taskids : row['id']
    //验收任务类型传2，不能盖章
    // if (row.type !== 2) {

    if (row.type !== 2) {
        isShowDqBtn.value = true
    } else {
        isShowDqBtn.value = false
    }
    const { error, code, data } = await tasksApi.queryTaskInfo({
        taskIds: taskids && taskids.length > 0 ? taskids : row['id'],
        type: row.type,

    })
    //处理数据
    if (!error && code === 200) {
        const alldata = getArrValue(data)
        let approvalFileList = alldata
        if (approvalFileList.length > 0) {
            // await queryCurrentUserData()
            if (row['type'] !== 2) {
                await queryCurrentUserData()
            }
            pdfDataClick(row, row.id)
            pdfItem.value.pdfUrl = approvalFileList[0].pdfUrl
            batchPdfUrl.value = approvalFileList[0].pdfUrl
            row['pdfUrl'] = approvalFileList[0].pdfUrl

        } else {
            batchPdfUrl.value = ''
            row['pdfUrl'] = ''
            window?.$message?.warning('PDF获取异常')
        }
    } else {
        batchPdfUrl.value = ''
        row['pdfUrl'] = ''
        window?.$message?.warning(data.msg || 'PDF异常')
    }
    // } else {
    //     batchPdfUrl.value = ''
    //     row['pdfUrl'] = ''
    // }


}
const finalArr = ref([])
//确认审批
const ConfirmApprovalClick = async () => {
    const formData = taskReviewForm.value
    let objarr = []
    if (taskReviewType.value === '1') {
        //单个废除任务
        console.log(111111)
        console.log(checkedRowsRef.value, '  checkedRowsRef.value')
        objarr.push({
            taskId: taskReviewInfo.value.id,
            comment: formData.comment,
            flag: formData.flag,
            sealStrategy: signArr.value,

        })
        console.log(objarr, 'objarr')
        finalArr.value = objarr
    } else if (taskReviewType.value === '2') {
        //上报任务
        if (formData.flag === 'NO' && !formData.comment) {
            window?.$message?.warning('请先输入审核意见')
        } else {
            formData.taskId = taskId.value
            console.log(checkedRowsRef.value, 'checkedRowsRef.value')
            checkedRowsRef.value.forEach((ele) => {
                objarr.push({
                    taskId: ele.id,
                    comment: formData.comment,
                    flag: formData.flag,
                    sealStrategy: ele.hcSignImageArr,

                })
            })
            console.log(objarr, 'objarr')
            finalArr.value = objarr
        }
    }

    SMSAuthLoading.value = true
    // const { error, code, msg, data } = await tasksApi.batchApproval({}, false)
    //判断数据
    SMSAuthLoading.value = false
    const ShowAuth = isCheckSmsCodeTime()
    SMSAuthShow.value = ShowAuth
    //免短信验证
    if (!ShowAuth) {
        SMSAuthConfirm()
    }
}

//短信验证有效期
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 () => {
    SMSAuthLoading.value = true
    const { error, code, msg, data } = await tasksApi.batchApproval({
        taskArchiveDtoList: finalArr.value,
        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 if (code === 400) {
        window?.$message?.error(msg)
    } else {
        window?.$message?.warning('审批异常')
    }
}

//批量审批
const batchCompleteApprovalTask = async () => {
    SMSAuthLoading.value = true
    const { error, code, msg, data } = await tasksApi.batchApproval({
        taskArchiveDtoList: finalArr.value,
        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 if (code === 400) {
        window?.$message?.error(msg)
    } else {
        window?.$message?.warning('审批出错')
    }
}

//设置重签规则
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>
