<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"
            @click="previewStoreImage"></van-image>
        </div>
        <div class="terminal-info">
          <div class="terminal-name">
            <span>终端名称：</span>
            <van-field v-model="form.storeName"
              placeholder="请输入终端名"
              @change="handleStoreNameChange" />
          </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"
              :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 :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="品类信息">
          <categoryInfomation :isInitializing="isInitializing"
            :form="form"
            ref="categoryInfomationRef" />
        </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"
              @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="4"
                accept="image/*"
                capture="camera"
                :model-value="form.longTimePictureArr"
                :after-read="longTimePictureArrRead"
                preview-size="78"
                @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 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 conventionRef = ref(null)
const scheduleDisplayRef = ref(null)
const scheduleAdjustmentRef = ref(null)
const categoryInfomationRef = ref(null)

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

// 稽查任务详情
const getInspectionTaskDetailFn = async () => {
  const res = await getInspectionTaskDetailAPI({
    storeCode: form.storeCode
  })
  if (res.data) {
    Object.assign(form, res.data)
    const { storeName, lhldArr, longTimePictureArr, storePicture, storeType, skuNum, cgclRiskRArr } = res.data
    // 终端照片取值优先级：1. 路由传递 2. 详情接口返回(门头照) 3. 空着
    if (route.query.storePicture) form.storePicture = route.query.storePicture
    if (!storeName) form.storeName = route.query.storeName
    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 (storePicture) form.commitStorePicture = [{
      url: form.storePicture
    }]
    if (storeType) form.selectedType = [storeType]

  } else {
    // 没有的话调用新建接口，得到一个总体稽查任务 id
    const res = await createInspectionTaskAPI({
      storeCode: form.storeCode,
    })
    form.rstId = res.data.rstId
  }

  nextTick(() => {
    isInitializing.value = false
    conventionRef.value.init()
    scheduleDisplayRef.value.init()
    scheduleAdjustmentRef.value.init()
    // categoryInfomationRef.value.init()
  })

  // 一定在这里获取地理位置（保证稽查任务 id 创建完毕）
  getLocationFn()
}
getInspectionTaskDetailFn()

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

// 终端门店名称修改
const handleStoreNameChange = async () => {
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    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 { standard_address } = res.result.formatted_addresses
        addressStr.value = standard_address
        // 准备给后台保存的参数
        const { province, city } = res.result.address_component
        addressLoading.value = false
        await createInspectionTaskAPI({
          rstId: form.rstId,
          storeCode: form.storeCode,
          province: province,
          city: city,
          address: standard_address,
          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) => {
  const pictureUrl = await uploadFileToOSSAPI(`risk/storeFrontPhoto/${useUserStore().empInfo.empNo}/${form.storeCode}.png`, file.file)
  form.commitStorePicture = [{
    url: pictureUrl
  }]
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    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,
    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 ({ selectedValues }) => {
  form.selectedType = selectedValues
  showTypePopup.value = false
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    rstId: form.rstId,
    storeType: selectedValues.join(',')
  })
}

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

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

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

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

// 大日期照片上传
const longTimePictureArrRead = async (file) => {
  const pictureUrl = await uploadFileToOSSAPI(`risk/longTimePicture/${useUserStore().empInfo.empNo}/${form.storeCode}/${uuidv4()}.png`, file.file)
  form.longTimePictureArr.push({
    url: pictureUrl
  })
  await createInspectionTaskAPI({
    storeCode: form.storeCode,
    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,
    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;

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

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