<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="订单编号" prop="orderNo">
          <el-input v-model="queryParams.orderNo" placeholder="订单编号" clearable style="width: 150px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="售后编号" prop="aftersaleNo">
          <el-input v-model="queryParams.aftersaleNo" placeholder="售后编号" clearable style="width: 150px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="申请类型" prop="applyType">
          <el-select v-model="queryParams.applyType" placeholder="全部" clearable style="width: 150px">
            <el-option v-for="item in applyTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <br/>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-tabs v-model="statusTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部" name="all" />
        <el-tab-pane label="进行中" name="1" />
        <el-tab-pane label="已完结" name="2" />
      </el-tabs>

      <el-row :gutter="10" class="mb8">
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="aftersaleList" :empty-text="emptyTableText">
        <el-table-column label="售后编号" align="center" prop="aftersaleNo" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column label="申请类型" align="center" width="130">
          <template slot-scope="scope">
            <span>{{ scope.row.applyTypeText || applyTypeLabel(scope.row.applyType) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售后订单信息" align="left" min-width="300">
          <template slot-scope="scope">
            <div class="order-info">
              <div class="order-no">订单号：{{ scope.row.orderNo || '—' }}</div>
              <div class="goods-info">
                <image-preview v-if="scope.row.goodsImage" :src="scope.row.goodsImage" :width="44" :height="44" />
                <div class="goods-text">
                  <div>{{ scope.row.goodsName || '—' }}</div>
                  <div class="sub-text">
                    {{ scope.row.goodsSpec || '默认' }}
                    × {{ scope.row.quantity != null ? scope.row.quantity : '—' }}
                    · ¥{{ scope.row.payAmount != null ? scope.row.payAmount : '—' }}
                  </div>
                  <div class="sub-text">
                    {{ scope.row.memberNickName || '—' }}
                    · {{ scope.row.consigneeName || '—' }}
                    · {{ scope.row.consigneeMobile || '—' }}
                  </div>
                  <div class="sub-text addr-text">{{ scope.row.consigneeAddress || '—' }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="售后原因" align="center" prop="applyReason" width="120" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.applyReason || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="退货数量" align="center" width="90">
          <template slot-scope="scope">
            <span>{{ returnQuantityText(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请金额" align="center" width="100">
          <template slot-scope="scope">
            <span>¥{{ scope.row.applyAmount != null ? scope.row.applyAmount : '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="售后状态" align="center" width="90">
          <template slot-scope="scope">
            <el-tag size="small" :type="aftersaleStatusTag(scope.row.aftersaleStatus)">
              {{ scope.row.aftersaleStatusText || aftersaleStatusLabel(scope.row.aftersaleStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="完结时间" align="center" width="160">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.finishTime) || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:seller:aftersale:query']">查看详情</el-button>
            <el-button
              v-if="scope.row.aftersaleStatus === '1'"
              size="mini"
              type="text"
              icon="el-icon-edit-outline"
              @click="handleFinish(scope.row)"
              v-hasPermi="['agri:seller:aftersale:finish']"
            >处理售后</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 详情抽屉 -->
    <seller-aftersale-detail
      ref="aftersaleDetail"
      :visible.sync="detailOpen"
      :aftersale-id="currentAftersaleId"
      @finish="openFinishDialog"
      @view-order="handleViewOrder"
    />

    <!-- 关联订单详情抽屉（只读） -->
    <seller-order-detail
      :visible.sync="orderDetailOpen"
      :order-id="currentOrderId"
      :show-actions="false"
    />

    <!-- 处理售后弹窗 -->
    <el-dialog title="处理售后" :visible.sync="finishOpen" width="560px" append-to-body @close="cancelFinish">
      <el-alert
        title="完结后不可回退，处理结果将同步展示给买家。"
        type="warning"
        :closable="false"
        show-icon
        class="finish-alert"
      />
      <el-form ref="finishFormRef" :model="finishForm" :rules="finishRules" label-width="90px" class="finish-form">
        <el-form-item label="处理结果" prop="processResult">
          <el-input
            v-model="finishForm.processResult"
            type="textarea"
            :rows="5"
            placeholder="请输入处理结果，买家可在退款/售后详情查看"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFinish">确认完结</el-button>
        <el-button @click="cancelFinish">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerAftersale,
  finishSellerAftersale
} from "@/api/agri/seller/aftersale"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"
import SellerAftersaleDetail from "./detail"
import SellerOrderDetail from "../order/detail"

const APPLY_TYPE_MAP = {
  "1": "仅退款-未发货",
  "2": "仅退款-已发货",
  "3": "退货退款"
}

const AFTERSALE_STATUS_MAP = {
  "1": "进行中",
  "2": "已完结"
}

export default {
  name: "AgriSellerAftersale",
  components: { SellerAftersaleDetail, SellerOrderDetail },
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      aftersaleList: [],
      statusTab: "all",
      detailOpen: false,
      currentAftersaleId: null,
      orderDetailOpen: false,
      currentOrderId: null,
      finishOpen: false,
      finishSubmitting: false,
      currentFinishAftersaleId: null,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        aftersaleNo: undefined,
        orderNo: undefined,
        applyType: undefined,
        aftersaleStatus: undefined
      },
      applyTypeOptions: [
        { value: "1", label: "仅退款-未发货" },
        { value: "2", label: "仅退款-已发货" },
        { value: "3", label: "退货退款" }
      ],
      finishForm: {
        processResult: ""
      },
      finishRules: {
        processResult: [{ required: true, message: "请填写处理结果", trigger: "blur" }]
      }
    }
  },
  computed: {
    hasSearchFilter() {
      const q = this.queryParams
      return !!(q.aftersaleNo || q.orderNo || q.applyType || q.aftersaleStatus)
    },
    emptyTableText() {
      return this.hasSearchFilter ? "未找到符合条件的售后申请" : "暂无售后申请"
    }
  },
  created() {
    this.initPage()
  },
  methods: {
    applyTypeLabel(type) {
      return APPLY_TYPE_MAP[type] || "—"
    },
    aftersaleStatusLabel(status) {
      return AFTERSALE_STATUS_MAP[status] || "—"
    },
    aftersaleStatusTag(status) {
      const map = { "1": "warning", "2": "success" }
      return map[status] || "info"
    },
    returnQuantityText(row) {
      if (row.applyType === "1") {
        return "—"
      }
      return row.returnQuantity != null ? row.returnQuantity : "—"
    },
    initPage() {
      this.loadShopContext().then(() => {
        this.getList()
      }).catch(() => {
        this.getList()
      })
    },
    loadShopContext() {
      return getSellerContext().then(response => {
        const data = response.data || {}
        if (data.shopId != null) {
          setSellerShopContext(data.shopId, data.shopName)
        }
      })
    },
    getList() {
      this.loading = true
      listSellerAftersale(this.queryParams).then(response => {
        this.aftersaleList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleTabClick() {
      this.queryParams.aftersaleStatus = this.statusTab === "all" ? undefined : this.statusTab
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.statusTab = "all"
      this.queryParams.aftersaleStatus = undefined
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleDetail(row) {
      this.currentAftersaleId = row.aftersaleId
      this.detailOpen = true
    },
    handleViewOrder(detail) {
      if (!detail.orderId) {
        return
      }
      this.currentOrderId = detail.orderId
      this.orderDetailOpen = true
    },
    openFinishDialog(detail) {
      this.handleFinish(detail)
    },
    handleFinish(row) {
      if (row.aftersaleStatus !== "1") {
        return
      }
      this.currentFinishAftersaleId = row.aftersaleId
      this.finishForm.processResult = ""
      this.finishOpen = true
      this.$nextTick(() => {
        if (this.$refs.finishFormRef) {
          this.$refs.finishFormRef.clearValidate()
        }
      })
    },
    cancelFinish() {
      this.finishOpen = false
      this.currentFinishAftersaleId = null
      this.finishForm.processResult = ""
      if (this.$refs.finishFormRef) {
        this.$refs.finishFormRef.resetFields()
      }
    },
    submitFinish() {
      this.$refs.finishFormRef.validate(valid => {
        if (!valid) {
          return
        }
        this.$modal.confirm("确认完结该售后单？完结后不可回退，处理结果将同步至买家端。").then(() => {
          finishSellerAftersale(this.currentFinishAftersaleId, {
            processResult: this.finishForm.processResult.trim()
          }).then(() => {
            this.$modal.msgSuccess("售后已完结")
            this.finishOpen = false
            this.getList()
            if (this.detailOpen && this.$refs.aftersaleDetail) {
              this.$refs.aftersaleDetail.reload()
            }
          })
        }).catch(() => {})
      })
    }
  }
}
</script>

<style scoped lang="scss">
.mb8 {
  margin-bottom: 8px;
}
.order-info {
  .order-no {
    font-weight: 600;
    margin-bottom: 6px;
  }
}
.goods-info {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}
.goods-text {
  flex: 1;
  min-width: 0;
}
.sub-text {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
}
.addr-text {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.finish-alert {
  margin-bottom: 16px;
}
.finish-form {
  margin-top: 4px;
}
</style>
