<template>
  <!-- :style="{paddingTop:navHeight+'px'}" -->
  <view>
    <y-tabs v-if="finallyTabList.length > 1" v-model="tabActiveKey" type="line-button" color="#007aff" sticky
      @change="tabChange">
      <y-tab class="y-tab-virtual" v-for="item in finallyTabList" :key="item.path" :title="item.title"
        :name="item.path">
      </y-tab>
    </y-tabs>
    <view>
      <view v-if="tabActiveKey === ProjectDetailTabPath.OVERVIEW && detail?.prj">
        <ProjectDetail :prj="detail?.prj" :account-list="accountList" :customer-list="customerList"
          :contract-list="contractList" :prj-type-tree-data="prjTypeTreeData" :region-tree-data="regionTreeData"
          :is-auth-contract="isAuthContract" :is-auth-customer="isAuthCustomer"/>
      </view>
      <view v-if="tabActiveKey === ProjectDetailTabPath.TASK && detail?.prj">
        <ProjectPlan :prj="detail?.prj" :account-list="accountList" :navigateOptions="navigateOptions" />
      </view>
      <view v-if="tabActiveKey === ProjectDetailTabPath.PROGRESSING && detail?.prj">
        <ProjectProgressing :prj_id="detail?.prj.id" />
      </view>
      <view v-if="tabActiveKey === ProjectDetailTabPath.CONTRACT && detail?.prj?.contract_id!">
        <ProjectContract :contract_id="detail?.prj.contract_id" :account-list="accountList"
          :customer-list="customerList" />
      </view>
      <view v-if="tabActiveKey === ProjectDetailTabPath.REPORT && detail?.prj">
        <WeekReport :isDetail="true" :account-list="accountList" :hiddenPrFilterItem="true" :prj="detail?.prj" />
      </view>
      <view v-if="tabActiveKey === ProjectDetailTabPath.DOCUMENT && detail?.prj">
        <ProjectDocument :prj_id="detail?.prj.id" :isDetail="true" :hiddenPrFilterItem="true" />
      </view>
    </view>
    <view style="padding-bottom: 100px;"></view>
    <!-- <uni-badge class="uni-badge-left-margin" :is-dot="false" :text="2" absolute="rightTop" size="small"> -->
    <uni-fab :content="[]" :popMenu="false" horizontal="right" :dotCount="detail.prj?.works?.length"
      direction="vertical" :pattern="{
        icon: 'email',
        buttonColor: '#4cd964'
      }" @fabClick="showProcessWorks">

    </uni-fab>
    <!-- <uni-popup ref="work_popup" background-color="#fff" type="center">
      <view class="popup-content" style="padding: 10px;min-height: 150px;">
        <view style="margin-bottom: 10px;" v-for="item in detail.prj?.works" :key="item.id">
          <custom-button width="100%" type="filled" :ripple="true" box-shadow="0 1px 5px 2px rgba(0, 0, 0, 0.3);" color="#007aff">
            {{ item.name }}
          </custom-button>
        </view>
      </view>
    </uni-popup> -->
    <!-- </uni-badge> -->
    <ProcessWork ref="processWorkRef" />
  </view>
</template>
<script setup lang="ts">
import { overviewProject } from '@/api/project-center/info';
import ProcessWork from '@/components/process-work/index.vue'
import {
  PhaseItem,
  ProjectDetailTabPath,
  ProjectDetailTabTitle,
  ProjectDetailTabTitleList,
} from '@/enums/api'
import { useUserStore } from '@/stores'
import { OverviewProjectResParams } from '@/types/project';
import ProjectDetail from './detail/overview.vue'
import ProjectPlan from './detail/plan-task-layout.vue'
import ProjectContract from './detail/contract-detail.vue'
import ProjectDocument from './detail/document/document-layout.vue'
import WeekReport from './detail/week-report/report-layout.vue'
import ProjectProgressing from './detail/progressing.vue'
import { useEmitt } from '@/logics/mitt/useEmitt';
import { DomainTree } from '@/types/domain';
import { getCustomerList } from '@/api/biz/customer';
import { getContractList } from '@/api/project-center/contract';
import { getStaffList } from '@/api/biz/staff';
import { getPrjTypeList } from '@/api/base/base';
import { Customer } from '@/types/customer';
import { getRegionTree } from '@/api/base/region';
import {
  Customer as CustomerApi,
  Project as ProjectApi
} from '@/enums/api'


const works = ref<{ id: string, name: string }[]>([])
const processWorkRef = ref<any>(null)
const navigateOptions = ref()



// 标签切换事件
const tabChange = (index: ProjectDetailTabPath, item: any) => {
  console.log("tabChange", index, item);

}



const processWork = async (itemList: string[]) => {
  if (itemList.length > 0) {
    uni.showActionSheet({
      title: detail?.prj?.name,
      itemList: itemList,
      success: async (res: UniApp.ShowActionSheetRes) => {
        const { tapIndex } = res;
        const work = works.value.find(item => item.name === itemList[tapIndex])
        processWorkRef.value?.showWorkModal(work!.id)
      }
    });
  }


}

const showProcessWorks = () => {
  const workBtnList = works.value && works.value.length > 0 ? works.value.map(work => work.name) : []
  // work_popup.value?.open()
  processWork(workBtnList)
}



const prjTypeTreeData = ref<DomainTree[]>([]) // 项目类型
const regionTreeData = ref<DomainTree[]>([]) // 区域树
const customerList = ref<Customer[]>([]) // 
const contractList = ref<{ id: string, name: string }[]>([]) // 
const accountList = ref<{ id: string, name: string }[]>([]) // 

const prj_id = ref()
const tabActiveKey = ref<ProjectDetailTabPath>(ProjectDetailTabPath.OVERVIEW)
// const permissionsList = ref<string[]>([])
const userStore = useUserStore()
const permissionsList = userStore.getPermissionsList


// 是否授权客户信息
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 detail = reactive<{ prj?: OverviewProjectResParams }>({
  prj: undefined
}) // 客户详情

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))
})


/**
 * 递归获取ng-tree需要的结构体
 * @param domains 接口返回的树状数组
 */
const getNodesTree = (domains: DomainTree): DomainTree => {
  domains.key = domains.id.toString()
  domains.title = domains.name
  if (domains.children && domains.children.length > 0) {
    domains.children.map(res => getNodesTree(res))
  } else {
    domains.children = undefined
  }
  return domains
}

/**
 * 获取区域树
 */
const getRegions = async () => {
  const { tree } = await getRegionTree()
  regionTreeData.value = tree.map(domains => {
    return getNodesTree(domains)
  })
}

// 获取客户列表
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 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 getAccounts = async () => {
  const { list } = await getStaffList({ page_no: 1, page_size: 9999 })
  accountList.value = list
}

const getProjectType = async () => {
  const { tree } = await getPrjTypeList()
  prjTypeTreeData.value = tree.map(domains => {
    return getNodesTree(domains)
  })
}

/**
 * 根据条件筛选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 getDetail = async () => {
  const prjDetail = await overviewProject(prj_id.value)
  detail.prj = prjDetail;
  works.value = prjDetail.works || []
  uni.setNavigationBarTitle({
    title: prjDetail.name,
  })
}

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

// 监听子组件增加，修改，删除事件，更新列表
useEmitt({
  name: 'get_contract_list',
  callback: () => {
    getContracts()
  }
})

onLoad((option) => {
  prj_id.value = option?.id
  if (option?.tabActiveKey) {
    tabActiveKey.value = option?.tabActiveKey as ProjectDetailTabPath
  }
  navigateOptions.value = option
  getDetail()
});

onPageScroll((e) => {
})

onMounted(async () => {
  getProjectType()
  getAccounts()
  getContracts()
  getCustomers()
  getRegions()
})



</script>
<script lang="ts">
export default {
  options: {
    styleIsolation: 'shared', //解除样式隔离
  }
}
</script>
<style scoped>
.container {
  padding: 0 5px 40px 5px;
}

:deep(.uni-list-item__content) {
  flex-direction: row;
  align-items: center;
  flex: 0 0 80px;
}

:deep(.uni-list-item__content-title) {
  font-size: 13px;
  color: #3b4144a8;
}

:deep(.uni-list-item__extra) {
  flex: 1 1 auto;
}

:deep(.uni-list-item__extra-text) {
  color: #5d5959;
  font-size: 13px;
  width: 200px;
  text-overflow: ellipsis;
  text-align: right;
  text-wrap: wrap;
  overflow-wrap: anywhere;
  white-space-collapse: collapse;
}

:deep(.ayi-progress) {
  min-width: 200px;
  margin-left: auto;
}

:deep(.ayi-progress__text) {
  text-align: right !important;
  width: 50rpx !important;
}

:deep(.uni-section) {
  margin-top: 5px;
}

.slot-box {
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: row;
  align-items: center;
  width: 45px;
  background-color: rgb(201, 205, 212);
  border-radius: 4px;
  margin-right: 10px;
  height: 45px;
}


.slot-content {
  display: flex;
  justify-content: space-between;
  flex-direction: row;
  width: 100%;
  /* height: 45px; */
}

.slot-panel {
  display: flex;
  flex-direction: column;
  height: 45px;
  justify-content: space-around;
}

.slot-title {
  display: flex;
  font-size: 14px;
  color: #3b4144;
}

.slot-subtitle {
  display: flex;
  font-size: 12px;
  color: #999
}

.slot-desc {
  color: #999;
  font-size: 13px;
  width: 200px;
  text-overflow: ellipsis;
  text-align: right;
  text-wrap: wrap;
  overflow-wrap: anywhere;
  white-space-collapse: collapse;

}

.mini-btn {
  color: #ffffff !important;
  background-color: #007aff;
  border-color: #007aff !important;
  font-size: 24rpx !important;
  -webkit-tap-highlight-color: transparent;
  border-radius: 5px;
  box-sizing: border-box;
  cursor: pointer;
  display: block;
  line-height: 2.55555556;
  margin-left: auto;
  margin-right: auto;
  overflow: hidden;
  padding-left: 28rpx;
  padding-right: 28rpx;
  position: relative;
  text-align: center;
  text-decoration: none;
  height: auto;
}

.y-tab-virtual {
  position: relative;
  flex-shrink: 0;
  width: 100%;
}

.scroll-wrap {
  height: calc(100vh - 44px);
  height: calc(100vh - 88px);
}
</style>
