<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

 https://www.mall4j.com/

 未经允许，不可做商业用途！

 版权所有，侵权必究！
-->
<template>
  <div class="page-refund-order">
    <div class="screening-conditions">
      <el-form
        :inline="true"
        :model="dataForm"
        @submit.prevent
        @keyup.enter="onGetDataList(true)"
      >
        <div>
          <!-- 退款编号 -->
          <el-form-item :label="$t('order.order.refundId')+ '：'">
            <el-input
              v-model="searchForm.refundId"
              oninput="value=value.replace(/[^0-9]/g,'')"
              :placeholder="$t('order.order.refundId')"
              maxlength="19"
              clearable
            />
          </el-form-item>
          <!-- 退款类型 -->
          <el-form-item
            :label="$t('order.order.typeOfRefund')+ '：'"
          >
            <el-select
              v-model="searchForm.refundType"
              clearable
              :placeholder="$t('order.order.typeOfRefund')"
            >
              <el-option
                v-for="item in refundType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 售后状态 -->
          <el-form-item
            :label="$t('order.order.afterSalesStatus')+ '：'"
          >
            <el-select
              v-model="returnMoneySts"
              clearable
              :placeholder="$t('order.order.pleSelAfterSalesSta')"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 订单编号 -->
          <el-form-item :label="$t('order.order.number')+ '：'">
            <el-input
              v-model="searchForm.orderId"
              oninput="value=value.replace(/[^0-9]/g,'')"
              :placeholder="$t('order.order.number')"
              maxlength="19"
              clearable
            />
          </el-form-item>
          <!-- 代销卖家 -->
          <el-form-item :label="$t('order.order.commissionMerchant')+ '：'">
            <el-input
              v-model="searchForm.shopName"
              :placeholder="$t('order.order.commissionMerchantTips')"
              maxlength="20"
              clearable
            />
          </el-form-item>
        </div>
        <div>
          <!-- 申请方式 -->
          <el-form-item
            :label="$t('order.order.applicationType')+ '：'"
          >
            <el-select
              v-model="searchForm.applyType"
              clearable
              :placeholder="
                $t('order.order.pleaseChooseHowToApply')
              "
            >
              <el-option
                v-for="item in applyType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <!-- 申请时间 -->
          <el-form-item :label="$t('order.order.applyTime')+ '：'">
            <el-date-picker
              v-model="dateRange"
              type="datetimerange"
              :range-separator="$t('date.tip')"
              value-format="YYYY-MM-DD HH:mm:ss"
              :start-placeholder="$t('date.start')"
              :end-placeholder="$t('date.end')"
              :default-time="defaultTime"
            />
            <el-button
              style="margin-left: 12px;"
              plain
              @click="onSetDateRange(1)"
            >
              {{
                $t("date.t")
              }}
            </el-button>
            <el-button
              plain
              @click="onSetDateRange(2)"
            >
              {{
                $t("date.y")
              }}
            </el-button>
            <el-button
              plain
              @click="onSetDateRange(3)"
            >
              {{
                $t("date.n")
              }}
            </el-button>
            <el-button
              plain
              @click="onSetDateRange(4)"
            >
              {{
                $t("date.m")
              }}
            </el-button>
          </el-form-item>
        </div>
        <div class="btn-row">
          <!-- 搜索 -->
          <el-button
            type="primary"
            @click="onSearch(true)"
          >
            {{ $t("table.search") }}
          </el-button>
          <!-- 重置 -->
          <el-button
            plain
            @click="onResetSearch()"
          >
            {{ $t("table.clear") }}
          </el-button>
        </div>
      </el-form>
    </div>
    <div class="main">
      <div class="content">
        <!-- 导航 -->
        <div class="status-nav clearfix">
          <ul
            :class="[
              'clearfix',
              $t('language') === 'English' ? 'nav-list-ul-en' : 'nav-list-ul-zh',
            ]"
          >
            <li
              :class="['nav-item-li', sts === 0 ? 'selected' : '']"
              data-sts="0"
              @click="onSelectNav($event)"
            >
              {{ $t("date.a") }}
            </li>
            <li
              :class="['nav-item-li', sts === 1 ? 'selected' : '']"
              data-sts="1"
              @click="onSelectNav($event)"
            >
              {{ $t("order.order.buyerApplication") }}
            </li>
            <li
              :class="['nav-item-li', sts === 2 ? 'selected' : '']"
              data-sts="2"
              @click="onSelectNav($event)"
            >
              {{ $t("order.order.sellerAccepts") }}
            </li>
            <li
              :class="['nav-item-li', sts === 3 ? 'selected' : '']"
              data-sts="3"
              @click="onSelectNav($event)"
            >
              {{ $t("order.order.buyShipment") }}
            </li>
            <li
              :class="['nav-item-li', sts === 4 ? 'selected' : '']"
              data-sts="4"
              @click="onSelectNav($event)"
            >
              {{ $t("order.order.selReceiving") }}
            </li>
            <li
              :class="['nav-item-li', sts === 5 ? 'selected' : '']"
              data-sts="5"
              @click="onSelectNav($event)"
            >
              {{ $t("order.order.refundsuccessfully") }}
            </li>
            <li
              :class="['nav-item-li', sts === -1 ? 'selected' : '']"
              data-sts="-1"
              @click="onSelectNav($event)"
            >
              {{ $t("order.order.refundClosed") }}
            </li>
            <li
              :class="['nav-item-li', sts === 6 ? 'selected' : '']"
              data-sts="6"
              @click="onSelectNav($event)"
            >
              平台介入中
            </li>
          </ul>
        </div>

        <!-- 列标题 -->
        <div :class="['tit', showHeadScroll ? (sidebarOpenState?'fixed-top fixed-top-w1':'fixed-top fixed-top-w2') : '']">
          <el-row
            style="width: 100%"
            class="pr-width"
          >
            <el-col :span="9">
              <span class="item product">{{ $t("constant.product") }}</span>
            </el-col>
            <el-col
              :span="3"
              class="column-title"
            >
              <span class="item">{{
                $t("order.order.commodityCondition")
              }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{
                $t("order.order.commodityUnitPriceYuanQuantity")
              }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span
                class="item"
              >{{ $t("order.order.returnAmount") }}({{
                $t("constant.dollar")
              }})</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.typeOfRefund") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.status") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("order.order.afterSalesStatus") }}</span>
            </el-col>
            <el-col
              :span="2"
              class="column-title"
            >
              <span class="item">{{ $t("table.actions") }}</span>
            </el-col>
          </el-row>
        </div>

        <div
          v-for="orderRefund in dataList"
          :key="orderRefund.refundId"
          class="prod"
          style="margin-bottom: 15px"
        >
          <div class="prod-tit">
            <span>{{ $t("order.order.refundId") }}：{{
              orderRefund.refundId
            }}</span>
            <span>{{ $t("order.order.number") }}:{{ orderRefund.orderId }}</span>
            <span>{{ $t("order.order.applyTime") }}：{{
              orderRefund.createTime
            }}</span>
          </div>
          <div class="prod-cont">
            <el-row style="width: 100%">
              <el-col :span="9">
                <div
                  v-for="orderItem in orderRefund.orderItems"
                  :key="orderItem.orderItemId"
                  class="prod-item"
                >
                  <div
                    class="items name"
                  >
                    <div class="prod-image">
                      <ImgShow :src="orderItem.supplierPic" />
                    </div>
                    <div class="prod-name">
                      <div class="prod-con">
                        <div class="prod-name-txt">
                          {{ orderItem.supplierSpuName }}
                        </div>
                        <div
                          v-if="
                            orderRefund.orderType === 1 ||
                              orderRefund.orderType === 2
                          "
                          class="order-status"
                        >
                          {{
                            orderRefund.orderType === 1
                              ? $t("order.order.groupPurchaseOrder")
                              : orderRefund.orderType === 2
                                ? $t("order.order.spikeOrder")
                                : ""
                          }}
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 组合信息 -->
                  <div
                    v-if="orderItem.comboList"
                    class="order-prod-item-give-con"
                  >
                    <div
                      v-for="(comboItem, comboIndex) in orderItem.comboList"
                      :key="comboIndex"
                      class="giveaway-item"
                    >
                      <div class="giveaway-item-name">
                        【组合】 {{ comboItem.spuName }}
                      </div>
                      <div class="giveaway-item-sku-count">
                        {{ comboItem.skuName || '' }} x{{ comboItem.count }}
                      </div>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="3"
                style="height: 100%"
              >
                <div class="item">
                  {{ orderRefund.shopName }}
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item flex-direction-column">
                  <div class="price-block">
                    <span class="totalprice">
                      {{ onHandlerPrice(orderRefund.purchaseRefundAmount) }}
                    </span>
                  </div>
                  <div>
                    {{ orderRefund.refundCount }}{{ $t("constant.piece") }}
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="price-block">
                    <span
                      v-if="orderRefund.refundAmount > 0"
                      class="totalprice"
                    >
                      {{ onHandlerPrice(orderRefund.refundAmount) }}
                      {{ $t("constant.dollar") }}
                    </span>
                    <span
                      v-if="orderRefund.refundAmount && orderRefund.refundScore"
                      class="totalprice"
                    >&nbsp;+&nbsp;</span>
                    <span
                      v-if="orderRefund.refundScore"
                      class="totalprice"
                    >{{ orderRefund.refundScore
                    }}{{ $t("order.order.integral") }}</span>
                    <!-- <div>
                      <span>{{ orderRefund.refundCount
                      }}{{ $t("constant.piece") }}</span>
                    </div> -->
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div>
                    <span v-if="orderRefund.refundType === 1">{{
                      $t("order.order.wholeGoodsRefund")
                    }}</span>
                    <span v-if="orderRefund.refundType === 2">{{
                      $t("order.order.singleItemRefund")
                    }}</span>
                  </div>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <span
                    type="danger"
                  >{{
                    [
                      "",
                      $t("pay.obligation"),
                      $t("order.order.toBeShipped"),
                      $t("order.order.pendingReceipt"),
                      "",
                      $t("order.order.successfulTransaction"),
                      $t("order.order.transactionFailed"),
                      $t("group.waitGroup"),
                    ][orderRefund.orderStatus]
                  }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div
                  v-if="orderRefund.platformInterventionStatus && orderRefund.platformInterventionStatus!==-1"
                  class="item"
                >
                  <!-- 平台介入状态 -1.没有介入 1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功 -->
                  <span>{{
                    [
                      "",
                      '平台介入中',
                      '平台介入中',
                      '退款关闭',
                      '',
                      '退款成功'
                    ][orderRefund.platformInterventionStatus]
                  }}</span>
                </div>
                <div
                  v-else
                  class="item"
                >
                  <span
                    v-if="orderRefund.returnMoneySts !== -1"
                    type="danger"
                  >{{
                    [
                      "",
                      $t("order.order.buyerApplication"),
                      $t("order.order.sellerAccepts"),
                      $t("order.order.buyShipment"),
                      $t("order.order.selReceiving"),
                      $t("order.order.refundsuccessfully"),
                    ][orderRefund.returnMoneySts]
                  }}</span>
                  <span
                    v-else
                    type="danger"
                  >{{
                    $t("order.order.refundClosed")
                  }}</span>
                </div>
              </el-col>
              <el-col
                :span="2"
                style="height: 100%"
              >
                <div class="item">
                  <div class="operate">
                    <el-button
                      v-permission="['order:refund:order']"
                      link
                      type="primary"
                      @click="onViewOrderHandle(orderRefund.orderId)"
                    >
                      {{ $t("order.order.viewOrder") }}
                    </el-button>
                    <el-button
                      v-permission="['order:refund:refund']"
                      link
                      type="primary"
                      @click="
                        onAddOrUpdate(orderRefund.refundId)
                      "
                    >
                      {{ [-1,2,5].includes(orderRefund.returnMoneySts) ? $t("order.order.refundDetails") : $t("order.order.processingRefunds") }}
                    </el-button>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
        <div
          v-if="!dataList.length"
          class="empty"
        >
          {{ $t("order.order.noData") }}
        </div>
      </div>
    </div>
    <!-- 分页条 -->
    <pagination
      v-show="pageVO.total > 0"
      v-model:page="pageQuery.pageNum"
      v-model:limit="pageQuery.pageSize"
      style="text-align: right"
      :total="pageVO.total"
      @pagination="onGetDataList()"
    />
  </div>
</template>

<script setup>
import moment from 'moment'
import Pagination from '@/components/Pagination/index.vue'
import * as api from '@/api/order/order-refund'
import Big from 'big.js'

const dataForm = reactive({})
// 侧边栏显隐状态
const appStore = useAppStore()
const sidebarOpenState = computed({
  get () {
    return appStore.sidebar.opened
  }
})

const options = computed(() => {
  return [{
    value: 1,
    label: $t('order.order.buyerApplication')
  },
  {
    value: 2,
    label: $t('order.order.sellerAccepts')
  },
  {
    value: 3,
    label: $t('order.order.buyShipment')
  },
  {
    value: 4,
    label: $t('order.order.selReceiving')
  },
  {
    value: 5,
    label: $t('order.order.refundsuccessfully')
  },
  {
    value: -1,
    label: $t('order.order.refundClosed')
  },
  {
    value: 6,
    label: '平台介入'
  }]
})

const refundType = computed(() => {
  return [{
    value: 1,
    label: $t('order.order.wholeOrderRefund')
  }, {
    value: 2,
    label: $t('order.order.singleItemRefund')
  }]
})

const applyType = computed(() => {
  return [{
    value: 1,
    label: $t('order.order.onlyRefund')
  }, {
    value: 2,
    label: $t('order.order.refunds')
  }]
})

const searchForm = ref([])
const returnMoneySts = ref(null)
onActivated(() => {
  // 携带参数查询
  const query = useRoute().query
  if (Object.keys(query).length > 0) {
    searchForm.value = useRoute().query
    returnMoneySts.value = null
    onGetDataList()
  }
})

onMounted(() => {
  // 携带参数查询
  searchForm.value = useRoute().query
  if (searchForm.value.sts) {
    onSelectNavBySts(searchForm.value.sts)
  } else {
    onGetDataList()
  }
  // 监听页面滚动
  window.addEventListener('scroll', onScrollToTop)
})

/**
 * 页面滚动事件
 */
const showHeadScroll = ref(false)
const onScrollToTop = () => {
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
  showHeadScroll.value = scrollTop > 400
}

const dataList = ref([])
const pageVO = reactive({
  total: 0, // 一共多少条数据
  pages: 0 // 一共多少页
})
const pageQuery = reactive({
  pageSize: 10,
  pageNum: 1
})
const dataListLoading = ref(false)
const sts = ref(0)
let tempSearchForm = null
const dateRange = ref([])
const defaultTime = ref([
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
])
/**
 * 获取列表数据
 */
const onGetDataList = (newdata = false) => {
  const params = searchForm.value
  if (newdata || !tempSearchForm) {
    tempSearchForm = {
      ...pageQuery,
      orderId: params ? (params.orderId ? params.orderId : null) : null,
      returnMoneySts: returnMoneySts.value || null,
      refundId: params ? (params.refundId ? params.refundId : null) : null,
      shopName: params ? (params.shopName ? params.shopName : null) : null,
      applyType: params ? (params.applyType ? params.applyType : null) : null,
      refundType: params ? (params.refundType ? params.refundType : null) : null,
      beginTime: dateRange.value ? (dateRange.value[0] ? dateRange.value[0] : null) : null, // 开始时间
      endTime: dateRange.value ? (dateRange.value[1] ? dateRange.value[1] : null) : null // 结束时间
    }
  } else {
    tempSearchForm.returnMoneySts = returnMoneySts.value || null
    tempSearchForm = { ...tempSearchForm, ...pageQuery }
  }
  dataListLoading.value = true
  api.page(Object.assign(tempSearchForm, params)).then(data => {
    dataList.value = data.list
    pageVO.total = data.total
    dataListLoading.value = false
    sts.value = returnMoneySts.value || 0
  })
}

/**
 * 点击导航选择状态
 */
const onSelectNav = (e) => {
  const sts = e.currentTarget.dataset.sts
  onSelectNavBySts(sts)
}

/**
 * 根据状态切换导航tag
 */
const onSelectNavBySts = (sts) => {
  sts = parseInt(sts)
  returnMoneySts.value = sts === 0 ? null : parseInt(sts)
  pageQuery.pageNum = 1
  onGetDataList()
}

/**
 * 查看订单
 */
const router = useRouter()
const onViewOrderHandle = (id) => {
  router.push(`/order/order-manage/order-info?orderId=${id}`)
}

/**
 * 处理退款
 */
const onAddOrUpdate = (refundId) => {
  router.push({
    path: '/order/order-manage/refund-order-info',
    query: {
      refundId
    }
  })
}

/**
 * 根据选项设置时间
 * 1:今天 2:昨天 3: 近七天 4:近30天 5:近60天
 */
const onSetDateRange = val => {
  let startDay = null
  let endDay = null
  if (val === 1) {
    startDay = 0
    endDay = 0
  } else if (val === 2) {
    startDay = -1
    endDay = -1
  } else if (val === 3) {
    startDay = -7
    endDay = -1
  } else if (val === 4) {
    startDay = -30
    endDay = -1
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days').startOf('days').format('LL')
  // 结束时间
  const endTime = moment().add(endDay, 'days').endOf('days').format('LL')
  dateRange.value = [startTime, endTime]
}

// 清空按钮
const onResetSearch = () => {
  searchForm.value = {}
  dateRange.value = []
  returnMoneySts.value = null
}

// 搜索查询
const onSearch = (newData = false) => {
  pageQuery.pageNum = 1
  onGetDataList(newData)
}

/**
 * 精度运算-过滤
 */
const onHandlerPrice = (val) => {
  if (val == null) {
    return ''
  }
  return new Big(val).div(100).toFixed(2)
}

</script>

<style lang="scss" scoped>
@use './index.scss';
</style>
