<template>
    <HcTabsSimple :cur="tabsKey" :datas="tabsData" @tab-click="tabsClick">
        <template #tab-base>
            <baseTabCard 
                v-if="tabsKey === 'base'" 
                :datas="infoData" 
                :disabled="dataType === 'view'" 
                :save-loaing="saveLoaing" 
                :contract-type="contractType" 
                :project-list="projectList" 
                :isres="isres"
                @save-click="saveClick"
                @change-isres="changeIsres"
            />
        </template>
        <template #tab-file>
            <fileTabCard v-if="tabsKey === 'file'" :datas="infoDataFile" :disabled="dataType === 'view'" :save-loaing="saveLoaing" @saveClick="saveClick" />
        </template>
        <template #tab-milestone>
            <milestoneTab v-if="tabsKey === 'milestone'" :datas="milestoneData" :disabled="dataType === 'view'" :save-loaing="saveLoaing" :reminder-user-list="reminderUserList" @saveClick="saveClick" />
        </template>
        <template #tab-record>
            <recordTabCard v-if="tabsKey === 'record'" :datas="recordData" />
        </template>
    </HcTabsSimple>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import baseTabCard from './components/base.vue'
import fileTabCard from './components/file.vue'
import milestoneTab from './components/milestone.vue'
import recordTabCard from './components/record.vue'
import { arrIndex, getArrValue, getObjValue } from 'js-fast-way'
import contractApi from '~api/project/project-contract.js'
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 ?? '')
const infoData = ref({})
//缓存页面被激活时
onActivated(() => {
    dataId.value = useRoutes?.query?.id ?? ''
    dataType.value = useRoutes?.query?.type ?? ''
    setTabsData()
    getContractType()
    getUserDict()
    tabsKey.value = 'base'
    if (dataType.value !== 'add') {
        getContractInfoById()
        getListByContractId()
        getRecordData()
        getProjectList(2)
    } else if (dataType.value === 'add') {
        infoData.value = {}
        infoDataFile.value = {}
        milestoneData.value = [{}]
        getProjectList(1)
    }

 
})
const infoDataFile = ref({ pdfUrl:'' })
//获取详情
const getContractInfoById = async ()=>{
    const { error, code, data } = await contractApi.getContractInfoById({ id: dataId.value })
    if (!error && code === 200) {
        infoData.value = getObjValue(data)
        infoDataFile.value.pdfUrl = infoData.value.contractAccessory

    } else {
        infoData.value = {}
    }
}
//设置选项卡数据
const setTabsData = () => {
    const index = arrIndex(tabsData.value, 'key', 'record')
    if (dataType.value === 'view') {
        //预览模式下，索引不存在，就添加此选项
        if (index === -1) {
            tabsData.value.push({
                icon: 'file-history',
                label: '合同开票记录',
                key: 'record',
            })
        }
    } else {
        //编辑模式下，索引存在，就删除此选项
        if (index !== -1) {
            tabsData.value.splice(index, 1)
        }
    }
}

//选项卡
const tabsKey = ref('base')
const tabsData = ref([
    { icon: 'file-list-3', label: '合同基础信息', key: 'base' },
    { icon: 'file-word', label: '合同附件', key: 'file' },
    { icon: 'creative-commons-sa', label: '合同回款里程碑', key: 'milestone' },
])
const tabsClick = (key) => {
    tabsKey.value = key
    if (tabsKey.value === 'base') {
        console.log(infoData.value, '基础信息')
    }

}


//合同里程碑
const milestoneData = ref([])
const getListByContractId = async ()=>{
    const { error, code, data } = await contractApi.getListByContractId({ contractId: dataId.value })
    if (!error && code === 200) {
        milestoneData.value = getArrValue(data)
       

    } else {
        milestoneData.value = []
    }
}
//合同开票记录
const recordData = ref([])
const getRecordData = async ()=>{
    const { error, code, data } = await contractApi.getContractInvoiceList({ contractId: dataId.value })
    if (!error && code === 200) {
        recordData.value = getArrValue(data)
       

    } else {
        recordData.value = []
    }
}
const saveLoaing = ref(false)
const isEmptyObj = (obj)=> {
    let arr = Object.keys(obj)
    return (arr.length === 0)

}
const isres = ref(false)
//改变是否可以保存的状态
const changeIsres = (val)=>{
    isres.value = val
}    
//保存
const saveClick = ()=>{
  //限制空对象不提交
  milestoneData.value.forEach((ele, index)=>{
    let ele1 = isEmptyObj(ele)
    if (ele1) {
        milestoneData.value.splice(index)
    }
  })
  console.log( milestoneData.value, ' milestoneData.value111')
  let saveobj = { ...infoData.value }
  saveobj.contractAccessory = infoDataFile.value.pdfUrl
  saveobj.list = milestoneData.value

    if (dataId.value.length > 0) {
        saveobj.id = dataId.value
        updateContractInfo(saveobj)
    } else {
        addContractInfo(saveobj)
    }

}
//新增合同
const addContractInfo = async (obj)=>{
    console.log(obj, '新增')
    saveLoaing.value = true
    const { error, code, msg } = await contractApi.addContractInfo( obj)
    saveLoaing.value = false
    if (!error && code === 200) {
        window.$message.success(msg)
        router.push({
            name: 'project-contract',
        })
    } 

}
//修改合同
const updateContractInfo = async (obj)=>{
    console.log(obj, '编辑')
    saveLoaing.value = true
    const { error, code, msg } = await contractApi.updateContractInfo( obj)
    saveLoaing.value = false
    if (!error && code === 200) {
       window.$message.success(msg)
       router.push({
            name: 'project-contract',
        })
    } 

}
//获取合同类型
const contractType = ref([])
const getContractType = async ()=>{
    const { error, code, data } = await contractApi.getContractTypeDict()
    if (!error && code === 200) {
        contractType.value = getArrValue(data)
    } else {
        contractType.value = []
    }
}
//所属项目projectList
const projectList = ref([])
const getProjectList = async (type)=>{
    const { error, code, data } = await contractApi.getNoConnectionProject({ type })
    if (!error && code === 200) {
        projectList.value = getArrValue(data)
    } else {
        projectList.value = []
    }
}
//催款执行人reminderUserList
const reminderUserList = ref([])
//获取部门人员列表
const getUserDict = async ()=>{
    const { error, code, data } = await getuserList({ tenantId:useAppState.tenantId })
    if (!error && code === 200) {
        reminderUserList.value = getArrValue(data)

    } else {
        reminderUserList.value = []

    }
}
</script>
