<template>
    <HcCard action-ui="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 v-model="editableTabsValue" type="border-card" class="form-tabs" @tab-change="changeTab">
                <el-tab-pane label="年度预算收入">
                    <HcTable :is-index="false" :column="tableColumn" :datas="incomeTable">
                        <template #projectId="{ row, index }">
                            <el-select v-model="row.projectId" style="width: 100%;">
                                <el-option v-for="item in projectData" :label="item.name" :value="item.id" />
                            </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 :getdata="getprojectType(row)" />
                        </template>
                        <template #contractTypeValue="{ row, index }">
                            <el-input v-model="row.contractTypeValue" disabled :getdata="getprojectType(row)" />
                        </template>
                        <template #predictSignDate="{ row, index }">
                            <el-date-picker v-model="row.predictSignDate" class="block" format="YYYY-MM-DD" type="date" value-format="YYYY-MM-DD" />
                        </template>
                        <template #predictContractMoney="{ row, index }">
                            <el-input v-model="row.predictContractMoney" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #predictAnnualReturned="{ row, index }">
                            <el-input v-model="row.predictAnnualReturned" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </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 :is-index="false" :column="tableColumn1" :datas="costTable">
                        <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" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #february="{ row, index }">
                            <el-input v-model="row.february" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #march="{ row, index }">
                            <el-input v-model="row.march" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #april="{ row, index }">
                            <el-input v-model="row.april" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #may="{ row, index }">
                            <el-input v-model="row.may" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #june="{ row, index }">
                            <el-input v-model="row.june" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #july="{ row, index }">
                            <el-input v-model="row.july" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #august="{ row, index }">
                            <el-input v-model="row.august" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #september="{ row, index }">
                            <el-input v-model="row.september" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #october="{ row, index }">
                            <el-input v-model="row.october" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #november="{ row, index }">
                            <el-input v-model="row.november" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </template>
                        <template #december="{ row, index }">
                            <el-input v-model="row.december" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                        </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(row, index)">
                                <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 :loading="saveLoaing" @click="saveClick">
                <HcIcon name="check-double" />
                <span>提交保存</span>
            </el-button>
        </template>
    </HcCard>
</template>

<script setup>
import { nextTick, onActivated, onDeactivated, ref, watch } from 'vue'
import { useRoute, useRouter } 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 { formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { getDictInfo, getProjectList } from '~api/other'
const router = useRouter()
const useRoutes = useRoute()
const dataId = ref(useRoutes?.query?.id ?? '')
const dataType = ref(useRoutes?.query?.type ?? '')
//页面激活
onActivated(() => {
    editableTabsValue.value = '0'
    setFormTabsStyle()
    windowResize()
    dataId.value = useRoutes?.query?.id ?? ''
    dataType.value = useRoutes?.query?.type ?? ''
    if (dataId.value.length > 0) {
        getDetail()
    } else {
       formModel.value = {}
        incomeTable.value = [{}]
        costTable.value = [{}]
        betweenTime.value = []
    }
    getProjectData()
    getIncomeType()
    getBudgetTypeList()
})
const costTable = ref([])
const incomeTable = ref([])
//深度监听
watch(() => [
    costTable.value,
    incomeTable.value,
], ([cost, income]) => {
    formModel.value.incomeList = cost
    formModel.value.disburseList = income
 
}, { deep: true })
const getDetail = async () => {
    const { error, code, data } = await annualApi.getAnnualBudget({ id:dataId.value })
    if (!error && code === 200) {
        formModel.value = getObjValue(data)
        incomeTable.value = data?.incomeList.length > 0 ? data?.incomeList : [{}]
        costTable.value = data?.disburseList.length > 0 ? data?.disburseList : [{}]
        
        betweenTime.value[0] = data['budgetStartTime']
        betweenTime.value[1] = data['budgetEndTime']
       
    } else {
        formModel.value = {}
    }
}

//获取项目数据
const projectData = ref([])
const getProjectData = async () => {
    const { error, code, data } = await annualApi.getProjectList()
    //判断状态
    if (!error && code === 200) {
        projectData.value = getArrValue(data)
    } else {
        projectData.value = []
    }
}
const getprojectType = (row)=>{
    projectData.value.forEach((ele)=>{
        if (row.projectId === ele.id) {
            row.contractTypeValue = ele.contractTypeValue
            row.projectTypeValue = ele.projectTypeValue
        }
    })
}
//收入类型字典
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 = {
    name: [{ required: true, message: '请输入预算名称', trigger: 'change' }],
}

//日期时间被选择
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()
    })
}
//tabs切换
const editableTabsValue = ref('0')
//获取数据
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' },
]


//切换tab页
const changeTab = (val)=>{
    console.log(val, 'val')
    console.log(incomeTable.value, 'incomeTable')
    console.log(costTable.value, 'incomeTable')
}

const tableData = ref([
    { id: 1 }, { id: 2 },
])
const addRow = ()=>{
    incomeTable.value.push({})
}
const delRow = (row, index)=>{
    incomeTable.value.splice(index, 1)
   if (incomeTable.value.length == 0) {
        incomeTable.value.push({})
    }
 
}
const addRow1 = ()=>{
    costTable.value.push({})
}
const delRow1 = (row, index)=>{
    costTable.value.splice(index, 1)
    if (costTable.value.length == 0) {
        costTable.value.push({})
    }
 
}
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)
        router.push({
            name: 'program-annual',
        })
    } 

}
//修改
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)
       router.push({
        name: 'program-annual',
       })
    } 

}
const isEmptyObj = (obj)=> {
    let arr = Object.keys(obj)
    return (arr.length == 0)

}  
//提交保存
const saveLoaing = ref(false)
const saveClick = async () => {
    const res = await formValidate(formRef.value)

    formModel.value.incomeList = incomeTable.value
    formModel.value.disburseList = costTable.value
    if (res) {
        //限制空数据提交
        formModel.value.disburseList = formModel.value.disburseList.filter((item)=>!isEmptyObj(item))
        formModel.value.incomeList = formModel.value.incomeList.filter((item)=>!isEmptyObj(item))

        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>
