<template>
    <div class="hc-table-list-content">
        <HcCard>
            <template #header>
                <div class="w-64">
                    <HcDatePicker :dates="betweenTime" clearable size="large" @change="betweenTimeUpdate" />
                </div>
                <div class="w-40 ml-3">
                    <el-select v-model="searchForm.createUser" block clearable placeholder="请选择记录人" size="large">
                        <el-option v-for="item in recordData" :label="item.userName" :value="item.userId" />
                    </el-select>
                </div>
                <div class="ml-2">
                    <el-button size="large" type="primary" @click="searchClick">
                        <HcIcon name="search-2" />
                        <span>搜索</span>
                    </el-button>
                </div>
            </template>
            <template #extra>
                <HcTooltip keys="ledger_query_report">
                    <el-button
                        :disabled="tableCheckedKeys.length <= 0" :loading="reportLoading" hc-btn
                        color="#FF976A" style="color: white;" @click="reportModalClick"
                    >
                        <HcIcon name="send-plane-2" />
                        <span>批量上报</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="ledger_query_abolish">
                    <el-button
                        :disabled="tableCheckedKeys.length <= 0" :loading="abolishLoading" hc-btn
                        color="#A16222" @click="batchAbolishClick"
                    >
                        <HcIcon name="delete-bin-3" />
                        <span>批量废除</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="ledger_query_delete">
                    <el-button
                        :disabled="tableCheckedKeys.length <= 0" :loading="deleteLoading" hc-btn
                        color="#e03997" @click="batchDeleteClick"
                    >
                        <HcIcon name="delete-bin" />
                        <span>批量删除</span>
                    </el-button>
                </HcTooltip>
                <HcTooltip keys="ledger_query_print">
                    <el-button
                        :disabled="tableCheckedKeys.length <= 0" :loading="previewPrintLoading" hc-btn
                        color="#567722" @click="previewAndPrintClick"
                    >
                        <HcIcon name="printer" />
                        <span>批量预览/打印</span>
                    </el-button>
                </HcTooltip>
            </template>
            <HcTable
                ref="tableListRef" :column="tableListColumn" :datas="tableListData" :loading="tableLoading" is-check
                border @selection-change="tableSelectionChange"
            >
                <template #action="{ row }">
                    <HcTooltip keys="ledger_query_table_query">
                        <el-button plain size="small" type="primary" @click="handleTableQuery(row)">查询</el-button>
                    </HcTooltip>
                    <HcTooltip keys="ledger_query_table_del">
                        <el-button
                            :disabled="!row.operation || row.status !== 0" plain size="small" type="danger"
                            @click="handleTableDel(row)"
                        >
                            删除
                        </el-button>
                    </HcTooltip>
                </template>
            </HcTable>
            <template #action>
                <HcPages :pages="searchForm" @change="pageChange" />
            </template>
        </HcCard>

        <!-- 批量上报审批 -->
        <HcReportModal
            :contract-id="contractId"
            :datas="reportDatas"
            :ids="reportIds"
            :project-id="projectId"
            :show="showReportModal"
            :task-name="reportTaskName"
            :type-data="menuItem.primaryKeyId"
            is-datas
            title="批量上报审批"
            type="log"
            url="contractLog/batchTask"
            @finish="showReportFinish"
            @hide="showReportModal = false"
            @tagClose="reportTaskTagClose"
        />
    </div>
</template>

<script setup>
import { nextTick, ref, watch } from 'vue'
import queryApi from '~api/ledger/query'
import { eVisaTaskCheckApi } from '~api/other'
import { arrToId, getArrValue, getObjValue, isString } from 'js-fast-way'

//参数
const props = defineProps({
    projectId: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    items: {
        type: Object,
        default: () => ({}),
    },
})

//变量
const projectId = ref(props.projectId)
const contractId = ref(props.contractId)
const menuItem = ref(props.items)

//监听
watch(() => [
    props.projectId,
    props.contractId,
    props.items,
], ([pid, cid, item]) => {
    projectId.value = pid
    contractId.value = cid
    menuItem.value = item
    getQueryData()
})

//渲染完成
nextTick(() => {
    getQueryData()
})

//获取相关数据
const getQueryData = () => {
    searchClick()
    queryFillUser()
}

//获取记录人数据
const recordData = ref([])
const queryFillUser = async () => {
    const { primaryKeyId } = menuItem.value
    const { data } = await queryApi.queryFillUser({
        contractId: contractId.value,
        primaryKeyId: primaryKeyId,
    })
    recordData.value = getArrValue(data)
}

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

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({ arr, query }) => {
    betweenTime.value = arr
    searchForm.value.queryTime = query
}

//搜索
const searchClick = () => {
    searchForm.value.current = 1
    getTableData()
}

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

//获取数据
const tableLoading = ref(false)
const tableListColumn = ref([
    { key: 'recordTime', name: '记录日期' },
    { key: 'statusValue', name: '流程状态' },
    { key: 'createUserName', name: '记录人员' },
    { key: 'action', name: '操作', width: 200 },
])
const tableListData = ref([])
const getTableData = async () => {
    //初始数据处理
    tableLoading.value = true
    const { primaryKeyId } = menuItem.value
    tableListRef.value?.clearSelection()
    tableCheckedKeys.value = []
    //请求数据
    const { error, code, data } = await queryApi.constructionLogPage({
        ...searchForm.value,
        wbsNodeId: primaryKeyId,
        projectId: projectId.value,
        contractId: contractId.value,
    })
    console.log(data)
    //处理数据
    tableLoading.value = false
    if (!error && code === 200) {
        tableListData.value = getArrValue(data['records'])
        searchForm.value.total = data.total || 0
    } else {
        tableListData.value = []
        searchForm.value.total = 0
    }
}

//多选
const tableListRef = ref(null)
const tableCheckedKeys = ref([])
const tableSelectionChange = (rows) => {
    tableCheckedKeys.value = rows.filter((item) => {
        return (item ?? '') !== ''
    })
}

//批量上报
const reportIds = ref('')
const reportTaskName = ref('')
const reportDatas = ref([])
const reportLoading = ref(false)
const showReportModal = ref(false)
const reportModalClick = async () => {
    const rows = tableCheckedKeys.value
    //判断是否满足条件
    const result = rows.every(({ status }) => {
        return status !== 1 && status !== 2
    })
    //判断状态
    if (result) {
        reportLoading.value = true
        const taskCheck = await eVisaTaskCheckApi({
            projectId: projectId.value,
            contractId: contractId.value,
        })
        if (taskCheck) {
            //初始ID
            const row = getObjValue(rows[0])
            reportIds.value = arrToId(rows)
            //设置任务数据
            let reportDataArr = []
            rows.forEach(item => {
                reportDataArr.push({
                    id: item?.id,
                    name: item?.fileName,
                })
            })
            reportDatas.value = reportDataArr
            //设置任务名称
            reportTaskName.value = rows.length > 1 ? `${row.fileName}等${rows.length}个文件` : row.fileName
            reportLoading.value = false
            showReportModal.value = true
        } else {
            reportLoading.value = false
        }
    } else {
        window.$message?.warning('已上报的文件不能进行再次上报，若要重新上报，要先撤回之前的上报，再重新上报')
    }
}

//上报的审批内容移除
const reportTaskTagClose = (index) => {
    const row = tableCheckedKeys.value[index]
    tableListRef.value?.toggleRowSelection(row, false)
}

//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableData()
}

//批量废除
const abolishLoading = ref(false)
const batchAbolishClick = () => {
    const rows = tableCheckedKeys.value
    //判断是否满足条件
    const result = rows.every(({ status, operation }) => {
        return status !== 0 && status !== 3 && operation
    })
    //判断状态
    if (result) {
        //拼接ID
        const ids = arrToId(rows)
        window?.$messageBox?.alert('是否废除勾选的已上报文件？', '废除文件', {
            showCancelButton: true,
            confirmButtonText: '确定废除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    batchAbolishSave(ids)
                }
            },
        })
    } else {
        window.$message?.warning('未上报的文件，和不是自己的文件，不能废除')
    }
}

//废除勾选的已上报文件
const batchAbolishSave = async (ids) => {
    abolishLoading.value = true
    const { error, code } = await queryApi.batchAbolish({ ids: ids })
    //处理数据
    abolishLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('批量废除成功')
        tableCheckedKeys.value = []
        getTableData()
    }
}

//批量删除
const batchDeleteClick = () => {
    const rows = tableCheckedKeys.value
    //判断是否满足条件
    const result = rows.every(({ status, operation }) => {
        return status === 0 && operation
    })
    //判断状态
    if (result) {
        const ids = arrToId(rows)
        window?.$messageBox?.alert('是否删除勾选的日志文件？', '删除文件', {
            showCancelButton: true,
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    theLogRemoveByIds(ids)
                }
            },
        })
    } else {
        window.$message?.warning('只能删除自己的未上报日志文件')
    }
}

//预览、打印
const previewPrintLoading = ref(false)
const previewAndPrintClick = async () => {
    previewPrintLoading.value = true
    const rows = tableCheckedKeys.value
    const rowsIds = arrToId(rows)
    const ids = rowsIds.split(',')
    const { error, code, data } = await queryApi.theLogPreviewAndPrint({
        ids: ids,
    })
    //处理数据
    previewPrintLoading.value = false
    const res = isString(data) ? data || '' : ''
    if (!error && code === 200 && res) {
        window.open(res, '_blank')
    }
}

//查询
const handleTableQuery = ({ evisaPdfUrl, pdfUrl }) => {
    if (evisaPdfUrl) {
        window.open(evisaPdfUrl, '_blank')
    } else if (pdfUrl) {
        window.open(pdfUrl, '_blank')
    } else {
        window.$message?.warning('该数据暂无PDF')
    }
}

//删除
const handleTableDel = ({ id, status, operation }) => {
    //判断是否满足条件
    if (status === 0 && operation) {
        window?.$messageBox?.alert('是否删除勾选的日志文件？', '删除文件', {
            showCancelButton: true,
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            callback: (action) => {
                if (action === 'confirm') {
                    theLogRemoveByIds([id])
                }
            },
        })
    } else {
        window.$message?.warning('只能删除自己的未上报日志文件')
    }
}

//删除
const deleteLoading = ref(false)
const theLogRemoveByIds = async (ids) => {
    deleteLoading.value = true
    const { error, code } = await queryApi.theLogRemoveByIds({
        ids: ids,
    })
    deleteLoading.value = false
    if (!error && code === 200) {
        window.$message?.success('删除成功')
        tableCheckedKeys.value = []
        getTableData()
    }
}
</script>

<style lang="scss" scoped>
.hc-table-list-content {
    flex: 1;
    position: relative;
    margin-left: 24px;
    height: 100%;
}
</style>
