<template>
  <div class="page-content">
    <div class="meeting-detail">
      <div class="normal-title text-center p-10 f-b">
        {{ meetingData.meetingTitle }}
        <van-icon v-if="isAuth('calendar:update') || userInfo.id === meetingData.createUser" name="edit"
          class="warning-text-color"
          @click="$router.push({ name: 'add-or-update-meeting', query: { meetingId: meetingId } })" />
        <van-icon v-if="isAuth('calendar:update') || userInfo.id === meetingData.createUser" name="delete-o"
          class="danger-text-color" @click="deleteMeeting" />
      </div>
      <div class="text-center m-5 f-b">{{ meetingData.meetingTime }}</div>
      <div class=" text-center m-5">
        <van-tag type="success" size="medium">{{ meetingData.meetingTypeName }}</van-tag>
      </div>
      <van-grid class="baseData" :column-num="2">
        <van-grid-item>会议形式</van-grid-item>
        <van-grid-item>{{ meetingData.meetingByName }}</van-grid-item>
        <van-grid-item>股票名称</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.stockNames }}</div>
        </van-grid-item>
        <van-grid-item>股票代码</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.stockCodes }}</div>
        </van-grid-item>
        <van-grid-item>电话拨入方式</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.phoneBy }}</div>
        </van-grid-item>
        <van-grid-item>网络端登录方式</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.netBy }}</div>
        </van-grid-item>
        <van-grid-item>会议密码</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.meetingPassword }}</div>
        </van-grid-item>
        <van-grid-item>嘉宾</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.meetingGuestList }}</div>
        </van-grid-item>
        <van-grid-item>研究员</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.oranizerName }}</div>
        </van-grid-item>
        <van-grid-item>发起人</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.organizer }}</div>
        </van-grid-item>
        <van-grid-item>IS参会人数</van-grid-item>
        <van-grid-item>{{ meetingData.meetingCusUserNum }}</van-grid-item>
        <van-grid-item>IS提问人数</van-grid-item>
        <van-grid-item>{{ meetingData.questionNum }}</van-grid-item>
        <van-grid-item>总参会人数</van-grid-item>
        <van-grid-item>{{ meetingData.userNumHigh }}</van-grid-item>
        <van-grid-item>总提问人数</van-grid-item>
        <van-grid-item>{{ meetingData.queationNumAll }}</van-grid-item>
        <van-grid-item>可见范围</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.visible === 1 ? '公开' : meetingData.visibleName }}</div>
        </van-grid-item>
        <van-grid-item>备注</van-grid-item>
        <van-grid-item>
          <div class="grid-item-text">{{ meetingData.content }}</div>
        </van-grid-item>
      </van-grid>
      <div class="sub-title m-16">会议资料</div>
      <file-list ref="meetingFile" />
      <div class="sub-title m-16">参会资料</div>
      <file-list ref="joinMeetingFile" />
      <div class="sub-title m-16 d-flex align-items-center">
        参会人员
        <van-button type="primary" size="mini" @click="addJoinPerson(1)" style="margin-left: 4px">报名</van-button>
        <van-button type="primary" size="mini" @click="addJoinPerson(2)">签到</van-button>
      </div>
      <van-popup v-model:show="showPersonPopup" position="bottom">
        <div class="p-10 box-popup">
          <div class="personTitle">当前添加联系人：{{ addPerson }}</div>
          <van-field v-model="searchCuseUser" placeholder="查找联系人" @input="onSearchInput"
            class="border-1 border-radius-8" />
          <div class="tip">
            <van-row v-if="personType === 2 || personType === 3">
              <van-col span="12">
                <van-field name="switch" label="签到">
                  <template #input>
                    <van-switch v-model="attend" size="20" :disabled="personType === 2" />
                  </template>
                </van-field>
              </van-col>
              <van-col span="12">
                <van-field name="switch" label="提问" v-show="attend">
                  <template #input>
                    <van-switch v-model="question" size="20" />
                  </template>
                </van-field>
              </van-col>
            </van-row>
            <van-picker show-toolbar title="" :columns="cusUserList" @click-option="onCusUserConfirm"
              @cancel="showPersonPopup = false">
              <template #confirm>
                <span></span>
              </template>
            </van-picker>
          </div>
        </div>
      </van-popup>
      <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <van-swipe-cell v-for="(item, index) in joinPersonList" :key="item.cusUserId">
          <van-cell>
            <div class="sub-title text-start balck-text-color">{{ item.cusUserName }}</div>
            <div class="d-flex">
              <div class="flex-1">
                <div class="content text-start">{{ item.cusName }}</div>
                <div class="content text-start">{{ item.positionName }}</div>
              </div>
              <div class="flex-1 text-end">
                <div class="content" :class="item.attend ? 'primary-text-color' : ''">
                  {{ item.attend ? '已到场' : '已报名' }}
                </div>
                <div class="content" v-if="item.attend" :class="item.question ? 'danger-text-color' : ''">
                  {{ item.attend ? item.question ? '已提问' : '未提问' : '' }}
                </div>
              </div>
            </div>
          </van-cell>
          <template #right>
            <van-button square type="danger" text="删除" @click="deleteJoinPerson(item, index)" />
            <van-button square type="primary" text="修改" @click="changeJoinPerson(item)" />
          </template>
        </van-swipe-cell>
      </van-list>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FileList from '@/components/file-list.vue'
import emitter from '@/utils/mitt'
import { isAuth } from '@/utils/index'
import userInfoStore from '@/stores/userInfo'
const userInfo = userInfoStore()
const route = useRoute()
const router = useRouter()
let meetingData = ref({
  meetingTime: '',
  meetingTitle: '',
  meetingTypeName: '',
  meetingByName: '',
  stockCodes: '',
  stockNames: '',
  phoneBy: '',
  netBy: '',
  meetingPassword: '',
  meetingCusUserNum: '',
  questionNum: '',
  userNumHigh: '',
  queationNumAll: '',
  meetingGuestList: '',
  organizer: '',
  oranizerName: '',
  visible: undefined,
  visibleName: '',
  content: '',
  createUser: ''
})
let meetingId: any = ref('')
const meetingFile: any = ref(null)
const joinMeetingFile: any = ref(null)
import fileInfoStore from '@/stores/fileInfo'
const fileInfo = fileInfoStore()

const init = () => {
  if (route.query && route.query.meetingId) {
    meetingId.value = route.query.meetingId
    emitter.emit('showLoading', '')
    getMeetingDetail()
  } else {
    router.push({ name: '404' })
  }
}

import {
  workMeetingInfo, workMeetingUserList, workMeetingGetFileId, workMeetinGetUserFileMenuId,
  cusUserMeetingLogList, cusUserMeetingLogDelete, cusUserLookUp, cusUserMeetingLogUpdateOrSave,
  workMeetingDelete
} from '@/utils/api'
const getMeetingDetail = async () => {
  const data1: any = await workMeetingInfo(meetingId.value)
  let meetingGuestNameList = data1.data.meetingGuestNames
    ? data1.data.meetingGuestNames.split(',')
    : []
  let meetingGuestList = ''
  meetingGuestNameList.forEach((item: any, index: number) => {
    meetingGuestList +=
      `
        ${item}
        ${index < meetingGuestNameList.length - 1 ? ',' : ''}
      `
  })
  data1.data.meetingGuestList = meetingGuestList
  meetingData.value = data1.data
  emitter.emit('setTitle', { title: meetingData.value.meetingTitle, type: 'meeting' })
  if (data1.data.visible === 3) {
    getVisible()
  }
  const data2: any = await workMeetingGetFileId({ meetingId: meetingId.value })
  if (meetingFile.value) {
    meetingFile.value.init(data2.data)
  }
  const data3: any = await workMeetinGetUserFileMenuId({ meetingId: meetingId.value })
  if (joinMeetingFile.value) {
    joinMeetingFile.value.init(data3.data)
  }
  nextTick(() => {
    if (fileInfo.fileId) {
      const el = document.getElementById(fileInfo.fileId)
      if (el) {
        el.scrollIntoView({ behavior: 'smooth' })
      }
      fileInfo.fileId = ''
      emitter.emit('hiddenLoading', '')
    } else {
      emitter.emit('hiddenLoading', '')
    }
  })
}

const getVisible = async () => {
  const { data } = await workMeetingUserList({ meetingId: meetingId.value })
  let name = ''
  data.forEach((ele: any, index: number) => {
    name += `${ele.userName}${index < data.length - 1 ? ',' : ''}`
  })
  meetingData.value.visibleName = name
}
let finished = ref(false)
let loading = ref(false)
let curPage = ref(1)
let joinPersonList = ref<{ cusUserId: string, cusUserName: string, cusName: string, positionName: string, attend: boolean, question: boolean }[]>([])
const onLoad = async () => {
  loading.value = true
  const { data } = await cusUserMeetingLogList({
    curPage: curPage.value,
    limit: 20,
    meetingId: meetingId.value
  })

  data.list.map((ele: any) => {
    ele.question = !!ele.question
    ele.attend = !!ele.attend
  })
  joinPersonList.value = joinPersonList.value.concat(data.list)
  if (joinPersonList.value.length >= data.totalCount) {
    finished.value = true
  } else {
    curPage.value++
  }
  loading.value = false
}

let attend = ref(false)
let question = ref(false)
let searchCuseUser = ref('')
let meetingUserId = ref('')
let personType = ref()
let showPersonPopup = ref(false)
let addPerson = ref('')
let cusUserList = ref<{ text: string, value: string, cusUserName: string, cusName: string, positionName: string, cusUserId: string }[]>([])
const addJoinPerson = (index: number) => {
  personType.value = index
  searchCuseUser.value = ''
  attend.value = false
  if (index === 2) {
    attend.value = true
  }
  question.value = false
  cusUserList.value = []
  meetingUserId.value = ''
  showPersonPopup.value = true
}

const changeJoinPerson = (e: any) => {
  personType.value = 3
  searchCuseUser.value = e.cusUserName
  attend.value = e.attend
  question.value = e.question
  cusUserList.value = [{
    cusUserName: e.cusUserName,
    cusName: e.cusName,
    positionName: e.positionName,
    cusUserId: e.cusUserId,
    text: `${e.cusUserName}${e.cusName ? '【' + e.cusName + '】' : ''}${e.positionName ? '(' + e.positionName + ')' : ''}`,
    value: e.cusUserId
  }]
  meetingUserId.value = e.meetingUserId
  showPersonPopup.value = true
}

import { debounceThrottle } from '@/mixins/debounce-throttle'
const { throttle } = debounceThrottle()
const onSearchInput = throttle(
  async () => {
    if (searchCuseUser.value) {
      const { data } = await cusUserLookUp({ cusUserName: searchCuseUser.value })
      cusUserList.value = data.map((ele: any) => {
        ele.text = `${ele.cusUserName}${ele.cusName ? '【' + ele.cusName + '】' : ''}${ele.positionName ? '(' + ele.positionName + ')' : ''}`
        ele.value = ele.cusUserId
        return ele
      })
      if (data.length === 1) {
        const res = {
          cusUserId: data[0].cusUserId,
          attend: attend.value ? 1 : 0,
          question: question.value ? 1 : 0,
          meetingId: meetingId.value,
          meetingUserId: meetingUserId.value || null
        }
        await cusUserMeetingLogUpdateOrSave(meetingUserId.value, res)
        addPerson.value = `${data[0].cusUserName},${addPerson.value}`
        searchCuseUser.value = ''
        cusUserList.value = []
      }
    } else {
      cusUserList.value = []
    }
  },
  500
)

const onCusUserConfirm = async (e: any) => {
  if (e.selectedIndexes[0] > -1) {
    const res = {
      cusUserId: e.selectedOptions[0].value,
      attend: attend.value ? 1 : 0,
      question: question.value ? 1 : 0,
      meetingId: meetingId.value,
      meetingUserId: meetingUserId.value || null
    }
    await cusUserMeetingLogUpdateOrSave(meetingUserId.value, res)
    addPerson.value = `${e.selectedOptions[0].cusUserName},${addPerson.value}`
    searchCuseUser.value = ''
    cusUserList.value = []
  }
}

watch(() => showPersonPopup.value, (val) => {
  if (!val) {
    curPage.value = 1
    joinPersonList.value = []
    finished.value = false
    addPerson.value = ''
    onLoad()
  }
})

const deleteJoinPerson = (e: any, index: number) => {
  showConfirmDialog({
    title: '提示',
    message:
      `是否确认删除${e.cusUserName}参加${meetingData.value.meetingTime} ${meetingData.value.meetingTitle}记录`,
  }).then(async () => {
    const data: any = await cusUserMeetingLogDelete([e.meetingUserId])
    if (data.code === 0) {
      showToast('删除成功')
      joinPersonList.value.splice(index, 1)
    }
  }).catch(() => {
  })
}
init()

import listRefreshInfoStore from '@/stores/listRefreshInfo'
const listRefreshInfo = listRefreshInfoStore()
const deleteMeeting = () => {
  showConfirmDialog({
    title: '提示',
    message:
      `是否确认删除会议${meetingData.value.meetingTitle}`,
  }).then(async () => {
    const data: any = await workMeetingDelete(meetingId.value)
    if (data.code === 0) {
      showToast('删除成功')
      listRefreshInfo.deleteId = meetingId.value
      router.go(-1)
    }
  }).catch(() => {
  })
}
</script>

<style lang='scss' scoped>
.meeting-detail {
  height: 100vh;
  overflow-y: auto;
}

.baseData {
  :deep(.van-grid-item:nth-child(2n)) {
    .van-grid-item__content {
      color: #1989fa;
    }
  }

  :deep(.van-grid-item__content) {
    font-size: 14px;
    font-weight: 400;
    padding: 8px 4px;
    font-size: 12px;
  }
}

.grid-item-text {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  text-align: center;
  max-width: calc(50vw - 16px);

  @media screen and (min-width: 678px) {
    max-width: 320px;
  }
}

:deep(.van-swipe-cell__right) {
  .van-button {
    height: 100%;
  }
}

.personTitle {
  height: 60px;
  overflow-y: auto;
}
</style>
