<template>
    <hc-new-card title="材料预付款报表手册">
        <template #extra>
            <el-button hc-btn type="primary" @click="addModalClick">
                <HcIcon name="add" />
                <span>新增</span>
            </el-button>
        </template>
        <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading" is-new :index-style="{ width: 60 }">
            <template #action="{ row }">
                <el-link type="primary" @click="viewPdf(row)">查看报表</el-link>
                <el-link type="success" @click="editRow(row)">修改</el-link>
                <el-link type="danger" @click="delCilck(row)">删除</el-link>
                <el-link v-loading="row?.recalculateLoading" @click="recalculate(row)">重新计算</el-link>
            </template>
        </hc-table>
        <template #action>
            <hc-pages :pages="searchForm" @change="pageChange" />
        </template>
        <!-- 新增/修改 -->
        <hc-new-dialog v-model="formModalShow" is-to-body widths="30rem" :title="modalTitle" :loading="saveLoading" @save="formModalSave" @close="formModalClose">
            <el-form ref="formRef" class="p-4" :model="formModel" :rules="formRules" label-position="top">
                <el-form-item label="计量期：" prop="meterPeriodId">
                    <el-select v-if="editType === 'add'" v-model="formModel.meterPeriodId" placeholder="选择计量期" filterable clearable block @change="selectPeriod">
                        <el-option v-for="item in periodData" :key="item.id" :label="item.periodName" :value="item.id" />
                    </el-select>
                    <el-select v-if="editType === 'edit'" v-model="formModel.meterPeriodId" placeholder="选择计量期" disabled filterable clearable block @change="selectPeriod">
                        <el-option v-for="item in key1Data" :key="item.id" :label="item.periodName" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="报表名称：" prop="statementName">
                    <el-input v-model="formModel.statementName" />
                </el-form-item>
                <el-form-item label="报表期：">
                    <el-input v-model="formModel.statementPeriod" disabled />
                </el-form-item>
                <el-form-item label="打印日期：">
                    <el-date-picker v-model="formModel.printDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="请款理由：">
                    <el-input v-model="formModel.repaymentCause" :autosize="{ minRows: 3, maxRows: 6 }" type="textarea" />
                </el-form-item>
            </el-form>
        </hc-new-dialog>
    </hc-new-card>
</template>

<script setup>
import { onActivated, onMounted, ref } from 'vue'
import bookApi from '~api/debit-pay/material/book.js'
import periodApi from '~api/debit-pay/material/periods.js'
import { useAppStore } from '~src/store'
import { formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { toPdfPage } from '~uti/btn-auth'
const useAppState = useAppStore()
const contractId = ref(useAppState.getContractId)
const projectId = ref(useAppState.getProjectId)
import { delMessageV2 } from '~com/message/index.js'
defineOptions({
    name: 'DebitPayMaterialBook',
})

//渲染完成
onActivated(() => {
    getTableData()
    getPeriodData()
    getKey1Data()
})


//计量期
const periodData = ref([])
//未被引用的
const getPeriodData = async ()=>{
    const { error, code, data } = await periodApi.conditionPeriod({
       contractId:contractId.value,
       type:1,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        periodData.value = getArrValue(data)
    } else {
        periodData.value = []
    }
}
//所有计量期
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)
    } else {
        key1Data.value = []
    }
}
const selectPeriod = (val)=>{
    periodData.value.forEach((ele)=>{
        if (ele.id === val) {
            formModel.value.statementPeriod = ele.periodName
            formModel.value.printDate = ele.formPrintDate
            formModel.value.periodNumber = ele.periodNumber
        }
    })
}
//搜索表单
const searchForm = ref({
    current: 1, size: 10, total: 0,
})

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

//表格数据
const tableLoading = ref(false)
const tableColumn = ref([
    { key: 'periodNumber', name: '计量期' },
    { key: 'statementName', name: '报表名称' },
    { key: 'printDate', name: '打印日期' },
    { key: 'calculateDate', name: '重新计算时间' },
    { key: 'action', name: '操作', width: 230 },
])
const tableData = ref([])
const getTableData = async () => {
    tableLoading.value = true
    const { error, code, data } = await bookApi.getPage({
       ...searchForm.value,
       contractId:contractId.value,
       type:1,
    //    meterPeriodId:searchForm.value.key1,
    })
    tableLoading.value = false
    if (!error && code === 200) {
        tableData.value = getArrValue(data['records'])
        searchForm.value.total = data['total']
    } else {
        tableData.value = []
        searchForm.value.total = 0
    }
}
//新增
const formModalShow = ref(false)
const editType = ref('')
const modalTitle = ref('材料预付款报表新增')
const addModalClick = () => {
    formModalShow.value = true
    formModel.value = {}
    editType.value = 'add'
    modalTitle.value = '材料预付款报表新增'
}
const editRow = (row)=>{
    formModalShow.value = true
    console.log(row, 'row')
    formModel.value = row
    editType.value = 'edit'
    modalTitle.value = '材料预付款报表修改'
}
const delCilck = (row)=>{
    delMessageV2(async (action, instance, done) => {
            if (action === 'confirm') {
                instance.confirmButtonLoading = true
                removeProPay(row.id)
                instance.confirmButtonLoading = false
                done()
            } else {
                done()
            }
    })
}
//查看报表
const viewPdf = (row)=>{
    toPdfPage(row.rawUrl)
}
//重新计算

const recalculate = async (row)=>{
    row.recalculateLoading = true
    const { error, code, msg } = await bookApi.meterPdfInfo({
        reportId:row.id,
        type:1,
    })
    row.recalculateLoading = false
    if (!error && code === 200) {
        window.$message.success('计算成功')
        getTableData()
    } 
}
const removeProPay = async (id) => {
    const { error, code } = await bookApi.remove({
        ids: id,
    })
    if (!error && code === 200) {
        window?.$message?.success('删除成功')
       getTableData()

    }
}
//表单
const formRef = ref(null)
const formModel = ref({})
const formRules = {
    meterPeriodId: {
        required: true,
        trigger: 'blur',
        message: '请选择计量期',
    },
    statementName: {
        required: true,
        trigger: 'blur',
        message: '请输入报表名称',
    },
}



const saveLoading = ref(false)
const formModalSave = async () => {
    const isValidate = await formValidate(formRef.value)
    if (!isValidate) return false

    saveLoading.value = true
    const { error, code, msg } = await bookApi.submit({
        ...formModel.value,
        contractId:contractId.value,
        projectId:projectId.value,
        type:1,
        })
        //判断状态
        saveLoading.value = false
        if (!error && code === 200) {
            window?.$message?.success(msg)


        }
    formModalClose()
}

const formModalClose = () => {
    formModalShow.value = false
    getTableData()
}
</script>

<style scoped lang="scss">

</style>
