<template>
  <view>
    <Navbar :textLeft="false" title="我的聊天" />
    <view class="box defaultBgc MiSans-Normal" :style="{'padding-top': navbarHeight + 'px', height: 'calc(100vh - ' + navbarHeight + 'px)'}">
      <view class="commonBackground"></view>
      <view class="box-top">
        <image class="box-top-image" :src="getUserAvatar(info.avatar, info.sex, info.channelID === 'system' ? true : false)" ></image>
        <view class="box-top-right MiSans-Normal">
          <view class="box-top-right-title">{{ info.name }}</view>
        </view>
      </view>


        <!-- newsId 需要和聊天列表里面的id对应 永远取最后列表中的最后一个就可以做到发送消息即时滚动到底部 -->
        <scroll-view ref="chatRef" :scroll-with-animation="scrollAnimation" :scroll-into-view="newsId" class="box-main" scroll-y="true">
          <view class="box-main-more" v-if="hasMore">
            <text @click="handleMore">查看更多</text>
          </view>
          <view v-for="(val, index) in items" :key="val.id" :id="'s'+val.id+index">
            <view class="box-main-time">{{ timesTampChange(+(val.timestamp.padEnd(13, '0'))) }}</view>
            <template v-if="val.payload?.type === 102">
              <view class="jobCard">
                <view class="jobCard-title"> {{ formatName(val.payload?.content?.positionInfo?.name) }}</view>
                <view
                  v-if="!val.payload?.content?.positionInfo?.payFrom && !val.payload?.content?.positionInfo?.payTo"
                  class="jobCard-subtitle">
                  薪酬待遇： 面议
                </view>
                <view
                  v-else
                  class="jobCard-subtitle"
                >
                  薪酬待遇： 
                  {{ val.payload?.content?.positionInfo?.payFrom ? val.payload?.content?.positionInfo?.payFrom + ' - ' : '' }}
                  {{ val.payload?.content?.positionInfo?.payTo }}
                </view>
                <view class="jobCard-tag">
                  <view
                    v-for="(v, i) in (val.payload?.content?.positionInfo?.enterprise?.welfareList || [])"
                    :key="val.message_id + v + i"
                    style="margin: 10rpx"
                  >
                    <uni-tag
                      :text="v"
                      type="success"
                    />
                  </view>
                </view>
                <view class="jobCard-divider"></view>
                <view class="jobCard-subtitle text-right">
                  <v-avatar size="24">
                    <v-img :src="val.payload?.content?.positionInfo?.contact?.avatar"></v-img>
                  </v-avatar>
                  {{ val.payload?.content?.positionInfo?.contact?.name }}
                  {{ val.payload?.content?.positionInfo?.contact?.postNameCn }}
                  <!-- {{ formatName(val.payload?.content?.positionInfo?.enterprise?.anotherName || val.payload?.content?.positionInfo?.enterprise?.name) }} -->
                </view>
                <div class="jobCard-subtitle text-right">
                  地址：{{ val.payload?.content?.positionInfo?.address }}
                </div>
              </view>
            </template>
            <!-- 面试邀请 -->
            <template v-if="val.payload?.type === 101">
              <view class="jobCard">
                <view class="font-size-15 ss-m-b-20">面试邀请</view>
                <view class="jobCard-title"> {{ formatName(val.payload?.content?.positionInfo?.data?.name) }}</view>
                <view
                  v-if="!val.payload?.content?.positionInfo?.data?.payFrom && !val.payload?.content?.positionInfo?.data?.payTo"
                  class="jobCard-subtitle">
                  薪酬待遇： 面议
                </view>
                <view v-else class="jobCard-subtitle">
                  薪酬待遇： 
                  {{ val.payload?.content?.positionInfo?.data?.payFrom ? val.payload?.content?.positionInfo?.data?.payFrom + ' - ' : '' }}
                  {{ val.payload?.content?.positionInfo?.data?.payTo }}
                </view>
                <view class="font-size-15">面试时间： {{ timesTampChange(val.payload?.content?.time) }}</view>
                <view class="font-size-15">面试地点： {{ val.payload?.content?.address }}</view>
                <view class="font-size-15">联系电话： {{ val.payload?.content?.invitePhone }}</view>
              </view>
            </template>
            <view :class="['message-view_item', val.from_uid === IM.uid ? 'is-self' : 'is-other']">
              <view class="image">
                <image
                  :data-target="getUserAvatar(info.avatar, info.sex, info.channelID === 'system' ? true : false)"
                  class="header"
                  :src="(
                    val.from_uid === IM.uid ?
                    getUserAvatar(useUserStore.userInfo?.avatar, useUserStore.userInfo?.sex) :
                    getUserAvatar(info.avatar, info.sex, info.channelID === 'system' ? true : false)
                  )"
                ></image>
              </view>
              <!-- 显示沟通职位 -->
              <template v-if="val.payload?.type === 102">              
                <view
                  class="message-text" 
                  :class="val.from_uid === IM.uid ? 'active' : ''" 
                  :style="{'border-radius': val.from_uid === IM.uid ? '20rpx 20rpx 9rpx 20rpx' : '20rpx 20rpx 20rpx 9rpx'}"
                >
                  {{ val.payload?.content.text }}
                </view>
              </template>
              <!-- 发起面试邀请 -->
              <view class="message-text none" v-else-if="val.payload?.type === 101">
                <uni-tag text="发起了面试邀请" custom-style="background-color: #00B760; border-color: #00B760; color: #fff;" />
              </view>
              <view class="message-text none" v-else-if="val.payload?.type === 103">
                <uni-tag text="拒绝了面试邀请" type="error" />
              </view>
              <view class="message-text none" v-else-if="val.payload?.type === 104">
                <uni-tag text="接受了面试邀请" custom-style="background-color: #00B760; border-color: #00B760; color: #fff;" />
              </view>
              <view v-else-if="val.payload.type === 105" class="text-end">
                <uni-tag
                  v-if="val.from_uid === IM.uid"
                  :text="val.payload.content?.type === 1 ? '附件简历已发送' : '简历请求已发送'"
                  custom-style="background-color: #00B760; border-color: #00B760; color: #fff;"
                />
                <view
                  v-if="val.payload.content?.type !== 2 || val.from_uid !== IM.uid"
                  class="message-text card"
                >
                  <view class="text-left">
                    <text v-if="val.payload.content?.type === 1">{{
                      val.payload.content?.query?.title || '附件简历' }}
                    </text>
                    <text v-if="val.payload.content?.type === 2">
                      我想要一份您的简历，您是否同意
                    </text>
                  </view>
                  <view class="btn-actions">
                    <text class="btn" v-if="val.payload.content?.type === 1" @tap="handlePreview(val.payload)">点击预览附件简历</text>
                  </view>
                </view>
              </view>
              <view v-else-if="val.payload.type === -1" class="message-text" :class="{ active: val.from_uid === IM.uid}">
                {{ val.payload?.content?.text }}
              </view>
              <view 
                v-else 
                class="message-text" 
                :class="{ active: val.from_uid === IM.uid}" 
                :style="{'border-radius': val.from_uid === IM.uid ? '20rpx 20rpx 9rpx 20rpx' : '20rpx 20rpx 20rpx 9rpx'}">
                {{ val.payload?.content }}
              </view>
            </view>
          </view>
        </scroll-view>
        
      <view class="box-bottom" v-if="channelItem?.channelID !== 'system'">
        <view class="box-bottom-tool" style="display: flex; justify-content: start;">
          <text class="toolBtn" @tap="handleFindResume">求简历</text>
          <text class="toolBtn ss-m-l-30" @tap="handleInviteInterview">面试邀约</text>
        </view>
        
        <view class="d-flex align-end textBox" v-if="channelItem?.channelID !== 'system'">
          <textarea
            v-model="inputValue"
            :cursor-spacing="25"
            :show-confirm-bar="false"
            :disable-default-padding="true"
            confirm-type="send"
            auto-height
            @confirm="handleSend"
          />
          <text class="submitBtn" @tap="handleSend">发 送</text>
        </view>
      </view>

      <!-- 求简历 -->
      <uni-popup ref="requestPopup" background-color="#fff" type="bottom">
        <view style="background-color: #fff; height: 50vh; padding: 30px 20px;">
          <uni-forms ref="requestFormRef" :modelValue="formData" :rules="formRules" validateTrigger="bind" label-width="80px" label-align="right" label-position="left">
            <uni-forms-item name="jobId" label="招聘职位" required>
              <view style="max-width: calc(100vw - 120px);">
                <uni-data-select v-model="formData.jobId" :localdata="jobList"	@change="handleChangeJob"	placeholder="请选择要求简历的职位"></uni-data-select>
              </view>
            </uni-forms-item>
          </uni-forms>
          <view style="margin-top: 50px;"></view>
          <button class="send-button" @tap="handleRequestSubmit">提 交</button>
        </view>
      </uni-popup>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted, computed, unref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useIMStore } from '@/store/im'
import { userStore } from '@/store/user'
import { initConnect, send, initChart, getMoreMessages, toChannel } from '@/hooks/useIM'
import { timesTampChange } from '@/utils/date'
import { getUserAvatar } from '@/utils/avatar'
import { formatName } from '@/utils/getText'
import { preview } from '@/utils/preview'
import { getAccessToken } from '@/utils/request'
import { showAuthModal } from '@/hooks/useModal'
import { getJobAdvertisedList } from '@/api/new/position'
import Navbar from '@/components/Navbar'

const navbarHeight = ref(uni.getStorageSync('navbarHeight'))
const useUserStore = userStore()
const userInfo = computed(() => useUserStore?.userInfo)

const IM = useIMStore()
const info = ref({})
const chatRef = ref()
const items = ref([])
const channelItem = ref(null)
const hasMore = ref(false)

const pageSize = ref(1)

const inputValue = ref('')

const newsId = ref('') // newsId 需要和聊天列表里面的id对应 永远取最后列表中的最后一个就可以做到发送消息即时滚动到底部
const scrollAnimation = ref(false)

const isEmployment = ref('-1')

onMounted(() => {
  setTimeout(() => {
    scrollAnimation.value = true
  }, 1500)
})

const {
  conversationList,
  updateUnreadCount,
  resetUnread
} = initConnect(async (successful) => {
  if (!successful) {
    uni.showToast({
      title: '发送失败',
      icon: 'none',
      mask: true,
    })
    return
  }
  inputValue.value = ''
  // // 发送成功
  const { list } = await getMoreMessages(1, channelItem.value)
  items.value = list.value
})

watch(
  () => conversationList.value,
  async (val) => {
    if (!channelItem.value) {
      return
    }
    const { list } = await getMoreMessages(1, channelItem.value)
    
    items.value = list.value
    setScrollBottom()
    // 清除未读消息
    resetUnread(channelItem.value, userInfo.value?.enterpriseId)
  },
  {
    deep: true,
    immediate: true
  }
)

async function init(userId, enterpriseId) {
  const { channel, list, more } = await initChart(userId, enterpriseId)
  hasMore.value = more
  channelItem.value = channel.value
  items.value = list.value
  setScrollBottom()
}


const setScrollBottom = () => {
  if (items.value?.length) {
    const lastOne = items.value[items.value.length-1]
    const index = items.value.length-1
    newsId.value = 's' + lastOne.id + index // newsId 需要和聊天列表里面的id对应 永远取最后列表中的最后一个就可以做到发送消息即时滚动到底部
  }
}

function handleSend () {
  if (!inputValue.value) {
    uni.showToast({ title: '不能发送空白信息', icon: 'none' })
    return
  }
  send(inputValue.value, channelItem.value)
}

// 职位列表
const jobNum = ref(0)
const jobList = ref([])
const getJobList = async () => {
  const { data } = await getJobAdvertisedList({ pageNo: 1, pageSize: 10, hasExpiredData: false, status: 0 })
  jobNum.value = data?.total || 0
  jobList.value = data?.list ? data?.list.map(e => {
    return { text: formatName(e.name), value: e.id, ...e }
  }) : []
}

// 求简历
const requestPopup = ref()
const requestFormRef = ref()
const formData = ref({
  jobId: null
})
const formRules = {
	jobId: {
		rules: [{ required: true, errorMessage: '请选择要求简历的职位' }]
	}
}
const handleFindResume = async () => {
  if (!getAccessToken()) {
    showAuthModal()
    return
  }
  // 企业必须有招聘中的职位才能发起面试邀请
  if (jobNum.value === 0) {
		uni.showToast({
			title: '请先发布招聘职位',
			icon: 'none',
			duration: 2000
		})
		return
	}
  requestPopup.value.open()
}

const handleChangeJob = (e) => {
  const job = jobList.value.find(item => item.value === e)
	if (!job) return
  formData.value.positionInfo = job
}

const handleRequestSubmit = async () => {
  const valid = await unref(requestFormRef).validate()
	if (!valid) return

  const text = {
    remark: '求简历',
    query: {
      src: '',
      title: '',
      id: '',
      positionInfo: formData.value.positionInfo
    },
    type: 2
  }
  send (JSON.stringify(text), channelItem.value, 105)
  formData.value = { jobId: null }
  requestPopup.value.close()
}

// 邀约面试
const handleInviteInterview = () => {
  if (!getAccessToken()) {
    showAuthModal()
    return
  }
  // 企业必须有招聘中的职位才能发起面试邀请
  if (jobNum.value === 0) {
		uni.showToast({
			title: '请先发布招聘职位',
			icon: 'none',
			duration: 2000
		})
		return
	}

  const chartData = {
    ...channelItem.value,
    id: info.value.id
  }
	uni.navigateTo({
	  url: `/pagesB/InviteInterview/index?chartData=${encodeURIComponent(JSON.stringify(chartData))}`
	})
}

// 预览简历
function handlePreview (payload) {
  if (!payload?.content?.query?.src) {
    uni.showToast({ title: '简历地址不存在', icon: 'none' })
    return
  }
  preview(payload.content.query.src)
}

// 查看更多
async function handleMore () {
  try {
    uni.showLoading({
      title: '加载中...'
    })
    pageSize.value++
    const { list, more } = await getMoreMessages(pageSize.value, channelItem.value)
    items.value.unshift(...list.value)
    hasMore.value = more
  } finally {
    uni.hideLoading()
  }
}
onLoad(async (options) => {
  info.value = Object.keys(options).reduce((r, k) => {
    r[k] = decodeURIComponent(options[k])
    return r
  }, {})
  isEmployment.value = info.value.isEmployment
  channelItem.value = toChannel(info.value.channelID, info.value.channelType)

  if (channelItem.value.channelID === 'system') {
    const { list, more } = await getMoreMessages(1, channelItem.value)
    hasMore.value = more
    items.value = list.value
    setScrollBottom()
    // 清除未读消息
    resetUnread(channelItem.value, userInfo.value?.enterpriseId)
    // 更新未读消息
    updateUnreadCount()
    return
  }
  await init(info.value.id, info.value.enterpriseId)

  await getJobList() // 获取招聘中的职位

  // 清除未读消息
  resetUnread(channelItem.value, userInfo.value?.enterpriseId)
  // 更新未读消息
  updateUnreadCount()
})
</script>

<style lang="scss" scoped>
.text-left {
  text-align: left !important;
}
.text-right {
  text-align: right !important;
}
.box {
  width: 100%;
  display: flex;
  flex-direction: column;
  &-top {
    z-index: 1;
    padding: 30rpx 30rpx 0 30rpx;
    display: flex;
    justify-content: center;
    &-image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      margin-right: 30rpx;
    }
    &-right {
      flex: 1;
      display: flex;
      align-items: center;
      &-title {
        box-sizing: border-box;
        width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        margin-bottom: 10rpx;
      }
      &-subText {
        font-size: .85em;
        color: #999;
        .gun {
          padding: 0 10rpx;
        }
      }
    }
    &-content {
      padding: 20rpx 50rpx;
      padding-bottom: 20rpx;
      border-bottom: 2rpx solid #eee;
      .color-666 {
        color: #666;
      }
      .font-weight-bold {
        font-weight: bold;
      }
      .color-primary {
        color: #00B760;
      }
      .ml-3 {
        margin-left: 40rpx;
      }
      .mt-1 {
        margin-top: 12rpx;
      }
      .font-size-14 {
        font-size: 24rpx;
      }
      .py-1 {
        padding: 4rpx 0;
      }
      .tipsText {
        font-size: .75em;
        color: #999;
      }
      &-t {
        display: flex;
        justify-content: space-between;
      }
      .btnBox {
        display: flex;
        padding: 20rpx 60rpx;
        justify-content: space-around;
      }
    }
  }

  &-main {
    flex: 1;
    height: 0;
    padding: 40rpx;
    // overflow-y: auto;
    box-sizing: border-box;
    &-more {
      display: flex;
      justify-content: center;
      align-items: center;
      color: #24bc3e;
      font-size: .9em;
      padding: 20rpx 0;
    }
    &-time {
      user-select: none;
      position: relative;
      top: 16rpx;
      margin: 40rpx 0;
      text-align: center;
      max-height: 40rpx;
      text-align: center;
      font-weight: 400;
      font-size: .85em;
      color: #999;
    }
    .jobCard {
      padding: 30rpx;
      background: #fbfbfb;
      margin: 20rpx 5px;
      max-width: unset;
      border-radius: 20rpx;
      box-shadow: 1px 2px 12px rgba(0, 0, 0, 0.1);
      &-title {
        font-weight: 600;
        font-size: 36rpx;
        margin-bottom: 30rpx;
      }
      &-subtitle {
        padding: 10rpx 0;
      }
      &-tag {
        display: flex;
        flex-wrap: wrap;
      }
    }
    .message-view_item {
      display: flex;
      flex-direction: row;
      align-items: flex-start;
      margin: 16rpx 0;
      position: relative;
      .image {
        width: 60rpx;
        height: 60rpx;
        border-radius: 180rpx;
        overflow: hidden;
        .header {
          width: 60rpx;
          height: 60rpx;
        }
      }
      .text-end {
        text-align: right !important;
        width: 400rpx;
        margin-right: 20rpx;
      }
      .message-text {
        overflow-wrap: break-word;
        background-color: #00B760;
        color: #fff;
        border-radius: 12rpx;
        max-width: 75%;
        padding: 20rpx;
        font-family: MiSans-Normal;
        &.active {
          color: #fff;
          background: #00B760;
        }
        &.card {
          // background: #E2F2F0;
          background: #fff;
          color: #00B760 ;
          margin-top: 20rpx;
          max-width: unset;
          margin-right: 0;
          box-shadow: 1px 2px 12px rgba(0, 0, 0, 0.1);
          .btn-actions {
            margin: 40rpx auto 20rpx auto ;
            text-align: center;
            .btn {
              padding: 10rpx 30rpx;
              background: #C8E7D8;
              color: #43AC57;
              font-size: .75em;
              border-radius: 10rpx;
            }
          }
        }
        &.none {
          padding: 10rpx 0;
          background-color: unset;
        }
        &.active {
          background: #00B760;
          color: #fff;
        }
      }
    }
    .is-self {
      flex-direction: row-reverse;
      display: flex;
      .message-text {
        margin-right: 20rpx;
      }
    }
    .is-other {
      .message-text {
        margin-left: 20rpx;
      }
    }
  }
  &-bottom {
    max-height: 300rpx;
    border-top: 2rpx solid #EEE;
    background: #fff;
    padding: 20rpx 40rpx 40rpx;

    box-sizing: border-box;
    &-tool {
      margin-bottom: 30rpx;
      .toolBtn {
        padding: 12rpx 20rpx;
        font-size: 24rpx;
        background: #00B760;
        color: #FFF;
        border-radius: 10rpx;
      }
    }
    .textBox {
      align-items: flex-end;
    }
    textarea {
      border-radius: 10rpx;
      width: 100%;
      min-height: 80rpx;
      max-height: 180rpx;
      padding: 20rpx;
      box-sizing: border-box;
      background: #f5f5f5;
    }
    .submitBtn {
      width: 140rpx;
      line-height: 80rpx;
      height: 80rpx;
      font-size: 28rpx;
      background: #00B760;
      color: #FFF;
      margin-left: 20rpx;
      text-align: center;
      border-radius: 10rpx;
    }
  }
  .popup-title {
    padding: 30rpx 20rpx;
    display: flex;
    justify-content: space-between;
    border-bottom: 2rpx solid #DDD;
  }
  .popup-content {
    padding: 20rpx 40rpx;
    color: #999;
    display: flex;
    align-content: center;
    justify-items: center;
    .iconBox {
      width: 40rpx;
    }
    .text {
      margin-left: 20rpx;
      &.active {
        color: #00B760;
      }
    }
  }
  .popup-upload {
    // display: flex;
    // align-items: center;
    // justify-content: center;
    // flex-direction: column;
    // width: 70%;
    width: 80vw;
    font-size: .75em;
    color: #999;
    padding: 40rpx;
    &-box {
      width: 200rpx;
      height: 200rpx;
      text-align: center;
      line-height: 200rpx;
      border: 4rpx solid #ddd;
      border-radius: 8rpx;
      margin: 0 auto;
    }
  }
  .popup-actions {
    padding: 60rpx;
    .default {
      background: #00B760;
      color: #DDD;
      font-size: .9em;
    }
  }
}
</style>