<template>
    <HcCard actionUi="text-center">
        <HcCardItem id="hc-program-annual-form-card-item" class="hc-program-annual-form-card-item">
            <el-form ref="formRef" inline :model="formModel" :rules="formRules">
                <div>
                    <el-form-item label="预算名称" prop="name" class="w-1/2 mr-6">
                        <el-input v-model="formModel.name" placeholder="请输入预算名称" />
                    </el-form-item>
                    <el-form-item label="预算起止时间" prop="time">
                        <HcDatePicker :dates="betweenTime" clearable @change="betweenTimeUpdate"/>
                    </el-form-item>
                </div>
                <div>
                    <el-form-item label="合同" prop="annualContractTarget">
                        <el-tooltip content="年度合同指标">
                            <el-input v-model="formModel.annualContractTarget" placeholder="年度合同指标" disabled/>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="利润" prop="annualProfitTarget">
                        <el-tooltip content="年度利润指标">
                            <el-input v-model="formModel.annualProfitTarget" placeholder="年度利润指标" disabled/>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="预算" prop="totalBudget">
                        <el-tooltip content="总经营预算">
                            <el-input v-model="formModel.totalBudget" placeholder="总经营预算" disabled>
                                <template #append>元</template>
                            </el-input>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="工资" prop="staffCost">
                        <el-tooltip content="人员成本">
                            <el-input v-model="formModel.staffCost" placeholder="人员成本" disabled>
                                <template #append>元</template>
                            </el-input>
                        </el-tooltip>
                    </el-form-item>
                    <el-form-item label="综合" prop="manageDisburse">
                        <el-tooltip content="管理支出">
                            <el-input v-model="formModel.manageDisburse" placeholder="管理支出" disabled>
                                <template #append>元</template>
                            </el-input>
                        </el-tooltip>
                    </el-form-item>
                </div>
            </el-form>
        </HcCardItem>
        <div class="hc-program-annual-form-tabs" :style="tabsStyle">
            <el-tabs type="border-card" class="form-tabs">
                <el-tab-pane label="年度预算收入">
                    <HcTable :isIndex="false" :column="tableColumn" :datas="formModel.incomeList">
                        <template #projectId="{row,index}">
                            <el-select v-model="row.projectId">
                                <el-option v-for="item in projectData" :label="item.projectName" :value="item.projectId"/>
                            </el-select>
                        </template>
                        <template #incomeType="{row,index}">
                            <el-select v-model="row.incomeType">
                                <el-option v-for="item in incomeTypeData" :label="item.dictName" :value="item.dictValue"/>
                                
                            </el-select>
                        </template>
                        <template #projectTypeValue="{row,index}">
                            <el-input v-model="row.projectTypeValue" disabled/>
                        </template>
                        <template #contractTypeValue="{row,index}">
                            <el-input v-model="row.contractTypeValue" disabled/>
                        </template>
                        <template #predictSignDate="{row,index}">
                            <el-date-picker class="block" v-model="row.predictSignDate" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD"/>
                        </template>
                        <template #predictContractMoney="{row,index}">
                            <el-input v-model="row.predictContractMoney"/>
                        </template>
                        <template #predictAnnualReturned="{row,index}">
                            <el-input v-model="row.predictAnnualReturned"/>
                        </template>
                        <template #action="{row,index}">
                            <el-button size="small" type="primary" @click="addRow">
                                <HcIcon name="add"/>
                                <span>新增</span>
                            </el-button>
                            <el-button size="small" type="danger" @click="delRow(index)">
                                <HcIcon name="delete-bin"/>
                                <span>删除</span>
                            </el-button>
                        </template>
                    </HcTable>
                </el-tab-pane>
                <el-tab-pane label="年度预算支出">
                    <HcTable :isIndex="false" :column="tableColumn1" :datas="formModel.disburseList">
                        <template #budgetSubject="{row,index}">
                            <el-select v-model="row.budgetSubject">
                                <el-option v-for="item in budgetTypeList" :label="item.dictName" :value="item.dictValue"/>
                            </el-select>
                        </template>
                        <template #secondSubject="{row,index}">
                            <el-select v-model="row.secondSubject" :getdata="getsecondBudgetTypeList(row.budgetSubject,index)">
                                <el-option v-for="item in secondBudgetTypeList[index]" :label="item.dictName" :value="item.dictValue"/>
                            </el-select>
                        </template>
                        <template #january="{row,index}">
                            <el-input v-model="row.january"/>
                        </template>
                        <template #february="{row,index}">
                            <el-input v-model="row.february"/>
                        </template>
                        <template #march="{row,index}">
                            <el-input v-model="row.march"/>
                        </template>
                        <template #april="{row,index}">
                            <el-input v-model="row.april"/>
                        </template>
                        <template #may="{row,index}">
                            <el-input v-model="row.may"/>
                        </template>
                        <template #june="{row,index}">
                            <el-input v-model="row.june"/>
                        </template>
                        <template #july="{row,index}">
                            <el-input v-model="row.july"/>
                        </template>
                        <template #august="{row,index}">
                            <el-input v-model="row.august"/>
                        </template>
                        <template #september="{row,index}">
                            <el-input v-model="row.september"/>
                        </template>
                        <template #october="{row,index}">
                            <el-input v-model="row.october"/>
                        </template>
                        <template #november="{row,index}">
                            <el-input v-model="row.november"/>
                        </template>
                        <template #december="{row,index}">
                            <el-input v-model="row.december"/>
                        </template>
                        <template #action="{row,index}">
                            <el-button size="small" type="primary" @click="addRow1">
                                <HcIcon name="add"/>
                                <span>新增</span>
                            </el-button>
                            <el-button size="small" type="danger"  @click="delRow1">
                                <HcIcon name="delete-bin"/>
                                <span>删除</span>
                            </el-button>
                        </template>
                    </HcTable>
                </el-tab-pane>
            </el-tabs>
        </div>
        <template #action>
            <el-button size="large" type="info" hc-btn @click="goBackClick">
                <HcIcon name="arrow-go-back"/>
                <span>取消并返回</span>
            </el-button>
            <el-button size="large" type="primary" hc-btn @click="saveClick" :loading="saveLoaing">
                <HcIcon name="check-double"/>
                <span>提交保存</span>
            </el-button>
        </template>
    </HcCard>
</template>

<script setup>
import {nextTick, onActivated, ref, onDeactivated,watch} from "vue"
import {useRouter, useRoute} from 'vue-router'
import annualApi from '~api/program/annual.js';
import costApi from '~api/project/cost.js';
import {getChildList} from '~api/system/parameter.js';
import {getArrValue,getObjValue} from "js-fast-way"
import {getProjectList, getDictInfo} from "~api/other";
const router = useRouter()
const useRoutes = useRoute()
const dataId = ref(useRoutes?.query?.id ?? '')
const dataType = ref(useRoutes?.query?.type ?? '')
//页面激活
onActivated(() => {
    setFormTabsStyle()
    windowResize()
    dataId.value = useRoutes?.query?.id ?? ''
    dataType.value = useRoutes?.query?.type ?? ''
    if(dataId.value.length>0){
        getDetail()
    }else{
       
        formModel.value={disburseList:[{}],incomeList:[{}]}
        betweenTime.value=[]
    }
    getProjectData()
    getIncomeType()
    getBudgetTypeList()
})

const getDetail = async() => {
    const {error, code, data} = await annualApi.getAnnualBudget({id:dataId.value})
    if (!error && code === 200) {
        console.log(data,'data');
        formModel.value=getObjValue(data)
  
        betweenTime.value[0]=data['budgetStartTime']
        betweenTime.value[1]=data['budgetEndTime']
    } else {
        formModel.value={}
    }
}

//获取项目数据
const projectData = ref([])
const getProjectData = async () => {
    const {error, code, data} = await getProjectList()
    //判断状态
    if (!error && code === 200) {
        projectData.value = getArrValue(data)
    } else {
        projectData.value = []
    }
}
//收入类型字典
const incomeTypeData = ref([])
const getIncomeType = async () => {
    const {error, code, data} = await getDictInfo('project_income_type')
    //判断状态
    if (!error && code === 200) {
        incomeTypeData.value = getArrValue(data)
    } else {
        incomeTypeData.value = []
    }
}
//获取预算分类getSecondSubject
const budgetTypeList=ref([])
const getBudgetTypeList=async()=>{
    const {error, code, data} = await costApi.getSecondSubject()
    if (!error && code === 200) {
        budgetTypeList.value=getArrValue(data)
     

    } else {
        budgetTypeList.value={}
    }
}
const secondBudgetTypeList=ref({})
const getsecondBudgetTypeList=async(val,index)=>{
    let id=''
    budgetTypeList.value.forEach((ele)=>{
        if(ele.dictValue===val){
            id=ele.id
        }
    })
    if(id.length>0){
        const {error, code, data} = await costApi.getChlidList({parentId:id,type:1})
        if (!error && code === 200) {
            secondBudgetTypeList.value[index]=getArrValue(data)
        } else {
            secondBudgetTypeList.value[index]=[]
           
        }
    }
   
}


//设置表单tabs样式
const tabsStyle = ref('')
const setFormTabsStyle = () => {
    //处理为响应式高度
    nextTick(() => {
        const cardItemHeight = document.getElementById('hc-program-annual-form-card-item')?.offsetHeight
        tabsStyle.value = 'height: calc(100% - ' + cardItemHeight + 'px)'
    })
}

//顶部表单数据
const formRef = ref(null)
const formModel = ref({
    key1: '', key2: '', key3: '', key4: '', key5: '',
})
const formRules = {}

//日期时间被选择
const betweenTime = ref([])
const betweenTimeUpdate = ({arr, query}) => {
    betweenTime.value = arr
    formModel.value.budgetStartTime = arr[0]
    formModel.value.budgetEndTime = arr[1] 
}

//监听浏览器窗口变化
const windowResize = () => {
    window.addEventListener("resize", resizeEvent);
}
const resizeEvent = () => {
    window.requestAnimationFrame(() => {
        setFormTabsStyle()
    })
}

//获取数据
const tableColumn = [
    {key: 'projectId', name: '项目名称', minWidth: '180', align: 'center'},
    {key: 'incomeType', name: '收入类别', width: '180', align: 'center'},
    {key: 'projectTypeValue', name: '项目类别', width: '180', align: 'center'},
    {key: 'contractTypeValue', name: '产品线', width: '180', align: 'center'},
    {key: 'predictSignDate', name: '预计签单时间', width: '220', align: 'center'},
    {key: 'predictContractMoney', name: '预计新签合同额', width: '180', align: 'center'},
    {key: 'predictAnnualReturned', name: '预计本年度回款额', width: '180', align: 'center'},
    {key: 'action', name: '操作', width: '200', align: 'center', fixed: 'right'},
]
const tableData = ref([
    {id: 1}, {id: 2},
])
const addRow=()=>{
    formModel.value.incomeList.push({})
}
const delRow=(index)=>{
    formModel.value.incomeList.splice(index, 1)
 
}
const addRow1=()=>{
    formModel.value.disburseList.push({})
}
const delRow1=(index)=>{
    formModel.value.disburseList.splice(index, 1)
 
}
const tableColumn1 = [
    {key: 'budgetSubject', name: '预算科目（一级）', minWidth: '180', align: 'center'},
    {key: 'secondSubject', name: '二级科目', minWidth: '180', align: 'center'},
    {key: 'january', name: '1月', width: '100', align: 'center'},
    {key: 'february', name: '2月', width: '100', align: 'center'},
    {key: 'march', name: '3月', width: '100', align: 'center'},
    {key: 'april', name: '4月', width: '100', align: 'center'},
    {key: 'may', name: '5月', width: '100', align: 'center'},
    {key: 'june', name: '6月', width: '100', align: 'center'},
    {key: 'july', name: '7月', width: '100', align: 'center'},
    {key: 'august', name: '8月', width: '100', align: 'center'},
    {key: 'september', name: '9月', width: '100', align: 'center'},
    {key: 'october', name: '10月', width: '100', align: 'center'},
    {key: 'november', name: '11月', width: '100', align: 'center'},
    {key: 'december', name: '12月', width: '100', align: 'center'},
    {key: 'action', name: '操作', width: '200', align: 'center', fixed: 'right'},
]
const tableData2 = ref([
    {id: 1}, {id: 2},
])


//返回
const goBackClick = () => {
    router.back()
}

//新增
const addAnnualBudget=async(obj)=>{
    console.log(obj,'新增');
    saveLoaing.value=true;
    const {error, code, data,msg} = await annualApi.addAnnualBudget( obj)
    saveLoaing.value=false;
    if (!error && code === 200) {
        window.$message.success(msg)
    } 

}
//修改
const updateAnnualBudget=async(obj)=>{
    saveLoaing.value=true;
    const {error, code, data,msg} = await annualApi.updateAnnualBudget( obj)
    saveLoaing.value=false;
    if (!error && code === 200) {
       window.$message.success(msg)
    } 

}
//提交保存
const saveLoaing=ref(false)
const saveClick = () => {
    if(formModel.value.disburseList[0]={}){
        formModel.value.disburseList=[]
    }else if(formModel.value.incomeList[0]={}){
        formModel.value.incomeList=[]
    }
    if(dataType.value=='edit'){
      updateAnnualBudget(formModel.value)
    }else{
        addAnnualBudget(formModel.value)
    }
}

//被卸载时
onDeactivated(() => {
    window.removeEventListener("resize",resizeEvent);
})
</script>

<style lang="scss" scoped>
.hc-program-annual-form-card-item {
    height: auto;
}
.hc-program-annual-form-tabs {
    position: relative;
    padding-top: 24px;
    .el-tabs.form-tabs {
        height: 100%;
    }
}
</style>

<style lang="scss">
.hc-program-annual-form-tabs .el-tabs.form-tabs .el-tabs__content {
    height: calc(100% - 39px);
    .el-tab-pane {
        height: 100%;
    }
}
</style>
