<template>
  <div class="w-full h-[100vh]">
    <!--  @open="openReportDropdownMenuRef" -->
    <van-dropdown-menu
      id="reportDropdownMenuRef"
      fixed
      ref="reportDropdownMenuRef"
      active-color="#FF9300"
    >
      <van-dropdown-item
        ref="reportItemRef"
        v-model="reportIndex"
        @change="onreportFilterClose"
        :options="
          reportList.map((item) => ({
            text: item?.typeName,
            value: item?.id
          }))
        "
      >
        <template #title class="relative" active-color="#FF9300">
          <div class="font-semibold text-2xl">
            <div @click.stop="goBack" class="absolute top-0 -left-135">
              <van-icon name="arrow-left" size="24" color="#000000" />
            </div>
            {{ title }}
          </div>
        </template>
      </van-dropdown-item>
    </van-dropdown-menu>

    <van-form @submit="onSubmit">
      <van-cell-group>
        <van-field
          :rules="[{ required: true, message: '请输入内容' }]"
          size="large"
          rows="2"
          readonly
          autosize
          type="textarea"
          v-model="form.elseTypeReason"
          :placeholder="
            form.elseTypeReason
              ? form.elseTypeReason
              : '对话中可能含有血腥、恐怖等内容，或者其他未提及的违规类型。'
          "
          label-align="top"
        >
          <template #label>
            <div>举报描述：{{ title }}</div>
          </template>
        </van-field>
        <van-field
          :rules="[{ required: true, message: '请输入违规描述' }]"
          required
          size="large"
          rows="6"
          autosize
          type="textarea"
          v-model="form.description"
          label="举报描述"
          maxlength="200"
          placeholder="请尽可能的描述存在的问题，如:让您感到不适的画面、或其他未提及的违规内容。"
          label-align="top"
        />

        <van-field
          id="image"
          class="image"
          style="background-color: white"
          required
          size="large"
          name="uploader"
          label="图片证据"
          label-align="top"
          :rules="[{ required: true, message: '请至少上传一张图片' }]"
        >
          <template #input>
            <div class="w-full flex justify-start items-start flex-wrap">
              <template v-if="form.image.length">
                <div
                  v-for="(item, index) in form.image"
                  :key="`img${index}`"
                  class="shrink-0 relative w-80 h-80 mr-7 rounded-xl overflow-hidden"
                >
                  <img class="w-full h-full object-cover" :src="item" alt="" />

                  <div
                    @click="deleteImage(index)"
                    class="absolute z-10 top-0 right-0 w-20 rounded-bl-md h-20 bg-black/[0.4] flex justify-center items-center"
                  >
                    <span class="icon iconfont text-white" style="font-size: 16px">&#xe7fc;</span>
                  </div>
                </div>
              </template>

              <div
                @click="handleChangeAvatar"
                class="border shrink-0 w-80 h-80 rounded-xl bg-[#F3F3F3] flex justify-center flex-wrap items-center"
              >
                <div>
                  <span class="iconfont icon-plus text-black/[0.4]" style="font-size: 18px"></span>
                  <p class="leading-3xl py-0 w-full text-sm text-center text-black/[0.4]">
                    {{ form.image?.length }}/3
                  </p>
                </div>
              </div>
            </div>
            <!-- <div
              class="border w-80 h-80 rounded-xl bg-[#F3F3F3] flex justify-center flex-wrap items-center"
            >
              <div @click="handleChangeAvatar">
                <span class="iconfont icon-plus text-black/[0.4]" style="font-size: 18px"></span>
                <p class="leading-3xl py-0 w-full text-sm text-center text-black/[0.4]">0/3</p>
              </div>
            </div> -->
          </template>
        </van-field>
      </van-cell-group>
      <div class="w-full fixed bottom-0 left-0 mt-90 px-16 pt-16 pb-40 box-border">
        <van-button
          size="large"
          round
          :color="isBtnDisabled ? '#A6A6A6' : '#FF9300'"
          class="font-semibold"
          block
          @click="handleReport"
          :loading="isSubmiting"
        >
          <!--  @click="isBtnDisabled ? handleReport : () => {}" -->
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script setup>
const route = useRoute()
const router = useRouter()
const goBack = () => router.back()

definePageMeta({
  layout: false
})

const TEXT = '举报类型'

// 刷新次数
const reportIndex = ref('')
const loading = ref(false)

const title = ref(TEXT)
const reportDropdownMenuRef = ref(null)
const reportItemRef = ref(null)

const form = reactive({
  typeId: null,
  objectType: computed(() => (route?.query?.objectType == 2 ? 2 : 1)),
  elseTypeReason: null,
  description: null,
  image: []
})

const { open, onChange } = useFileDialog({
  accept: '.png,.png,.jpeg,.JPG,Png '
})

function handleChangeAvatar() {
  open()
}

onChange(async (files) => {
  if (!files.length) return

  const formData = new FormData()
  formData.append('uploadFile', files[0])
  formData.append('asImage', true)
  formData.append('fieldName', 'image')
  const maxSize = 5 * 1024 * 1024 // 10 MB
  if (form.image.length <= 3) {
    if (files[0].size > maxSize) {
      showToast('上传图片过大，请重新上传')
      return
    } else {
      try {
        showLoadingToast({
          message: '图片上传中...',
          duration: 1000000
        })

        const { data } = await request('/website/tourComplait/upload', {
          method: 'post',
          body: formData
        })

        form.image.push(data.fileUrl)
        closeToast()
        showToast('图片上传成功')
      } catch (error) {
        form.image.push({
          url: files[0].name,
          status: 'failed',
          isImage: true,
          message: '上传失败',
          imageFit: 'contain'
        })
        closeToast()
        showToast('图片上传失败')

        console.log('图片上传失败')
      }
    }
  } else {
    showToast('最多上传图片数量3张')
  }
})

// 删除图片
const deleteImage = (index) => {
  form.image = form.image.filter((it, filterIndex) => filterIndex != index)
}

const reportList = ref([])

// 下拉菜单的方法
function onreportFilterClose(value) {
  form.elseTypeReason = '55555'
  console.log(value, '12')

  reportIndex.value = value

  let el = reportList.find((item) => item?.id == value)
  console.log(el, 'el')

  title.value = el.typeName
  form.elseTypeReason = el.description
}

function openReportDropdownMenuRef() {
  nextTick(() => {
    reportItemRef.value?.toggle(true)
  })
}

// 获取举报类型
const getreportType = async () => {
  try {
    let { data } = await request('/website/tourComplaintType/getTypeList')

    if (Array.isArray(data) && data?.length) {
      reportIndex.value = data[0]?.id
      form.typeId = data[0]?.id
      title.value = data[0]?.typeName
      form.elseTypeReason = '5555'
      reportList.value = data
    } else {
      reportList.value = []
    }
  } catch (err) {}
}

const isBtnDisabled = computed(() => {
  return !form.elseTypeReason || !form.description || !form.image.length != 0
})

const isSubmiting = ref(false)

const handleReport = async () => {
  try {
    isSubmiting.value = true

    if (form.objectType == 2) {
      // form.groupId = route.query.groupId
      form.groupId = '1876571259412688897'
    } else {
      form.userId = route.query.userId
    }
    let { data } = await request('/website/tourComplait/add', {
      method: 'post',
      body: form
    })
    if (data) {
      showSuccessToast('操作成功')
    }
    isSubmiting.value = false
  } catch (err) {
  } finally {
    isSubmiting.value = false
  }
}

onMounted(() => {
  getreportType()
})

useSeoMeta({
  title: TEXT
})
</script>
<style lang="scss" scoped>
::v-deep .van-field__body {
  background-color: #f3f3f3;
  border-radius: 8px;
  padding: 12px;
  padding-bottom: 20px;
}

::v-deep .image .van-field__value .van-field__body {
  background-color: #fff !important;
  padding: 0;
}

::v-deep .van-field__label {
  font-weight: 600;
}

::v-deep .van-field__label--required::after {
  margin-left: 2px;
  color: var(--van-field-required-mark-color);
  content: '*';
}
::v-deep .van-field__label--required::before {
  content: '';
}
</style>
