<template>
  <div class="_ProjectDetail">
    <div class="detailHeader">
      <div>
        <div>
          <h2>
            {{ projectDetail?.['xmmc'] ?? '' }}
            <span class="subTitle" v-show="projectDetail?.['xmbh']"
              >（{{ 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-if="projectPermis.projectPermisState.all || projectPermis.projectPermisState.xmLeader"
            v-show="currentIndex === 0 && ![2].includes(projectDetail?.['xmzt'])"
            @click="editorProject"
            >{{ !isEditorProject ? '编辑' : '保存' }}
          </li>
          <template v-if="projectDetail?.['isSign'] === 1">
            <template
              v-if="
                (projectPermis.projectPermisState.all ||
                  projectPermis.projectPermisState.xsLeader ||
                  projectPermis.projectPermisState.projectMember) &&
                !signContract.flowStatus &&
                isShowSign
              "
            >
              <dialog-confirm
                title="是否发起合同签订流程？"
                v-if="!signContract?.exist"
                @confirm="handleStartContractSign"
              >
                <template #reference>
                  <li>合同签订</li>
                </template>
              </dialog-confirm>
              <li
                v-else-if="signContract.flowStatus === 1"
                @click="processLookHandle(signContract.instanceId)"
              >
                合同签订
              </li>
            </template>
          </template>
          <!-- <li
            v-if="projectPermis.projectPermisState.all || projectPermis.projectPermisState.xmLeader"
            v-show="currentIndex === 0 && ![2, 3].includes(projectDetail?.['xmzt'])"
            @click="addSubProject"
          >
            添加子项目
          </li> -->
          <li
            v-if="projectPermis.projectPermisState.all || projectPermis.projectPermisState.xmLeader"
            v-show="projectDetail?.['xmzt'] === 1"
            @click="projectStatusAndProcessHandler('ys')"
          >
            验收
          </li>
          <dialog-confirm
            :title="`是否中止项目【${projectDetail?.['xmbh']}】？`"
            v-if="projectPermis.projectPermisState.all || projectPermis.projectPermisState.xmLeader"
            @confirm="projectTerminateHandler"
          >
            <template #reference>
              <li v-show="projectDetail?.['xmzt'] === 1"> 中止 </li>
            </template>
          </dialog-confirm>
          <dialog-confirm
            :title="`是否恢复项目【${projectDetail?.['xmbh']}】？`"
            width="280px"
            v-if="projectPermis.projectPermisState.all || projectPermis.projectPermisState.xmLeader"
            @confirm="projectRecoverHandler"
          >
            <template #reference>
              <li v-show="projectDetail?.['xmzt'] === 3"> 恢复中止 </li>
            </template>
          </dialog-confirm>
          <li
            v-if="projectPermis.projectPermisState.all || projectPermis.projectPermisState.xmLeader"
            v-show="projectDetail?.['xmzt'] === 4"
            @click="projectStatusAndProcessHandler('jx')"
          >
            结项
          </li>
          <li @click="processLookHandle(projectDetail.instanceId)">查看流程</li>
        </ul>
      </div>
      <div>
        <ul>
          <li @click="switchComponent(XmxxComp, 0)" :class="currentIndex === 0 ? 'active' : ''">
            <div><i class="icon"></i>项目信息</div>
          </li>
          <li
            v-show="
              signContract.exist && signContract.isvalid == 1 && signContract.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">
          <template v-if="projectDetail?.['isSign'] === 0">
            <p style="margin-right: 0">该项目不签合同</p>
          </template>
          <template v-else-if="!signContract.exist">
            <p style="margin-right: 0">该项目待签合同</p>
          </template>
          <template
            v-else-if="
              signContract.exist && signContract.isvalid == 1 && signContract.flowStatus != 90
            "
          >
            <p style="margin-right: 0">合同签订过程中</p>
          </template>
          <template v-else>
            <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?.['returnAmount'] ?? '0' }}</span>
            </p>
            <p>
              <span class="title">合同余额(元):</span>
              <span class="value">{{ projectDetail?.['contractBalance'] ?? '' }}</span>
            </p>
          </template>
        </div>
      </div>
    </div>
    <div class="detailContent">
      <component
        :is="currentComponent"
        ref="dynamicRef"
        :editor="isEditorProject"
        :isContract="signContract.exist"
        :isEstimateAmount="
          signContract.exist &&
          signContract.isvalid == 1 &&
          (signContract.flowStatus == 90 || signContract.flowStatus == 1)
        "
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import { type Component } from 'vue'
import { useRoute } from 'vue-router'
import { useProjectPermis } from '@/store/modules/projectPermis'
import {
  isProjectContractExist,
  getContractsByProject,
  startContractSign
} from '@/service/contract'
import subscribe from '@/utils/Subscribe'
import { openFlow, openProcessFlow } from '@/utils/flow'
import { useMutation } from '@tanstack/vue-query'
import { ProjectId } from '@/interface/project'
import { Contract } from '@/interface/contract'
import {
  getProjectWithChildrenById,
  projectStatusAndProcess,
  projectTerminate,
  projectRecover
} from '@/service/project'
import XmxxComp from './components/xmxx/index.vue'
import XmhtComp from './components/xmht/index.vue'
import XmcbComp from './components/xmcb/index.vue'
import FjclComp from './components/fjcl/index.vue'

const router = useRouter()

defineOptions({ name: 'ProjectDetail' })
const message = useMessage()
const dynamicRef = shallowRef<Component>()
const { query } = useRoute()
const { id: projectId, contractId } = query
const currentIndex = ref<number>(0)
const currentComponent = shallowRef<Component>(XmxxComp)
const switchComponent: (c: Component, i: number) => void = (c: Component, i: number) => {
  currentComponent.value = c
  currentIndex.value = i
}
const projectPermis = useProjectPermis()
projectPermis.initProjectPermis(projectId as string)
/***
 * 初始化项目中是否存在合同
 */
const signContract = ref<{
  exist: boolean //判断是否存在合同
  contractId: string
  instanceId: string
  isvalid: number //判断有没有作废 0 已作废 1 未作废
  flowStatus: number //0|null 未开始 1 进行中 90 已完成
}>({
  exist: false,
  contractId: '',
  instanceId: '',
  isvalid: 0,
  flowStatus: 0
})
const queryProjectContractExist = async (projectId: string) => {
  const result: any = await isProjectContractExist(projectId)
  if (result) {
    signContract.value = result
  }
}
// queryProjectContractExist(query?.id as string)
/***
 * 查询项目详情
 * **/
const projectDetail = ref()
provide('projectDetail', projectDetail)
const queryProjectByDetail = async (projectId: string) => {
  const result = await getProjectWithChildrenById(projectId)
  if (result) {
    projectDetail.value = result
    queryProjectContractExist(projectDetail.value.id)
  }
}
queryProjectByDetail(query?.id as string)

subscribe.on('mainContractRefetch', () => {
  queryProjectByDetail(query?.id as string)
})
/**
 * 添加子项目
 * **/
const addSubProject: () => void = () => {
  dynamicRef.value?.handleAddSubProject()
}
/**
 * 项目中止
 */
const projectTerminateHandler = async () => {
  const id = projectDetail.value.id
  if (!id) {
    console.error('项目ID不存在!')
    return
  }
  await projectTerminate(id as string)
  message.success('中止成功')
  queryProjectByDetail(query?.id as string)
}
/**
 * 项目恢复
 */
const projectRecoverHandler = async () => {
  const id = projectDetail.value.id
  if (!id) {
    console.error('项目ID不存在!')
    return
  }
  await projectRecover(id as string)
  message.success('中止成功')
  queryProjectByDetail(query?.id as string)
}
/**
 * 发起项目验收或结项
 */
const sfysType: Ref<string> = ref('')
const { mutate: startProjectStatusAndProcess } = useMutation(projectStatusAndProcess, {
  onSuccess: (data) => {
    const subTitle: string =
      sfysType.value === 'ys'
        ? '验收'
        : sfysType.value === 'jx'
        ? '结项'
        : sfysType.value === 'zz'
        ? '中止'
        : ''
    openFlow(router, data, `项目${subTitle}`)
  }
})
const projectStatusAndProcessHandler = (sfys: string) => {
  if (!sfys) {
    console.warn('sfys字段值不能为空!')
    return
  }
  sfysType.value = sfys
  startProjectStatusAndProcess({
    projectId: projectId as ProjectId,
    sfys
  })
}

/**
 * 流程查看
 */
const processLookHandle = (instanceId: string) => {
  openProcessFlow(router, instanceId)
}
/***
 * 查询合同数据：存在多主合同情况
 * **/
const contractDatas = ref<Contract[]>([])
const queryContractsByProject = async (projectId: string) => {
  const tData: Contract[] = await getContractsByProject(projectId)
  contractDatas.value = tData
  if (contractDatas.value.length > 0 && contractId) {
    switchComponent(XmhtComp, 1)
  }
}
queryContractsByProject(query?.id as string)
/**
 * 项目编辑
 *  **/
const isEditorProject = ref<boolean>(false)
const editorProject: () => void = (): void => {
  isEditorProject.value = !isEditorProject.value
  if (isEditorProject.value) return
  //@ts-ignore
  dynamicRef.value.saveProjectHandle(0)
}

/**
 * 发起合同签订
 */
const isShowSign = ref<boolean>(true)
const { mutate: startContractSignMutate } = useMutation(startContractSign, {
  onSuccess: (data) => openFlow(router, data, '合同签订')
})
const handleStartContractSign = () => {
  isShowSign.value = false
  startContractSignMutate(projectId as ProjectId)
}
</script>
<style lang="scss" scoped>
@import url('./projectDetail.scss');
</style>
