<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="订单号" prop="orderNum">
        <el-input
          v-model="queryParams.orderNum"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="三方订单号" prop="thirdPartyOrderNum">
        <el-input
          v-model="queryParams.thirdPartyOrderNum"
          placeholder="支持模糊搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="团队名称" prop="deptName">
        <el-input
          v-model="queryParams.deptName"
          placeholder="支持模糊搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="支持模糊搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" clearable style="width: 140px">
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['/ai/video/order/']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList">
      <el-table-column label="团队名称" align="center" prop="deptName" width="140" show-overflow-tooltip />
      <el-table-column label="用户名称" align="center" prop="userName" width="120" show-overflow-tooltip />
      <el-table-column label="订单号" align="center" prop="orderNum" width="200" show-overflow-tooltip />
      <el-table-column label="三方订单号" align="center" prop="thirdPartyOrderNum" width="200" show-overflow-tooltip />
      <el-table-column label="积分" align="center" prop="amount" width="100" />
      <el-table-column label="tokens" align="center" prop="totalUsage" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.totalUsage != null && scope.row.totalUsage !== '' ? scope.row.totalUsage : '—' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <span>{{ statusLabel(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结果预览" min-width="200">
        <template slot-scope="scope">
          <div v-if="extractVideoUrl(scope.row.result)">
            <video
              :src="extractVideoUrl(scope.row.result)"
              controls
              preload="metadata"
              style="width: 180px; max-height: 100px; border-radius: 4px;"
            />
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="90" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleDetail(scope.row)">详情</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-dialog title="订单详情" :visible.sync="detailVisible" width="720px" append-to-body>
      <el-descriptions :column="1" border size="small">
        <el-descriptions-item v-for="(value, key) in detailData" :key="key" :label="key">
          <pre v-if="isObjectValue(value)" style="margin: 0; white-space: pre-wrap;">{{ formatJson(value) }}</pre>
          <span v-else>{{ value === null || value === undefined || value === "" ? "-" : value }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer">
        <el-button size="mini" @click="detailVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listOrder } from "@/api/ai/order"

export default {
  name: "TeamChargeOrder",
  data() {
    return {
      loading: true,
      showSearch: true,
      total: 0,
      orderList: [],
      detailVisible: false,
      detailData: {},
      orderTypeOptions: [
        { label: "充值", value: 0 },
        { label: "退款", value: 1 }
      ],
      statusOptions: [
        { label: "进行中", value: 0 },
        { label: "完成", value: 1 },
        { label: "失败", value: 2 }
      ],
      dateRange: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNum: null,
        thirdPartyOrderNum: null,
        userName: null,
        deptName: null,
        orderType: null,
        status: null
      }
    }
  },
  created() {
    this.initDefaultDateRange()
    this.getList()
  },
  methods: {
    initDefaultDateRange() {
      this.dateRange = this.buildLastMonthDateRange()
    },
    buildLastMonthDateRange() {
      const end = new Date()
      const start = new Date(end.getTime())
      start.setMonth(start.getMonth() - 1)
      return [this.formatYmd(start), this.formatYmd(end)]
    },
    formatYmd(d) {
      const y = d.getFullYear()
      const m = String(d.getMonth() + 1).padStart(2, "0")
      const day = String(d.getDate()).padStart(2, "0")
      return `${y}-${m}-${day}`
    },
    orderTypeLabel(orderType) {
      const n = orderType !== undefined && orderType !== null ? Number(orderType) : null
      const hit = this.orderTypeOptions.find(o => o.value === n)
      return hit ? hit.label : "—"
    },
    statusLabel(status) {
      const n = status !== undefined && status !== null ? Number(status) : null
      const hit = this.statusOptions.find(o => o.value === n)
      return hit ? hit.label : "—"
    },
    extractVideoUrl(result) {
      if (!result) return ""
      if (typeof result === "string") {
        const value = result.trim()
        if (!value) return ""
        if (/^https?:\/\/|^\/\//.test(value)) return value
        try {
          const parsed = JSON.parse(value)
          return this.extractVideoUrl(parsed)
        } catch (e) {
          return ""
        }
      }
      if (Array.isArray(result)) {
        for (let i = 0; i < result.length; i += 1) {
          const url = this.extractVideoUrl(result[i])
          if (url) return url
        }
        return ""
      }
      if (typeof result === "object") {
        const directKeys = ["videoUrl", "url", "resultUrl", "playUrl", "output", "fileUrl"]
        for (let i = 0; i < directKeys.length; i += 1) {
          const key = directKeys[i]
          if (result[key]) {
            const url = this.extractVideoUrl(result[key])
            if (url) return url
          }
        }
      }
      return ""
    },
    handleDetail(row) {
      this.detailData = row || {}
      this.detailVisible = true
    },
    isObjectValue(value) {
      return value !== null && typeof value === "object"
    },
    formatJson(value) {
      try {
        return JSON.stringify(value, null, 2)
      } catch (e) {
        return String(value)
      }
    },
    getList() {
      this.loading = true
      listOrder(this.addDateRange(this.queryParams, this.dateRange, "CreateTime")).then(response => {
        this.orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.initDefaultDateRange()
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleExport() {
      const q = { ...this.queryParams }
      this.download(
        "ai/video/order/export",
        this.addDateRange(q, this.dateRange, "CreateTime"),
        `team_orders_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
