<script setup lang="ts">
import { fullUrl, previewImg } from '@/utils/common'
import { getDeliveryCompanyApi } from '@/api/delivery'
import { getOrderRefundDetailApi, postOrderRefundReturnApi } from '@/api/order'
import type { deliveryCompanyItem } from '@/types/delivery'
import type { orderRefundDetailResult } from '@/types/order'
import { onLoad } from '@dcloudio/uni-app'
import { computed } from 'vue'
import { ref } from 'vue'
import { pageUrl } from '@/utils/constants'

const props = defineProps<{
  data: string
  id: number
}>()

const orderData = ref<orderRefundDetailResult>()

const getOrderData = async () => {
  const res = await getOrderRefundDetailApi({ id: props.id })
  orderData.value = res.result
}

// 审核状态
enum auditStatusEnum {
  wait_audit = 1,
  agree = 2,
  refuse = 3,
  cancel = 4,
}

// 显示协商历史
const showHistory = computed(() => {
  return orderData.value?.audit_status == auditStatusEnum.refuse
})
// 显示退货地址
const showDelivery = computed(() => {
  return orderData.value?.audit_status == auditStatusEnum.agree && orderData.value.refund_address
})
// 复制地址
const copyAddress = () => {
  const fullAddress = `收货人：${orderData.value?.refund_address.name}联系电话：${orderData.value?.refund_address.phone}详细地址：${orderData.value?.refund_address.full_address}`

  uni.setClipboardData({
    data: fullAddress,
    success: () => {
      uni.showToast({
        title: '复制成功',
        icon: 'none',
      })
    },
  })
}

const deliveryCompanyOptions = ref<deliveryCompanyItem[]>([])
const companyIndex = ref(0)

const getDeliveryCompanyData = async () => {
  // 有物流信息时不请求
  if (deliverForm.value.delivery_company && deliverForm.value.delivery_no) return

  const res = await getDeliveryCompanyApi()
  res.result.unshift({ id: 0, name: '请选择物流公司', code: '' })
  deliveryCompanyOptions.value = res.result
}

const deliverForm = ref({
  delivery_company_id: 0,
  delivery_company: '',
  delivery_no: '',
})
const deliverFormRules = ref({
  delivery_no: {
    rules: [{ required: true, errorMessage: '请输入物流单号' }],
  },
})

const onChnageCompanyIndex = (event: UniHelper.SelectorPickerOnChangeEvent) => {
  companyIndex.value = event.detail.value
  const deliveryCompany = deliveryCompanyOptions.value.find((item) => item.id == companyIndex.value)

  deliverForm.value.delivery_company_id = deliveryCompany!.id
  deliverForm.value.delivery_company = deliveryCompany!.name
}

const formRef = ref()
const onSubmit = async () => {
  if (!deliverForm.value.delivery_company_id) {
    uni.showToast({
      title: '请选择物流公司',
      icon: 'none',
    })
    return
  }
  await formRef.value.validate()
  const params = {
    id: props.id,
    ...deliverForm.value,
  }
  const res = await postOrderRefundReturnApi(params)
  uni.showToast({
    title: res.msg,
    icon: 'none',
  })
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

const refundTypeText = computed(() => {
  switch (orderData.value?.refund_type) {
    case 1:
      return '退货退款'
    case 2:
      return '换货'
    default:
      return ''
  }
})

onLoad(async () => {
  await getOrderData()
  await getDeliveryCompanyData()
})
</script>

<template>
  <view class="detail" v-if="orderData">
    <view class="status">
      <image class="image" src="/static/images/bg.png" />
      <text>{{ orderData.status_text }}</text>
    </view>
    <view class="order">
      <view class="card">
        <text class="title">售后商品</text>
        <navigator
          class="goods"
          :url="`${pageUrl['shopping-mall-goods-detail']}?id=${orderData.detail.goods_id}`"
          hover-class="none"
        >
          <image class="cover" :src="fullUrl(orderData.detail.image)"></image>
          <view class="meta">
            <view class="name ellipsis">{{ orderData.detail.goods_name }}</view>
            <view class="meta-spec">{{ orderData.detail.spec }}</view>
            <view class="meta-quantity">x{{ orderData!.refund_num }}</view>
          </view>
        </navigator>
        <view class="detail">
          <view class="detail-item" v-if="parseFloat(orderData.apply_money) > 0">
            <text>申请金额</text>
            <text class="amount">￥{{ orderData.apply_money }}</text>
          </view>
          <view class="detail-item" v-if="parseFloat(orderData.refund_money) > 0">
            <text>退款金额</text>
            <text class="amount">￥{{ orderData.refund_money }}</text>
          </view>
          <view class="detail-item" v-if="parseFloat(orderData.refund_freight) > 0">
            <text>退款运费</text>
            <text>￥{{ orderData.refund_freight }}</text>
          </view>
          <view class="detail-item">
            <text>申请时间</text>
            <text>{{ orderData.create_time }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="block" v-if="showHistory">
      <view class="history">
        <view class="header">
          <text class="title">协商历史</text>
        </view>
        <view class="history-item">
          <text>售后类型：{{ refundTypeText }}</text>
        </view>
        <view class="history-item">
          <text>申请原因：{{ orderData.remark }}</text>
        </view>
        <view class="history-item" v-if="orderData.remark_images">
          <text>申请凭证：</text>
          <view class="images-container">
            <image
              v-for="(item, index) in orderData.remark_images"
              :key="index"
              :src="item"
              mode="aspectFit"
              @tap="previewImg(item, orderData!.remark_images)"
            />
          </view>
        </view>
        <view class="history-item" v-if="orderData.refuse_reason">
          <text>商家回复：{{ orderData.refuse_reason }}</text>
        </view>
      </view>
    </view>

    <view class="block" v-if="showDelivery">
      <view class="address">
        <view class="header">
          <text class="title">退货地址</text>
          <button class="copy-button" @tap="copyAddress">复制</button>
        </view>
        <view>
          <text>收货人：{{ orderData.refund_address.name }}</text>
        </view>
        <view>
          <text>联系电话：{{ orderData.refund_address.phone }}</text>
        </view>
        <view>
          <text>详细地址：{{ orderData.refund_address.full_address }}</text>
        </view>
        <view class="remark">
          <text>未与商家协商一致情况下，请勿使用平邮或到付邮寄方式</text>
        </view>
      </view>
    </view>

    <view class="block" v-if="showDelivery">
      <view class="delivery">
        <view class="header">
          <text class="title">退货物流</text>
        </view>
        <uni-list v-if="orderData.user_ship_delivery">
          <uni-list-item
            title="物流公司"
            :rightText="orderData.user_ship_delivery.delivery_company"
          >
          </uni-list-item>
          <uni-list-item title="物流单号" :rightText="orderData.user_ship_delivery.delivery_no">
          </uni-list-item>
        </uni-list>
        <view v-else>
          <uni-forms
            ref="formRef"
            label-width="100"
            validate-trigger="blur"
            :rules="deliverFormRules"
            :model="deliverForm"
          >
            <uni-forms-item required label="物流公司" name="delivery_company">
              <view style="display: flex; align-items: center; height: 35px">
                <picker
                  mode="selector"
                  :range="deliveryCompanyOptions"
                  range-key="name"
                  :value="companyIndex"
                  @change="onChnageCompanyIndex"
                >
                  <text>{{ deliveryCompanyOptions[companyIndex]?.name }}</text>
                </picker>
              </view>
            </uni-forms-item>
            <uni-forms-item required label="物流单号" name="delivery_no">
              <uni-easyinput
                v-model="deliverForm.delivery_no"
                placeholder="请输入物流单号"
                :disabled="Boolean(orderData.user_ship_status)"
              />
            </uni-forms-item>
          </uni-forms>
          <button class="sub-button" @tap="onSubmit" v-if="!Boolean(orderData.user_ship_status)">
            录入物流信息
          </button>
        </view>
      </view>
    </view>

    <view class="block" v-if="orderData.exchange_delivery">
      <view class="delivery">
        <view class="header">
          <text class="title">换货物流</text>
        </view>
        <uni-list>
          <uni-list-item title="物流公司" :rightText="orderData.exchange_delivery.delivery_company">
          </uni-list-item>
          <uni-list-item title="物流单号" :rightText="orderData.exchange_delivery.delivery_no">
          </uni-list-item>
        </uni-list>
      </view>
    </view>

    <view :style="{ paddingBottom: '100rpx' }"></view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f6f6f6;
}

.status {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 150rpx;

  /* 图片样式 */
  .image {
    width: 100%;
    height: 150rpx;
    position: absolute;
    top: 0;
    left: 0;
  }

  /* 文本样式 */
  text {
    z-index: 1;
    font-size: 36rpx;
    color: #fff;
  }
}

.order {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;

  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .text {
      color: red;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    padding-top: 20rpx;
    padding-bottom: 20rpx;

    .cover {
      width: 170rpx;
      height: 170rpx;
      margin-right: 20rpx;
      border-radius: 10rpx;
      overflow: hidden;
      position: relative;
    }

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;

      &-spec {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
        max-width: 90%;
      }

      &-quantity {
        position: absolute;
        right: 20px;
        font-size: 24rpx;
        color: #9e9c9c;
      }
    }

    .name {
      font-size: 26rpx;
      color: #444;
      max-width: 90%;
    }
  }

  .detail {
    display: flex;
    flex-direction: column;
    color: #999;
    font-size: 28rpx;
  }

  .detail-item {
    display: flex;
    justify-content: space-between;
    padding: 5rpx;
  }

  .amount {
    color: red;
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .pay-time {
      font-size: 24rpx;
      color: #999;
      margin-right: 20rpx;
    }

    .countdown {
      font-size: 24rpx;
      color: #999;
      margin-left: auto;
      display: flex;
    }

    .button {
      width: 130rpx;
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-left: 20rpx;
      border-radius: 60rpx;
      font-size: 26rpx;
      color: #444;
    }

    .secondary {
      color: #ff5f3c;
      border-color: #ff5f3c;
    }

    .primary {
      color: #fff;
      background-color: #ff5f3c;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}

.block {
  display: flex;
  flex-direction: column;
  padding: 20rpx;
  margin: 20rpx 20rpx 0;
  border-radius: 10rpx;
  background-color: #fff;
}

.address view {
  margin-bottom: 20rpx;
  font-size: 24rpx;
}

.history view {
  margin-bottom: 20rpx;
}

.images-container {
  display: flex;

  image {
    width: 150rpx;
    height: 120rpx;
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
}

.title {
  font-size: 35rpx;
}

.copy-button {
  display: flex;
  height: 50rpx;
  font-size: 24rpx;
  margin-right: initial;
  align-items: center;
}

.remark {
  padding: 10rpx 0 10rpx 0;
  font-size: 24rpx;
  color: #999;
  line-height: 1.5;
}

.sub-button {
  background-color: #ff5f3c;
  color: white;
  border-radius: 20rpx;
  text-align: center;
  cursor: pointer;
  margin: 20rpx;
}
</style>
