<template>
    <div class="relative h-full">
        <hc-new-card title="中期支付证书列表">
            <template #extra>
                <hc-tooltip keys="debit_pay_admin_certificate_recalculate_btn">
                    <el-button :disabled="tableCheckedKeys.length <= 0" hc-btn type="warning" :loading="recalculateLoading" @click="recalculateClick">重新计算</el-button>
                </hc-tooltip>
                <el-button hc-btn type="primary" @click="addModalClick">
                    <hc-icon name="add" />
                    <span>新增</span>
                </el-button>
            </template>
            <hc-table
                :column="tableColumn" :datas="tableData" :loading="tableLoading" :index-style="{ width: 60 }"
                is-check :check-style="{ width: 29 }" @selection-change="tableSelectionChange"
            >
                <template #action="{ row }">
                    <el-link type="primary" :disabled="!row.rawUrl" @click="rowViewRawPdf(row)">查看电签报表</el-link>
                    <el-link type="primary" @click="rowViewPdf(row)">查看报表</el-link>
                    <el-link type="primary" :disabled="row.approveStatus === 0" @click="eVisaRowClick(row)">查看电签流程</el-link>
                    <el-link type="success" :disabled="row.isLock === 1" @click="rowEditClick(row)">修改</el-link>
                    <el-link type="danger" :disabled="row.isLock === 1" @click="rowDelClick(row)">删除</el-link>
                    <el-link v-loading="row?.recalculateLoading" :disabled="row.isLock === 1 || row.approveStatus !== 0" @click="rowRecalculateClick(row)">重新计算</el-link>
                    <el-link type="warning" @click="rowLockingClick(row)">{{ row.isLock === 1 ? '取消锁定' : '锁定' }}</el-link>
                </template>
            </hc-table>
            <template #action>
                <hc-pages :pages="searchForm" @change="pageChange" />
            </template>
        </hc-new-card>

        <!-- 中间计量新增 -->
        <HcAddModal v-model="addModalShow" @finish="addModalFinish" />

        <!-- 中间计量编辑 -->
        <HcEditModal v-model="editModalShow" :ids="editModalIds" @finish="editModalFinish" />

        <!-- 查看报表 -->
        <hc-view-report v-model="isReportDrawer" :datas="pdfList" />
        <!-- 任务流程 -->
        <HcTaskModal v-model="isTaskModal" :ids="taskDataId" @close="taskDataId = ''" />
    </div>
</template>

<script setup>
import { onActivated, ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import { delMessage } from '~uti/tools'
import { getArrValue, isNullES } from 'js-fast-way'
import HcAddModal from './components/certificate/addModal.vue'
import HcEditModal from './components/certificate/editModal.vue'
import HcTaskModal from '~src/components/task-modal/task-modal.vue'
import mainApi from '~api/debit-pay/admin/certificate'
import { toPdfPage } from '~uti/btn-auth'
import { useRoute } from 'vue-router'

const useAppState = useAppStore()
const useRoutes = useRoute()
const projectId = ref(useAppState.getProjectId || '')
const contractId = ref(useAppState.getContractId || '')

defineOptions({
    name: 'DebitPayAdminCertificate',
})

//渲染完成
onActivated(() => {
    getTableData()
})
const isReportDrawer = ref(false)
watch(() => useRoutes, (val) => {
if (val) {
    isReportDrawer.value = false
}
}, { immediate: true, deep: true })


//搜索表单
const searchForm = ref({ current: 1, size: 20, total: 0 })

//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'periodNumber', name: '期号' },
    { key: 'certificateNumber', name: '证书编号' },
    { key: 'startDate', name: '开始日期' },
    { key: 'endDate', name: '结束日期' },
    { key: 'printDate', name: '打印日期' },
    { key: 'calculateDate', name: '重新计算时间' },
    { key: 'payMoney', name: '支付金额' },
    { key: 'action', name: '操作', width: 440, align: 'center' },
])
const tableData = ref([])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.getPage({
        ...searchForm.value,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    tableData.value = getArrValue(data['records'])
    searchForm.value.total = data.total || 0
    tableLoading.value = false
}

//新增
const addModalShow = ref(false)
const addModalClick = () => {
    addModalShow.value = true
}
const addModalFinish = () => {
    getTableData()
}

//多选
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows
}

//修改
const editModalShow = ref(false)
const editModalIds = ref('')
const rowEditClick = (row) => {
    editModalIds.value = row.id
    editModalShow.value = true
}
const editModalFinish = () => {
    getTableData()
    editModalIds.value = false
}

//删除
const rowDelClick = (row) => {
    delMessage(async () => {
        const { error, code, msg } = await mainApi.remove({ ids: row.id })
        if (!error && code === 200) {
            window.$message.success('删除成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//锁定还是解锁
const rowLockingClick = async (row) => {
    //isLock,是否锁定：0未锁定，1锁定
    const { error, code, msg } = await mainApi.setLocking({
        id: row.id,
        isLock: row.isLock,
    })
    if (!error && code === 200) {
        window.$message.success('操作成功')
        getTableData().then()
    } else {
        window.$message.error(msg ?? '操作失败')
    }
}

//重新计算
const recalculateLoading = ref(false)
const recalculateClick = async () => {
    const rows = tableCheckedKeys.value
    if (rows.length <= 0) {
        window.$message.warning('请先勾选一条数据')
        return
    }
    if (rows.length > 1) {
        window.$message.warning('目前仅支持选择一条数据')
        return
    }
    recalculateLoading.value = true
    const isRes = await postRecalculateApi(rows[0])
    recalculateLoading.value = false
    if (isRes) {
        editModalIds.value = false
        getTableData().then()
    }
}

//重新计算报表
const rowRecalculateClick = async (row) => {
    row.recalculateLoading = true
    const isRes = await postRecalculateApi(row)
    row.recalculateLoading = false
    if (isRes) {
        editModalIds.value = false
        getTableData().then()
    }
}

//发起重新计算请求
const postRecalculateApi = async ({ id }) => {
    const { error, code, msg } = await mainApi.recalculate({
        reportId: id,
        type: 0,
        taskType: 1,
    })
    if (!error && code === 200) {
        window.$message.success('操作成功')
        return true
    } else {
        window.$message.error(msg ?? '操作失败')
        return false
    }
}

//查看报表
const pdfList = ref([])
const rowViewPdf = (row)=>{
    pdfList.value = []
    if (getArrValue(row?.urlListData).length > 0) {
        pdfList.value = getArrValue(row?.urlListData)
        console.log(pdfList.value, 'pdfList.value')
        isReportDrawer.value = true
    } else {
        window.$message.warning('暂无报表数据')
    }
}
const rowViewRawPdf = (row)=>{
    toPdfPage(row?.rawUrl)
}

//查看电签流程
const isTaskModal = ref(false)
const taskDataId = ref('')
const eVisaRowClick = ({ taskId }) => {
    if (isNullES(taskId)) {
        window.$message.warning('暂无电签数据')
        return
    }
    taskDataId.value = taskId
    setTimeout(()=> {
        isTaskModal.value = true
    }, 200)
}
</script>

<style scoped lang="scss">

</style>
