<template>
  <div class="mobile-container">
    <van-nav-bar left-text="返回"
      :right-text="(examined ? '已' : '未') + '稽查'"
      left-arrow
      @click-left="clickBack()"
      @click-right="clickExamine()"
      fixed
      placeholder />
    <van-cell-group>
      <van-cell>
        <template #title>
          <p>{{ planDetail.storeName }}</p>
          <p>{{ planDetail.pattern }}</p>
        </template>
        <template #label>
          <p class="employee"
            v-if="planDetail.planStatus === 0">未执行</p>
          <p v-else
            class="employee plan-go">执行</p>
          <p class="employee">活动日期：&emsp;{{ parseTime(planDetail.date, '{y}-{m}-{d} (周{a})') }}</p>
          <p class="employee">归属人：&emsp;&emsp;{{ planDetail.employeeName }}（{{ planDetail.employeeNo }}）</p>
          <p class="employee">战区：&emsp;&emsp;&emsp;{{ planDetail.orgName }}</p>

          <p class="employee">系统名称：&emsp;{{ planDetail.lineName }}</p>
          <p class="employee">店铺编码：&emsp;{{ planDetail.storeCode }}</p>
          <p class="employee">上班时间：&emsp;{{ parseTime(planDetail.clockInTime, "{h}:{i}:{s}") }}</p>
          <p class="employee">下班时间：&emsp;{{ parseTime(planDetail.clockOutTime, "{h}:{i}:{s}") }}</p>
          <p class="employee">促销员薪资：¥{{ planDetail.salary }}</p>
          <p class="employee">杂费：&emsp;&emsp;&emsp;¥{{ planDetail.incidentals }}</p>
          <p class="employee">经销商：&emsp;&emsp;{{ planDetail.dealerName }}</p>
          <p class="employee">创建人：&emsp;&emsp;{{ planDetail.createBy }}</p>
          <p class="employee">修改人：&emsp;&emsp;{{ planDetail.modifyBy }}</p>
          <p class="employee">地址：&emsp;&emsp;&emsp;{{ planDetail.addr }}</p>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 任务列表 -->
    <van-pull-refresh v-model="refreshLoading"
      :pull-distance="100"
      @refresh="onRefresh">
      <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 in planList"
            :key="item.id"
            label-class="image-cell">
            <template #title>
              <p>{{ item.temporaryName }}</p>
              <p class="gray_title">参考地址：{{ 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-pull-refresh>

    <van-image-preview v-model:show="show"
      :images="images"
      :start-position="startIndex"
      @change="onChange">
      <template v-slot:index>第{{ index + 1 }}张</template>
    </van-image-preview>
  </div>
</template>

<script setup>
import { getPlanDetailAPI, createExamine } from '@/api'
import { parseTime } from '@/utils'
import userStore from '@/store/modules/user'
const { proxy } = getCurrentInstance()
// 获取路由路径上的 id 参数
const route = useRoute();
const router = useRouter();

// 稽查
const examined = ref(0) // 获取默认的
const newExamined = ref(0) // 没有默认创建的新的

// 获取计划详情
const planDetail = ref({})
const planList = ref([])
const getPlanDetail = async () => {
  const res = await getPlanDetailAPI(route.params.id)
  planDetail.value = res.data.planInfo
  examined.value = res.data.examine?.id

  // 循环多人打卡记录
  planList.value = res.data.reporteds?.map(o => {
    const { tgcjPhotoInfos: tgcjPhotoInfosList, tghdPhotoInfos: tghdPhotoInfosList, tgscPhotoInfos: tgscPhotoInfosList } = o.reported
    if (tgscPhotoInfosList) {
      var tgscPhotoInfos = [...tgscPhotoInfosList?.map(item => ({
        time: parseTime(item.createTime, '{h}:{i}'),
        photoUrl: item.photoUrl
      }))]
    }
    if (tghdPhotoInfosList) {
      var tghdPhotoInfos = [...tghdPhotoInfosList?.map(item => ({
        time: parseTime(item.createTime, '{h}:{i}'),
        photoUrl: item.photoUrl
      }))]
    }
    if (tgcjPhotoInfosList) {
      var tgcjPhotoInfos = [...tgcjPhotoInfosList?.map(item => ({
        time: parseTime(item.createTime, '{h}:{i}'),
        photoUrl: item.photoUrl
      }))]
    }

    // 判断上班卡，午休下班卡，午休上班卡，下班卡是否有值，有则添加到数组中
    // 数组是二维数组，第一到三是推广数据，第四个是打卡数据
    const { clockInTime, clockInPhoto, noonClockOutTime, noonClockOutPhoto, noonClockInTime, noonClockInPhoto, clockOutTime, clockOutPhoto } = o.clock
    const clockList = []
    if (clockInTime) {
      clockList.push({
        time: parseTime(clockInTime, '{h}:{i}'),
        title: '上班卡',
        photoUrl: clockInPhoto
      })
    }
    if (noonClockOutTime) {
      clockList.push({
        time: parseTime(noonClockOutTime, '{h}:{i}'),
        title: '午休下班卡',
        photoUrl: noonClockOutPhoto
      })
    }
    if (noonClockInTime) {
      clockList.push({
        time: parseTime(noonClockInTime, '{h}:{i}'),
        title: '午休上班卡',
        photoUrl: noonClockInPhoto
      })
    }
    if (clockOutTime) {
      clockList.push({
        time: parseTime(clockOutTime, '{h}:{i}'),
        title: '下班卡',
        photoUrl: clockOutPhoto
      })
    }

    // 组装数据
    const photoDialogList = ref([{
      title: '推广试吃照片',
      list: tgscPhotoInfos
    }, {
      title: '推广互动照片',
      list: tghdPhotoInfos
    }, {
      title: '推广成交照片',
      list: tgcjPhotoInfos
    }, {
      title: '考勤打卡照片',
      list: clockList
    }])
    // 把数组里图片合并成一个大数组
    // const allPhotoList = ref([])
    // photoDialogList.value.forEach(o => {
    //   if (o.list) {
    //     allPhotoList.value.push(...o.list)
    //     allPhotoList.value.push(...o.list)
    //     allPhotoList.value.push(...o.list)
    //   }
    // })
    return {
      id: o.reported.id, // 用的是促销上报的id，不是打卡的 id 
      province: o.reported.province, // 省份
      city: o.reported.city, // 城市
      addr: o.clock.clockInAddress, // 地址
      temporaryName: o.reported.temporaryName, // 临时名称
      photoList: photoDialogList, // 照片列表
    }
  })
}
getPlanDetail()

// 点击稽查按钮
const clickExamine = async () => {
  // 确认是否开始稽查
  proxy.$modal.confirm(`确认 ${examined.value ? '编辑' : '创建'} 稽查任务吗？`).then(async () => {
    // 如果稽查 ID 是空则创建一个
    if (!examined.value) {
      const result = await createExamine({
        ...planDetail.value,
        id: '',
        planId: planDetail.value.id,
        planStatus: planDetail.value.planStatus === 0 ? '未执行' : '执行',
        employeeId: userStore().userInfo.userId, // 稽查人id
        employeeName: userStore().userInfo.nickName, // 稽查人名字
        employeeNo: userStore().getEmployeeNo, // 稽查人工号
      })
      if (!result.data) {
        return proxy.$modal.msgError('创建稽查任务失败')
      }
      newExamined.value = result.data.id
    }
    router.push({ path: `/examine/${examined?.value || newExamined.value}` })
  })
}

const refreshLoading = ref(false)
const onRefresh = () => {
  refreshLoading.value = true
  setTimeout(() => {
    refreshLoading.value = false
    getPlanDetail()
  }, 1000)
}
const loading = ref(false)
const finished = ref(false)
const onLoad = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    finished.value = true
  }, 1000)
}

const clickBack = () => {
  router.back()
}

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
}


</script>

<style scoped>
p {
  margin: 0;
}

.plan-go {
  color: #39bb74;
}

.mobile-container {
  background: #f5f5f5;
  min-height: 100vh;

  .van-cell-group {
    background: #f5f5f5;
  }

  .van-list {
    margin-top: 20px;
    min-height: 100vh;

    ::v-deep(.van-cell:nth-child(n+2)) {
      margin-top: 20px;
    }

    ::v-deep(.van-cell) {
      .item {
        margin-top: 20px;
      }
    }
  }

  ::v-deep(.van-cell__title) {
    flex: 3;
    width: 100%;

    .image-wrap {
      /* 强制内容在一行 */
      white-space: nowrap;
      flex: 1;
      overflow: scroll;
      overflow-y: hidden;

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

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

  }

  ::v-deep(.van-cell__label) {
    flex: 1;
    width: 100%;
  }
}

::v-deep(.employee) {
  margin-bottom: 5px !important;
}

::v-deep(.van-popup--right) {
  width: 85% !important;
}

::v-deep(.van-cell__label) {
  font-size: 14px !important;
}

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

  .van-image {
    height: 135px;
  }
}


.gray_title {
  color: gray;
}

.black_title {
  color: black;
}
</style>