<template>
    <HcCard actionUi="text-center" :title="detailData?.projectName">
        <template #extra>
            <HcNewSwitch :datas="tabTab" :keys="tabKey" @change="tabChange" :round="false"/>
        </template>
        <template #search>
            <div class="hc-program-project-form-radio-group">
                <el-radio-group v-model="radioType" size="large">
                    <el-radio-button label="1">市场部</el-radio-button>
                    <el-radio-button label="2">研发部</el-radio-button>
                    <el-radio-button label="3">实施部</el-radio-button>
                    <el-radio-button label="4">维护部</el-radio-button>
                    <el-radio-button label="5">管理支出</el-radio-button>
                    <el-radio-button label="6">外包劳务</el-radio-button>
                </el-radio-group>
            </div>
        </template>
        <HcTable :isIndex="false" :column="tableColumn" :datas="tableData" :row-style="tableRowStyle" hasChildren="hasChildren1" children="childrenList">
            <template #planTaskType="{row,index}">
                <el-select v-model="row.planTaskType" v-if="row.isEdit">
                    <el-option label="选项1" value="选项1"/>
                    <el-option label="选项2" value="选项2"/>
                </el-select>
                <span v-else>{{row.planTaskType}}</span>
            </template>
            <template #planTaskDesc="{row,index}">
                <el-input v-model="row.planTaskDesc" v-if="row.isEdit"/>
                <span v-else>{{row.planTaskDesc}}</span>
            </template>
            <template #planTarget="{row,index}">
                <el-input v-model="row.planTarget" v-if="row.isEdit"/>
                <span v-else>{{row.planTarget}}</span>
            </template>
            <template #key7="{row,index}">
                <HcDatePicker :dates="[row.planStartTime,row.planEndTime]" @change="betweenTimeUpdate($event,row)" v-if="row.isEdit"/>
                <!-- <span v-else>{{row.key7}}</span> -->
                <span v-else>
                    <span >{{row.planStartTime?row.planStartTime:''}}</span>
                    <span  v-if="row.planEndTime">~</span>
                    <span >{{row.planEndTime?row.planEndTime:''}}</span>
                </span>
             
      
            </template>
            <template #planDays="{row,index}">
                <el-input v-model="row.planDays" v-if="row.isEdit" disabled/>
                <span v-else>{{row.planDays}}</span>
            </template>
            <!-- <template #key9="{row,index}">
                <el-input v-model="row.key9" v-if="row.isEdit"/>
                <span v-else>{{row.key9}}</span>
            </template> -->
            <template #action="{row,index}">
                <el-button size="small" type="success" v-if="row.isEdit" @click="getWorkDays(row)">保存</el-button>
                <el-button size="small" type="primary" v-else @click="row.isEdit = true">编辑</el-button>
                <el-button size="small" type="warning" @click="relatedModalShow(row)">关联回款</el-button>
                <el-button size="small" type="danger" @click="subplanModalShow(row)" :disabled="row?.isShowChildren==0">分解子计划</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="saveClick" :loading="saveLoaing">
                <HcIcon name="check-double"/>
                <span>提交保存</span>
            </el-button>
        </template>

        <!--分解子计划-->
        <HcDialog bgColor="#ffffff" isToBody isTable
                  title="分解子计划" widths="80%"
                  saveText="保存"
                  :show="subplanModal"
                  @close="subplanCloseClick"
                  @save="subplanSaveClick"
        >
        <template #extra>
            <el-button size="large" type="primary"  @click="addplan()">新增</el-button>
        </template>
            <HcTable :isIndex="false" :column="tableSubplanColumn" :datas="tableSubplanData">
                <template #planTaskType="{row,index}">
                    <el-select v-model="row.planTaskType" :disabled="!row.isEdit">
                        <el-option label="选项1" value="1"/>
                        <el-option label="选项2" value="2"/>
                    </el-select>
                </template>
                <template #planTaskDesc="{row,index}">
                    <el-input v-model="row.planTaskDesc" :disabled="!row.isEdit"/>
                </template>
                <template #planTarget="{row,index}">
                    <el-input v-model="row.planTarget" :disabled="!row.isEdit"/>
                </template>
                <template #key7="{row,index}">
                    <HcDatePicker :dates="[row.planStartTime,row.planEndTime]" @change="subbetweenTimeUpdate($event,row)"  :disabled="!row.isEdit"/>
              
                </template>
                <template #planDays="{row,index}" >
                    <!-- <el-input v-model="row.planDays" disabled/> -->
                    <el-input v-model="row.planDays" disabled  />
                </template>
                <template #key9="{row,index}">
                    <el-input v-model="row.key9"/>
                </template>
                <template #action="{row,index}">
                <el-button size="small" type="success" v-if="row.isEdit" @click="getWorkDays(row)">保存</el-button>
                <el-button size="small" type="primary" v-else @click="row.isEdit = true">编辑</el-button>
            </template>
            </HcTable>
        </HcDialog>

        <!--关联回款里程碑-->
        <HcDialog bgColor="#ffffff" isToBody isTable :footer="false" :show="relatedModal" title="关联回款里程碑" widths="70%" @close="relatedCloseClick">
            <HcTable :column="tableRelatedColumn" :datas="tableRelatedData">
                <template #action="{row,index}">
                    <el-button size="small" type="success" v-if="row.isRelation==1" @click="relation(row,0)">取消关联</el-button>
                    <el-button size="small" type="primary" v-else @click="relation(row,1)">关联</el-button>
                </template>
            </HcTable>
        </HcDialog>

    </HcCard>
</template>

<script setup>

import {useRouter, useRoute} from 'vue-router'
import {onActivated, ref,watch} from "vue";
import projectApi from '~api/program/project.js';
import contractApi from '~api/project/project-contract.js';
import {getArrValue,getObjValue} from "js-fast-way"
import { getuserList} from "~api/other";
import {useAppStore} from "~src/store";
const useAppState = useAppStore();

//初始变量
const router = useRouter()
const useRoutes = useRoute()
const dataId = ref(useRoutes?.query?.id ?? '')
const dataType = ref(useRoutes?.query?.type ?? '')

//缓存页面被激活时
onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
    dataType.value = useRoutes?.query?.type ?? ''
    getUserDict()
    if(dataType.value!=='add'){
        getPlanByProjectId()
    
    }else if(dataType.value=='add'){
  
    }

 
})

const detailData=ref({})
const constructionData=ref([])
const buildData=ref([])
const supervisorUnitData=ref([])
//获取详情
const getPlanByProjectId=async()=>{
    const {error, code, data} = await projectApi.getPlanByProjectId({id: dataId.value})
    if (!error && code === 200) {
        console.log(getObjValue(data),'详情');
        detailData.value=getObjValue(data)
        constructionData.value=detailData.value?.constructUnit||[]
        buildData.value=detailData.value?.buildUnit||[]
        supervisorUnitData.value=detailData.value?.supervisorUnit||[]
        tabKey.value='construction'
        radioType.value=1
     
        // milestoneData.value=getArrValue(data)
       

    } else {
        // milestoneData.value=[]
    }
}
//获取所有员工
const userList=ref([])
//获取部门人员列表
const getUserDict=async()=>{
    const {error, code, data} = await getuserList({tenantId:useAppState.tenantId})
    if (!error && code === 200) {
        userList.value = getArrValue(data)

    } else {
        userList.value = []

    }
}

//类型tab数据和相关处理
const tabKey = ref('')
const tabTab = ref([
    {key: 'build', name: '施工单位成本'},
    {key: 'supervision', name: '监理单位成本'},
    {key: 'construction', name: '建设单位成本'}
]);
const originTableData=ref([ {}])

const tabChange = ({key}) => {
    tabKey.value = key
    if(key=='supervision'){
        tableData.value=supervisorUnitData.value&&supervisorUnitData.value[radioType.value]?.length>0?supervisorUnitData.value:originTableData.value
        detailData.value.supervisorUnit=tableData.value
    }else if(key=='construction'){
        tableData.value=constructionData.value[radioType.value]?.length>0?constructionData.value:originTableData.value
        detailData.value.constructUnit=tableData.value
      
      
    }else if(key=='bulid'){
        tableData.value=buildData.value[radioType.value]?.length>0?buildData.value:originTableData.value
        detailData.value.buildUnit=tableData.value
       
    }
}

const radioType = ref('')
//深度监听
watch(() => [
radioType.value,
tabKey.value
], ([radioType]) => {
    if(tabKey.value==='construction'){
        console.log(constructionData.value[radioType],'constructionData.value');
        tableData.value=constructionData.value[radioType]
    }else if(tabKey.value==='build'){
        console.log(buildData.value[radioType],'buildData.value');
        tableData.value=buildData.value[radioType]
    }else if(tabKey.value==='supervision'){
        console.log(supervisorUnitData.value[radioType],'supervisorUnitData.value');
        tableData.value=supervisorUnitData.value[radioType]
    }
}, {deep: true})
//表格
const tableColumn = [
    {key: 'projectProcessValue', name: '项目环节', width: '160', align: 'center'},
    {key: 'budgetTypeValue', name: '预算类型', width: '160', align: 'center'},
    {key: 'taskDetailValue', name: '任务明细', width: '160', align: 'center'},
    {key: 'planTaskType', name: '任务类型', width: '160',  align: 'center'},
    {key: 'planTaskDesc', name: '任务描述', minWidth: '200',  align: 'center', isTooltip: true},
    {key: 'planTarget', name: '完成指标', minWidth: '200', align: 'center', isTooltip: true},
    {key: 'key7', name: '计划起止日期', width: '280', align: 'center'},
    {key: 'planDays', name: '预计工作量（小数/整数/天）', width: '160', align: 'center'},
    {key: 'postTypeValue', 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: 'returnedValue', name: '关联回款里程碑', minWidth: '200', isTooltip: true},
    {key: 'action', name: '操作', width: '280', align: 'center', fixed: 'right'},
]
const tableData = ref([

])

//表格行样式
const tableRowStyle = ({row, rowIndex}) => {
    if (row.taskFinishedStatus === 1) {
        return {
            'background-color': '#E99D42',
            '--el-fill-color-lighter': '#E99D42',
            '--el-table-row-hover-bg-color': '#E99D42'
        }
    } else if (row.taskFinishedStatus === 2 ) {
        return {
            'background-color': '#7e9559',
            '--el-fill-color-lighter': '#7e9559',
            '--el-table-row-hover-bg-color': '#7e9559'
        }
    }
}

//日期时间被选择
const betweenTime = ref(null)
const betweenTimeUpdate = ({arr, query},item) => {
    item.planStartTime=arr[0]
    item.planEndTime=arr[1]
    item.betweenTime=arr
}
//日期时间被选择
const subbetweenTime = ref(null)
const subbetweenTimeUpdate = ({arr, query},item) => {
    console.log(item,'item');
    item.planStartTime=arr[0]
    item.planEndTime=arr[1]
    item.subbetweenTime=arr
}

const subplanModal = ref(false)
const subPlanItem=ref({})
const subplanModalShow = (row) => {
    console.log(row,'row');
    subPlanItem.value=row
    subplanModal.value = true
    tableSubplanData.value=row?.childrenList||[]

}
//表格
const tableSubplanColumn = [
    {key: 'projectProcessValue', name: '项目环节', width: '160', align: 'center'},
    {key: 'budgetTypeValue', name: '预算类型', width: '160', align: 'center'},
    {key: 'taskDetailValue', name: '任务明细', width: '160', align: 'center'},
    {key: 'planTaskType', name: '任务类型', width: '160',  align: 'center'},
    {key: 'planTaskDesc', name: '任务描述', minWidth: '200',  align: 'center', isTooltip: true},
    {key: 'planTarget', name: '完成指标', minWidth: '200', align: 'center', isTooltip: true},
    {key: 'key7', name: '计划起止日期', width: '280', align: 'center'},
    {key: 'planDays', name: '预计工作量（小数/整数/天）', width: '160', align: 'center'},
    {key: 'action', name: '操作', width: '80', align: 'center', fixed: 'right'},
]
const tableSubplanData = ref([

])

const subplanCloseClick = () => {
    subplanModal.value = false
}
//分解子计划保存
const subplanSaveClick = () => {
    tableData.value.forEach((ele)=>{
        if(ele.id==subPlanItem.value.id){
            ele.childrenList=tableSubplanData.value
        }
    })
    subplanModal.value = false
    console.log(tableData.value,'tableData.value');
    // subPlanItem.value.childrenList=tableSubplanData.value

}
const addplan=()=>{
    tableSubplanData.value.push({
        projectProcessValue:subPlanItem.value?.projectProcessValue,
        budgetTypeValue:subPlanItem.value?.budgetTypeValue,
        taskDetailValue:subPlanItem.value?.taskDetailValue,
        planTaskType:subPlanItem.value?.planTaskType,
        isEdit:true


    })
}


const relatedModal = ref(false)
const rePlanid=ref('')
const relatedModalShow = (row) => {
    relatedModal.value = true
    rePlanid.value=row.id
    getListByProjectId(row.projectId)
   
}
//保存获取工作时长
const getWorkDays=async(row)=>{
    row.isEdit = false
    if(row?.planStartTime&&row?.planEndTime){
        const {error, code, data,msg} = await projectApi.getWorkDays( {
            startDate:row.planStartTime,
            endDate:row.planEndTime,
        
        })
        if (!error && code === 200) {
            if(data){
                row.planDays=data
            }
        
        }
    }
 
}
//关联回款
const relation=async(row,type)=>{
    const {error, code, data,msg} = await projectApi.relationPlanAndReturned( {
        planId:rePlanid.value,
        returnedId:row.id,
        type
    })
    if (!error && code === 200) {
       window.$message.success(msg)
       getListByProjectId(row.projectId).then()
    } 
}
//表格
const tableRelatedColumn = [
    {key: 'returnedCondition', name: '回款条件', minWidth: '260'},
    {key: 'shouldReturnedTime', name: '应收回款时间', width: '160', align: 'center'},
    {key: 'shouldReturnedMoney', name: '应收回款金额(元)', width: '160', align: 'center'},
    {key: 'reminderUserName', name: '催款执行人', width: '160',  align: 'center'},
    {key: 'action', name: '操作', width: '130', align: 'center'},
]
const tableRelatedData = ref([
    {id: 1, key1: 'xx', key2: 'xx', key3: 'xx', key4: 'xx', key5: 'xx', key6: 'xx', key7: 'xx', key8: 'xx', key9: 'xx', key10: 'xx'},
    {id: 2, key1: 'xx', key2: 'xx', key3: 'xx', key4: 'xx', key5: 'xx', key6: 'xx', key7: 'xx', key8: 'xx', key9: 'xx', key10: 'xx'},
    {id: 3, key1: 'xx', key2: 'xx', key3: 'xx', key4: 'xx', key5: 'xx', key6: 'xx', key7: 'xx', key8: 'xx', key9: 'xx', key10: 'xx'},
    {id: 4, key1: 'xx', key2: 'xx', key3: 'xx', key4: 'xx', key5: 'xx', key6: 'xx', key7: 'xx', key8: 'xx', key9: 'xx', key10: 'xx'},
    {id: 5, key1: 'xx', key2: 'xx', key3: 'xx', key4: 'xx', key5: 'xx', key6: 'xx', key7: 'xx', key8: 'xx', key9: 'xx', key10: 'xx'},
    {id: 6, key1: 'xx', key2: 'xx', key3: 'xx', key4: 'xx', key5: 'xx', key6: 'xx', key7: 'xx', key8: 'xx', key9: 'xx', key10: 'xx'},
])
//合同里程碑

const getListByProjectId=async(projectId,planId)=>{
    const {error, code, data} = await contractApi.getListByProjectId({projectId,planId:rePlanid.value})
    if (!error && code === 200) {
        tableRelatedData.value=getArrValue(data)
       

    } else {
        tableRelatedData.value=[]
    }
}

const relatedCloseClick = () => {
    relatedModal.value = false
}
//修改合同
const updatePlan=async(obj)=>{
    console.log(obj,'编辑');
    saveLoaing.value=true;
    const {error, code, data,msg} = await projectApi.updatePlan( obj)
    saveLoaing.value=false;
    if (!error && code === 200) {
       window.$message.success(msg)
       getPlanByProjectId()
    } 

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

}    
//批量保存
const saveLoaing=ref(false)
const saveClick = () => {
   console.log(tableData.value,'tableData.value');
   console.log( detailData.value,' detailData.value');
       //取消空对象提交
       if(detailData.value?.supervisorUnit?.length>0){
        let suisnullObj= isEmptyObj(detailData.value?.supervisorUnit[0]) 
        if(suisnullObj===true){
            detailData.value.supervisorUnit=null
        }
    } 
    if(detailData.value?.constructUnit?.length>0){
        let coisnullObj= isEmptyObj(detailData.value?.constructUnit[0]) 
        if(coisnullObj){
            detailData.value.constructUnit=null
        }
    }
    if(detailData.value?.buildUnit?.length>0){
        let buisnullObj= isEmptyObj(detailData.value?.buildUnit[0]) 
        if(buisnullObj){
            detailData.value.buildUnit=null
        }
    }
   updatePlan(detailData.value)
}
//取消并返回
const goBackClick = () => {
    router.back()
}
</script>

<style lang="scss">
.hc-program-project-form-radio-group {
    position: relative;
    width: 100%;
    .el-radio-group, .el-radio-group .el-radio-button .el-radio-button__inner {
        width: 100%;
    }
    .el-radio-group .el-radio-button {
        flex: 1;
    }
}
</style>
