<template>
    <hc-drawer v-model="isShow" to-id="add-card-target" is-close @close="dialogClose">
        <div class="relative h-95% overflow-y-auto bg-#F2F3F5 p-2">
            <div>
                <hc-icon class="text-18px text-black font-600" name="add-box" />
                <span class="ml-2 text-18px text-black font-800">新增项目</span>
            </div>
            <div class="mt-4">
                <hc-card-item class="hac-card-item">
                    <template #header>
                        <div class="hac-card-title g">基础信息</div>
                    </template>
                    <el-form ref="formRef" :inline="true" :model="baseForm" :rules="formRules" label-width="auto" label-position="left" :disabled="data?.isView">
                        <div>
                            <div class="hc-form-item">
                                <el-form-item label="路线名称:" prop="projectName">
                                    <el-input v-model="baseForm.projectName" clearable placeholder="请输入" />
                                </el-form-item>
                                <el-form-item label="项目类型:" prop="type">
                                    <el-select v-model="baseForm.type" filterable clearable block placeholder="项目类型" @change="typeClick">
                                        <el-option v-for="item in typeOptions" :key="item.id" :label="item.dictValue" :value="item.id" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="路线类型:" prop="routeType">
                                    <el-select v-model="baseForm.routeType" filterable clearable block placeholder="路线类型">
                                        <el-option v-for="item in routeOptions" :key="item.id" :label="item.dictValue" :value="item.id" />
                                    </el-select>
                                </el-form-item>
                            </div>
                            <div class="hc-form-item">
                                <el-form-item label="项目阶段:" prop="stage">
                                    <el-select v-model="baseForm.stage" filterable clearable block placeholder="项目阶段">
                                        <el-option v-for="item in stateOptions" :key="item.value" :label="item.label" :value="item.value" />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="建设期时间:" prop="key5">
                                    <hc-date-picker :dates="betweenTime" clearable :disabled="data?.isView" @change="betweenTimeUpdate" />
                                </el-form-item>
                                <el-form-item label="运营期时间:" prop="key6">
                                    <hc-date-picker :dates="betweenTime1" clearable :disabled="data?.isView" @change="betweenTimeUpdate1" />
                                </el-form-item>
                            </div>
                            <div class="hc-form-item">
                                <el-form-item label="运营公司:" prop="operationCompany">
                                    <el-input v-model="baseForm.operationCompany" clearable placeholder="请输入" />
                                </el-form-item>
                                <el-form-item label="实际运营里程（公里）:" prop="actualOperatingMileage">
                                    <HcInputNumber1 v-model="baseForm.actualOperatingMileage" clearable placeholder="请输入" class="w-full" />
                                </el-form-item>
                                <el-form-item label="车道数" prop="lane">
                                    <HcInputNumber1 v-model="baseForm.lane" clearable placeholder="请输入" class="w-full" />
                                </el-form-item>
                            </div>
                        </div>
                    </el-form>
                </hc-card-item>
            </div>
            <div class="mt-4">
                <hc-card-item class="hac-card-item">
                    <template #header>
                        <div class="hac-card-title g">
                            <div class="w-[180px]">
                                <el-select v-model="stageYearVal" filterable clearable block placeholder="请选择" @change="stageYearClick">
                                    <el-option v-for="item in stageYearOptions" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </div>
                            <span class="ml-2">项目信息</span>
                        </div>
                    </template>
                    <div class="flex p-1 text-sm font-bold">
                        <hc-icon name="arrow-down" class="mr-1 text-lightBlue" /><div>现金流入 </div>
                     
                        <span class="ml-2 mr-1 text-blue">共计：{{ yearFuns[selectIndex].inflowTotal }}</span><span class="ml-1 text-blue">万元</span>
                    </div>
                    <div class="cash-in-list mt-2 flex justify-between">
                        <div class="cash-in-list-item text-sm">
                            <div class="flex font-bold">
                                <hc-icon name="coupon-2" class="mr-1 text-lightBlue" /><div>通行费</div>
                            </div>
                            <div class="jitems-center mt-1 w-full flex justify-between">
                                <span class="text-gray">年度收入</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].tollInflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                        <div class="cash-in-list-item text-sm">
                            <div class="flex items-center font-bold">
                                <img :src="totalPng" class="icon-avatar mr-1">
                                <div>其他收入</div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">年度收入</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].otherInflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mt-2 flex p-1 text-sm font-bold">
                        <hc-icon name="arrow-up" class="mr-1 text-orange" /><div>现金流出</div>
                        <span class="ml-2 mr-1 text-blue">共计：{{ yearFuns[selectIndex].outflowTotal }}</span><span class="ml-1 text-blue">万元</span>
                    </div>
                    <div class="cash-in-list1 mt-2 flex justify-between">
                        <div class="cash-in-list-item text-sm">
                            <div class="flex items-center font-bold">
                                <img :src="jianshePng" class="icon-avatar mr-1">
                                <div>建设期总投资额</div>
                            </div>
                            <div class="jitems-center mt-1 w-full flex justify-between">
                                <span class="text-gray">总投资</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].constructInvestOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                        <div class="cash-in-list-item text-sm">
                            <div class="flex items-center font-bold">
                                <img :src="sizePng" class="icon-avatar mr-1">
                                <div>建设期各年份投入比例</div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">投入比例</span>
                                <div class="ml-3 w-64">
                                    <el-input v-model="yearFuns[selectIndex].constructProportionOutflow" clearable placeholder="请输入(格式如：14:45:60)" :disabled="data?.isView" class="w-full" @input="(value) => validateInput(value, selectIndex)" />
                                </div>
                            </div>
                        </div>
                        <div class="cash-in-list-item text-sm">
                            <div class="flex items-center font-bold">
                                <img :src="jiechangPng" class="icon-avatar mr-1"><div>借款本金偿还</div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">年度偿还</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].borrowPrincipalOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="cash-in-list1 mt-4 flex justify-between">
                        <div class="cash-in-list-item text-sm">
                            <div class="flex font-bold">
                                <hc-icon name="percent" class="mr-1 text-lightBlue" /><div>借款利息偿还</div>
                            </div>
                            <div class="jitems-center mt-1 w-full flex justify-between">
                                <span class="text-gray">年度偿还</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].borrowInterestOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                        <div class="cash-in-list-item text-sm">
                            <div class="flex items-center font-bold">
                                <img :src="chengbenPng" class="icon-avatar mr-1">
                                <div>经营成本</div>
                               
                               
                                <span class="ml-2 mr-1 text-blue">共计：{{ yearFuns[selectIndex].costTotal }}</span><span class="ml-1 text-blue">万元</span>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">养护、小修费</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].operateMaintainOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">大修费</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].operateOverhaulOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">资本性支出</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].operateCapitalOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">运营管理费</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].operateOperationOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">其他费用</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].operateOtherOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                        <div class="cash-in-list-item text-sm">
                            <div class="flex items-center font-bold">
                                <img :src="shuijinPng" class="icon-avatar mr-1">
                                <div>运营期税金</div>
                            </div>
                            <div class="mt-1 w-full flex items-center justify-between">
                                <span class="text-gray">年度税金</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].operationTaxesOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="cash-in-list1 mt-2 flex justify-between">
                        <div class="cash-in-list-item text-sm">
                            <div class="flex font-bold">
                                <hc-icon name="bank-card" class="mr-1 text-purple" /><div>其他费用</div>
                            </div>
                            <div class="jitems-center mt-1 w-full flex justify-between">
                                <span class="text-gray">年度费用</span>
                                <div class="ml-3 w-64 flex items-center whitespace-nowrap">
                                    <HcInputNumber1 v-model="yearFuns[selectIndex].otherOutflow" clearable placeholder="请输入" :disabled="data?.isView" class="w-full" />
                                    <span class="ml-1 flex-shrink-0 font-900">万元</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </hc-card-item>
            </div>
            <div class="mt-4">
                <hc-card-item class="hac-card-item">
                    <template #header>
                        <div class="hac-card-title g">
                            <div class="w-[180px]">
                                <el-select v-model="carYearVal" filterable clearable block placeholder="请先选择运营期时间" @change="carYearClick">
                                    <el-option v-for="item in stageYearOptions1" :key="item.value" :label="item.label" :value="item.value" />
                                </el-select>
                            </div>
                            <span class="ml-2">车流量信息</span>
                        </div>
                    </template>
         
                    <div class="cash-in-list mt-2 flex flex-wrap justify-between">
                        <div v-for="(_, index) in 12" :key="index" class="cash-in-list-item mb-4 w-[48%] text-sm">
                            <div class="flex font-bold">
                                <div>{{ index + 1 }}月</div>
                            </div>
                            <div class="jitems-center mt-1 w-full flex justify-between">
                                <span class="text-gray">车流量</span>
                                <div class="ml-3 w-64 flex items-center">
                                    <HcInputNumber1 
                                        v-model="carList[carSelectIndex].numbers[index]" 
                                        clearable 
                                        placeholder="请输入" 
                                        :disabled="data?.isView"
                                        class="w-full"
                                    /><span class="ml-1 font-900">辆</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </hc-card-item>
            </div>
        </div>
        <div class="mt-4 text-center">
            <el-button type="info" style="background-color: white; color: black; border-color: white" @click="dialogClose">退出</el-button>
            <el-button type="primary" style="background-color: #2550A2; color: white; border-color: #2550A2" :loading="submitLoading" :disabled="data?.isView" @click="dialogSubmit">保存</el-button>
        </div>
    </hc-drawer>
</template>

<script setup>
import { computed, nextTick, ref, watch } from 'vue'
import jianshePng from '~src/assets/view/jianshe.png'
import sizePng from '~src/assets/view/size.png'
import jiechangPng from '~src/assets/view/jiechang.png'
import chengbenPng from '~src/assets/view/chengben.png'
import shuijinPng from '~src/assets/view/shuijin.png'
import totalPng from '~src/assets/view/total.png'
import { getDictionaryData } from '~src/utils/tools'
import { arrIndex, formValidate, getArrValue } from 'js-fast-way'
import projectApi from '~api/promanage/project'
import { getDictionary } from '~api/dictbiz.js'
import HcInputNumber1 from './input-number.vue'
const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
    disabled: {
        type: Boolean,
        default: false,
    },
})

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

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})
const stageYearOptions = ref([
{
        value: '1',
        label: '建设期',
    },
])
const stageYearOptions1 = ref([
  
])
const validateInput = (value, index) => {
    if (yearFuns.value && yearFuns.value[index]) {
        // 移除所有非数字和英文符号的字符
        const filteredValue = value.replace(/[^0-9:.-]/g, '')
        yearFuns.value[index].constructProportionOutflow = filteredValue
    }
}
const yearFuns = ref([
{

    year: stageYearOptions.value?.[0]?.value || '', // 设置默认年份选项的value值，如果没有则默认为空字符串

            tollInflow: '',
            otherInflow: '',
            constructInvestOutflow: '',
            constructProportionOutflow: '',
            borrowPrincipalOutflow: '',
            borrowInterestOutflow: '',
            operateMaintainOutflow: '',
            operateOverhaulOutflow: '',
            operateCapitalOutflow: '',
            operateOperationOutflow: '',
            operateOtherOutflow: '',
            operationTaxesOutflow: '',
            otherOutflow: '',
            inflowTotal:'',
            outflowTotal:'',
            costTotal:'',
        },
])
const carList = ref([{
    year: stageYearOptions1.value?.[0]?.value || '', // 设置默认年份
    numbers: Array(12).fill(''), // 初始化12个月份的数据，默认值为0
}])
// 添加 watch 来监听 stageYearOptions 的变化
watch(() => stageYearOptions.value, (newOptions) => {
    if (newOptions && newOptions.length > 0) {
        // 更新 yearFuns 的年份
        yearFuns.value = yearFuns.value.map(item => ({
            ...item,
            year: item.year || newOptions[0].value,
        }))
        
        // 更新 carList 的年份
        // carList.value = carList.value.map(item => ({
        //     ...item,
        //     year: item.year || newOptions[0].value,
        // }))
    }
}, { immediate: true })
// 添加 watch 来监听 stageYearOptions 的变化
watch(() => stageYearOptions1.value, (newOptions) => {
    if (newOptions && newOptions.length > 0) {
        // 更新 yearFuns 的年份
        // yearFuns.value = yearFuns.value.map(item => ({
        //     ...item,
        //     year: item.year || newOptions[0].value,
        // }))
        
        // 更新 carList 的年份
        carList.value = carList.value.map(item => ({
            ...item,
            year: item.year || newOptions[0].value,
        }))
    }
}, { immediate: true })



const betweenTime = ref(null)
const betweenTime1 = ref(null)
//监听
const baseForm = ref(props.data)
// const stageYearOptions = ref([
   
// ])
watch(() => props.data, (data) => {
  if (!data.id) {
    betweenTime.value = []
    betweenTime1.value = []
    carList.value = [{
    year: '',
    numbers: Array(12).fill(''), // 初始化12个月份的数据，默认值为0
}]
    yearFuns.value = [
{

            year: '',
            tollInflow: '',
            inflowTotal:'',
            outflowTotal:'',
            costTotal:'',
            otherInflow: '',
            constructInvestOutflow: '',
            constructProportionOutflow: '',
            borrowPrincipalOutflow: '',
            borrowInterestOutflow: '',
            operateMaintainOutflow: '',
            operateOverhaulOutflow: '',
            operateCapitalOutflow: '',
            operateOperationOutflow: '',
            operateOtherOutflow: '',
            operationTaxesOutflow: '',
            otherOutflow: '',
        },
]
baseForm.value = {}
stageYearOptions.value = [{
        value: '1',
        label: '建设期',
    
}]
    return
  }
    baseForm.value = data
    carList.value = data.list
    yearFuns.value = data.funds
    console.log(data, 'data')
    
    if (data['constructStartTime'] && data['constructEndTime']) {
        betweenTime.value = [data['constructStartTime'], data['constructEndTime']]

        if (stageYearVal.value) {
            return
        } else {
            betweenTimeUpdate({ arr:[data['operationStartTime'], data['operationEndTime']] })
        }

    }
    
    if (data['operationStartTime'] && data['operationEndTime']) {
        
        betweenTime1.value = [data['operationStartTime'], data['operationEndTime']]
     
        if (carYearVal.value) {
            return
        } else {
            betweenTimeUpdate1({ arr:[data['operationStartTime'], data['operationEndTime']] })
        }
    }
}, { deep: true })

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



//日期时间被选择
const betweenTimeUpdate = ({ arr, val, query }) => {

    
    if (arr) {
        // 开始时间
        if (arr[0]) {
            baseForm.value.constructStartTime = arr[0]
        }
        // 结束时间
        if (arr[1]) {
            baseForm.value.constructEndTime = arr[1]
        }
        
        // 生成年份区间选项
     
      
    } else {
        baseForm.value.constructStartTime = null
        baseForm.value.constructEndTime = null
        stageYearOptions.value = [
        {
                value: '建设期',
                label: '建设期',
            },
        ]
    }
}


//日期时间被选择
const betweenTimeUpdate1 = ({ arr, val, query }) => {

    
    betweenTime1.value = arr
    if (arr) {
        // 开始时间
        if (arr[0]) {
            baseForm.value.operationStartTime = arr[0]
        }
        // 结束时间
        if (arr[1]) {
            baseForm.value.operationEndTime = arr[1]
        }
          
        if (arr[0] && arr[1]) {
            const startYear = new Date(arr[0]).getFullYear()
     
            
            const endYear = new Date(arr[1]).getFullYear()
            const years = []
            for (let year = startYear; year <= endYear; year++) {
                years.push({
                    value: year,
                    label: `${year}年`,
                })
            }
            // stageYearOptions.value = years
            stageYearOptions.value = [{
                value: '建设期',
                label: '建设期',
            }, ...years]
            stageYearOptions1.value = years
            carYearVal.value = stageYearOptions1.value[0].value
       
            stageYearVal.value = stageYearOptions.value[0].value
            
          
            // if (stageYearVal.value) {
            //      stageYearClick(stageYearVal.value)
            // }
            //  if (carYearVal.value) {
            //      carYearClick(carYearVal.value)
            // }
            
        }
    } else {
        baseForm.value.constructStartTime = null
        baseForm.value.constructEndTime = null
    }
}
//设置数据
const setDataApi = async () => {
   await getProType()
   await getProRouteType()
   await getProStation()
   await getProOperationCompany()
}
//项目类型
const typeOptions = ref([])
const getProType = async () => {
    await getTypeListData(1, 'ibaProjectType')
  }
  const typeClick = async (val) => {

    await nextTick(() => {
          
            getTypeListData(val, 'ibaRouteType')
    })
    baseForm.value.routeType = ''
  
}
const getTypeListData = async (parentId, code) => {
        const { data } = await getDictionary({ parentId, code, type:2 })

        if (code === 'ibaProjectType') {
            typeOptions.value = getArrValue(data)
            return
        } else {
            routeOptions.value = getArrValue(data)
            return
        }
        
    
    
}
  //路线类型
const routeOptions = ref([])
const getProRouteType = async () => {
    await getTypeListData(baseForm.value.type, 'ibaRouteType')
  
}
//项目阶段
const stateOptions = ref([])
const getProStation = async () => {
    stateOptions.value = await getDictionaryData('ibaProjectStage', true)

}
//运营公司
const operationCompanyOptions = ref([])
const getProOperationCompany = async () => {

  
    const { error, code, data } = await projectApi.selectProjectOrCompanyList({ type: 2 })
    //处理数
    if (!error && code === 200) {
        operationCompanyOptions.value = getArrValue(data)
     
    } else {
        operationCompanyOptions.value = []
  
    }
}
const selectIndex = ref(0)
watch(
    () => [yearFuns.value[selectIndex.value].tollInflow, yearFuns.value[selectIndex.value].otherInflow],
    ([tollInflow, otherInflow]) => {
        yearFuns.value[selectIndex.value].inflowTotal = (tollInflow || 0) + (otherInflow || 0)
    },
    { immediate: true },
)
watch([
  () => yearFuns.value[selectIndex.value].operateMaintainOutflow,
  () => yearFuns.value[selectIndex.value].operateOverhaulOutflow,
  () => yearFuns.value[selectIndex.value].operateCapitalOutflow,
  () => yearFuns.value[selectIndex.value].operateOperationOutflow,
  () => yearFuns.value[selectIndex.value].operateOtherOutflow,
], () => {
    yearFuns.value[selectIndex.value].costTotal 
    = Number(yearFuns.value[selectIndex.value].operateMaintainOutflow || 0)
    + Number(yearFuns.value[selectIndex.value].operateOverhaulOutflow || 0)
    + Number(yearFuns.value[selectIndex.value].operateCapitalOutflow || 0)
    + Number(yearFuns.value[selectIndex.value].operateOperationOutflow || 0)
    + Number(yearFuns.value[selectIndex.value].operateOtherOutflow || 0)
}, { immediate: true })

watch([
  () => yearFuns.value[selectIndex.value].constructInvestOutflow,
  () => yearFuns.value[selectIndex.value].borrowPrincipalOutflow,
  () => yearFuns.value[selectIndex.value].borrowInterestOutflow,
  () => yearFuns.value[selectIndex.value].costTotal,
  () => yearFuns.value[selectIndex.value].operationTaxesOutflow,
  () => yearFuns.value[selectIndex.value].otherOutflow,
], () => {
yearFuns.value[selectIndex.value].outflowTotal 
  = Number(yearFuns.value[selectIndex.value].constructInvestOutflow || 0)
  + Number(yearFuns.value[selectIndex.value].borrowPrincipalOutflow || 0)
  + Number(yearFuns.value[selectIndex.value].borrowInterestOutflow || 0)
  + Number(yearFuns.value[selectIndex.value].costTotal || 0)
  + Number(yearFuns.value[selectIndex.value].operationTaxesOutflow || 0)
  + Number(yearFuns.value[selectIndex.value].otherOutflow || 0)
}, { immediate: true })
const stageYearClick = async (val) => {
    if (yearFuns.value[selectIndex]) {
        yearFuns.value[selectIndex].year = val
    }

    console.log(val, 'val11111')
    stageYearVal.value = val
    // await nextTick()
    selectIndex.value = arrIndex(stageYearOptions.value, 'value', val)
    console.log( selectIndex.value, '  selectIndex.value')
    
    if (!yearFuns.value[selectIndex.value]) {
        // 如果当前索引位置没有数据，初始化一个空对象
        yearFuns.value[selectIndex.value] = {
            year: val,
            inflowTotal:'',
            tollInflow: '',
            outflowTotal:'',
            costTotal:'',
            otherInflow: '',
            constructInvestOutflow: '',
            constructProportionOutflow: '',
            borrowPrincipalOutflow: '',
            borrowInterestOutflow: '',
            operateMaintainOutflow: '',
            operateOverhaulOutflow: '',
            operateCapitalOutflow: '',
            operateOperationOutflow: '',
            operateOtherOutflow: '',
            operationTaxesOutflow: '',
            otherOutflow: '',
        }
    } else {
        // yearFuns.value[selectIndex.value].year = val
    
        
        // yearFuns.value = baseForm.value.funds
        if (baseForm.value.id) {
           yearFuns.value = baseForm.value.funds
        }
    }
}

const stageYearVal = ref('')

const carYearVal = ref('')

const carSelectIndex = ref(0)// ... existing code ...
const carYearClick = (year) => {
    if (carList.value[carSelectIndex]) {
        carList.value[carSelectIndex].year = year
    }
    
     carSelectIndex.value = arrIndex(stageYearOptions1.value, 'value', year)
  
    if (!carList.value[carSelectIndex.value]) {
        // 如果当前索引位置没有数据，初始化一个新对象
        carList.value[carSelectIndex.value] = {
            year: year,
            numbers: Array(12).fill(''),
        }
    } else {
        // 如果对象已存在，只更新年份
        // carList.value[carSelectIndex.value].year = year
        if (baseForm.value.id) {
            carList.value[carSelectIndex.value].numbers = baseForm.value.list[carSelectIndex.value].numbers
            
        }

    }
}

// 在模板中的v-model绑定也需要相应修改
// ... existing code ...
//新增、编辑 显示
const formRef = ref(null)
const formRules = {
    projectName: { required: true, trigger: 'blur', message: '请输入路线名称' },
    operationCompany: { required: true, trigger: 'blur', message: '请选择运营公司' },
}

//新增、编辑提交
const submitLoading = ref(false)
const dialogSubmit = async () => {
    const formRes = await formValidate(formRef.value)
    if (!formRes) return false
    // 确保每个对象都有默认年份
    yearFuns.value = yearFuns.value.map(item => {
        if (!item || !item.year) {
            return {
                year: stageYearOptions.value[0].value,
                tollInflow: '',
                inflowTotal:'',
                outflowTotal:'',
                costTotal:'',
                otherInflow: '',
                constructInvestOutflow: '',
                constructProportionOutflow: '',
                borrowPrincipalOutflow: '',
                borrowInterestOutflow: '',
                operateMaintainOutflow: '',
                operateOverhaulOutflow: '',
                operateCapitalOutflow: '',
                operateOperationOutflow: '',
                operateOtherOutflow: '',
                operationTaxesOutflow: '',
                otherOutflow: '',
            }
        }
        return item
    })
 // 确保每个对象都有默认年份



for (let i = 0; i < yearFuns.value.length; i++) {

 if (!yearFuns.value[i]) {
  yearFuns.value[i] = {
                year: stageYearOptions.value[i].value,
                tollInflow: '',
                inflowTotal:'',
                outflowTotal:'',
                costTotal:'',
                otherInflow: '',
                constructInvestOutflow: '',
                constructProportionOutflow: '',
                borrowPrincipalOutflow: '',
                borrowInterestOutflow: '',
                operateMaintainOutflow: '',
                operateOverhaulOutflow: '',
                operateCapitalOutflow: '',
                operateOperationOutflow: '',
                operateOtherOutflow: '',
                operationTaxesOutflow: '',
                otherOutflow: '',
            }
  
 }
 
}


for (let i = 0; i < carList.value.length; i++) {

if (!carList.value[i]) {
    carList.value[i] = {
        year: stageYearOptions1.value[i]?.value || '',
        numbers: new Array(12).fill(''), // 初始化12个月份的数据，默认值为0
           }
 
}

}
  


    
    const params = {
        ...baseForm.value,
        list: carList.value,
        funds: yearFuns.value,
    }
    
  if (!baseForm.value.id) {
    submitLoading.value = true
        //发起请求
     const { error, code, msg } = await projectApi.add(params)   
    //判断状态
    submitLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
        //刷新页面
    //    setTimeout(()=>{
    //     window.location.reload()
    //    }, 1000)
        // baseForm.value = {}
       
        
    } else {
        window.$message.error(msg ?? '操作失败')
    }
    // dialogClose()
    emit('finish')
  } else {
    submitLoading.value = true
        //发起请求
     const { error, code, msg } = await projectApi.edit(params)   
    //判断状态
    submitLoading.value = false
    if (!error && code === 200) {
        window?.$message?.success(msg)
    //     setTimeout(()=>{
    //     window.location.reload()
    //    }, 1000)
        // baseForm.value = {}
       
        
    } else {
        window.$message.error(msg ?? '操作失败')
    }
    // dialogClose()
    emit('finish')
  }
}

//新增、编辑关闭
const dialogClose = () => {
    isShow.value = false
    // baseForm.value = {}
    emit('close')
   
}
</script>

<style lang="scss">
.hac-card-item.hc-card-item-box {
    background: white;
    .hc-card-item-header {
        .item-header, .item-extra {
            height: 100%;
        }
        .item-extra {
            margin-left: 14px;
        }
    }
}

.hac-card-title {
    color: #000;
    position: relative;
    display: flex;
    align-items: center;
    height: 100%;
    margin-left: 8px;
    &::before {
        content: '';
        position: relative;
        display: inline-block;
        width: 5px;
        height: 18px;
        border-radius: 10px;
        background-color: var(--el-color-primary-dark-2);
        right: 8px;
    }
}
.cash-in-list{
    width: 100%;
    .cash-in-list-item{
        padding: 10px;
        width: 48%;
        border: 1px solid #E6E6E6;
     
   }
}
.cash-in-list1{
    width: 100%;
    .cash-in-list-item{
        padding: 10px;
        width: 32%;
        border: 1px solid #E6E6E6;
     
   }
}
.cash-in-list2{
    width: 48%;
    .cash-in-list-item{
        padding: 10px;
        width: 32%;
        border: 1px solid #E6E6E6;
     
   }
}
.icon-avatar{
    width: 14px;
    height: 14px;
}
</style>
