<template>
  <view class="container">
    <view class="input-container">
      <textarea 
        v-model="reason" 
        placeholder="请输入您的退款原因..." 
        class="remark-input"
      ></textarea>
    </view>
    <button @click="submitRemark" class="submit-button">提交</button>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { apiImageUrl } from '../../API/api';
import { onMounted } from 'vue';

const reason = ref('');
const amount = ref(0);
const orderId = ref('');
const status = ref(0);

// 获取订单信息
const getOrder = () => {
  const refundId = uni.getStorageSync("refundId");
  uni.request({
    url: apiImageUrl + '/api/orders/get/my',
    method: 'GET',
    data: { id: refundId },
    header: {
      'Content-Type': 'application/json',
      'cookie': uni.getStorageSync("cookie") || ''
    },
    success(res) {
      if (res.data.code === 0) { // 使用可选链操作符
	  console.log(res);
        const orderData = res.data.data;
        amount.value = orderData.totalPrice || 0;
        orderId.value = refundId;
      } else {
        uni.showToast({
          title: res.data?.msg || '获取订单信息失败',
          icon: 'none'
        });
      }
    },
    fail() {
      uni.showToast({
        title: '网络错误,请重试',
        icon: 'none'
      });
    }
  });
}


// 提交退款申请
const submitRemark = async () => {
  if (!reason.value.trim()) {
    return uni.showToast({
      title: '请填写退款原因',
      icon: 'none'
    });
  }
  const requestData = {
    amount: amount.value,
    orderId: orderId.value,
    reason: reason.value,
    status: 0
  };
  uni.request({
    url: apiImageUrl + '/api/refund/add', 
    method: 'POST',
    data: requestData, 
    header: {
      'Content-Type': 'application/json',
      'cookie': uni.getStorageSync("cookie") || ''
    },
    success(res) {
      console.log(res);
      if (res.data.code === 50000) {
        uni.showToast({
          title: '此订单已存在退款记录,请勿重复提交',
          icon: 'none'
        });
      } else if (res.data.code === 0) {
        uni.showToast({
          title: '提交成功',
          icon: 'none'
        });
		  uni.navigateBack({
		     delta: 1 
		 })
      }else {
        console.log(res);
      }
    },
    fail(err) {
      console.log(err);
      uni.showToast({
        title: '网络错误,请重试',
        icon: 'none'
      });
    }
  });
}

onMounted(getOrder);
</script>

<style scoped>
/* 原有样式保持不变 */
.container {
  padding: 20px;
}

.input-container {
  margin-bottom: 20px;
}

.remark-input {
  height: 150px;
  padding: 10px;
  font-size: 16px;
  border: 1px solid #ccc;
  border-radius: 8px;
  resize: none;
}

.submit-button {
  width: 100%;
  background-color: #4095e5;
  color: white;
  font-size: 16px;
  border: none;
  border-radius: 8px;
}
</style>