<script setup>
  import CardInput from '../my-index/components/card-input.vue'
  import { reactive } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import { addProductComment } from '../../api/mall'
  import { useUI } from '../../utils/use-ui'
  import { navigateBack } from '../../utils/router'

  const { showToast } = useUI()

  const formData = reactive({
    content: '',
    rating: 5,
    isAnonymous: false,
    imageUrls: '',
    productId: ''
  })

  const switchChange = ({ detail }) => {
    formData.isAnonymous = detail.value
  }

  const onAdd = async () => {
    const data = {
      ...formData,
      isAnonymous: formData.isAnonymous ? 1 : 0
    }
    await addProductComment(data)
    await showToast('添加成功', 'success')
    navigateBack()
  }

  onLoad(e => {
    formData.productId = e.productId
  })
</script>

<template>
  <view>
    <CardInput :is-input="false" title="评论内容">
      <textarea v-model="formData.content" placeholder="请输入评论内容" />
    </CardInput>

    <CardInput :is-input="false" title="评分">
      <template #right>
        <uni-rate v-model="formData.rating" />
      </template>
    </CardInput>

    <CardInput :is-input="false" title="是否匿名">
      <template #right>
        <switch style="transform: scale(0.8)" @change="switchChange" />
      </template>
    </CardInput>

    <CardInput :is-input="false" title="添加图片">
      <cb-file-picker v-model="formData.imageUrls"></cb-file-picker>
    </CardInput>

    <bottom-view>
      <cb-button @click="onAdd">确认添加</cb-button>
    </bottom-view>
  </view>
</template>

<style lang="scss" scoped>
  page {
    background: #f9f9f9;
  }
</style>
