<script setup lang="ts">
import {appMerchantOrderDetailPost, appMerchantOrderEvaluateOrderPost, type MerchantOrderVo} from "@/service";

const {t} = useI18n()
import StarRating from './components/star-rating.vue'
import ChooseImage from "@/components/choose-image/choose-image.vue";
import {getDictFineList} from "@/pages-store/service";

// 配送员评分
const deliveryRating = ref(4)
// 商品评分
const goodsRating = ref(4)

// 评价文字
const reviewText = ref('')
const maxTextLength = 200

// 上传的图片列表
const uploadedImages = ref<string[]>([])
// 评价配送员图片
const deliveryUploadedImages = ref<string[]>([])
const maxImages = 3

// 评价标签
const deliveryTags = ref([])

// 计算剩余字数
const remainingChars = computed(() => {
  return maxTextLength - reviewText.value.length
})



// 切换标签选中状态
const toggleTag = (item: any) => {
  item.selected = !item.selected
}

// 删除图片
const removeImage = (index: number) => {
  uploadedImages.value.splice(index, 1)
}

// 预览图片
const previewImage = (index: number) => {
  uni.previewImage({
    current: index,
    urls: uploadedImages.value
  })
}

// 提交评价
const submitReview = () => {
  if (reviewText.value.trim() === '') {
    uni.showToast({
      title: '请输入评价内容',
      icon: 'none'
    })
    return
  }
  
  const reviewData = {
    deliveryRating: deliveryRating.value,
    goodsRating: goodsRating.value,
    reviewText: reviewText.value,
    deliveryTags: deliveryTags.value.filter(t => t.selected).map(t => t.text),
    goodsTags: goodsTags.value.filter(t => t.selected).map(t => t.text),
    images: uploadedImages.value
  }
  
  console.log('提交评价:', reviewData)
  
  uni.showToast({
    title: '评价提交成功',
    icon: 'none'
  })
  
  // 返回上一页
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

const chooseImageRef = ref()
// 点击上传图片的类型
const uploadType = ref(1)
const dishIndex = ref(0)
const handleChooseImage = (type: number, index?: number) => {
  uploadType.value = type
  if(type === 2) {
    // 菜品图片上传
    dishIndex.value = index
  }
  chooseImageRef.value.init()
}
function onImageChange(files: string[]) {
  console.log(files)
  // form.value.images = files.join(',')
  switch (uploadType.value) {
    case 1:
      deliveryUploadedImages.value.push(...files)
      break
    case 2:
      // uploadedImages.value.push(...files)
        formData.value.merchantDishReviewList[dishIndex.value].uploadedImages.push(...files)
      break
  }
}

const orderId = ref('')
onLoad((options) => {
  if(options.id) {
    orderId.value = options.id;
    appMerchantOrderDetail()
    // 获取评价标签
    getDeliveryTags()
  }
})

const loading = ref(true)
const orderDetail = ref<MerchantOrderVo>()
function appMerchantOrderDetail() {
  loading.value = true;
  appMerchantOrderDetailPost({
    params: {
      orderId: orderId.value,
    }
  }).then((res: any)=> {
    console.log('订单详情', res)
    orderDetail.value = res.data
    // 是自取订单还是配送订单 1-派送 2-自取 orderDetail.value.receiveMethod
    if(res.data && res.data.merchantOrderDishVoList.length > 0) {
      formData.value.merchantDishReviewList = res.data.merchantOrderDishVoList.map(item=> {
        return {
          dishId: item.dishId, // 菜品ID
          merchantId: item.merchantId, // 菜品ID
          merchantOrderDishId: item.id,//商家订单关联菜品ID
          dishImage: item.merchantDishVo?.dishImage?.split(',')[0],
          dishName: item.merchantDishVo?.dishName,
          dishDescription: item.merchantDishVo?.dishDescription,
          rating: 0,
          content: '',
          images: '',
          uploadedImages: [],
        }
      })
    }
  }).finally(() => {
    loading.value = false;
  })
}

function getDeliveryTags() {
  getDictFineList({
    dictType: 'review_tag'
  }).then(res=> {
    console.log('评价标签', res)
    if(res.data) {
      deliveryTags.value = res.data.map((item) => {
        return {
          text: item.dictLabel,
          selected: false
        }
      })
    }
  })
}

// 是自取订单还是配送订单
const isSelfPickup = computed(()=> {
  return orderDetail.value?.receiveMethod === 2
})

const formData = ref({
  deliveryReview: {
    tags: '',
    rating: 0,
    content: '',
    images: '',
  }, // 配送员评价信息
  merchantDishReviewList: [
    {
      dishId: '', // 菜品ID
      dishImage: '',
      dishName: '',
      dishDescription: '',
      rating: 0,
      content: '',
      images: '',
      uploadedImages: [],
    }
  ]
})

function submitForm() {
  // 表单验证
  if(!isSelfPickup.value) {
    // 配送订单需要验证配送员评价
    if(formData.value.deliveryReview.rating === 0) {
      uni.showToast({
        title: t('common.pleaseRateDelivery'),
        icon: 'none'
      })
      return
    }
    if(!formData.value.deliveryReview.content || formData.value.deliveryReview.content.trim() === '') {
      uni.showToast({
        title: t('common.pleaseEnterDeliveryReview'),
        icon: 'none'
      })
      return
    }
  }
  
  // 验证菜品评价
  for(let i = 0; i < formData.value.merchantDishReviewList.length; i++) {
    const dish = formData.value.merchantDishReviewList[i]
    if(dish.rating === 0) {
      uni.showToast({
        title: `${t('common.pleaseRateDish')} "${dish.dishName}"`,
        icon: 'none'
      })
      return
    }
    if(!dish.content || dish.content.trim() === '') {
      uni.showToast({
        title: `${t('common.pleaseEnterDishReview')} "${dish.dishName}"`,
        icon: 'none'
      })
      return
    }
  }
  
  if(!isSelfPickup.value) {
    // 配送订单
    formData.value.deliveryReview.tags = deliveryTags.value.filter(t => t.selected).map(t => t.text).join(',')
    formData.value.deliveryReview.images = deliveryUploadedImages.value.join(',')
  }
  formData.value.merchantDishReviewList.forEach(item=> {
    item.images = item.uploadedImages.join(',')
  })
  console.log('提交评价', formData.value)
  if(isSelfPickup.value) {
    // 自取订单
    formData.value.deliveryReview = null
  }
  appMerchantOrderEvaluateOrderPost({
    body: {
      orderId: orderId.value,
      ...formData.value,
    }
  }).then(res=> {
    console.log('评价成功', res)
    setTimeout(()=> {
      uni.redirectTo({
        url: '/pages-store/pages/order/view-reviews?id=' + orderId.value
      })
    },1000)
  })
}
</script>

<template>
  <view class="pb-100rpx">
    <!-- 导航栏 -->
    <navbar customClass="!bg-transparent" />

    <view class="pl-30rpx pt-20rpx text-46rpx lh-46rpx font-bold text-#333 mb-52rpx">{{ t("common.evaluate") }}</view>
    
    <!-- 配送员评价区域 -->
    <view v-if="!isSelfPickup" class="bg-white px-30rpx py-40rpx mb-20rpx">
      <text class="text-36rpx lh-36rpx text-#333 font-500 block mb-34rpx">{{ t('pages-store.view-reviews.deliveryDriver') }}</text>
      <view class="bg-#F7F7F7 h-100rpx rounded-16rpx pl-16rpx flex items-center mb-28rpx">
        <image
            :src="orderDetail?.deliveryAvatar"
            mode="aspectFill"
            class="w-80rpx h-80rpx rounded-full mr-20rpx"
        />
        <text class="text-28rpx lh-28rpx text-#333">{{ orderDetail?.deliveryFirstName }} {{ orderDetail?.deliverySurname }}</text>
      </view>
      <!-- 评分区域 -->
      <view class="flex items-center mb-40rpx">
        <text class="text-28rpx lh-28rpx text-#333 font-500 mr-66rpx">{{ t('pages-store.view-reviews.Score') }}</text>
        <StarRating v-model="formData.deliveryReview.rating" />
      </view>
      <!-- 评价标签 -->
      <view class="flex flex-wrap gap-16rpx">
        <view
            v-for="tag in deliveryTags"
            :key="tag.id"
            :class="[
              'px-24rpx h-50rpx rounded-25rpx border-1rpx text-24rpx center transition-all',
              tag.selected
                ? 'bg-#333333 text-white'
                : 'bg-#F6F6F6 text-#999'
            ]"
            @click="toggleTag(tag)"
        >
          {{ tag.text }}
        </view>
      </view>

      <view
          class="mt-30rpx min-h-206rpx box-border bg-#F6F6F6 rounded-20rpx overflow-hidden p-20rpx pb-40rpx relative"
      >
        <wd-textarea
            v-model="formData.deliveryReview.content"
            :maxlength="200"
            custom-class="!bg-#F6F6F6"
            custom-textarea-container-class="!bg-#F6F6F6"
            no-border
            auto-height
            :placeholder="t('common.enter')"
        />
        <view class="absolute bottom-26rpx right-20rpx text-28rpx lh-28rpx text-#999">{{ formData.deliveryReview.content.length }}/200</view>
      </view>

      <!-- 图片上传区域 -->
      <view class="mt-34rpx">
        <view class="flex flex-wrap gap-20rpx">
          <!-- 已上传的图片 -->
          <view
              v-for="(image, index) in deliveryUploadedImages"
              :key="index"
              class="relative w-158rpx h-158rpx"
          >
            <image
                :src="image"
                mode="aspectFill"
                class="w-full h-full rounded-16rpx bg-#F5F5F5"
                @click="previewImage(index)"
            />
            <!-- 删除按钮 -->
            <image
                @click="removeImage(index)"
                src="@img/chef/113.png"
                class="absolute top--10rpx right--10rpx z-1 w-36rpx h-36rpx"
            ></image>
          </view>

          <!-- 添加图片按钮 -->
          <view
              v-if="deliveryUploadedImages.length < maxImages"
              class="w-158rpx h-158rpx bg-#F5F5F5 rounded-16rpx flex-center cursor-pointer"
              @click="handleChooseImage(1)"
          >
            <image
                src="@img/chef/112.png"
                class="w-158rpx h-158rpx"
            ></image>
          </view>
        </view>
      </view>
    </view>

    <!-- 商品评价区域 -->
    <view class="pt-40rpx pb-32rpx bg-white">
      <text class="pl-30rpx text-36rpx lh-36rpx text-#333 font-500 block mb-34rpx">{{ t('pages-store.view-reviews.goods') }}</text>

      <template v-for="(item, index) in formData.merchantDishReviewList">
        <view class="px-30rpx border-b-1rpx border-b-solid border-b-#D8D8D8 pb-32rpx mb-32rpx last:mb-0 last:border-none">
          <view class="bg-#F7F7F7 h-100rpx rounded-16rpx pl-16rpx pr-24rpx flex items-center mb-28rpx">
            <image
                :src="item.dishImage"
                mode="aspectFill"
                class="w-80rpx h-80rpx rounded-16rpx mr-20rpx shrink-0"
            />
            <view class="h-80rpx mt-10rpx">
              <text class="text-28rpx text-#333 line-clamp-1">{{ item.dishName }}</text>
              <view class="text-24rpx lh-24rpx text-#999 mt-12rpx line-clamp-1">{{ item.dishDescription }}</view>
            </view>
          </view>

          <!-- 评分区域 -->
          <view class="flex items-center mb-28rpx">
            <text class="text-28rpx lh-28rpx text-#333 font-500 mr-66rpx">{{ t('pages-store.view-reviews.Score') }}</text>
            <StarRating v-model="item.rating" />
          </view>

          <view
              class="mt-30rpx min-h-206rpx box-border bg-#F6F6F6 rounded-20rpx overflow-hidden p-20rpx pb-40rpx relative"
          >
            <wd-textarea
                v-model="item.content"
                :maxlength="200"
                custom-class="!bg-#F6F6F6"
                custom-textarea-container-class="!bg-#F6F6F6"
                no-border
                auto-height
                :placeholder="t('common.enter')"
            />
            <view class="absolute bottom-26rpx right-20rpx text-28rpx lh-28rpx text-#999">{{ item.content.length }}/200</view>
          </view>

          <!-- 图片上传区域 -->
          <view class="mt-34rpx">
            <view class="flex flex-wrap gap-20rpx">
              <!-- 已上传的图片 -->
              <view
                  v-for="(image, index) in item.uploadedImages"
                  :key="index"
                  class="relative w-158rpx h-158rpx"
              >
                <image
                    :src="image"
                    mode="aspectFill"
                    class="w-full h-full rounded-16rpx bg-#F5F5F5"
                    @click="previewImage(index)"
                />
                <!-- 删除按钮 -->
                <image
                    @click="removeImage(index)"
                    src="@img/chef/113.png"
                    class="absolute top--10rpx right--10rpx z-1 w-36rpx h-36rpx"
                ></image>
              </view>

              <!-- 添加图片按钮 -->
              <view
                  v-if="item.uploadedImages.length < maxImages"
                  class="w-158rpx h-158rpx bg-#F5F5F5 rounded-16rpx flex-center cursor-pointer"
                  @click="handleChooseImage(2, index)"
              >
                <image
                    src="@img/chef/112.png"
                    class="w-158rpx h-158rpx"
                ></image>
              </view>
            </view>
          </view>
        </view>
      </template>
    </view>

    <!-- 底部提交按钮 -->
    <fixed-bottom-large-btn
        class="z-100"
        :fixed="true"
        :text="`${t('common.submit')}`"
        @click="submitForm"
    />

    <ChooseImage ref="chooseImageRef" @change="onImageChange" />
  </view>
</template>

<style>
page {
  background-color: #F6F6F6;
}
</style>
<style scoped lang="scss">
.evaluate-page {
  padding-bottom: 200rpx; // 为底部按钮留出空间
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.cursor-pointer {
  cursor: pointer;
}

.transition-all {
  transition: all 0.3s ease;
}

// 修复 textarea 在某些平台的样式问题
textarea {
  box-sizing: border-box;
  font-family: inherit;
}
</style>