<template>
    <HcTabsSimple :cur="tabsKey" :datas="tabsData" @tab-click="tabsClick">
        <template #tab-base>
            <HcCard scrollbar action-ui="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" :key="item.id" :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 :loading="submitLoaing" @click="submitForm">
                        <HcIcon name="check-double" />
                        <span>提交保存</span>
                    </el-button>
                </template>
            </HcCard>
        </template>
        <template #tab-table>
            <HcCard action-ui="text-center" :title="formBaseModel.projectName">
                <template #extra>
                    <HcNewSwitch :datas="tabTab" :keys="tabKey" :round="false" @change="tabChange" />
                </template>
              
                <HcTable :is-index="false" :column="tableColumn" :datas="tableData">
                    <template #deptId="{ row }">  
                        <el-select v-model="row.deptId" block placeholder="请选择" :disabled="!row.isEdit">
                            <el-option v-for="item in departMent" :key="item.id" :label="item.deptName" :value="item.id" />
                        </el-select>
                    </template>
                    <template #costType="{ row }">  
                        <el-select v-model="row.costType" block placeholder="请选择" :disabled="!row.isEdit">
                            <el-option v-for="item in costTypeList" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
                        </el-select>
                    </template>
                    <template #projectProcess="{ row }">
                        <el-select v-model="row.projectProcess" block placeholder="请选择" :disabled="!row.isEdit">
                            <el-option v-for="item in processList" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </template>
                    <template #budgetType="{ row }">
                        <el-select v-model="row.budgetType" :disabled="!row.isEdit">
                            <el-option v-for="item in budgetTypeList" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
                        </el-select>
                    </template>
                    <template #taskDetail="{ row, index }">
                        <el-select v-model="row.taskDetail" :getdata="budgetTypeChange(row?.budgetType, index)" :disabled="!row.isEdit">
                            <el-option v-for="item in taskDetailList[index]" :key="item.dictValue" :label="item.dictName" :value="item.dictValue" />
                        </el-select>
                    </template>
                    <template #budgetDays="{ row }">
                        <el-input v-model="row.budgetDays" :disabled="!row.isEdit" />
                    </template>
                    <template #postType="{ row }">
                        <el-select v-model="row.postType" :disabled="!row.isEdit">
                            <el-option v-for="item in postTypeList" :key="item.id" :label="item.dictName" :value="item.id" />
                        </el-select>
                    </template>
                    
                    <template #staffCount="{ row }">
                        <el-input v-model="row.staffCount" :disabled="!row.isEdit" />
                    </template>
                    <template #budgetStaffCost="{ row }">
                        <el-input v-model="row.budgetStaffCost" disabled />
                    </template>
                    <template #budgetTravelExpense="{ row }">
                        <el-input v-model="row.budgetTravelExpense" :disabled="!row.isEdit" />
                    </template>
                    <template #outsourceUnitPrice="{ row }">
                        <el-input v-model="row.outsourceUnitPrice" :disabled="!row.isEdit" />
                    </template>
                    <template #outsourcePeopleCount="{ row }">
                        <el-input v-model="row.outsourcePeopleCount" :disabled="!row.isEdit" />
                    </template>
                    <template #outsourceCountMoney="{ row }">
                        <el-input v-model="row.outsourceCountMoney" disabled />
                    </template>
                    <template #otherBudgetMoney="{ row }">
                        <el-input v-model="row.otherBudgetMoney" :disabled="!row.isEdit" onkeyup="this.value=this.value.match(/\d+\.?\d{0,2}/)" />
                    </template>
                    <template #budgetCountMoney="{ row }">
                        <el-input v-model="row.budgetCountMoney" disabled />
                    </template> 
                    <template #budgetRemark="{ row }">
                        <el-input v-model="row.budgetRemark" :disabled="!row.isEdit" />
                    </template>
                    <template #key15="{ row }">
                        <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 v-if="row.isEdit" size="small" type="success" @click="saveRow(row)">
                            保存
                        </el-button>
                        <el-button v-else size="small" type="primary" :disabled="row?.approve === 1 || row?.approve === 2" @click="row.isEdit = true">
                            编辑
                        </el-button>
                        <el-button size="small" type="danger" :disabled="row?.approve === 1 || row?.approve === 2" @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 :loading="submitLoaing" @click="submitForm"> 
                        <HcIcon name="check-double" />
                        <span>提交保存</span>
                    </el-button>
                </template>
            </HcCard>
        </template>
    </HcTabsSimple>
</template>

<script setup>
import { onActivated, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import costApi from '~api/project/cost.js'
import { formValidate, getArrValue, getObjValue } from 'js-fast-way'
import { getdepartmentList } from '~api/other'
//初始变量
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 = []
    tableData.value = [{}]
    tabsKey.value = 'base'
    tabKey.value = 'construction'
    getBudgetTypeList()
    if (dataId.value.length > 0) {
        getBudgetStatsById()
        getProjectList(2)
    } else {
        getProjectList(1)
        formBaseModel.value = {}
    }

    getCostTypeDict()
   
    getPostDict()
    getdepartmentListData()


  
   
    
})


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 ()=>{
    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, 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) {
            taskDetailList.value[index] = getArrValue(data)

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

    } else {
        postTypeList.value = []
    }
}
//费用分摊部门
const departMent = ref([])
const getdepartmentListData = async () => {
    const { error, code, data } = await getdepartmentList({ deptType:2 })
    //判断状态
    if (!error && code === 200) {
        departMent.value = getArrValue(data)
    } else {
        departMent.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 || [{}]
        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('')
const tableData = ref([])//成本测算表格
//深度监听
watch(() => [
    tabKey.value,
    tableData.value,
], ([val, table]) => {
   if (val === 'construction') {
    constructUnitData.value = table
    formBaseModel.value.constructUnit = table
   } else if (val === 'supervision') {
    supervisorUnitData.value = table
   } else if (val === 'bulid') {
    bulidUnitData.value = table
   }
}, { deep: true })
const tabTab = ref([
    { key: 'bulid', name: '施工单位成本' },
    { key: 'supervision', name: '监理单位成本' },
    { key: 'construction', name: '建设单位成本' },
])

const tabChange = ({ key }) => {
    tabKey.value = key
    if (key === 'supervision') {
        tableData.value = supervisorUnitData.value.length > 0 ? supervisorUnitData.value : [{}]
        formBaseModel.value.supervisorUnit = tableData.value
    } else if (key === 'construction') {
        tableData.value = constructUnitData.value.length > 0 ? constructUnitData.value : [{}]
        formBaseModel.value.constructUnit = tableData.value
        console.log( formBaseModel.value.constructUnit, ' formBaseModel.value.constructUnit')
    } else if (key === 'bulid') {
        tableData.value = bulidUnitData.value.length > 0 ? bulidUnitData.value : [{}]
        formBaseModel.value.buildUnit = tableData.value
    }
 
}


//成本测算表格
const tableColumn = [
    { key: 'deptId', name: '费用分摊部门', width: '160', align: 'center' },
    { 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: '300', align: 'center', fixed: 'right' },
]



const addRow = ()=>{
    tableData.value.push({
        isEdit:true,
    })
}
const delRow = (index)=>{
    tableData.value.splice(index, 1)
    console.log( tableData.value, ' tableData.value')
    if ( tableData.value.length === 0) {
        tableData.value.push({})
    }
 
}
//保存单行
const saveRow = async (row)=>{
    row.isEdit = false
    //统一测算金额
    const { error, code, data } = await costApi.saveCountMoney(row)
    if (!error && code === 200) {
       let obj = getObjValue(data)
       row.budgetCountMoney = obj.budgetCountMoney
       row.outsourceCountMoney = obj.outsourceCountMoney
       row.budgetStaffCost = obj.budgetStaffCost

    }
    
}
//取消并返回
const goBackClick = () => {
    router.back()
}
const isEmptyObj = (obj)=> {
    let arr = Object.keys(obj)
    return (arr.length === 0)

}    


//保存submitForm
const submitLoaing = ref(false)
const submitForm = async ()=>{
 console.log(formBaseModel.value.supervisorUnit, 'formBaseModel.value.supervisorUnit')
    //取消空对象提交
    if (formBaseModel.value?.supervisorUnit?.length > 0) {
        let suisnullObj = isEmptyObj(formBaseModel.value?.supervisorUnit[0]) 
        if (suisnullObj === true) {
            formBaseModel.value.supervisorUnit = null
        }
    } 
    if (formBaseModel.value?.constructUnit?.length > 0) {
        let coisnullObj = isEmptyObj(formBaseModel.value?.constructUnit[0]) 
        if (coisnullObj) {
            formBaseModel.value.constructUnit = null
        }
    }
    if (formBaseModel.value?.buildUnit?.length > 0) {
        let buisnullObj = isEmptyObj(formBaseModel.value?.buildUnit[0]) 
        if (buisnullObj) {
            formBaseModel.value.buildUnit = null
        }
    }


    const res = await formValidate(formBaseRef.value)
    if (res) {
        submitLoaing.value = true
        const { error, code, msg } = await costApi.AddOrUpdate( formBaseModel.value)
        submitLoaing.value = false
        if (!error && code === 200) {
        window.$message.success(msg)
          
            router.push({
                name: 'project-cost',
                
            })
        } 
    }

}
</script>

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