<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.periodNumber" :value="item.id" clearable />
                    </el-select>
                </template>
                <hc-lazy-tree :h-props="treeProps" tree-key="id" :auto-expand-keys="TreeAutoExpandKeys" @load="treeLoadNode" @node-tap="treeNodeTap" />
            </hc-new-card>
        </div>
        <div :id="`hc_table_card_${uuid}`" class="flex-1">
            <hc-new-card>
                <template #header>
                    <div class="text-orange font-400">收方总金额：{{ meterMoney }}元</div>
                </template>
                <template #extra>
                    <el-button hc-btn type="primary" :disabled="approveStatus !== 0" @click="addModalClick">新增</el-button>
                    <el-button hc-btn type="warning" :disabled="approveStatus !== 0" @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" @click="sortClick(1)">按部位排序</el-button>
                    <el-button hc-btn color="#626aef" @click="sortClick(2)">按录入时间排序</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="primary" @click="rowViewClick(row)">预览</el-link>
                        <el-link type="success" :disabled="approveStatus !== 0" @click="rowEditClick(row)">修改</el-link>
                        <el-link type="danger" :disabled="approveStatus !== 0" @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" :ids="addModalIds" :project-id="projectId" :contract-id="contractId" :all-periods="key1Data" :period-id="searchForm.contractPeriodId" :is-view="isView" @finish="addModalFinish" />

        <!-- 清单明细 -->
        <HcDetailsModal v-model="detailsModalShow" :project-id="projectId" :contract-id="contractId" :period-id="searchForm.contractPeriodId" />

        <!-- 上报弹窗 -->
        <hc-report-dialog v-model="isReport" :info="reportInfo" @finish="reportFinish" />

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

<script setup>
import { nextTick, onActivated, 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 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(async () => {
    setSplitRef()
})

//激活
onActivated(async () => {
    await getKey1Data()
    getCurrentMeterMoney().then()
})

//初始化设置拖动分割线
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, type: 1,
    current: 1, size: 20, total: 0,
})
const approveStatus = ref(0)

//计量期
const key1Data = ref([])
const getKey1Data = async ()=>{
    const { error, code, data } = await mainApi.getAllPeriod({
        contractId: contractId.value,
        type: 1,
    })
    if (!error && code === 200) {
        let newArr = getArrValue(data), info = getObjValue(newArr[newArr.length - 1])
        searchForm.value.contractPeriodId = info.id
        approveStatus.value = info.approveStatus
        key1Data.value = newArr
    } else {
        key1Data.value = []
    }
}
const searchKey1Click = () => {
    let info = getObjValue(key1Data.value.find((item) => item.id === searchForm.value.contractPeriodId))
    approveStatus.value = info.approveStatus
    searchForm.value.current = 1
    getTableData()
    getCurrentMeterMoney()
}

//获取本期计量总金额
const meterMoney = ref(0)
const getCurrentMeterMoney = async () => {
    const { error, code, data } = await mainApi.getCurrentMeterMoney({
        contractId: contractId.value,
        contractPeriodId: searchForm.value.contractPeriodId,
    })
    if (!error && code === 200) {
        meterMoney.value = data
    } else {
        meterMoney.value = 0
    }
}

//数据格式
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 sortClick = (type) => {
    searchForm.value.type = type
    searchForm.value.current = 1
    getTableData()
}

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

//获取表格状态
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 addModalClick = () => {
    isView.value = false
    addModalIds.value = ''
    nextTick(() => {
        addModalShow.value = true
    })
}

//修改
const addModalIds = ref('')
const rowEditClick = (row) => {
    addModalIds.value = row.id
    isView.value = false
    nextTick(() => {
        addModalShow.value = true
    })
}
//预览rowViewClick
const isView = ref(false)
const rowViewClick = (row) => {
    addModalIds.value = row.id
    isView.value = true
    nextTick(() => {
        addModalShow.value = true
    })
}
//删除
const rowDelClick = (row) => {
    delMessage(async () => {
        const { code, msg } = await mainApi.remove({ ids: row.id })
        if (code === 200) {
            window.$message.success('删除成功')
            getTableData().then()
        } else {
            window.$message.error(msg ?? '删除失败')
        }
    })
}

//保存完成
const addModalFinish = () => {
    addModalShow.value = false
    TreeAutoExpandKeys.value = getStoreValue('middlepay-tree-auto-expand-keys') || []
    getTableData()
}

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

//是否上报
const isReport = ref(false)
const reportInfo = ref({})
const reportClick = () => {
    reportInfo.value = {
        type: 1,
        periodId: searchForm.value.contractPeriodId,
    }
    nextTick(() => {
        isReport.value = true
    })
}

//上报完成
const reportFinish = () => {
    window.location.reload()
}

const isReportDrawer = ref(false)
</script>
