<template>
    <hc-card title="资金预算期">
        <template #extra>
            <el-button hc-btn type="primary" @click="addRowClick">
                <hc-icon name="add" />
                <span>新增</span>
            </el-button>
            <el-button :disabled="!isAddModal" hc-btn type="warning" :loading="saveLoading" @click="saveRowClick">
                <hc-icon name="add" />
                <span>保存</span>
            </el-button>
        </template>
        <hc-table :column="tableColumn" :datas="tableData" :loading="tableLoading">
            <template #periodYear="{ row }">
                <el-select v-if="isNullES(row.id)" v-model="row.periodYear" placeholder="选择年份" filterable block @change="yearDataChange($event, row)">
                    <el-option v-for="item in yearDatas" :key="item" :label="item" :value="item" />
                </el-select>
                <span v-else>{{ row.periodYear }}</span>
            </template>
            <template #action="{ row, index }">
                <el-link type="danger" @click="delRowClick(row, index)">删除</el-link>
            </template>
        </hc-table>
    </hc-card>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { useAppStore } from '~src/store'
import { HcDelMsg } from 'hc-vue3-ui'
import { getArrValue, isNullES } from 'js-fast-way'
import mainApi from '~api/funding/index'
import dayjs from 'dayjs'

//获取全局变量
const store = useAppStore()
const projectId = ref(store.getProjectId)
const contractId = ref(store.getContractId)

defineOptions({
    name: 'FundingPlan',
})

//选项卡被激活
onActivated(() => {
    projectId.value = store.getProjectId
    contractId.value = store.getContractId
    setYearDatas()
    getTableData()
})

//生成年份 (根据当前年，生成上下 10年的日期)
const yearDatas = ref([])
const setYearDatas = () => {
    let newYear = []
    const year = Number(new dayjs().format('YYYY'))
    for (let i = 0; i < 11; i++) {
        newYear.push(year - i)
        newYear.push(year + i)
    }
    const newArr = [...new Set(newYear)]
    newArr.sort((a, b) => a - b)
    yearDatas.value = newArr
}

//表格数据
const tableData = ref([])
const tableColumn = ref([
    { key: 'periodName', name: '期名称' },
    { key: 'periodYear', name: '年份' },
    { key: 'action', name: '操作', width: 80, align: 'center' },
])

//获取表格数据
const tableLoading = ref(false)
const getTableData = async () => {
    tableLoading.value = true
    const { data } = await mainApi.periodPage({
        projectId: projectId.value,
        contractId: contractId.value,
    })
    tableLoading.value = false
    tableData.value = getArrValue(data)
}

//新增数据
const isAddModal = ref(false)
const addRowClick = () => {
    let periodName, year, toYear = Number(new dayjs().format('YYYY'))
    const data = tableData.value, years = yearDatas.value
    if (data.length <= 0) {
        year = toYear //如果没有上一条数据，就取今年
        periodName = toYear + '年资金预算'
    } else {
        //如果存在上一条数据
        const newYear = Number(data[data.length - 1].periodYear) + 1
        //判断，上一条数据的年份 + 1，是否超过了可选的年份
        if (years[years.length - 1] < newYear) {
            //如果超过了，就取可选年份的最后一年
            year = years[years.length - 1]
            periodName = years[years.length - 1] + '年资金预算'
        } else {
            //如果没有超过，就取上一条数据的年份 + 1
            year = newYear
            periodName = newYear + '年资金预算'
        }
    }
    //插入数据
    tableData.value.push({ periodName, periodYear: year })
    isAddModal.value = true
}

//年份被选择
const yearDataChange = (val, row) => {
    row.periodName = val + '年资金预算'
}

//批量保存
const saveLoading = ref(false)
const saveRowClick = async () => {
    const table = tableData.value
    saveLoading.value = true
    const { error, code } = await mainApi.periodEdit({
        projectId: projectId.value,
        contractId: contractId.value,
        list: table,
    })
    saveLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success('保存成功')
        isAddModal.value = false
        getTableData().then()
    }
}

//删除数据
const delRowClick = ({ id, citeStatus }, index) => {
    if (citeStatus === 1) {
        window?.$message?.warning('当前数据已被计量，不允许删除')
        return
    }
    //删除弹窗
    HcDelMsg(async (resolve) => {
        const { error, code } = await mainApi.deleteById(id)
        if (error && code !== 200) {
            resolve() //关闭弹窗的回调
            return
        }
        window?.$message?.success('操作成功')
        const rows = tableData.value
        rows.splice(index, 1)
        isAddModal.value = true
        resolve() //关闭弹窗的回调
    })
}
</script>

<style scoped lang="scss">

</style>
