<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">
            <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)">分解子计划</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"
        >
            <HcTable :isIndex="false" :column="tableSubplanColumn" :datas="tableSubplanData">
                <template #planTaskType="{row,index}">
                    <el-select v-model="row.planTaskType">
                        <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"/>
                </template>
                <template #planTarget="{row,index}">
                    <el-input v-model="row.planTarget"/>
                </template>
                <template #key7="{row,index}">
                    <HcDatePicker :dates="[row.planStartTime,row.planEndTime]" @change="subbetweenTimeUpdate($event,row)" v-if="true"/>
                    <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" 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"

//初始变量
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 ?? ''
   
    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?.buildDatatUnit||[]
        supervisorUnitData.value=detailData.value?.supervisorUnit||[]
        tabKey.value='construction'
        radioType.value=1
     
        // milestoneData.value=getArrValue(data)
       

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

const tabChange = ({key}) => {
    tabKey.value = key
    console.log(tableData.value,'tableData.value');
    if(key=='supervision'){
        tableData.value=supervisorUnitData.value.length>0?supervisorUnitData.value:originTableData.value
        detailData.value.supervisorUnit=tableData.value
    }else if(key=='construction'){
        tableData.value=constructionData.value.length>0?constructionData.value:originTableData.value
        detailData.value.constructUnit=tableData.value
      
    }else if(key=='bulid'){
        console.log(buildData.value,'=buildData.value');
        tableData.value=buildData.value.length>0?buildData.value:originTableData.value
        detailData.value.buildUnit=tableData.value
    }
}

const radioType = ref('')
//深度监听
watch(() => [
radioType.value,
tabKey.value
], ([radioType]) => {
    console.log(radioType,'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: 'postType', name: '投入岗位类型(日单价)', width: '160', align: 'center'},
    {key: 'staffCount', name: '投入人员数量', width: '160', align: 'center'},
    {key: 'returnedValue', name: '关联回款里程碑', minWidth: '200', isTooltip: true},
    {key: 'action', name: '操作', width: '280', align: 'center', fixed: 'right'},
]
const tableData = 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 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([
    {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 subplanCloseClick = () => {
    subplanModal.value = false
}
//分解子计划保存
const subplanSaveClick = () => {
    tableData.value.forEach((ele)=>{
        if(ele.id==subPlanItem.id){
            ele.childrenList=tableSubplanData.value
        }
    })
    subplanModal.value = false
    // subPlanItem.value.childrenList=tableSubplanData.value

}



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 saveLoaing=ref(false)
const saveClick = () => {
   console.log(tableData.value,'tableData.value');
   console.log( detailData.value,' detailData.value');
   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>
