<template>
    <div class="relative h-full flex">
        <div :id="`hc_tree_card_${uuid}`">
            <hc-new-card scrollbar>
                <template #header>
                    <el-select v-model="searchForm.contractPeriodId" placeholder="选择计量期" filterable clearable block @change="searchKey1Click">
                        <el-option v-for="item in key1Data" :key="item.id" :label="item.periodName" :value="item.id" clearable />
                    </el-select>
                </template>
                <hc-lazy-tree :h-props="treeProps" tree-key="id" :auto-expand-keys="TreeAutoExpandKeys" @load="treeLoadNode" @nodeTap="treeNodeTap" />
            </hc-new-card>
        </div>
        <div :id="`hc_table_card_${uuid}`" class="flex-1">
            <hc-new-card>
                <template #header>
                    <div class="font-400 text-orange">收方总金额：0元</div>
                </template>
                <template #extra>
                    <el-button hc-btn type="primary" @click="addModalClick">新增</el-button>
                    <el-button hc-btn type="warning" @click="reportClick">按期上报</el-button>
                    <el-button hc-btn type="success" @click="detailsModalClick">清单明细</el-button>
                    <el-button hc-btn type="success" @click="isReportDrawer = true">查看报表</el-button>
                    <el-button hc-btn color="#626aef">按部位排序</el-button>
                    <el-button hc-btn color="#626aef">按录入时间排序</el-button>
                </template>
                <hc-table
                    :column="tableColumn" :datas="tableData" :loading="tableLoading"
                    is-new is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }"
                    @selection-change="tableCheckChange"
                >
                    <template #contractPeriodId="{ row }">
                        {{ getTablePeriod(row) }}
                    </template>
                    <template #approveStatus="{ row }">
                        {{ getTableStatus(row) }}
                    </template>
                    <template #action="{ row }">
                        <el-link type="success" @click="rowEditClick(row)">修改</el-link>
                        <el-link type="danger" @click="rowDelClick(row)">删除</el-link>
                    </template>
                </hc-table>
                <template #action>
                    <hc-pages :pages="searchForm" @change="pageChange" />
                </template>
            </hc-new-card>
        </div>
        <!-- 中间计量新增 -->
        <HcAddModal v-model="addModalShow" :project-id="projectId" :contract-id="contractId" :type="isAddModalType" :all-periods="key1Data" :period-id="searchForm.contractPeriodId" @finish="addModalFinish" />

        <!-- 清单明细 -->
        <HcDetailsModal v-model="detailsModalShow" />

        <!-- 上报弹窗 -->
        <hc-report-dialog v-model="isReport" />

        <!-- 查看报表 -->
        <hc-view-report v-model="isReportDrawer" />
    </div>
</template>

<script setup>
import { nextTick, onMounted, ref } from 'vue'
import { useAppStore } from '~src/store'
import { getArrValue, getObjValue, getRandom } from 'js-fast-way'
import { getStoreValue, setStoreValue } from '~src/utils/storage'
import { delMessage } from '~uti/tools'

import HcAddModal from './components/middlepay/addModal.vue'
import HcDetailsModal from './components/middlepay/detailsModal.vue'

import periodApi from '~api/debit-pay/material/periods'
import unitApi from '~api/project/debit/contract/unit'
import mainApi from '~api/debit-pay/admin/middlepay'

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

defineOptions({
    name: 'DebitPayAdminMiddlepay',
})

const uuid = getRandom(4)

//渲染完成
onMounted(() => {
    setSplitRef()
    getKey1Data()
})

//初始化设置拖动分割线
const setSplitRef = () => {
    //配置参考： https://split.js.org/#/?direction=vertical&snapOffset=0
    nextTick(() => {
        window.$split(['#hc_tree_card_' + uuid, '#hc_table_card_' + uuid], {
            sizes: [20, 80],
            snapOffset: 0,
            minSize: [50, 500],
        })
    })
}

//搜索表单
const searchForm = ref({
    contractPeriodId: null, contractUnitId: null, contractId: contractId.value,
    current: 1, size: 10, total: 0,
})

//计量期
const key1Data = ref([])
const getKey1Data = async ()=>{
    const { error, code, data } = await periodApi.allPeriod({
       contractId:contractId.value,
       type:1,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        key1Data.value = getArrValue(data)
        searchForm.value.contractPeriodId = key1Data.value[ key1Data.value.length - 1].id
    } else {
        key1Data.value = []
    }
}
const searchKey1Click = () => {
    searchForm.value.current = 1
    getTableData()
}

//数据格式
const treeProps = {
    label: 'nodeName',
    children: 'children',
    isLeaf: 'notExsitChild',
}
const TreeAutoExpandKeys = ref(getStoreValue('middlepay-tree-auto-expand-keys') || [])
//懒加载的数据
const treeLoadNode = async ({ item, level }, resolve) => {
    let id = 0
    if (level !== 0) {
        const nodeData = getObjValue(item)
        id = nodeData?.id || ''
    }
    //获取数据
    const { data } = await unitApi.lazyTree({
        contractId: contractId.value,
        id:id,
        contractPeriodId:searchForm.value.contractPeriodId,
    })
    resolve(getArrValue(data))
}
const treeNodeTap = ({ data, keys }) => {
    searchForm.value.current = 1
    searchForm.value.contractUnitId = data.id
    TreeAutoExpandKeys.value = keys || []
    setStoreValue('middlepay-tree-auto-expand-keys', keys)
    getTableData()
}
//分页
const pageChange = ({ current, size }) => {
    searchForm.value.current = current
    searchForm.value.size = size
    getTableData()
}

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'meterNumber', name: '计量单编号' },
    { key: 'contractPeriodId', name: '计量期' },
    { key: 'engineerDivide', name: '工程划分部位' },
    { key: 'meterMoney', name: '计量金额' },
    { key: 'businessDate', name: '业务日期' },
    { key: 'approveStatus', name: '审核状态' },
    { key: 'action', name: '操作', width: 130, align: 'center' },
])
const tableData = ref([])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.getPage({
        ...searchForm.value,
        contractId: contractId.value,
    })
    tableData.value = getArrValue(data['records'])
    searchForm.value.total = data.total || 0
    tableLoading.value = false
}

//获取表格计量期
const getTablePeriod = ({ contractPeriodId }) => {
    const periods = key1Data.value
    const periodData = periods.find((item) => item.id === contractPeriodId)
    return periodData?.periodName || ''
}

//获取表格状态
const getTableStatus = ({ approveStatus }) => {
    if (approveStatus === 0) {
        return '未上报'
    } else if (approveStatus === 1) {
        return '待审批'
    } else if (approveStatus === 2) {
        return '已审批'
    } else if (approveStatus === 3) {
        return '已废除'
    }
}

//表格选择
const tableCheckChange = () => {

}

//中间收方新增
const addModalShow = ref(false)
const isAddModalType = ref('add')
const addModalClick = () => {
    isAddModalType.value = 'add'
    addModalShow.value = true
}

//修改
const rowEditClick = (row) => {

}

//删除
const rowDelClick = (row) => {
    delMessage(() => {
        console.log('删除')
    })
}


//保存完成
const addModalFinish = () => {
    addModalShow.value = false
    getTableData()
}


//收方清单明细
const detailsModalShow = ref(false)
const detailsModalClick = () => {
    detailsModalShow.value = true
}

//是否上报
const isReport = ref(false)
const reportClick = () => {
    isReport.value = true
}

const isReportDrawer = ref(false)
</script>
