<template>
  <!-- 稽查任务 -->
  <div class="wrap">
    <van-nav-bar left-arrow
      left-text="返回"
      fixed
      @click-left="router.back()">
    </van-nav-bar>
    <div class="content">
      <!-- <p class="title">稽查任务:</p> -->
      <!-- 终端名称 -->
      <div class="terminal-wrap">
        <div class="terminal-name">
          <span>终端名称：</span>
          <van-field v-model="form.storeName"
            placeholder="请输入终端名"
            @change="handleStoreNameChange"
            class="store-name-input" />
        </div>
        <div class="img-info">
          <div>
            <van-image fit="scale-down"
              width="2.25rem"
              height="3.5rem"
              :src="form.storePicture"
              @click="previewStoreImage"></van-image>
          </div>
          <div class="terminal-info">

            <p>终端编码：{{ form.storeCode }}</p>
            <p>经销商：{{ form.dealersName }}</p>
            <p>地址：{{ form.storeAddr }}</p>
          </div>
        </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"
          v-if="!isEdit" />
      </div>

      <!-- 门头照上传 -->
      <div class="header-photo-section">
        <van-field label="门头照"
          label-align="top">
          <template #input>
            <van-uploader :max-count="1"
              accept="image/*"
              :model-value="form.commitStorePicture"
              :after-read="commitStorePhotosRead"
              preview-size="2.13333rem"
              @delete="deleteCommitStorePhotos">
            </van-uploader>
          </template>
        </van-field>
      </div>


      <!-- 渠道类型选择 -->
      <van-field label-width="150px"
        label-position="top"
        label="渠道类型："
        :model-value="form.selectedType"
        placeholder="请选择">
        <template #input>
          <el-select v-model="form.selectedType"
            placeholder="请选择"
            @change="handleTypeConfirm">
            <el-option v-for="item in typeOptions"
              :label="item.text"
              :value="item.value" />
          </el-select>
        </template>
      </van-field>

      <!-- 信息填写组 -->
      <van-tabs v-model:active="active"
        class="tabs"
        swipeable
        sticky
        :lazy-render="false">
        <van-tab title="常规陈列">
          <convention :isInitializing="isInitializing"
            :form="form"
            ref="conventionRef" />
        </van-tab>
        <van-tab title="档期陈列">
          <scheduleDisplay :isInitializing="isInitializing"
            :form="form"
            ref="scheduleDisplayRef" />
        </van-tab>
        <van-tab title="档期补差">
          <scheduleAdjustment :isInitializing="isInitializing"
            :form="form"
            ref="scheduleAdjustmentRef" />
        </van-tab>
        <van-tab title="品类信息">
          <categoryInformation :isInitializing="isInitializing"
            :form="form"
            ref="categoryInformationRef" />
        </van-tab>
      </van-tabs>

      <!-- 竞品填写组 -->
      <div class="comper-summary">
        <p class="title">竞品信息：</p>
        <van-field v-model.number="form.competitorWangjiafuSkuTotal"
          label="旺家福SKU总数："
          type="number"
          placeholder="请输入"
          label-align="left"
          @change="handleComPePrdChange" />
        <van-field v-model.number="form.competitorWangjiafuFacingTotal"
          label="旺家福排面总数："
          type="number"
          placeholder="请输入"
          label-align="left"
          @change="handleComPePrdChange" />
        <van-field v-model.number="form.competitorQianjiaxiangSkuTotal"
          label="钱家香SKU总数："
          type="number"
          placeholder="请输入"
          label-align="left"
          @change="handleComPePrdChange" />
        <van-field v-model.number="form.competitorQianjiaxiangFacingTotal"
          label="钱家香排面总数："
          type="number"
          placeholder="请输入"
          label-align="left"
          @change="handleComPePrdChange" />
        <van-field v-model.number="form.competitorJinchuniangSkuTotal"
          label="金厨娘SKU总数："
          type="number"
          placeholder="请输入"
          label-align="left"
          @change="handleComPePrdChange" />
        <van-field v-model.number="form.competitorJinchuniangFacingTotal"
          label="金厨娘排面总数："
          type="number"
          placeholder="请输入"
          label-align="left"
          @change="handleComPePrdChange" />
      </div>
      <!-- 任务总结 -->
      <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"
              @change="handleLhldArrChange">
              <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"
          @change="handleSkuNumChange" />
        <van-field v-model="form.remark"
          label="备注："
          placeholder="请输入"
          label-align="top"
          type="textarea"
          border
          @change="handleRemarkChange" />
        <!-- 大日期产品照片 -->
        <div class="header-photo-section">
          <van-field label="大日期产品照片"
            label-align="top">
            <template #input>
              <van-uploader :max-count="3"
                accept="image/*"
                capture="camera"
                :model-value="form.longTimePictureArr"
                :after-read="longTimePictureArrRead"
                preview-size="2.13333rem"
                @delete="deleteLongTimePictureArr">
              </van-uploader>
            </template>
          </van-field>
        </div>
      </div>
    </div>
    <!-- 加载进度 -->
    <van-overlay :show="isInitializing">
      <van-loading v-if="isInitializing"
        vertical
        color="#f12528"
        size="40"
        text-color="#f12528">加载中...</van-loading>
    </van-overlay>
  </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 categoryInformation from './tabs/categoryInformation.vue'
import useUserStore from '@/store/modules/user'
import { v4 as uuidv4 } from 'uuid';
import { getFileTypeExt } from '@/utils'
import { getMobileType } from '@/views/mobile/utils'
// 引入必要的组件
import { showImagePreview } from 'vant';

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

const conventionRef = ref(null)
const scheduleDisplayRef = ref(null)
const scheduleAdjustmentRef = ref(null)
const categoryInformationRef = ref(null)

/*************** 稽查任务总体 ***************/
const isInitializing = ref(true)
const isEdit = ref(Boolean(route.query.rstId))
const form = reactive({ // 当前页信息总对象
  rstId: route.query.rstId, // 稽查任务 ID（获取详情接口有则保存，没有则主动新建一次并获取 id）
  storePicture: route.query.storePicture, // 门店照片（原始门店照片,来自于上一页的接口）
  storeName: route.query.storeName, // 门店名称
  storeCode: route.query.storeCode, // 门店编码
  dealersName: route.query.dealersName, // 经销商名称
  dealerCode: route.query.dealerCode, // 经销商编码
  storeAddr: route.query.storeAddr, // 门店地址
  lhldArr: [], // 其他-礼盒礼袋是否在售
  skuNum: '', // 我品 SKU 总数
  remark: '', // 备注
  longTimePictureArr: [], // 大日期产品照片
  // 前端特有属性和后端接口不一致
  commitStorePicture: [], // 上报拍摄的门店照片
  selectedType: "", // 渠道类型
})

// 稽查任务详情
const getInspectionTaskDetailFn = async () => {
  const res = await getInspectionTaskDetailAPI({
    storeCode: form.storeCode,
    // storeName: form.storeName,
    rstId: form.rstId,
  })
  if (res.data) {
    Object.assign(form, res.data)
    const { storeName, lhldArr, longTimePictureArr, storePicture, storeType, skuNum, cgclRiskRArr, dqclRiskRArr, dealerName, storeAddr, address } = res.data
    // 终端门店照片一直应该是路由上的照片参数，如果路由上没有门头照证明上一个页面列表里这个门店就本身没有照片，那就用门头照拍摄的
    if (route.query.storePicture) form.storePicture = route.query.storePicture
    // 详情接口有门头照照片，需要设置到特有的属性commitStorePicture
    if (storePicture) form.commitStorePicture = [{
      url: storePicture
    }]
    // 详情接口门店名称如果是空的就用路由传递的
    if (!storeName) form.storeName = route.query.storeName
    // 详情接口经销商名称和门店地址是空的就用路由传递的
    if (!dealerName) form.dealersName = route.query.dealersName
    else form.dealersName = dealerName
    if (!storeAddr) form.storeAddr = route.query.storeAddr
    if (!lhldArr) form.lhldArr = []

    if (!longTimePictureArr) form.longTimePictureArr = []
    else {
      // 前端特有结构数据格式处理
      form.longTimePictureArr = longTimePictureArr?.map(o => ({
        url: o
      }))
    }
    if (skuNum === 0) form.skuNum = ''
    if (!cgclRiskRArr) form.cgclRiskRArr = []
    if (!dqclRiskRArr) form.dqclRiskRArr = []
    if (route.query.selectedType) form.selectedType = route.query.selectedType
    // 如果从新建稽查任务页面过来的，门头照路由上传递过来的
    if (route.query.taskStatus && route.query.storePicture) form.commitStorePicture = [{
      url: route.query.storePicture
    }]

    if (storeType) form.selectedType = storeType

    // 保存地址
    if (address) {
      addressLoading.value = false
      addressStr.value = address
    }

  } else {
    // 没有的话调用新建接口，得到一个总体稽查任务 id
    const res = await createInspectionTaskAPI({
      storeCode: form.storeCode,
      storeName: form.storeName,
      dealerName: form.dealersName,
      dealerCode: form.dealerCode
    })
    form.rstId = res.data.rstId
    // 一定在这里获取地理位置（保证稽查任务 id 创建完毕）
    getLocationFn()
  }

  nextTick(() => {
    isInitializing.value = false
    // 初始化 4 个分组
    conventionRef.value.init()
    scheduleDisplayRef.value.init()
    scheduleAdjustmentRef.value.init()
    categoryInformationRef.value.init()
  })


}
getInspectionTaskDetailFn()

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

// 终端门店名称修改
const handleStoreNameChange = async () => {
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    rStoreName: form.storeName // 修改门店名称
  })
  showNotify({ type: 'success', message: '门店名称修改成功' })
}

/*************** 地理定位 ***************/
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 { recommend } = res.data.result.formatted_addresses
        addressStr.value = recommend
        // 准备给后台保存的参数
        const { province, city } = res.data.result.address_component
        addressLoading.value = false
        await createInspectionTaskAPI({
          rstId: form.rstId,
          storeCode: form.storeCode,
          storeName: form.storeName,
          province: province,
          city: city,
          address: recommend,
          coordinates: JSON.stringify([lat, lng])
        })
      },
      function (error) {
        showDialog({
          title: '系统提示',
          message: '请开启软件的定位授权，再试',
        })
      },
      {
        enableHighAccuracy: true,
        timeout: 5000,
        maximumAge: 0
      }
    );
  } else {
    showDialog({
      title: '系统提示',
      message: '你的设备不支持定位',
    })
  }
}

const handleClickLocation = () => {
  addressLoading.value = true
  setTimeout(() => {
    getLocationFn()
  }, 1500)
}

/*************** 门头照上传 ***************/
const commitStorePhotosRead = async (file) => {
  form.commitStorePicture = [{
    status: 'uploading',
    message: '上传中...',
    url: file.content
  }]

  const date = new Date()
  const month = date.getMonth() + 1
  const pictureUrl = await uploadFileToOSSAPI(`risk/${date.getFullYear()}-${month}/storeFrontPhoto/${useUserStore().empInfo.empNo}/${uuidv4()}.${getFileTypeExt(file.file.name)}`, file.file)

  const targetObj = form.commitStorePicture[0]
  targetObj.status = 'done'
  targetObj.url = pictureUrl

  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    storePicture: pictureUrl
  })

  if (!form.storePicture) form.storePicture = pictureUrl
  showNotify({ type: 'success', message: '门头照，上传成功' })
}
// 删除照片
const deleteCommitStorePhotos = async () => {
  form.commitStorePicture = []
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    storePicture: ""
  })
  if (!route.query.storePicture) form.storePicture = ""
  showNotify({ type: 'success', message: '门头照，删除成功' })
}

/*************** 渠道类型 ***************/
const typeOptions = ref(typeOption) // 渠道类型
const showTypePopup = ref(false)
// 确认渠道类型
const handleTypeConfirm = async () => {
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    storeType: form.selectedType
  })
  showNotify({ type: 'success', message: '渠道类型，修改成功' })
}

/*************** tabs 组 ***************/
const active = ref(0)

/*************** 竞品组 ***************/
const handleComPePrdChange = async () => {
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    // 判断空字符串传 null
    "competitorWangjiafuSkuTotal": form.competitorWangjiafuSkuTotal || null,
    "competitorWangjiafuFacingTotal": form.competitorWangjiafuFacingTotal || null,
    "competitorQianjiaxiangSkuTotal": form.competitorQianjiaxiangSkuTotal || null,
    "competitorQianjiaxiangFacingTotal": form.competitorQianjiaxiangFacingTotal || null,
    "competitorJinchuniangSkuTotal": form.competitorJinchuniangSkuTotal || null,
    "competitorJinchuniangFacingTotal": form.competitorJinchuniangFacingTotal || null,
  })
  showNotify({ type: 'success', message: '竞品信息，修改成功' })
}

/*************** 其他信息填写 ***************/
// 礼盒礼袋在售
const handleLhldArrChange = async () => {
  if (isInitializing.value) return
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    lhldArr: form.lhldArr
  })
  showNotify({ type: 'success', message: '礼盒礼袋在售，修改成功' })
}

// 我品 SKU 总数
const handleSkuNumChange = async () => {
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    skuNum: form.skuNum * 1
  })
  showNotify({ type: 'success', message: '我品 SKU 总数，修改成功' })
}

// 备注
const handleRemarkChange = async () => {
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    remark: form.remark
  })
  showNotify({ type: 'success', message: '备注，修改成功' })
}

// 大日期照片上传
const longTimePictureArrRead = async (file) => {
  const index = form.longTimePictureArr.length
  form.longTimePictureArr[index] = {
    url: file.content,
    status: 'uploading',
    message: '上传中...'
  }
  const date = new Date()
  const month = date.getMonth() + 1
  const theDate = date.getDate()
  const pictureUrl = await uploadFileToOSSAPI(`risk/${date.getFullYear()}-${month}/longTimePicture/${useUserStore().empInfo.empNo}/${form.storeCode}/${uuidv4()}.png`, file.file)
  form.longTimePictureArr[index] = {
    url: pictureUrl,
    status: 'done'
  }
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    longTimePictureArr: form.longTimePictureArr.map(o => o.url)
  })
  showNotify({ type: 'success', message: '大日期产品照片，上传成功' })
}
// 删除照片
const deleteLongTimePictureArr = async (file, { name, index }) => {
  form.longTimePictureArr.splice(index, 1)
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    storeName: form.storeName,
    rstId: form.rstId,
    longTimePictureArr: form.longTimePictureArr.map(o => o.url)
  })
  showNotify({ type: 'success', message: '大日期产品照片，删除成功' })
}
</script>

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

    .van-nav-bar{
      z-index: 1000;
    }

    .content {
      padding: 20px;
      padding-top: 66px;

      .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;
        flex-direction: column;
        gap: 20px;

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

          .store-name-input {
            ::v-deep(input) {
              border-bottom: 1px solid gray;
            }
          }
        }

        .img-info {
          display: flex;
          gap: 20px;

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

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

              &:first-child {
                margin-top: 0;
              }
            }
          }
        }

      }


      .store-type {
        ::v-deep(input) {
          border-bottom: 1px solid gray;
        }
      }

      /* 位置信息 */
      .location-wrap {
        width: 100%;
        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; */
        gap: 20px;

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

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

        .refresh-icon {
          margin-left: auto;
        }
      }

      /* 门头照 */
      .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;
        }

        /* 原来上传预览内容样式 */
        ::v-deep(.van-uploader__file) {
          .van-badge__wrapper {
            display: none;
          }

          .van-ellipsis {
            display: none;
          }
        }
      }



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

      /* 竞品信息组 */
      .comper-summary {
        margin-top: 10px;
        background: white;
        padding: 10px;
        color: var(--main-color);
        --van-field-label-width: 120px !important;

        .title {
          margin-bottom: 10px;
        }

        .van-cell {
          padding: 0;
          margin-bottom: 20px;
        }

      }

      /* 其他 */
      .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;
          }
        }
      }
    }

    .van-overlay {
      background-color: rgba(0, 0, 0, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
    }

    /* 全屏预览 */
    ::v-deep(.fullscreen-video-dialog) {
      width: 100%;
      max-width: 100%;
      height: 100% !important;
      top: 0;
      padding: 0;
      margin: 0;
      transform: translateY(0);
      border-radius: 0;

      .van-dialog__header {
        display: none;
      }
    }

    .fullscreen-video-dialog .van-dialog__content {
      padding: 0 !important;
      height: calc(100% - 50px);
      /* 减去标题栏高度 */
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .video-container {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #000;

      /* 添加关闭按钮 */
      .close-button {
        position: absolute;
        top: 10px;
        right: 10px;
        width: 30px;
        height: 30px;
        background-color: rgba(0, 0, 0, 0.5);
        color: white;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 10;
      }
    }

    .fullscreen-video {
      max-width: 100%;
      max-height: 100%;
      object-fit: contain;
    }

    /* 预览中的视频样式 */
    .preview-media {
      width: 100%;
      height: 100%;
      object-fit: cover;
      cursor: pointer;
    }
  }
</style>