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

          <p>
            <span>系统名称：</span>
            <span>{{ planDetail.lineName }}</span>
          </p>
          <p>
            <span>店铺编码：</span>
            <span>{{ planDetail.storeCode }}</span>
          </p>
          <p>
            <span>上班时间：</span>
            <span>{{ parseTime(planDetail.clockInTime, "{h}:{i}:{s}") }}</span>
          </p>
          <p>
            <span>下班时间：</span>
            <span>{{ parseTime(planDetail.clockOutTime, "{h}:{i}:{s}") }}</span>
          </p>
          <p>
            <span>促销员薪资：</span>
            <span>¥{{ planDetail.salary }}</span>
          </p>
          <p>
            <span>杂费：</span>
            <span>¥{{ planDetail.incidentals }}</span>
          </p>
          <p>
            <span>经销商：</span>
            <span>{{ planDetail.dealerName }}</span>
          </p>
          <p>
            <span>创建人：</span>
            <span>{{ planDetail.createBy }}</span>
          </p>
          <p>
            <span>修改人：</span>
            <span>{{ planDetail.modifyBy }}</span>
          </p>
          <p>
            <span>地址：</span>
            <span>{{ planDetail.addr }}</span>
          </p>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 任务列表 -->
    <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">
          <template #title>
            <p>{{ item.temporaryName }}</p>
            <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>
  </div>
</template>

<script setup>
import { getPlanDetailAPI, createExamine } from '@/api'
import { parseTime } from '@/utils'
import userStore from '@/store/modules/user'
import { getPromotionActiveStatus } from '@/dicts'

const { proxy } = getCurrentInstance()
const isCityManager = ref(userStore().promotionIdentity)
// 获取路由路径上的 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.planId)
  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
    }])
    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: null,
        planId: planDetail.value.id,
        planStatus: planDetail.value.planStatus === 0 ? '否' : '是',
        employeeId: userStore().userInfo.userId, // 稽查人id
        employeeName: userStore().userInfo.nickName, // 稽查人名字
        employeeNo: userStore().employeeNo, // 稽查人工号
      })
      if (!result.data) {
        return proxy.$modal.msgError('创建稽查任务失败')
      }
      newExamined.value = result.data.id
    }
    router.push({ path: `/m/examine/${examined?.value || newExamined.value}` })
  })
}

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
  lang="scss">

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

    /* 计划详情 */
    .van-cell-group {
      background: #f5f5f5;

      .van-cell__title {
        p {
          font-size: 14px;
          margin: 0 0 5px;
        }
      }

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

        p {
          display: flex;

          span:first-child {
            width: 100px;
            display: inline-block;
          }

          span:nth-child(2) {
            flex: 1;
          }
        }

      }

    }

    /* 任务列表 */
    .van-list {
      margin-top: 20px;
      overflow: hidden;

      .van-cell-group {
        margin: 0 20px;
        width: 100%;

        /* 每个上报人组 */
        ::v-deep(.van-cell) {
          width: calc(100% - 40px);

          .van-cell__title {
            width: 100%;

            .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>