<template>
  <div class="container">
    <a-affix :offset-top="0">
      <a-card class="general-card" :bordered="false">
        <template #title>
          <a-space :size="1" align="center" class="project-detail-nav">
            <template #split>
              <a-divider direction="vertical" />
            </template>
            <icon-font type="my-package" :size="25" />
            <span class="title">项目工作台</span>
            <span class="sub-title">{{ detail.prj?.name }} </span>
            <span>
              <a-tag
                v-for="item in selectedPhase(
                  detail.prj?.phase_id,
                  prjPhaseList
                )"
                :key="item.id"
                :color="item.color"
                >{{ item.name }}</a-tag
              ></span
            >
            <span v-for="item in detail.prj?.works" :key="item.id">
              <!-- <a-button-group size="small"> -->
              <a-button type="primary" size="mini" @click="showWorkModal(item)">
                {{ item.name }}
              </a-button>
              <!-- </a-button-group> -->
            </span>
            <span class="theme" style="padding-right: 5px">
              <a-tooltip content="我的工作">
                <div class="message-box-trigger">
                  <!-- <a-badge :count="9" dot> -->
                  <a-button
                    class="nav-btn"
                    type="outline"
                    @click="setPopoverVisible"
                  >
                    <template #icon>
                      <icon-font type="my-work" :size="23" />
                    </template>
                  </a-button>
                  <!-- <a-button type="outline" @click="setPopoverVisible"> -->
                  <!-- <template #icon>
                      <icon-more />
                    </template> -->
                  <!-- 更多任务
                  </a-button> -->
                  <!-- </a-badge> -->
                </div>
                <a-popover
                  position="lt"
                  trigger="click"
                  :content-style="{ width: '500px' }"
                  content-class="message-popover"
                >
                  <div ref="refBtn" class="ref-btn"></div>
                  <template #content>
                    <message-box :prj-id="id" />
                  </template>
                </a-popover>
              </a-tooltip>
              <!-- <a-tooltip
                :content="theme === 'light' ? '暗黑模式' : '明亮模式'"
                position="top"
              >
                <a-button
                  class="nav-btn"
                  type="outline"
                  :shape="'circle'"
                  @click="handleToggleTheme"
                >
                  <template #icon>
                    <icon-moon-fill v-if="theme === 'dark'" />
                    <icon-sun-fill v-else />
                  </template>
                </a-button>
              </a-tooltip> -->
            </span>
          </a-space>
        </template>
        <a-tabs
          v-model:active-key="tabActiveKey"
          :hide-content="true"
          size="large"
          @change="(key: string | number) => redirectPage(key as string)"
        >
          <a-tab-pane
            v-for="item in finallyTabList"
            :key="item.path"
            :title="item.title"
          >
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </a-affix>
    <div class="router-container">
      <router-view
        v-slot="{ Component, route: currentRoute }"
        :prj-id="id"
        :account-list="accountList"
      >
        <component
          :is="Component"
          v-bind="getPropsBasedOnRoute(currentRoute)"
        />
      </router-view>
    </div>
    <!-- <Overview
      v-if="tabActiveKey === ProjectDetailTabPath.OVERVIEW"
      :prj-id="id"
      :account-list="accountList"
      :prj-phase-list="prjPhaseList"
      :prj-type-tree-data="prjTypeTreeData"
      :region-tree-data="regionTreeData"
      :customer-list="customerList"
      @set-prj-name="setPrjName"
      @set-contract-id="setContractId"
    ></Overview> -->
    <!-- <TaskLayout
      v-if="tabActiveKey === ProjectDetailTabPath.TASK"
      :prj-id="id as string"
      :account-list="accountList"
    ></TaskLayout>
    <Progressing
      v-if="tabActiveKey === ProjectDetailTabPath.PROGRESSING"
      :prj-id="id"
    ></Progressing>
    <Contract
      v-if="tabActiveKey === ProjectDetailTabPath.CONTRACT"
      :contract-id="contractId"
      :account-list="accountList"
      :customer-list="customerList"
    ></Contract>
    <Doucment
      v-if="tabActiveKey === ProjectDetailTabPath.DOCUMENT"
      :prj-id="id as string"
    ></Doucment>
    <ReportLayout
      v-if="tabActiveKey === ProjectDetailTabPath.REPORT"
      :prj-id="id"
      :account-list="accountList"
    ></ReportLayout> -->
    <WorkModal ref="workModalRef"></WorkModal>
  </div>
</template>

<script lang="ts" setup>
import {
  RouteLocationNormalized,
  RouteLocationNormalizedLoaded,
  useRoute,
  useRouter
} from 'vue-router'
import {
  IconFontUrl,
  PhaseItem,
  ProjectDetailTabPath,
  ProjectDetailTabTitle,
  ProjectDetailTabTitleList,
  Customer as CustomerApi,
  Project as ProjectApi
} from '@/enums/api'
import { selectedPhase } from '@/utils'
import MessageBox from '@/components/message-box/index.vue'
import { onMounted, ref, computed, reactive } from 'vue'
import { Icon } from '@arco-design/web-vue'
import { useAppStore, useUserStore } from '@/store'
import { getStaffList } from '@/api/base/staff'
import { getCustomerList } from '@/api/biz/customer'
import { Customer } from '@/types/customer'

import { overviewProject } from '@/api/project/info'
import { OverviewProjectResParams } from '@/types/project'
import { useEmitt } from '@/logics/mitt/useEmitt'
import { listenerRouteChange } from '@/logics/mitt/routeChange'
import { getContractList } from '@/api/project/contract'
import { useDark } from '@vueuse/core'
import { getPrjPhaseList } from '@/api/base/base'
import WorkModal from '../../components/work-modal.vue'

const { emitter } = useEmitt()
const route = useRoute()
const id = route.params?.prjId as string // id
const refBtn = ref()
const setPopoverVisible = () => {
  const event = new MouseEvent('click', {
    view: window,
    bubbles: true,
    cancelable: true
  })
  refBtn.value.dispatchEvent(event)
}
const userStore = useUserStore()
const { permissionsList } = userStore
const tabActiveKey = ref<ProjectDetailTabPath>(ProjectDetailTabPath.OVERVIEW)
const IconFont = Icon.addFromIconFontCn({
  src: IconFontUrl.URL
})
const workModalRef = ref<any>(null) // Modal 增删改子组件ref
const appStore = useAppStore()
const detail = reactive<{ prj?: OverviewProjectResParams }>({
  prj: undefined
}) // 客户详情
const router = useRouter()
useDark({
  selector: 'body',
  attribute: 'arco-theme',
  valueDark: 'dark',
  valueLight: 'light',
  storageKey: 'arco-theme',
  onChanged(dark: boolean) {
    appStore.toggleTheme(dark)
  }
})

const finallyTabList = computed(() => {
  if (!detail.prj?.phase_id) {
    return []
  }
  const isCreated = [
    PhaseItem.NEW,
    PhaseItem.REJECT_CREATE,
    PhaseItem.APPLY_CREATE,
    PhaseItem.OVERVIEW_CREATE
  ].includes(detail.prj?.phase_id)
  return isCreated
    ? ProjectDetailTabTitleList.filter(item =>
        [ProjectDetailTabPath.OVERVIEW, ProjectDetailTabPath.CONTRACT].includes(
          item.path
        )
      ).filter(item => showTab(item))
    : ProjectDetailTabTitleList.filter(item => showTab(item))
})

/**
 * 根据条件筛选tablist
 * @param item
 */
const showTab = (item: {
  title: ProjectDetailTabTitle
  path: ProjectDetailTabPath
  api: string[]
  redirectId?: string[] | undefined
  routerName: string
}) => {
  const duplicatedValues = permissionsList?.filter(p =>
    item.api.includes(`api/${p}`)
  )
  const permission = duplicatedValues ? duplicatedValues.length : 0
  const isContract = !(
    item.routerName === 'ProjectContract' &&
    detail.prj?.contract_id === undefined
  )
  return permission && isContract
}

const prjPhaseList = ref<{ id: string; name: string; color: string }[]>([])
const accountList = ref<{ id: string; name: string }[]>([])
const customerList = ref<Customer[]>([])
const contractList = ref<{ id: string; name: string }[]>([])

// 获取主责人账号信息
const getAccounts = async () => {
  const { list } = await getStaffList({ page_no: 1, page_size: 9999 })
  accountList.value = list
}

// v-bind="
//             currentRoute.name === 'ProjectDetail'
//               ? { detail: toRaw(detail.prj) }
//               : undefined
//           "
const getPropsBasedOnRoute = (currentRoute: RouteLocationNormalizedLoaded) => {
  if (currentRoute.name === 'ProjectDetail') {
    return {
      isAuthCustomer: isAuthCustomer.value,
      customerList: customerList.value,
      isAuthContract: isAuthContract.value,
      contractList: contractList.value,
      prjPhaseList: prjPhaseList.value
    }
  }
  if (currentRoute.name === 'ProjectContract') {
    // 当路由是 'AnotherRouteName' 时，传递其他参数
    return {
      contractId: detail.prj?.contract_id,
      isAuthCustomer: isAuthCustomer.value,
      customerList: customerList.value
    }
  }
  if (currentRoute.name === 'ProjectProgressing') {
    // 当路由是 'AnotherRouteName' 时，传递其他参数
    return {
      phaseId: detail.prj?.phase_id
    }
  }
  // 更多的条件判断...
  // 如果没有匹配的路由，返回一个空对象
  return undefined
}

const redirectPage = (key: string) => {
  const item = ProjectDetailTabTitleList.find(item => item.path === key)
  router.push({
    name: item?.routerName,
    params: { prjId: id }
  })
  // 在新窗口中打开 URL
  // window.open(routeData.href, '_blank')
}

const getDetail = async (first?: boolean) => {
  if (!first) {
    return
  }
  const prjDetail = await overviewProject(id)
  detail.prj = prjDetail
  const index = contractList.value.findIndex(
    item => item.id === prjDetail.contract_id
  )
  if (index === -1 && prjDetail.contract_id) {
    contractList.value.push({
      id: prjDetail.contract_id,
      name: prjDetail.contract_name!
    })
  }
  emitter.emit('project-overview', prjDetail)
}

// 是否授权客户信息
const isAuthCustomer = computed(() => {
  return (
    permissionsList?.findIndex(
      item => `api/${item}` === CustomerApi.BIZ_CUSTOMER_LIST
    ) !== -1
  )
})

// 是否授权客户信息
const isAuthContract = computed(() => {
  return (
    permissionsList?.findIndex(
      item => `api/${item}` === ProjectApi.PROJECT_CONTRACT_LIST
    ) !== -1
  )
})

// 获取客户列表
const getCustomers = async (name?: string) => {
  if (isAuthCustomer.value) {
    try {
      const params = {
        page_no: 1,
        page_size: 9999,
        name
      }
      const { list } = await getCustomerList(params)
      customerList.value = list
    } catch (e) {
      console.error(e)
    }
  }
}

const getPrjPhase = async () => {
  const { list } = await getPrjPhaseList()
  prjPhaseList.value = list
}

const getContracts = async () => {
  if (isAuthContract.value) {
    try {
      const params = {
        page_no: 1,
        page_size: 9999,
        binded: false
      }
      const { list } = await getContractList(params)
      contractList.value = list
    } catch (e) {
      console.error(e)
    }
  }
}

const showWorkModal = async (work: { id: string }) => {
  workModalRef.value?.showWorkModal(work.id)
}

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'get_project_detail',
  callback: (first: boolean) => {
    // emitter.emit('get_task_list')
    getDetail(first)
  }
})

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'show_work_modal',
  callback: (id: string) => {
    workModalRef.value?.showWorkModal(id)
  }
})

listenerRouteChange(async (r: RouteLocationNormalized) => {
  const item = ProjectDetailTabTitleList.find(
    item => item.routerName === r.name
  )
  tabActiveKey.value = item!.path
})
onMounted(() => {
  getCustomers()
  getContracts()
  getDetail(true)
  getAccounts()
  getPrjPhase()

  console.log('跳转')
})
</script>

<script lang="ts">
export default {
  name: 'Workplace'
}
</script>

<style lang="less">
html,
body {
  overflow: hidden;
  ::-webkit-scrollbar {
    display: none !important;
  }
}
.arco-scrollbar-thumb .arco-scrollbar-thumb-direction-vertical {
  padding-left: 15px;
}
.arco-scrollbar-thumb-direction-vertical .arco-scrollbar-thumb-bar {
  width: 5px;
  // padding-left: 15px;
}
</style>

<style scoped lang="less">
// ::-webkit-scrollbar {
//   display: none;
//   width: 12px;
//   height: 4px;
// }

// ::-webkit-scrollbar-thumb {
//   border: 4px solid transparent;
//   background-clip: padding-box;
//   border-radius: 7px;
//   background-color: var(--color-fill-3);
// }

.container {
  // height: 100vh;
  background-color: var(--color-fill-2);
  .router-container {
    overflow-y: hidden;
    // height: 100%;
    // position: relative;
    // margin: 0;
    // padding: 0;
    transition: padding 0.2s cubic-bezier(0.34, 0.69, 0.1, 1);
  }
  .general-card {
    :deep(.arco-card-header) {
      padding: 20px 20px 10px 20px;
    }
    :deep(.arco-card-body) {
      padding: 0 20px;
    }
    .project-detail-nav {
      width: 100%;
      // :deep(.arco-space-item-split):last-child {
      //   display: none !i
      // }
      :deep(.arco-space-item):last-child {
        margin-left: auto;
      }
    }
    .title {
      font-size: 18px;
    }
    .sub-title {
      color: var(--color-text-3);
      font-size: 18px;
    }
    .nav-btn {
      border: none;
      border-color: rgb(var(--gray-2));
      // color: rgb(var(--gray-8));
      // font-size: 16px;
    }
  }
}
</style>
