<template>
    <hc-new-dialog is-table widths="1200px" :show="isShow" title="添加分解清单" @save="modalSave" @close="modalClose">
        <hc-table
            :column="tableColumn" :datas="tableData" :loading="tableLoading"
            is-new is-check :check-style="{ width: 29 }" :index-style="{ width: 60 }"
            @selection-change="tableCheckChange"
        />
    </hc-new-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { arrToId, getArrValue } from 'js-fast-way'
import mainApi from '~api/debit-pay/admin/middlepay'

const props = defineProps({
    ids: {
        type: [String, Number],
        default: '',
    },
    idn: {
        type: [String, Number],
        default: '',
    },
    contractId: {
        type: [String, Number],
        default: '',
    },
    periodId: {
        type: [String, Number],
        default: '',
    },
})

//事件
const emit = defineEmits(['finish', 'close'])

//双向绑定
// eslint-disable-next-line no-undef
const isShow = defineModel('modelValue', {
    default: false,
})

//监听
const dataId = ref(props.ids)
const nodeId = ref(props.idn)
const cid = ref(props.contractId)
const contractPeriodId = ref(props.periodId)

watch(() => [
    props.ids,
    props.idn,
    props.periodId,
    props.contractId,
], ([ids, idn, periodId, contractId]) => {
    dataId.value = ids
    nodeId.value = idn
    cid.value = contractId
    contractPeriodId.value = periodId
}, { immediate: true })

//监听
watch(isShow, (val) => {
    if (val) {
        getTableData()
    }
})

//表格数据
const tableLoading = ref(false)
const tableColumn = [
    { key: 'formNumber', name: '清单编号' },
    { key: 'formName', name: '清单名称' },
    { key: 'currentPrice', name: '单价(元)' },
    { key: 'contractTotal', name: '合同数量' },
    { key: 'changeTotal', name: '合同变更后数量' },
    { key: 'buildChangeTotal', name: '施工图变更后数量' },
    { key: 'resolveResidueTotal', name: '分解剩余量' },
]
const tableData = ref([])
const getTableData = async () => {
    tableData.value = []
    tableLoading.value = true
    const { data } = await mainApi.addFormList({
        contractPeriodId: contractPeriodId.value,
        contractId: cid.value,
        ids: dataId.value,
        nodeId: nodeId.value,
    })
    tableData.value = getArrValue(data)
    tableLoading.value = false
}

//表格选择
const checksData = ref([])
const tableCheckChange = (data) => {
    checksData.value = data
}

//确定保存
const modalSave = async () => {
    const rows = checksData.value
    if (rows.length <= 0) {
        window.$message.warning('请先选择清单')
        return false
    }
    const rowIds = arrToId(rows)
    const { data } = await mainApi.addResolveForm({
        contractPeriodId: contractPeriodId.value,
        contractId: cid.value,
        nodeId: nodeId.value,
        ids: rowIds,
    })
    emit('finish', getArrValue(data))
    modalClose()
}

//取消关闭
const modalClose = () => {
    isShow.value = false
    emit('close')
}
</script>
