<template>
  <view>
    <Navbar title="企业详情" :textLeft="false" />
    <view class="ss-p-b-30" :style="{'padding-top': navbarHeight + 'px'}">
      <view class="commonBackground"></view>
      <view class="defaultBgc" >
        <view style="position: relative; z-index: 1;">
          <view class="mar">
            <view class="f-horizon ss-p-x-20">
              <image 
                class="default-border default-radius" 
                style="width: 70px; height: 70px; z-index: 1;" 
                :src="info.logoUrl || 'https://minio.menduner.com/dev/cd7f5e26a239fb0ab335585e04c709b065f52832fc31539b3a5423224fc6d16c.png'"
              ></image>
              <view class="f-straight ss-m-l-20" style="flex: 1;position: relative;">
                <view class="title-des MiSans-Semibold" style="max-width: 60vw;;">{{ formatName(info.anotherName || info.name) }}</view>
                <view class="color-999 ellipsis font-size-14 MiSans-Normal" style="max-width: 60vw;">
                  <span class="ss-m-r-10">{{ !!info.industryName? info.industryName : ''}}</span>
                  <span>{{ info.scaleName || '' }}</span>
                </view>
                <view class="collect-icon" @click="handleFollow">
                  <uni-icons :type="isCollection ? 'heart-filled' : 'heart'" color="#00B760" size="25"></uni-icons>
                </view>
              </view>
            </view>
          </view>
        
          <view class="ss-m-t-30">
            <uni-segmented-control :current="current" class="MiSans-Normal" :values="items" @clickItem="changeControl" styleType="text" activeColor="#00B760"></uni-segmented-control>
          </view>

          <!-- 企业信息 -->
          <view v-if="current === 0" class="ss-m-t-30 ss-m-x-30 ss-p-b-30" style="min-height: 75vh;">
            <span v-for="(tag, i) in info.tagList" :key="i" class="ss-m-r-10 ss-m-b-10" style="display: inline-block;">
              <uni-tag 
                :text="tag" 
                inverted="false" 
                size="default" 
                custom-style="background-color: #eef1f7;color:#7f828b;border-color:#eef1f7; display: inline-block;font-family: MiSans-Normal;"
              />
            </span>
            <!-- 简介 -->
            <view class="ss-m-t-30">
              <h4 class="MiSans-Semibold font-size-17">企业简介</h4>
              <view v-if="info.introduce" class="ss-m-t-20 htmlCss color-666 font-size-14 MiSans-Normal" v-html="info.introduce?.replace(/\n/g, '</br>')"></view>
              <view v-else></view>
            </view>
            <!-- 福利标签 -->
            <view class="topLine"></view>
            <view >
              <h4 class="MiSans-Semibold font-size-17">企业福利标签</h4>
              <view class="ss-m-t-20" v-if="info?.welfareList?.length">
                <span v-for="(tag, i) in info.welfareList" :key="i" class="ss-m-r-10 ss-m-b-10" style="display: inline-block;">
                  <uni-tag 
                    :text="tag" 
                    inverted="false" 
                    size="default" 
                    custom-style="background-color: #eef1f7;color:#7f828b;border-color:#eef1f7; display: inline-block; font-family: MiSans-Normal;"
                  />
                </span>
              </view>
              <view v-else></view>
            </view>
            <!-- 网址 -->
            <view class="topLine"></view>
            <view>
              <h4 class="MiSans-Semibold font-size-17">企业网址</h4>
              <view class="ss-m-t-20">
                <uni-link v-if="info.website" :href="info.website" :text="info.website" class="MiSans-Normal" color="#00B760"></uni-link>
                <view v-else></view>
              </view>
            </view>
            <view class="topLine"></view>
            <!-- 工商信息 -->
            <view>
              <h4 class="MiSans-Semibold font-size-17">工商信息</h4>
              <view v-if="info.business && Object.keys(info.business).length">
                <view class="ss-m-y-15" v-for="k in business" :key="k.value">
                  <view class="MiSans-Normal">{{ k.name }}</view>
                  <view class="color-666 ss-m-t-5 MiSans-Normal font-size-14">
                    {{ info.business[k.value] ? k.value === 'establishmentTime' ? timesTampChange(info.business[k.value], 'Y-M-D') : info.business[k.value] : '' }}
                  </view>
                </view>
              </view>
              <view v-else></view>
            </view>
            <!-- 地址 -->
            <view class="topLine"></view>
            <view>
              <h4 class="MiSans-Semibold font-size-17">企业地址</h4>
              <view class="ss-m-t-20" v-if="info?.business?.address">
                <uni-icons type="map-pin-ellipse" color="#00B760" size="20"></uni-icons>
                <span class="color-666 font-size-15 MiSans-Normal">{{ info?.business?.address }}</span>
              </view>
              <view v-else></view>
            </view>
            <view class="topLine"></view>
            <!-- 企业相册 -->
            <view>
              <h4 class="MiSans-Semibold font-size-17">企业相册</h4>
              <view class="ss-m-t-20" v-if="info?.albumList">
                <swiper class="swiper-box" :indicator-dots="true" indicator-active-color="#fff">
                  <swiper-item v-for="(item ,index) in info?.albumList" :key="index" style="overflow-x:hidden;overflow-y: auto;">
                    <image v-if="checkIsImage(item)" class="ac-imgs" :src="item" @click="previewImage(index)"></image>
                    <video v-else :id="'albumListVideo'+index" class="ac-imgs" :src="item" @error="videoErrorCallback" controls></video>
                  </swiper-item>
                </swiper>
              </view>
              <view v-else></view>
            </view>
          </view>

          <!-- 招聘岗位 -->
          <view v-if="current == 1">
            <scroll-view class="scrollBox" scroll-y="true" @scrolltolower="loadingMore">
              <view v-if="positionList.length > 0">
                <PositionList class="pb-10" :list="positionList" :noMore="false"></PositionList>
                <uni-load-more :status="status" />
              </view>
              <view v-else class="nodata-img-parents">
                <image src="https://minio.menduner.com/dev/bb43df1dc91945e05ee93da76e49b34f87b0d10203eb76c20e2d4999a13b9a0a.png" mode="widthFix" class="nodata-img-child"></image>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import { getEnterpriseDetails, enterpriseClick, getEnterpriseSubscribeCheck, getEnterpriseUnsubscribe, getEnterpriseSubscribe } from '@/api/user'
import { dealDictObjData } from '@/utils/position'
import { timesTampChange } from '@/utils/date'
import { getJobAdvertisedSearch } from '@/api/position'
import { getAccessToken } from '@/utils/request'
import PositionList from '@/components/PositionList'
import { checkIsImage } from '@/utils'
import { formatName } from '@/utils/getText'
import Navbar from '@/components/Navbar'

const navbarHeight = ref(0)

onMounted(async () => {
  try {
    const res = await new Promise((resolve, reject) => {
      uni.getStorage({
        key: 'navbarHeight',
        success: (result) => resolve(result),
        fail: (err) => reject(err)
      })
    })
    navbarHeight.value = res.data
	  console.log(navbarHeight.value, '企业详情-导航栏高度')
  } catch (error) {
    console.error('读取本地缓存出错:', error)
  }
})

const current = ref(0)
const items = ['企业介绍', '招聘职位']
const info = ref({})
const id = ref(null)
const title = ref('')
const business = [
  { name: '成立日期', value: 'establishmentTime' },
  { name: '注册资金', value: 'registeredCapital' },
  { name: '统一社会信用代码', value: 'code' },
]
const status = ref('more')
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  enterpriseId: id.value
})
const positionList = ref([])

// 预览
const previewImage = (i) => {
  uni.previewImage({
    current: i,
    urls: info.value.albumList
  })
}

// 企业埋点
const enterpriseClickFn = async () => {
  if (!id.value) return
  await enterpriseClick({ id: id.value })
}
enterpriseClickFn()

// 效验求职者是否关注该企业
const isCollection = ref(false)
const getCollectionStatus = async () => {
  if (!getAccessToken()) return isCollection.value = false
  const data = await getEnterpriseSubscribeCheck({ enterpriseId: id.value })
  isCollection.value = data.data
}

// 关注&取消关注企业
const handleFollow = async () => {
  if (!id.value) return
  const api = isCollection.value ? getEnterpriseUnsubscribe : getEnterpriseSubscribe
  await api(isCollection.value ? id.value : { enterpriseId: id.value })
  getCollectionStatus()
}

// 企业详情
const getData = async () => {
  const { data } = await getEnterpriseDetails(id.value)
  title.value = formatName(data.enterprise.anotherName || data.enterprise.name)
  info.value = data.enterprise ? { ...data, ...dealDictObjData({}, data.enterprise) } : data
  getCollectionStatus()
}

// 招聘职位列表
const getPositionList = async () => {
  queryParams.value.enterpriseId = id.value
  const { data } = await getJobAdvertisedSearch(queryParams.value)
  const list = data?.list || []
  if (list?.length) {
    list.forEach(e => {
      e.job = { ...e.job, ...dealDictObjData({}, e.job) }
      e.enterprise = { ...e.enterprise, ...dealDictObjData({}, e.enterprise)}
    })
    positionList.value = positionList.value.concat(list)
  }
  status.value = list?.length < queryParams.value.pageSize ? 'noMore' : 'more'
}

const loadingMore = () => {
  status.value = 'loading'
  queryParams.value.pageNo++
  getPositionList()
}

onLoad(async (options) => {
  id.value = options?.id || ''
  if (id.value) await getData()
  if (options?.index) {
    current.value = Number(options?.index)
    if (current.value === 1) getPositionList()
  }
})

wx.showShareMenu({
  withShareTicket: true,
  menus: ['shareAppMessage', 'shareTimeline']
})
onShareAppMessage(() => {
  if(!title.value){
		setTimeout(() => {},1000)
	}
  return {
    title: title.value || '门墩儿 专注顶尖招聘',
    path: `/pagesB/companyDetail/index?id=${id.value}&index=${current.value}`
  }
})
onShareTimeline(() => {
  if(!title.value){
		setTimeout(() => {},1000)
	}
  return {
    title: title.value || '门墩儿 专注顶尖招聘',
    path: `/pagesB/companyDetail/index?id=${id.value}&index=${current.value}`
  }
})

const changeControl = (e) =>{
  current.value = e.currentIndex
  if (current.value === 0) getData()
  else getPositionList()
}
const videoErrorCallback = (e) =>{
  uni.showToast({
    title: e?.target?.errMsg || '播放错误',
    icon: 'none'
  })
}
</script>

<style scoped lang="scss">
.title-des {
  color: #0E100F;
  font-size: 30rpx;
  margin-right: 30px;
  margin-top: 1px;
  vertical-align: middle;
  flex: 1;
}
.title-text{
  font-weight: 700;
  font-size: 18px;
}
.topLine {
  border-top: 1px solid #EDEDED;
  margin: 20px 0;
}
.swiper-box {
	height: 29vh;
}
.ac-imgs{
  width: 100%;
  height: 29vh;
  border-radius: 20px;
}
.collect-icon {
  position: absolute;
  top: 3px;
  right: 10px;
}
.scrollBox {
  height: 100vh;
}
</style>
