<template>
  <div class="_ProjectDetail">
    <div class="detailHeader">
      <div>
        <div>
          <h2>
            {{ projectDetail?.['xmmc'] ?? '' }}
            <span class="subTitle">（{{ projectDetail?.['xmbh'] ?? '' }}）</span>
            <span class="statu" v-if="projectDetail?.['xmzt'] === 0">立项申请中</span>
            <span class="statu" v-else-if="projectDetail?.['xmzt'] === 1">进行中</span>
            <span class="statu" v-else-if="projectDetail?.['xmzt'] === 2">已结项</span>
            <span class="statu" v-else-if="projectDetail?.['xmzt'] === 3">中止</span>
            <span class="statu" v-else-if="projectDetail?.['xmzt'] === 4">已验收</span>
          </h2>
        </div>
        <ul>
          <li v-show="currentIndex === 0" @click="editorProject"
            >{{ !isEditorProject ? '编辑' : '保存' }}
          </li>
          <template v-if="projectDetail?.['isSign'] !== 0 && contractData?.flowStatus !== 90">
            <el-popconfirm
              title="当前存在进行中的合同，是否重复发起？"
              v-if="contractData?.flowStatus != null"
              @confirm="handleStartContractSign"
            >
              <template #reference>
                <li>合同签订</li>
              </template>
            </el-popconfirm>
            <li v-else @click="handleStartContractSign">合同签订</li>
          </template>
          <li v-show="currentIndex === 0" @click="addSubProject">添加子项目</li>
          <li>验收</li>
          <li>结项</li>
          <li>查看流程</li>
        </ul>
      </div>
      <div>
        <ul>
          <li @click="switchComponent(XmxxComp, 0)" :class="currentIndex === 0 ? 'active' : ''">
            <div><i class="icon"></i>项目信息</div>
          </li>
          <li
            v-show="contractData?.flowStatus === 90"
            @click="switchComponent(XmhtComp, 1)"
            :class="currentIndex === 1 ? 'active' : ''"
          >
            <div><i class="icon"></i>项目合同</div>
          </li>
          <li @click="switchComponent(XmcbComp, 2)" :class="currentIndex === 2 ? 'active' : ''">
            <div><i class="icon"></i>项目成本</div>
          </li>
          <li @click="switchComponent(FjclComp, 3)" :class="currentIndex === 3 ? 'active' : ''">
            <div><i class="icon"></i>附件材料</div>
          </li>
        </ul>
        <div class="projectInfo">
          <p>
            <span class="title">合同额(元):</span>
            <span class="value">{{ projectDetail?.['contractAmount'] ?? '' }}</span>
          </p>
          <p>
            <span class="title">应收款(元):</span>
            <span class="value">{{ projectDetail?.['receivableAmount'] ?? '' }}</span>
          </p>
          <p>
            <span class="title">合同余额(元):</span>
            <span class="value">{{ projectDetail?.['contractBalance'] ?? '' }}</span>
          </p>
        </div>
      </div>
    </div>
    <div class="detailContent">
      <component
        :is="currentComponent"
        :detailData="projectDetail"
        ref="dynamicRef"
        :editor="isEditorProject"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { type Component } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/config/axios'

defineOptions({ name: 'ProjectDetail' })
const dynamicRef = shallowRef<Component>()

import XmxxComp from './components/xmxx/index.vue'
import XmhtComp from './components/xmht/index.vue'
import { getContractsByProject, startContractSign, startOutsourcing } from '@/service/contract'
import { openFlow } from '@/utils/flow'
import { useMutation, useQuery } from '@tanstack/vue-query'
import { ProjectId } from '@/interface/project'
import { getProjectWithChildrenById } from '@/service/project'

const router = useRouter()

const XmcbComp = defineAsyncComponent(() => {
  return import('./components/xmcb/index.vue')
})
const FjclComp = defineAsyncComponent(() => {
  return import('./components/fjcl/index.vue')
})

const { query } = useRoute()
const { id: projectId, contractId } = query
const currentComponent = shallowRef<Component>(XmxxComp)
const currentIndex = ref<number>(0)
const switchComponent: (c: Component, i: number) => void = (c: Component, i: number) => {
  currentComponent.value = c
  currentIndex.value = i
}

// 添加子项目
const addSubProject: () => void = () => {
  dynamicRef.value?.handleAddSubProject()
}

/***
 * 查询项目详情
 * **/
const { data: projectDetail } = useQuery(
  [getProjectWithChildrenById.name, projectId],
  async () => await getProjectWithChildrenById(projectId as string),
  {
    enabled: (query?.id ?? '') !== ''
  }
)
/**
 * 项目编辑
 *  **/
const isEditorProject = ref<boolean>(false)
const editorProject: () => void = (): void => {
  isEditorProject.value = !isEditorProject.value
  if (isEditorProject.value) return
  //@ts-ignore
  dynamicRef.value.saveProjectHandle()
}

/***
 * 查询合同数据
 * **/
const { data: contractData } = useQuery(
  [getContractsByProject.name, projectId],
  async () => await getContractsByProject(projectId as string),
  {
    onSuccess: (tData) => {
      if (tData?.flowStatus === 90 && contractId) {
        // 查看合同详情
        switchComponent(XmhtComp, 1)
      }
    },
    enabled: (projectId ?? '') !== '',
    refetchOnWindowFocus: true
  }
)
console.log('contractData: ', unref(contractData))
/**
 * 发起合同签订
 */
const { mutate: startContractSignMutate } = useMutation(startContractSign, {
  onSuccess: (data) => openFlow(router, data, '合同签订')
})
const handleStartContractSign = () => startContractSignMutate(projectId as ProjectId)
</script>
<style lang="scss" scoped>
@import './projectDetail.scss';
</style>
