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

        <!--批量上报审批-->
        <HcReportModal  title="批量上报审批" url="contractLog/batchTask" :show="showReportModal" :projectId="projectId" :contractId="contractId"
                        :taskName="reportTaskName" :ids="reportIds" @hide="showReportModal = false" @finish="showReportFinish"/>
    </div>
</template>

<script setup>
import {ref, watch, nextTick} from "vue";
import queryApi from '~api/ledger/query';
import {getArrValue, getObjValue, isString} from "vue-utils-plus"

//参数
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 showReportModal = ref(false)
const reportIds = ref('')
const reportTaskName = ref('')
const reportModalClick = () => {
    const rows = tableCheckedKeys.value;
    //判断是否满足条件
    const result = rows.every(({status})=> {
        return status !== 1 && status !== 2
    })
    //判断状态
    if (result) {
        const row = getObjValue(rows[0])
        reportIds.value = rowsToId(rows)
        reportTaskName.value = rows.length > 1 ? `${row.name}等${rows.length}个文件` : row.name
        showReportModal.value = true
    } else {
        window.$message?.warning('已上报的文件不能进行再次上报，若要重新上报，要先撤回之前的上报，再重新上报')
    }
}
//上报完成
const showReportFinish = () => {
    showReportModal.value = false
    getTableData()
}

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

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

//批量删除
const batchDeleteClick = () => {
    window.$message?.warning('暂无接口')
}

//预览、打印
const previewPrintLoading = ref(false)
const previewAndPrintClick = async () => {
    previewPrintLoading.value = true
    const rows = tableCheckedKeys.value;
    const rowsIds = rowsToId(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 = (row) => {
    window.$message?.warning('暂无接口')
}

//删除
const handleTableDel = (row) => {
    window.$message?.warning('暂无接口')
}


//拼接ID
const rowsToId = (rows) => {
    return rows.map((obj) => {
        return obj.id;
    }).join(",")
}
</script>

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