<template>
  <view class="aftersale-container">
    <!-- 订单信息 -->
    <view class="order-section">
      <view class="section-title">订单信息</view>
      <view class="order-card">
        <view class="order-header">
          <text class="order-no">订单号：{{ orderInfo.orderNo }}</text>
          <text class="order-status">{{ getOrderStatusText(orderInfo.status) }}</text>
        </view>
        <view class="supplier-info">
          <text class="supplier-name">供应商：{{ orderInfo.supplierName }}</text>
        </view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="goods-section">
      <view class="section-title">选择售后商品</view>
      <view class="goods-list">
        <view
          class="goods-item"
          v-for="goods in orderInfo.orderGoods"
          :key="goods.id"
          :class="{ 'selected': selectedGoods.includes(goods.id) }"
          @click="toggleGoodsSelect(goods)"
        >
          <view class="goods-checkbox">
            <view class="checkbox" :class="{ 'checked': selectedGoods.includes(goods.id) }">
              <text class="checkbox-icon" v-if="selectedGoods.includes(goods.id)">✓</text>
            </view>
          </view>
          <view class="goods-image">
            <image :src="showImgJdsz(goods.goodsImg)" mode="aspectFill" />
          </view>
          <view class="goods-info">
            <view class="goods-name">{{ goods.goodsTitle }}</view>
            <view class="goods-sku" v-if="goods.skuName">{{ goods.skuName }}</view>
            <view class="goods-meta">
              <text class="goods-price">¥{{ goods.price }}</text>
              <text class="goods-quantity">×{{ goods.num }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 售后类型 -->
    <view class="type-section">
      <view class="section-title">售后类型</view>
      <view class="type-list">
        <view
          class="type-item"
          v-for="type in aftersaleTypes"
          :key="type.value"
          :class="{ 'selected': aftersaleForm.type === type.value }"
          @click="selectType(type.value)"
        >
          <view class="type-radio">
            <view class="radio" :class="{ 'checked': aftersaleForm.type === type.value }">
              <view class="radio-dot" v-if="aftersaleForm.type === type.value"></view>
            </view>
          </view>
          <view class="type-info">
            <text class="type-name">{{ type.name }}</text>
            <text class="type-desc">{{ type.desc }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 售后原因 -->
    <view class="reason-section">
      <view class="section-title">售后原因</view>
      <view class="reason-list">
        <view
          class="reason-item"
          v-for="reason in reasonList"
          :key="reason.value"
          :class="{ 'selected': aftersaleForm.reason === reason.value }"
          @click="selectReason(reason.value)"
        >
          <text class="reason-text">{{ reason.name }}</text>
          <view class="reason-check" v-if="aftersaleForm.reason === reason.value">✓</view>
        </view>
      </view>
    </view>

    <!-- 问题描述 -->
    <view class="description-section">
      <view class="section-title">问题描述</view>
      <textarea
        class="description-input"
        v-model="aftersaleForm.description"
        placeholder="请详细描述遇到的问题，以便我们更好地为您处理"
        maxlength="500"
      />
      <view class="char-count">{{ aftersaleForm.description.length }}/500</view>
    </view>

    <!-- 上传凭证 -->
    <view class="upload-section">
      <view class="section-title">上传凭证（选填）</view>
      <view class="upload-area">
        <view class="image-list">
          <view
            class="image-item"
            v-for="(image, index) in aftersaleForm.images"
            :key="index"
          >
            <image class="uploaded-image" :src="image" mode="aspectFill" />
            <view class="delete-btn" @click="deleteImage(index)">×</view>
          </view>
          <view class="upload-btn" @click="chooseImage" v-if="aftersaleForm.images.length < 6">
            <text class="upload-icon">+</text>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
        <view class="upload-tip">最多可上传6张图片，支持jpg、png格式</view>
      </view>
    </view>

    <!-- 联系方式 -->
    <view class="contact-section">
      <view class="section-title">联系方式</view>
      <view class="contact-form">
        <view class="form-item">
          <text class="form-label">联系人</text>
          <input
            class="form-input"
            v-model="aftersaleForm.contactName"
            placeholder="请输入联系人姓名"
          />
        </view>
        <view class="form-item">
          <text class="form-label">联系电话</text>
          <input
            class="form-input"
            v-model="aftersaleForm.contactPhone"
            placeholder="请输入联系电话"
            type="number"
          />
        </view>
      </view>
    </view>

    <!-- 底部提交按钮 -->
    <view class="submit-section">
      <button class="submit-btn" @click="submitAftersale" :disabled="!canSubmit">
        提交售后申请
      </button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      orderInfo: {
        orderNo: '',
        status: 0,
        supplierName: '',
        orderGoods: []
      },
      selectedGoods: [], // 选中的商品ID列表
      aftersaleForm: {
        type: 1, // 售后类型：1-退货退款，2-换货，3-仅退款
        reason: '', // 售后原因
        description: '', // 问题描述
        images: [], // 上传的图片
        contactName: '', // 联系人
        contactPhone: '' // 联系电话
      },
      aftersaleTypes: [
        {
          value: 1,
          name: '退货退款',
          desc: '商品有质量问题，需要退货并退款'
        },
        {
          value: 2,
          name: '换货',
          desc: '商品有问题，需要更换同款商品'
        },
        {
          value: 3,
          name: '仅退款',
          desc: '未收到商品或商品严重损坏'
        }
      ],
      reasonList: [
        { value: 'quality', name: '商品质量问题' },
        { value: 'damage', name: '商品破损' },
        { value: 'wrong', name: '发错商品' },
        { value: 'description', name: '与描述不符' },
        { value: 'logistics', name: '物流问题' },
        { value: 'other', name: '其他原因' }
      ]
    };
  },
  computed: {
    // 是否可以提交
    canSubmit() {
      return (
        this.selectedGoods.length > 0 &&
        this.aftersaleForm.type &&
        this.aftersaleForm.reason &&
        this.aftersaleForm.description.trim() &&
        this.aftersaleForm.contactName.trim() &&
        this.aftersaleForm.contactPhone.trim()
      );
    }
  },
  onLoad(options) {
    if (options.orderId) {
      this.orderId = options.orderId;
      this.loadOrderInfo();
      this.loadUserInfo();
    }
  },
  methods: {
    showImgJdsz(img) {
      if (!img) return '/static/images/default-goods.png';
      if (img.indexOf("https://") != -1 || img.indexOf("http://") != -1) {
        return img;
      } else {
        return this.JDSU_IMG_URL + img;
      }
    },

    // 加载订单信息
    async loadOrderInfo() {
      try {
        this.Post(
          { orderId: this.orderId },
          '/framework/haveFeeling/order/detail',
          'DES'
        ).then((res) => {
          if (res.code == 200) {
            this.orderInfo = res.data;
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            });
          }
        });
      } catch (error) {
        console.error('加载订单信息失败:', error);
      }
    },

    // 加载用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        const user = JSON.parse(userInfo);
        this.aftersaleForm.contactName = user.nickName || '';
        this.aftersaleForm.contactPhone = user.phone || '';
      }
    },

    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        "-1": "已取消",
        0: "待支付",
        1: "已支付",
        2: "已发货",
        3: "已完成"
      };
      return statusMap[status] || "未知";
    },

    // 切换商品选择
    toggleGoodsSelect(goods) {
      const index = this.selectedGoods.indexOf(goods.id);
      if (index > -1) {
        this.selectedGoods.splice(index, 1);
      } else {
        this.selectedGoods.push(goods.id);
      }
    },

    // 选择售后类型
    selectType(type) {
      this.aftersaleForm.type = type;
    },

    // 选择售后原因
    selectReason(reason) {
      this.aftersaleForm.reason = reason;
    },

    // 选择图片
    chooseImage() {
      const remainCount = 6 - this.aftersaleForm.images.length;
      uni.chooseImage({
        count: remainCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths);
        }
      });
    },

    // 上传图片
    async uploadImages(filePaths) {
      uni.showLoading({
        title: '上传中...'
      });

      try {
        for (let filePath of filePaths) {
          const uploadResult = await this.uploadSingleImage(filePath);
          if (uploadResult) {
            this.aftersaleForm.images.push(uploadResult);
          }
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },

    // 上传单张图片
    uploadSingleImage(filePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: this.BASE_URL + '/framework/upload/image',
          filePath: filePath,
          name: 'file',
          success: (res) => {
            try {
              const data = JSON.parse(res.data);
              if (data.code === 200) {
                resolve(data.data.url);
              } else {
                reject(new Error(data.msg));
              }
            } catch (error) {
              reject(error);
            }
          },
          fail: (error) => {
            reject(error);
          }
        });
      });
    },

    // 删除图片
    deleteImage(index) {
      this.aftersaleForm.images.splice(index, 1);
    },

    // 提交售后申请
    async submitAftersale() {
      if (!this.canSubmit) {
        uni.showToast({
          title: '请完善售后信息',
          icon: 'none'
        });
        return;
      }

      // 验证联系电话格式
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!phoneReg.test(this.aftersaleForm.contactPhone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }

      uni.showLoading({
        title: '提交中...'
      });

      try {
        const params = {
          orderId: this.orderId,
          goodsIds: this.selectedGoods,
          type: this.aftersaleForm.type,
          reason: this.aftersaleForm.reason,
          description: this.aftersaleForm.description,
          images: this.aftersaleForm.images.join(','),
          contactName: this.aftersaleForm.contactName,
          contactPhone: this.aftersaleForm.contactPhone
        };

        this.Post(
          params,
          '/framework/haveFeeling/aftersale/submit',
          'DES'
        ).then((res) => {
          uni.hideLoading();
          if (res.code == 200) {
            uni.showToast({
              title: '售后申请提交成功',
              icon: 'success'
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: res.msg || '提交失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        uni.hideLoading();
        console.error('提交售后申请失败:', error);
        uni.showToast({
          title: '提交失败',
          icon: 'none'
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.aftersale-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 100rpx;
}

// 通用样式
.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

// 订单信息
.order-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.order-card {
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 24rpx;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.order-no {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

.order-status {
  font-size: 24rpx;
  color: #007aff;
  background-color: #e6f3ff;
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
}

.supplier-info {
  .supplier-name {
    font-size: 24rpx;
    color: #666;
  }
}

// 商品选择
.goods-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.goods-list {
  .goods-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    transition: all 0.3s ease;

    &:last-child {
      border-bottom: none;
    }

    &.selected {
      background-color: #f0f8ff;
    }
  }
}

.goods-checkbox {
  margin-right: 20rpx;

  .checkbox {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #ddd;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &.checked {
      background-color: #007aff;
      border-color: #007aff;

      .checkbox-icon {
        color: #fff;
        font-size: 24rpx;
        font-weight: bold;
      }
    }
  }
}

.goods-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  overflow: hidden;
  margin-right: 20rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-size: 26rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 8rpx;
}

.goods-sku {
  font-size: 22rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.goods-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 24rpx;
  color: #f56565;
  font-weight: 600;
}

.goods-quantity {
  font-size: 22rpx;
  color: #999;
}

// 售后类型
.type-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.type-list {
  .type-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &.selected {
      background-color: #f0f8ff;
    }
  }
}

.type-radio {
  margin-right: 20rpx;

  .radio {
    width: 40rpx;
    height: 40rpx;
    border: 2rpx solid #ddd;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s ease;

    &.checked {
      border-color: #007aff;

      .radio-dot {
        width: 20rpx;
        height: 20rpx;
        background-color: #007aff;
        border-radius: 50%;
      }
    }
  }
}

.type-info {
  flex: 1;
}

.type-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
  margin-bottom: 6rpx;
}

.type-desc {
  font-size: 22rpx;
  color: #666;
  line-height: 1.4;
}

// 售后原因
.reason-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.reason-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.reason-item {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16rpx 24rpx;
  background-color: #f5f5f5;
  border-radius: 24rpx;
  border: 1rpx solid transparent;
  transition: all 0.3s ease;
  min-width: 140rpx;

  &.selected {
    background-color: #e6f3ff;
    border-color: #007aff;
    color: #007aff;
  }
}

.reason-text {
  font-size: 24rpx;
  color: #333;
}

.reason-check {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 24rpx;
  height: 24rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 50%;
  font-size: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

// 问题描述
.description-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.description-input {
  width: 100%;
  min-height: 200rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 26rpx;
  color: #333;
  line-height: 1.6;
  border: none;
  resize: none;
}

.char-count {
  text-align: right;
  font-size: 22rpx;
  color: #999;
  margin-top: 12rpx;
}

// 上传凭证
.upload-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.upload-area {
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 16rpx;
  }

  .image-item {
    position: relative;
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx;
    overflow: hidden;

    .uploaded-image {
      width: 100%;
      height: 100%;
    }

    .delete-btn {
      position: absolute;
      top: -8rpx;
      right: -8rpx;
      width: 32rpx;
      height: 32rpx;
      background-color: #ff4757;
      color: #fff;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20rpx;
      font-weight: bold;
    }
  }

  .upload-btn {
    width: 160rpx;
    height: 160rpx;
    background-color: #f8f9fa;
    border: 2rpx dashed #ddd;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #666;

    .upload-icon {
      font-size: 48rpx;
      margin-bottom: 8rpx;
    }

    .upload-text {
      font-size: 22rpx;
    }
  }

  .upload-tip {
    font-size: 22rpx;
    color: #999;
    text-align: center;
  }
}

// 联系方式
.contact-section {
  background-color: #fff;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.contact-form {
  .form-item {
    display: flex;
    align-items: center;
    margin-bottom: 24rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .form-label {
    width: 160rpx;
    font-size: 26rpx;
    color: #333;
    font-weight: 500;
  }

  .form-input {
    flex: 1;
    height: 80rpx;
    background-color: #f8f9fa;
    border-radius: 8rpx;
    padding: 0 20rpx;
    font-size: 26rpx;
    color: #333;
    border: none;
  }
}

// 提交按钮
.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  border-top: 1rpx solid #eee;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 12rpx;
  font-size: 28rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;

  &:disabled {
    background-color: #ccc;
    color: #999;
  }

  &:not(:disabled):active {
    transform: scale(0.98);
  }
}
</style>