<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="goodsName">
          <el-input v-model="queryParams.goodsName" placeholder="商品名称" clearable style="width: 140px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item label="发货状态" prop="shipStatus">
          <el-select v-model="queryParams.shipStatus" placeholder="全部" clearable style="width: 120px">
            <el-option label="待支付" value="0" />
            <el-option label="待发货" value="1" />
            <el-option label="已发货" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="收货人" prop="consigneeName">
          <el-input v-model="queryParams.consigneeName" placeholder="收货人" clearable style="width: 110px" />
        </el-form-item>
        <el-form-item label="收货手机" prop="consigneeMobile">
          <el-input v-model="queryParams.consigneeMobile" placeholder="手机号" clearable style="width: 130px" />
        </el-form-item>
        <el-form-item label="收货地址" prop="consigneeAddress">
          <el-input v-model="queryParams.consigneeAddress" placeholder="地址关键词" clearable style="width: 140px" />
        </el-form-item>
        <el-form-item label="配送方式" prop="deliveryType">
          <el-select v-model="queryParams.deliveryType" placeholder="全部" clearable style="width: 120px">
            <el-option label="物流配送" value="1" />
            <el-option label="商家配送" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px"
          />
        </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-tab-pane label="已关闭" name="4" />
        <el-tab-pane label="已完成" name="3" />
        <el-tab-pane label="已删除" name="5" />
      </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="orderList">
        <el-table-column label="订单信息" align="left" min-width="280">
          <template slot-scope="scope">
            <div class="order-info">
              <div class="order-no">订单号：{{ scope.row.orderNo || '—' }}</div>
              <div class="order-time">下单：{{ parseTime(scope.row.createTime) || '—' }}</div>
              <div v-if="scope.row.items && scope.row.items.length" class="goods-info">
                <image-preview v-if="scope.row.items[0].goodsImage" :src="scope.row.items[0].goodsImage" :width="44" :height="44" />
                <div class="goods-text">
                  <div>{{ scope.row.items[0].goodsName || '—' }}</div>
                  <div class="sub-text">
                    {{ scope.row.items[0].goodsSpec || '默认' }}
                    × {{ scope.row.items[0].quantity }}
                    · ¥{{ scope.row.items[0].unitPrice != null ? scope.row.items[0].unitPrice : '—' }}
                  </div>
                  <div v-if="scope.row.itemCount > 1" class="more-tip">共 {{ scope.row.itemCount }} 件商品</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="订单金额" align="center" width="110">
          <template slot-scope="scope">
            <div>¥{{ scope.row.payAmount != null ? scope.row.payAmount : '—' }}</div>
            <div v-if="Number(scope.row.freightAmount) > 0" class="sub-text">含运费 ¥{{ scope.row.freightAmount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="会员名称" align="center" prop="memberNickName" width="100" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.memberNickName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收货人信息" align="left" min-width="160">
          <template slot-scope="scope">
            <div>{{ scope.row.consigneeName || '—' }}</div>
            <div class="sub-text">{{ scope.row.consigneeMobile || '—' }}</div>
            <div class="sub-text addr-text">{{ scope.row.consigneeAddress || '—' }}</div>
          </template>
        </el-table-column>
        <el-table-column label="配送方式" align="center" width="100">
          <template slot-scope="scope">
            <span>{{ scope.row.deliveryTypeLabel || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" width="90">
          <template slot-scope="scope">
            <el-tag size="small" :type="orderStatusTag(scope.row.orderStatus)">
              {{ scope.row.orderStatusLabel || orderStatusLabel(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['agri:seller:order:query']">详情</el-button>
            <el-button
              v-if="canShip(scope.row)"
              size="mini"
              type="text"
              icon="el-icon-truck"
              @click="handleShip(scope.row)"
              v-hasPermi="['agri:seller:order:ship']"
            >去发货</el-button>
            <el-button
              v-if="canLogistics(scope.row)"
              size="mini"
              type="text"
              icon="el-icon-position"
              @click="handleLogistics(scope.row)"
              v-hasPermi="['agri:seller:order:ship']"
            >更新物流</el-button>
            <el-button
              v-if="canDelivered(scope.row)"
              size="mini"
              type="text"
              icon="el-icon-circle-check"
              @click="handleDelivered(scope.row)"
              v-hasPermi="['agri:seller:order:ship']"
            >商品到货</el-button>
            <el-button
              v-if="canDelete(scope.row)"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['agri:seller:order:remove']"
            >删除</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-order-detail
      ref="orderDetail"
      :visible.sync="detailOpen"
      :order-id="currentOrderId"
      @ship="handleShipFromDetail"
      @logistics="handleLogisticsFromDetail"
      @delivered="handleDeliveredFromDetail"
      @delete="handleDeleteFromDetail"
    />

    <!-- 发货弹窗 -->
    <el-dialog title="去发货" :visible.sync="shipOpen" width="680px" append-to-body @close="cancelShip">
      <el-form ref="shipFormRef" :model="shipForm" :rules="shipRules" label-width="110px">
        <el-form-item label="发货时间" prop="shipTime">
          <el-date-picker
            v-model="shipForm.shipTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择发货时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="配送方式" prop="deliveryType">
          <el-radio-group v-model="shipForm.deliveryType">
            <el-radio label="1">物流配送</el-radio>
            <el-radio label="2">商家配送</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="shipForm.deliveryType === '1'">
          <el-form-item label="物流公司" prop="logisticsCompany">
            <el-input v-model="shipForm.logisticsCompany" placeholder="请输入物流公司" maxlength="64" />
          </el-form-item>
          <el-form-item label="快递单号" prop="trackingNo">
            <el-input v-model="shipForm.trackingNo" placeholder="请输入快递单号" maxlength="64" />
          </el-form-item>
        </template>
        <template v-if="shipForm.deliveryType === '2'">
          <el-form-item label="车辆号码" prop="vehicleNo">
            <el-input v-model="shipForm.vehicleNo" placeholder="请输入车辆号码" maxlength="32" />
          </el-form-item>
          <el-form-item label="配送员" prop="courierName">
            <el-input v-model="shipForm.courierName" placeholder="请输入配送员姓名" maxlength="32" />
          </el-form-item>
          <el-form-item label="配送员手机" prop="courierMobile">
            <el-input v-model="shipForm.courierMobile" placeholder="请输入配送员手机号" maxlength="20" />
          </el-form-item>
        </template>
        <el-form-item label="发货备注" prop="shipRemark">
          <el-input v-model="shipForm.shipRemark" type="textarea" :rows="2" placeholder="选填" maxlength="200" show-word-limit />
        </el-form-item>
        <el-form-item label="发货商品">
          <el-table border size="small" :data="shipItems">
            <el-table-column label="商品" min-width="180">
              <template slot-scope="scope">
                <div class="goods-cell">
                  <image-preview v-if="scope.row.goodsImage" :src="scope.row.goodsImage" :width="40" :height="40" />
                  <span>{{ scope.row.goodsName || '—' }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="规格" prop="goodsSpec" width="90">
              <template slot-scope="scope">
                <span>{{ scope.row.goodsSpec || '默认' }}</span>
              </template>
            </el-table-column>
            <el-table-column label="数量" prop="quantity" width="70" align="center" />
          </el-table>
          <div class="form-tip">须整单一次发完，不可拆单</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitShip">确 定</el-button>
        <el-button @click="cancelShip">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更新物流弹窗 -->
    <el-dialog title="更新物流信息" :visible.sync="logisticsOpen" width="520px" append-to-body @close="cancelLogistics">
      <el-form ref="logisticsFormRef" :model="logisticsForm" :rules="traceRules" label-width="110px">
        <el-form-item label="运输更新时间" prop="traceTime">
          <el-date-picker
            v-model="logisticsForm.traceTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="运输状态描述" prop="content">
          <el-input v-model="logisticsForm.content" type="textarea" :rows="3" placeholder="如：到达 XX 中转站" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitLogistics">确 定</el-button>
        <el-button @click="cancelLogistics">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商品到货弹窗 -->
    <el-dialog title="商品到货登记" :visible.sync="deliveredOpen" width="520px" append-to-body @close="cancelDelivered">
      <el-form ref="deliveredFormRef" :model="deliveredForm" :rules="deliveredRules" label-width="100px">
        <el-form-item label="送达时间" prop="traceTime">
          <el-date-picker
            v-model="deliveredForm.traceTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择送达时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="送达说明" prop="content">
          <el-input v-model="deliveredForm.content" type="textarea" :rows="3" placeholder="选填" maxlength="500" show-word-limit />
        </el-form-item>
      </el-form>
      <div class="form-tip">登记送达不替代买家确认收货，订单仍为「已发货」直至买家确认</div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDelivered">确 定</el-button>
        <el-button @click="cancelDelivered">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSellerOrder,
  getSellerOrder,
  shipSellerOrder,
  logisticsSellerOrder,
  deliveredSellerOrder,
  delSellerOrder
} from "@/api/agri/seller/order"
import { getSellerContext } from "@/api/agri/seller/context"
import { setSellerShopContext } from "@/utils/sellerShop"
import SellerOrderDetail from "./detail"

export default {
  name: "AgriSellerOrder",
  components: { SellerOrderDetail },
  data() {
    const validateLogisticsCompany = (rule, value, callback) => {
      if (this.shipForm.deliveryType !== '1') {
        callback()
        return
      }
      if (!value || !String(value).trim()) {
        callback(new Error("请输入物流公司"))
        return
      }
      callback()
    }
    const validateTrackingNo = (rule, value, callback) => {
      if (this.shipForm.deliveryType !== '1') {
        callback()
        return
      }
      if (!value || !String(value).trim()) {
        callback(new Error("请输入快递单号"))
        return
      }
      callback()
    }
    const validateVehicleNo = (rule, value, callback) => {
      if (this.shipForm.deliveryType !== '2') {
        callback()
        return
      }
      if (!value || !String(value).trim()) {
        callback(new Error("请输入车辆号码"))
        return
      }
      callback()
    }
    const validateCourierName = (rule, value, callback) => {
      if (this.shipForm.deliveryType !== '2') {
        callback()
        return
      }
      if (!value || !String(value).trim()) {
        callback(new Error("请输入配送员姓名"))
        return
      }
      callback()
    }
    const validateCourierMobile = (rule, value, callback) => {
      if (this.shipForm.deliveryType !== '2') {
        callback()
        return
      }
      if (!value || !String(value).trim()) {
        callback(new Error("请输入配送员手机号"))
        return
      }
      if (!/^1[3-9]\d{9}$/.test(String(value).trim())) {
        callback(new Error("请输入正确的手机号"))
        return
      }
      callback()
    }
    return {
      loading: false,
      showSearch: true,
      total: 0,
      orderList: [],
      statusTab: "all",
      dateRange: [],
      detailOpen: false,
      currentOrderId: null,
      shipOpen: false,
      shipItems: [],
      shipForm: {},
      logisticsOpen: false,
      logisticsForm: {},
      deliveredOpen: false,
      deliveredForm: {},
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderStatus: undefined,
        orderNo: undefined,
        goodsName: undefined,
        shipStatus: undefined,
        consigneeName: undefined,
        consigneeMobile: undefined,
        consigneeAddress: undefined,
        deliveryType: undefined
      },
      shipRules: {
        shipTime: [{ required: true, message: "请选择发货时间", trigger: "change" }],
        deliveryType: [{ required: true, message: "请选择配送方式", trigger: "change" }],
        logisticsCompany: [{ validator: validateLogisticsCompany, trigger: "blur" }],
        trackingNo: [{ validator: validateTrackingNo, trigger: "blur" }],
        vehicleNo: [{ validator: validateVehicleNo, trigger: "blur" }],
        courierName: [{ validator: validateCourierName, trigger: "blur" }],
        courierMobile: [{ validator: validateCourierMobile, trigger: "blur" }]
      },
      traceRules: {
        traceTime: [{ required: true, message: "请选择运输更新时间", trigger: "change" }],
        content: [{ required: true, message: "请填写运输状态描述", trigger: "blur" }]
      },
      deliveredRules: {
        traceTime: [{ required: true, message: "请选择送达时间", trigger: "change" }]
      }
    }
  },
  created() {
    this.applyRouteTab()
    this.initPage()
  },
  methods: {
    applyRouteTab() {
      const tab = this.$route.query.orderStatus
      if (tab === undefined || tab === null || tab === '') {
        return
      }
      const allowed = ['all', '1', '2', '3', '4', '5']
      if (allowed.includes(String(tab))) {
        this.statusTab = String(tab) === 'all' ? 'all' : String(tab)
        this.syncTabToQuery()
      }
    },
    syncTabToQuery() {
      this.queryParams.orderStatus = this.statusTab === 'all' ? undefined : this.statusTab
    },
    initPage() {
      this.syncTabToQuery()
      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
      listSellerOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.orderList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    handleTabClick() {
      this.syncTabToQuery()
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.syncTabToQuery()
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleDetail(row) {
      this.currentOrderId = row.orderId
      this.detailOpen = true
    },
    orderStatusLabel(status) {
      const map = { "0": "待支付", "1": "待发货", "2": "已发货", "3": "已完成", "4": "已关闭", "5": "已删除" }
      return map[status] || "—"
    },
    orderStatusTag(status) {
      const map = { "0": "warning", "1": "primary", "2": "", "3": "success", "4": "info", "5": "info" }
      return map[status] || "info"
    },
    canShip(row) {
      return row.orderStatus === '1'
    },
    canLogistics(row) {
      return row.orderStatus === '2'
    },
    canDelivered(row) {
      return row.orderStatus === '2'
    },
    canDelete(row) {
      return row.orderStatus === '4'
    },
    nowDateTime() {
      return this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
    },
    prepareShipDialog(orderId) {
      this.currentOrderId = orderId
      return getSellerOrder(orderId).then(response => {
        const data = response.data || {}
        this.shipItems = data.items || []
        this.resetShipForm()
        this.shipOpen = true
      })
    },
    handleShip(row) {
      this.prepareShipDialog(row.orderId)
    },
    handleShipFromDetail(detail) {
      this.prepareShipDialog(detail.orderId)
    },
    resetShipForm() {
      this.shipForm = {
        shipTime: this.nowDateTime(),
        deliveryType: "1",
        logisticsCompany: undefined,
        trackingNo: undefined,
        vehicleNo: undefined,
        courierName: undefined,
        courierMobile: undefined,
        shipRemark: undefined
      }
      this.resetForm("shipFormRef")
    },
    cancelShip() {
      this.shipOpen = false
      this.resetShipForm()
    },
    submitShip() {
      this.$refs["shipFormRef"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = {
          shipTime: this.shipForm.shipTime,
          deliveryType: this.shipForm.deliveryType,
          shipRemark: this.shipForm.shipRemark || undefined
        }
        if (this.shipForm.deliveryType === '1') {
          payload.logisticsCompany = this.shipForm.logisticsCompany
          payload.trackingNo = this.shipForm.trackingNo
        } else {
          payload.vehicleNo = this.shipForm.vehicleNo
          payload.courierName = this.shipForm.courierName
          payload.courierMobile = this.shipForm.courierMobile
        }
        shipSellerOrder(this.currentOrderId, payload).then(() => {
          this.$modal.msgSuccess("发货成功")
          this.shipOpen = false
          this.getList()
          if (this.detailOpen && this.$refs.orderDetail) {
            this.$refs.orderDetail.reload()
          }
        })
      })
    },
    openTraceDialog(type, orderId) {
      this.currentOrderId = orderId
      if (type === 'logistics') {
        this.logisticsForm = {
          traceTime: this.nowDateTime(),
          content: undefined
        }
        this.resetForm("logisticsFormRef")
        this.logisticsOpen = true
      } else {
        this.deliveredForm = {
          traceTime: this.nowDateTime(),
          content: undefined
        }
        this.resetForm("deliveredFormRef")
        this.deliveredOpen = true
      }
    },
    handleLogistics(row) {
      this.openTraceDialog('logistics', row.orderId)
    },
    handleLogisticsFromDetail(detail) {
      this.openTraceDialog('logistics', detail.orderId)
    },
    cancelLogistics() {
      this.logisticsOpen = false
      this.logisticsForm = {}
      this.resetForm("logisticsFormRef")
    },
    submitLogistics() {
      this.$refs["logisticsFormRef"].validate(valid => {
        if (!valid) {
          return
        }
        logisticsSellerOrder(this.currentOrderId, this.logisticsForm).then(() => {
          this.$modal.msgSuccess("物流信息已更新")
          this.logisticsOpen = false
          this.getList()
          if (this.detailOpen && this.$refs.orderDetail) {
            this.$refs.orderDetail.reload()
          }
        })
      })
    },
    handleDelivered(row) {
      this.openTraceDialog('delivered', row.orderId)
    },
    handleDeliveredFromDetail(detail) {
      this.openTraceDialog('delivered', detail.orderId)
    },
    cancelDelivered() {
      this.deliveredOpen = false
      this.deliveredForm = {}
      this.resetForm("deliveredFormRef")
    },
    submitDelivered() {
      this.$refs["deliveredFormRef"].validate(valid => {
        if (!valid) {
          return
        }
        deliveredSellerOrder(this.currentOrderId, this.deliveredForm).then(() => {
          this.$modal.msgSuccess("送达登记成功")
          this.deliveredOpen = false
          this.getList()
          if (this.detailOpen && this.$refs.orderDetail) {
            this.$refs.orderDetail.reload()
          }
        })
      })
    },
    handleDelete(row) {
      this.confirmDelete(row.orderId)
    },
    handleDeleteFromDetail(detail) {
      this.confirmDelete(detail.orderId)
    },
    confirmDelete(orderId) {
      this.$modal.confirm('确认删除该已关闭订单？删除后将移至「已删除」页签，默认列表不再展示。').then(() => {
        return delSellerOrder(orderId)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getList()
        if (this.detailOpen && this.currentOrderId === orderId) {
          this.detailOpen = false
        }
      }).catch(() => {})
    }
  }
}
</script>

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