<template>
    <HcTabsSimple :cur="tabsKey" :datas="tabsData" @tabClick="tabsClick">
        <template #tab-base>
            <HcCard scrollbar actionUi="text-center">
                <div class="hc-card-form-center">
                    <el-form ref="formBaseRef" :model="formBaseModel" :rules="formBaseRules" label-width="auto" size="large">
                        <el-form-item label="项目名称：" prop="projectId">
                            <el-select v-model="formBaseModel.projectId" block placeholder="项目名称">
                                <el-option v-for="item in projectList" :label="item.name" :value="item.id"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="成本测算总金额：">
                            <el-input v-model="formBaseModel.projectCostTotal" disabled/>
                        </el-form-item>
                        <el-form-item label="研发部成本总金额：">
                            <el-input v-model="formBaseModel.devCostTotal" disabled/>
                        </el-form-item>
                        <el-form-item label="业务部成本总金额：">
                            <el-input v-model="formBaseModel.businessCostTotal" disabled/>
                        </el-form-item>
                        <el-form-item label="市场部成本总金额：">
                            <el-input v-model="formBaseModel.marketCostTotal" disabled/>
                        </el-form-item>
                        <el-form-item label="维护部成本总金额：">
                            <el-input v-model="formBaseModel.maintainCostTotal" disabled/>
                        </el-form-item>
                        <el-form-item label="外包劳务成本总金额：">
                            <el-input v-model="formBaseModel.outsourceCostTotal" disabled/>
                        </el-form-item>
                        <el-form-item label="管理费成本总金额：">
                            <el-input v-model="formBaseModel.manageCostTotal" disabled/>
                        </el-form-item>
                    </el-form>
                </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="submitForm" :loading="submitLoaing">
                        <HcIcon name="check-double"/>
                        <span>提交保存</span>
                    </el-button>
                </template>
            </HcCard>
        </template>
        <template #tab-table>
            <HcCard actionUi="text-center" :title="formBaseModel.projectName">
                <template #extra>
                    <HcNewSwitch :datas="tabTab" :keys="tabKey" @change="tabChange" :round="false"/>
                
          
                </template>
              
                <HcTable :isIndex="false" :column="tableColumn" :datas="tableData">

                    <template #costType="{row,index}">  
                            <el-select  v-model="row.costType" block placeholder="请选择">
                                <el-option v-for="item in costTypeList" :label="item.dictName" :value="item.dictValue"/>
                             </el-select>
                    </template>
                    <template #projectProcess="{row,index}">
                        <el-select  v-model="row.projectProcess" block placeholder="请选择">
                                <el-option v-for="item in processList" :label="item.name" :value="item.id"/>
                         </el-select>
                    </template>
                    <template #budgetType="{row,index}">
                        <el-select v-model="row.budgetType" @change="budgetTypeChange">
                            <el-option v-for="item in budgetTypeList" :label="item.dictName" :value="item.dictValue"/>
                        </el-select>
                    </template>
                    <template #taskDetail="{row,index}">
                        <el-select v-model="row.taskDetail">
                            <el-option v-for="item in taskDetailList" :label="item.dictName" :value="item.dictValue"/>
                        </el-select>
                    </template>
                    <template #budgetDays="{row,index}">
                        <el-input v-model="row.budgetDays"/>
                    </template>
                    <template #postType="{row,index}">
                        <el-select v-model="row.postType">
                            <el-option v-for="item in postTypeList" :label="item.dictName" :value="item.code"/>
                        </el-select>
                    </template>
                    
                    <template #staffCount="{row,index}">
                        <el-input v-model="row.staffCount"/>
                    </template>
                    <template #budgetStaffCost="{row,index}">
                        <el-input v-model="row.budgetStaffCost" disabled/>
                    </template>
                    <template #budgetTravelExpense="{row,index}">
                        <el-input v-model="row.budgetTravelExpense" />
                    </template>
                    <template #outsourceUnitPrice="{row,index}">
                        <el-input v-model="row.outsourceUnitPrice"/>
                    </template>
                    <template #outsourcePeopleCount="{row,index}">
                        <el-input v-model="row.outsourcePeopleCount"/>
                    </template>
                    <template #outsourceCountMoney="{row,index}">
                        <el-input v-model="row.outsourceCountMoney" disabled />
                    </template>
                    <template #otherBudgetMoney="{row,index}">
                        <el-input v-model="row.otherBudgetMoney" />
                    </template>
                <template #budgetCountMoney="{row,index}">
                        <el-input v-model="row.budgetCountMoney"/>
                    </template> 
                   <template #budgetRemark="{row,index}">
                        <el-input v-model="row.budgetRemark" />
                    </template>
                    <template #key15="{row,index}">
                        <el-input v-model="row.key15"/>
                    </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>
                <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="submitForm" :loading="submitLoaing"> 
                        <HcIcon name="check-double"/>
                        <span>提交保存</span>
                    </el-button>
                </template>
            </HcCard>
        </template>
    </HcTabsSimple>
</template>

<script setup>
import {onActivated, ref,watch} from "vue";
import {useRouter, useRoute} from 'vue-router'
import costApi from '~api/project/cost.js';
import {getArrValue,getObjValue,formValidate} from "js-fast-way"
//初始变量
const router = useRouter()
const useRoutes = useRoute()
const dataId = ref(useRoutes?.query?.id ?? '')

//缓存页面被激活时
onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
  //清除数据
    tableData.value=[{}]
    constructUnitData.value=[]
    supervisorUnitData.value=[]
    bulidUnitData.value=[]
    tabsKey.value = 'base'
    tabKey.value='construction'
    getBudgetTypeList()
    if(dataId.value.length>0){
        getBudgetStatsById()
        getProjectList(2)
    }else{
        getProjectList(1)
        formBaseModel.value={}
    }

    getCostTypeDict()
   
    getPostDict()


  
   
    
})


const projectList=ref([])
//获取项目下拉框
const getProjectList=async(type)=>{
    const {error, code, data} = await costApi.getProjectList({type})
    if (!error && code === 200) {
        projectList.value=getArrValue(data)

    } else {
        projectList.value={}
    }
}
//获取费用分类
const costTypeList=ref([])
const getCostTypeDict=async(type)=>{
    const {error, code, data} = await costApi.getCostTypeDict()
    if (!error && code === 200) {
        costTypeList.value=getArrValue(data)

    } else {
        costTypeList.value={}
    }
}
//获取项目环节
const processList=ref([])
const getProcessList=async(projectId)=>{
    const {error, code, data} = await costApi.getProcessList({projectId:projectId})
    if (!error && code === 200) {
        processList.value=getArrValue(data)

    } else {
        processList.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 taskDetailList=ref([])
const budgetTypeChange=async(val)=>{
    let id=''
    budgetTypeList.value.forEach((ele)=>{
        if(ele.dictValue===val){
            id=ele.id
        }
    })
    const {error, code, data} = await costApi.getChlidList({parentId:id,type:1})
    if (!error && code === 200) {
        taskDetailList.value=getArrValue(data)

    } else {
        taskDetailList.value={}
    }
}
//获取岗位分类postTypeList
const postTypeList=ref([])
const getPostDict=async(type)=>{
    const {error, code, data} = await costApi.getPostDict()
    if (!error && code === 200) {
        postTypeList.value=getArrValue(data)
        postTypeList.value.forEach((ele)=>{
            ele.code=parseInt(ele.code)
        })


    } else {
        postTypeList.value={}
    }
}
//测算表格数据
const constructUnitData=ref([])
const bulidUnitData=ref([])
const supervisorUnitData=ref([])
//获取详情
const getBudgetStatsById=async()=>{
    const {error, code, data} = await costApi.getBudgetStatsById({id: dataId.value})
    if (!error && code === 200) {
        formBaseModel.value=getObjValue(data)
        tableData.value= formBaseModel.value.constructUnit.length>0?formBaseModel.value.constructUnit:originTableData.value
        constructUnitData.value=formBaseModel.value.constructUnit
        bulidUnitData.value=formBaseModel.value.buildUnit
        supervisorUnitData.value=formBaseModel.value.supervisorUnit

    } else {
        formBaseModel.value={}
    }
}
//选项卡
const tabsKey = ref('base')
const tabsData = ref([
    {icon: 'file-list-3', label: '基础信息', key: 'base'},
    {icon: 'file-list-2', label: '成本测算', key: 'table'},
])
const tabsClick = (key) => {
   
    if(!formBaseModel.value.projectId){
        window.$message.warning('请先在基础信息栏选择项目')
    }else{
        if(key==='table'){
            tabsKey.value = key
            getProcessList(formBaseModel.value.projectId)

        }
    }
 

}



//任务操作数据
const formBaseRef = ref(null)
const formBaseModel = ref({})
const formBaseRules = {
    projectId: {
        required: true,
        trigger: 'blur',
        message: "请选择项目名称"
    },
}

//类型tab数据和相关处理
const tabKey = ref('construction')

const tabTab = ref([
    {key: 'bulid', name: '施工单位成本'},
    {key: 'supervision', name: '监理单位成本'},
    {key: 'construction', name: '建设单位成本'}
]);
const tabChange = ({key}) => {
    tabKey.value = key
    console.log(key,'key');
    console.log(tableData.value,'tableData.value');
    if(key=='supervision'){
        tableData.value=supervisorUnitData.value.length>0?supervisorUnitData.value:originTableData.value
        formBaseModel.value.supervisorUnit=tableData.value
    }else if(key=='construction'){
        tableData.value=constructUnitData.value.length>0?constructUnitData.value:originTableData.value
        formBaseModel.value.constructUnit=tableData.value
        console.log( formBaseModel.value.constructUnit,' formBaseModel.value.constructUnit');
    }else if(key=='bulid'){
        console.log(bulidUnitData.value,'=bulidUnitData.value');
        tableData.value=bulidUnitData.value.length>0?bulidUnitData.value:originTableData.value
        formBaseModel.value.buildUnit=tableData.value
    }
 
}


//成本测算表格
const tableColumn = [
    {key: 'costType', name: '费用分类', width: '160', align: 'center'},
    {key: 'projectProcess', name: '项目环节', width: '160', align: 'center'},
    {key: 'budgetType', name: '预算类型', width: '160', align: 'center'},
    {key: 'taskDetail', name: '任务明细', width: '160',  align: 'center'},
    {key: 'budgetDays', name: '预计工作量(小数/整数/天)', width: '160',  align: 'center'},
    {key: 'postType', name: '投入岗位类型(日单价)', width: '160', align: 'center'},
    {key: 'staffCount', name: '投入人员数量', width: '160', align: 'center'},
    {key: 'budgetStaffCost', name: '预计人工成本(元)', width: '160', align: 'center'},
    {key: 'budgetTravelExpense', name: '预计差旅费(元)', width: '160', align: 'center'},
    {key: 'outsourceUnitPrice', name: '外包单价', width: '160', align: 'center'},
    {key: 'outsourcePeopleCount', name: '外包数量', width: '160', align: 'center'},
    {key: 'outsourceCountMoney', name: '外包金额', width: '160', align: 'center'},
    {key: 'otherBudgetMoney', name: '其他预算金额', width: '160', align: 'center'},
    {key: 'budgetCountMoney', name: '总预算金额', width: '160', align: 'center'},
    {key: 'budgetRemark', name: '测算备注', width: '160', align: 'center'},
    {key: 'action', name: '操作', width: '200', align: 'center', fixed: 'right'},
]
const tableData = ref([{}])
//深度监听
watch(() => [
  tableData.value,
], ([data]) => {
   if(data!=={}&&data.length>0){
    budgetTypeChange(data[0].budgetType)
   }
//    
}, {deep: true})
const originTableData=ref([ {}])
const addRow=()=>{
    tableData.value.push({})
}
const delRow=(index)=>{
    tableData.value.splice(index, 1)
 
}
//取消并返回
const goBackClick = () => {
    router.back()
}
//保存submitForm
const submitLoaing=ref(false)
const submitForm=async()=>{
    console.log(formBaseModel.value,'formBaseModel.value');
   if(tabKey.value='construction'){
        formBaseModel.value.constructUnit=tableData.value
   }
    const res = await formValidate(formBaseRef.value)
    if(res){
        submitLoaing.value=true
        const {error, code, data,msg} = await costApi.AddOrUpdate( formBaseModel.value)
        submitLoaing.value=false
        if (!error && code === 200) {
        window.$message.success(msg)
        } 
    }

}


</script>

<style lang="scss" scoped>
.hc-card-form-center {
    position: relative;
    width: 80%;
    margin-left: 10%;
    margin-top: 10%;
}
</style>
