<template>
  <!-- 稽查任务 -->
  <div class="wrap">
    <van-nav-bar left-arrow
      left-text="返回"
      @click-left="router.back()">
    </van-nav-bar>
    <div class="content">
      <p class="title">稽查任务:</p>
      <!-- 终端名称 -->
      <div class="terminal-wrap">
        <div>
          <van-image fit="scale-down"
            width="2.25rem"
            height="3.5rem"
            :src="form.storePicture || form.commitStorePicture[0]?.url"
            @click="previewStoreImage"></van-image>
        </div>
        <div class="terminal-info">
          <div class="terminal-name">
            <span>终端名称：</span>
            <van-field v-model="form.storeName"
              placeholder="请输入终端名" />
          </div>
          <p>终端编码：P0500052306</p>
          <p>经销商：秦皇岛红朗森商贸有限公司</p>
          <p>地址：河北省秦皇岛市海港区北环路街道秦皇岛冻结附录</p>
        </div>
      </div>
      <!-- 地址 -->
      <div class="location-wrap">
        <van-icon name="location-o"
          class="location-icon" />
        <van-loading size="20px"
          v-if="addressLoading">正在获取您的位置...</van-loading>
        <p v-else>{{ addressStr }}</p>
        <van-icon name="replay"
          class="refresh-icon"
          @click="handleClickLocation" />
      </div>
      <!-- 门头照上传 -->
      <div class="header-photo-section">
        <van-field label="门头照"
          label-align="top">
          <template #input>
            <van-uploader :max-count="1"
              accept="image/*"
              capture="camera"
              reupload
              :model-value="form.commitStorePicture"
              :after-read="commitStorePhotosRead"
              preview-size="78"
              @delete="deleteCommitStorePhotos">
            </van-uploader>
          </template>
        </van-field>
      </div>
      <!-- 门店类型选择 -->
      <van-field :model-value="form.selectedType.join('')"
        readonly
        label="门店类型"
        label-align="top"
        placeholder="请选择"
        @click="showTypePopup = true" />
      <van-popup v-model:show="showTypePopup"
        position="bottom"
        @close="showTypePopup = false">
        <van-picker v-model="form.selectedType"
          :columns="typeOptions"
          @confirm="handleTypeConfirm"
          @cancel="showTypePopup = false" />
      </van-popup>
      <!-- 信息填写组 -->
      <van-tabs v-model:active="active"
        class="tabs"
        swipeable
        sticky>
        <van-tab title="常规陈列">
          <convention />
        </van-tab>
        <van-tab title="档期陈列">
          <scheduleDisplay />
        </van-tab>
        <van-tab title="档期补差">
          <scheduleAdjustment />
        </van-tab>
        <van-tab title="品类信息">
          <categoryInfomation />
        </van-tab>
      </van-tabs>
      <!-- 任务总结 -->
      <div class="task-summary">
        <p class="title">其他：</p>
        <van-field label="礼盒/礼袋是否在售："
          label-align="top">
          <template #input>
            <van-checkbox-group v-model="form.lhldArr"
              direction="horizontal"
              shape="square">
              <van-checkbox name="礼盒">礼盒</van-checkbox>
              <van-checkbox name="礼袋">礼袋</van-checkbox>
            </van-checkbox-group>
          </template>
        </van-field>
        <van-field v-model="form.skuNum"
          label="我品 SKU 总数："
          type="number"
          placeholder="请输入"
          label-align="top" />
        <van-field v-model="form.remark"
          label="备注："
          placeholder="请输入"
          label-align="top"
          type="textarea"
          border />
        <!-- 大日期产品照片 -->
        <div class="header-photo-section">
          <van-field label="大日期产品照片"
            label-align="top">
            <template #input>
              <van-uploader :max-count="4"
                accept="image/*"
                capture="camera"
                reupload
                :model-value="form.longTimePictureArr"
                :after-read="longTimePictureArrRead"
                preview-size="78"
                @delete="deleteLongTimePictureArr">
              </van-uploader>
            </template>
          </van-field>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { uploadFileToOSSAPI, getLocation, getInspectionTaskDetailAPI, createInspectionTaskAPI } from '@/api'
import { typeOptions as typeOption } from '@/views/mobile/constant'
import convention from './tabs/conventionalDisplay.vue'
import scheduleDisplay from './tabs/scheduleDisplay.vue'
import scheduleAdjustment from './tabs/scheduleAdjustment.vue'
import categoryInfomation from './tabs/categoryInfomation.vue'
import { showImagePreview } from 'vant';
import useUserStore from '@/store/modules/user'
import { v4 as uuidv4 } from 'uuid'

const router = useRouter()
const route = useRoute()

/*************** 稽查任务总体 ***************/
const form = reactive({ // 当前页信息总对象
  selectedType: [], // 门店类型
  storePicture: route.query.storePicture, // 门店照片（原始门店照片）
  storeName: route.query.storeName, // 门店名称
  storeCode: route.query.storeCode, // 门店编码
  dealersName: route.query.dealersName, // 经销商名称
  storeAddr: route.query.storeAddr, // 门店地址
  commitStorePicture: [], // 上报拍摄的门店照片
  lhldArr: [], // 其他-礼盒礼袋是否在售
  skuNum: '', // 我品 SKU 总数
  remark: '', // 备注
  longTimePictureArr: [], // 大日期产品照片
})

// 稽查任务详情
const getInspectionTaskDetailFn = async () => {
  const res = await getInspectionTaskDetailAPI({
    storeCode: form.storeCode
  })
  console.log(res)
}
getInspectionTaskDetailFn()

// 门店图片预览
const previewStoreImage = () => {
  showImagePreview({
    images: [form.storePicture],
  })
}

/*************** 地理定位 ***************/
const addressStr = ref('')
const addressLoading = ref(true)
const getLocationFn = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(
      async function (position) {
        const lat = position.coords.latitude;
        const lng = position.coords.longitude;
        const res = await getLocation({
          lat,
          lng
        })
        const { standard_address } = res.result.formatted_addresses
        addressStr.value = standard_address

        addressLoading.value = false
      },
      function (error) {
        showDialog({
          title: '系统提示',
          message: '请开启软件的定位授权，再试',
        })
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      }
    );
  } else {
    showDialog({
      title: '系统提示',
      message: '你的设备不支持定位',
    })
  }
}
getLocationFn()
const handleClickLocation = () => {
  addressLoading.value = true
  setTimeout(() => {
    getLocationFn()
  }, 1500)
}

/*************** 门头照上传 ***************/
// 上传照片
const commitStorePhotosRead = async (file) => {
  const pictureUrl = await uploadFileToOSSAPI(`risk/${form.storeCode}storeFrontPhoto/${useUserStore().userInfo.employeeNo}/${uuidv4()}.png`, file.file)
  form.commitStorePicture = [{
    url: pictureUrl
  }]
  showNotify({ type: 'success', message: '门头照，上传成功' })
}
// 删除照片
const deleteCommitStorePhotos = async () => {
  form.commitStorePicture = []
  showNotify({ type: 'success', message: '门头照，删除成功' })
}

/*************** 门店类型 ***************/
const typeOptions = ref(typeOption); // 门店类型
const showTypePopup = ref(false)
// 确认门店类型
const handleTypeConfirm = ({ selectedValues }) => {
  form.selectedType = selectedValues;
  showTypePopup.value = false;
};

/****** 大日期产品照片 ***************/
const longTimePictureArrRead = async (file) => {
  const pictureUrl = await uploadFileToOSSAPI(`risk/${form.storeCode}longTimePicture/${useUserStore().userInfo.employeeNo}/${uuidv4()}.png`, file.file)
  form.longTimePictureArr.push({
    url: pictureUrl
  })
  showNotify({ type: 'success', message: '大日期产品照片，上传成功' })
}
// 删除照片
const deleteLongTimePictureArr = async (file, { name, index }) => {
  form.longTimePictureArr.splice(index, 1)
  showNotify({ type: 'success', message: '大日期产品照片，删除成功' })
}

/*************** 信息填写组 ***************/
const active = ref(0)
</script>

<style scoped
  lang="scss">
  .wrap {
    background-color: #f5f5f5;
    min-height: 100vh;
    font-size: 16px;

    .content {
      padding: 20px;

      .title {
        margin: 0;
        font-size: 14px;
        font-weight: bold;
      }

      /* 终端名称信息 */
      .terminal-wrap {
        margin-top: 10px;
        padding: 10px;
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        display: flex;
        gap: 20px;

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

          .terminal-name {
            color: black;
            font-size: 15px;
            font-weight: bold;
            display: flex;
            align-items: center;

            span {
              display: inline-block;
              width: 120px;
            }

            .van-cell {
              padding: 0;
            }
          }

          p {
            font-size: 14px;
            margin: 0;
            color: #a1a1a1;
          }
        }


      }

      /* 位置信息 */
      .location-wrap {
        margin-top: 10px;
        padding: 10px;
        background-color: #fff;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: space-between;

        .location-icon {
          font-size: 20px;
          color: #da5c50;
        }

        p {
          font-size: 14px;
          margin: 0;
        }
      }

      /* 门头照 */
      .header-photo-section {
        margin-top: 10px;

        ::v-deep(.van-uploader__upload) {
          width: 80px !important;
          height: 80px !important;
          border: 1px dashed #ccc;
          border-radius: 4px;
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #f8f8f8;
        }
      }

      /* 信息填写组 */
      .tabs {
        margin-top: 10px;
      }


      /* 其他 */
      .task-summary {
        margin-top: 10px;
        background: white;
        padding: 10px;
        color: var(--main-color);

        .title {
          margin-bottom: 10px;
        }

        ::v-deep(textarea) {
          border: 1px solid lightgray;
        }

        .van-cell {
          padding: 0;

          .van-checkbox {
            margin-bottom: 10px;
          }
        }
      }
    }

  }
</style>