<template>
  <p class="title">
    <span>促销员打卡记录：</span>
    <span>共 {{ planList.length || 0 }} 条</span>
  </p>
  <!-- 任务列表 -->
  <van-list v-model:loading="loading"
    :finished="finished"
    :immediate-check="false"
    finished-text="没有更多了"
    @load="onLoad">
    <van-cell-group inset
      v-if="planList?.length > 0">
      <van-cell v-for="item, index in planList"
        :key="item.id">
        <template #title>
          <div class="cell-info">
            <div class="info">
              <span>促销员名字：{{ item.temporaryName }}</span>
              <span>手机号码：
                <span class="phone-link"
                  @click="showPhonePicker(item)"> {{ item.phone }}</span>
              </span>
            </div>
            <van-button class="delete-btn"
              type="danger"
              v-if="showDelete(planDetail)"
              @click="deleteView(item, index)">删除此打卡记录</van-button>
          </div>
          <p>打卡参考地址：{{ item.province + item.city + item.addr }}</p>
        </template>
        <template #label>
          <div class="item"
            v-for="o in item.photoList">
            <template v-if="o.list">
              <p class="black_title">{{ o.title }}：</p>
              <div class="image-wrap">
                <div class="small-item"
                  v-for="obj, index in o.list">
                  <van-image :src="obj.photoUrl"
                    @click="previewImage(o.list, index)" />
                  <p>{{ obj.title }}</p>
                  <p>{{ obj.time }}</p>
                </div>
              </div>
            </template>
          </div>
        </template>
      </van-cell>
    </van-cell-group>
  </van-list>
  <!-- 图片预览 -->
  <van-image-preview v-model:show="show"
    :images="images"
    :start-position="startIndex"
    @change="onChange">
    <template v-slot:index>第{{ index + 1 }}张</template>
  </van-image-preview>

  <!-- 手机号码选择器 -->
  <van-action-sheet v-model:show="showPicker"
    :actions="phoneActions"
    cancel-text="取消"
    @select="onPickerConfirm" />
</template>

<script setup>
import { parseTime } from '@/utils'
import { deletePromotionSystemAPI } from '@/api'

const { proxy } = getCurrentInstance()

const props = defineProps({
  planDetail: {
    type: Object,
    default: () => ({})
  },
  planList: {
    type: Array,
    default: () => []
  }
})
const emits = defineEmits(['refresh'])

// 加载更多-刷新列表
const loading = ref(false)
const finished = ref(false)
const onLoad = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    finished.value = true
  }, 1000)
}

// 图片预览
const show = ref(false)
const images = ref([])
const index = ref(0)
const startIndex = ref(0)
const previewImage = (list, ind) => {
  show.value = true
  startIndex.value = ind
  images.value = list.map(o => o.photoUrl)
}
const onChange = (ind) => {
  index.value = ind
}

// 手机号码选择器相关
const showPicker = ref(false)
const currentPhoneItem = ref(null) // 现在要拨打或复制的信息对象
const phoneActions = ref([
  { name: '拨打电话', value: 'call' },
  { name: '复制号码', value: 'copy' }
])

const showPhonePicker = (item) => {
  currentPhoneItem.value = item
  showPicker.value = true
}

// 选择器确认事件
const onPickerConfirm = (value) => {
  const phone = currentPhoneItem.value.phone
  switch (value.value) {
    case 'call':
      // 拨打电话
      window.location.href = `tel:${phone}`
      break
    case 'copy':
      // 复制号码
      copyToClipboard(phone)
      break
  }
  showPicker.value = false
}

// 删除计划
// 是否展示删除按钮
const showDelete = (row) => {
  // 上报日期不是当月则隐藏按钮
  // const date = parseTime(row.date, '{y}-{m}')
  // const currentDate = parseTime(new Date(), '{y}-{m}')
  // return date === currentDate
  return true
}

// 复制到剪贴板
const copyToClipboard = (text) => {
  if (navigator.clipboard && window.isSecureContext) {
    navigator.clipboard.writeText(text).then(() => {
      showNotify({ type: 'success', message: '号码已复制' })
    }).catch(() => {
      fallbackCopyText(text)
    })
  } else {
    fallbackCopyText(text)
  }
}

// 兼容性复制方法
const fallbackCopyText = (text) => {
  const textArea = document.createElement('textarea')
  textArea.value = text
  textArea.style.position = 'fixed'
  textArea.style.left = '-999999px'
  textArea.style.top = '-999999px'
  document.body.appendChild(textArea)
  textArea.focus()
  textArea.select()
  try {
    document.execCommand('copy')
    showNotify({ type: 'success', message: '号码已复制' })
  } catch (err) {
    showNotify({ type: 'warning', message: '复制失败，请手动复制' })
  }
  document.body.removeChild(textArea)
}

// 点击删除
const deleteView = (item, index) => {
  // 确认是否删除
  showConfirmDialog({
    title: '系统提示',
    message: '确认删除该记录吗？'
  }).then(async () => {
    // 删除
    await deletePromotionSystemAPI(item.id)
    showNotify({ type: 'success', message: '删除成功' })
    props.planList.splice(index, 1)
    emits('refresh')
    proxy.eventBus.emit('delPromotionTaskEvent')
  })
}
</script>

<style scoped
  lang="scss">

  /* 标题 */
  .title {
    font-size: 14px;
    margin: 20px 0 0 0;
    background-color: white;
    padding: 10px;

    span:last-child {
      float: right;
    }
  }

  /* 任务列表 */
  .van-list {
    overflow: hidden;

    .van-cell-group {
      margin: 0;
      background-color: transparent;

      /* 每个上报人组 */
      ::v-deep(.van-cell) {
        width: 100%;
        padding: 0 10px;
        border-top: 5px solid #f5f5f5;

        .van-cell__title {
          width: 100%;

          .cell-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;

            .info {
              display: flex;
              flex-direction: column;
              justify-content: space-between;

              .phone-link {
                color: #1989fa;
                cursor: pointer;
              }
            }

            .delete-btn {
              height: 30px;
            }
          }

          .van-cell__label {

            /* 每个照片组（推广试吃，推荐成交） */
            .item {
              margin-top: 20px;

              /* 横向图片容器 */
              .image-wrap {
                /* 强制内容在一行 */
                white-space: nowrap;
                overflow: scroll;
                overflow-y: hidden;


                .small-item {
                  width: 125px;
                  text-align: center;
                  display: inline-block;

                  .van-image {
                    height: 135px;
                  }

                  p {
                    display: block;
                  }

                }

                &::-webkit-scrollbar-track {
                  background-color: transparent;
                }

                .van-image {
                  display: inline-block;
                  margin: 0 10px;
                }
              }
            }
          }
        }

        &:nth-child(n+2) {
          margin-top: 20px;
        }
      }
    }
  }
</style>