<template>
  <SettlementPageFrame>
    <SettlementPageHeader
      icon="el-icon-s-promotion"
      title="提交审批"
      description="将草稿、审批拒绝或结算失败的结算单提交审批。提交成功后状态更新为审批中（approving）。"
      endpoint="GET /bill/finance_settlement_submit.dspy"
    >
      <template #actions>
        <button type="button" class="settlement-btn settlement-btn--primary" :disabled="loadingList" @click="loadList">
          <i class="el-icon-refresh" />{{ loadingList ? '刷新中...' : '刷新' }}
        </button>
      </template>
    </SettlementPageHeader>

    <div class="settlement-split-layout">
      <aside class="settlement-card settlement-selector">
        <div class="settlement-card-head">
          <div class="settlement-card-heading">
            <i class="el-icon-filter" />
            <span>待提交结算单</span>
            <small class="settlement-card-subtitle">· 3</small>
          </div>
        </div>
        <button
          v-for="row in submitRows"
          :key="row.id"
          type="button"
          class="settlement-selector-item"
          :class="{ 'is-active': selectedRow && row.id === selectedRow.id }"
          @click="selectRow(row)"
        >
          <span class="settlement-selector-no">{{ row.no }}</span>
          <span class="settlement-selector-name">{{ row.name }}</span>
          <span class="settlement-selector-date">{{ row.start }} ~ {{ row.end }}</span>
          <span style="display: block; margin-top: 7px;"><SettlementStatusBadge :status="row.status" /></span>
        </button>
      </aside>

      <main style="min-width: 0;">
        <template v-if="selectedRow">
          <section class="settlement-card" style="margin-bottom: 20px;">
            <div class="settlement-detail-head">
              <div>
                <div class="settlement-detail-no">
                  <i class="el-icon-document" style="color: #0ea5e9; font-size: 17px;" />
                  {{ selectedRow.no }}
                  <SettlementStatusBadge :status="selectedRow.status" />
                </div>
                <div class="settlement-detail-meta">
                  <i class="el-icon-office-building" /> {{ selectedRow.name }}
                  <span style="margin: 0 7px; color: #cbd5e1;">|</span>
                  <i class="el-icon-date" /> {{ selectedRow.start }} ~ {{ selectedRow.end }}
                </div>
              </div>
            </div>
            <div class="settlement-metric-grid settlement-metric-grid--three" style="margin: 0; padding: 0 20px 20px;">
              <SettlementMetricCard label="销售金额" :value="selectedRow.sales" icon="el-icon-wallet" />
              <SettlementMetricCard label="结算金额" :value="selectedRow.settlement" variant="emerald" icon="el-icon-s-order" />
              <SettlementMetricCard label="平台收入" :value="selectedRow.income" variant="amber" icon="el-icon-s-marketing" />
            </div>
          </section>

          <section class="settlement-card">
            <div class="settlement-form-section">
              <div class="settlement-section-title">
                <span class="settlement-section-title-icon"><i class="el-icon-s-promotion" /></span>
                <div>
                  <b>提交审批</b>
                  <span>填写审批信息后提交</span>
                </div>
              </div>
              <div class="settlement-inline-grid">
                <div class="settlement-field">
                  <label class="settlement-label">操作用户 ID *</label>
                  <input v-model.trim="form.userid" class="settlement-input" type="text" placeholder="请输入当前操作用户 ID">
                </div>
                <div class="settlement-field">
                  <label class="settlement-label">审批业务名</label>
                  <input v-model.trim="form.business_name" class="settlement-input" type="text" placeholder="财务结算">
                  <small style="display: block; margin-top: 6px; color: #94a3b8; font-size: 11px;">需要在 apv_business 表中存在该业务配置</small>
                </div>
              </div>

              <section class="settlement-alert settlement-alert--warning" style="margin: 20px 0;">
                <span class="settlement-alert-icon"><i class="el-icon-warning-outline" /></span>
                <div class="settlement-alert-content">
                  <b>提交前请确认结算数据</b>
                  <p>提交后结算单状态将变为审批中，等待审批系统回调结果。</p>
                </div>
              </section>

              <section v-if="result" class="settlement-alert" style="margin: 0 0 20px;">
                <span class="settlement-alert-icon"><i class="el-icon-circle-check" /></span>
                <div class="settlement-alert-content">
                  <b>提交成功</b>
                  <p>审批 ID：{{ result.approvalId || '-' }}，当前状态：<SettlementStatusBadge :status="result.status" /></p>
                </div>
              </section>

              <button type="button" class="settlement-btn settlement-btn--primary" :disabled="submitting" @click="submitApproval">
                <i class="el-icon-s-promotion" />{{ submitting ? '提交中...' : '提交审批' }}
              </button>
            </div>
          </section>
        </template>
        <section v-else class="settlement-card settlement-card--padded" style="color: #94a3b8; text-align: center;">
          {{ loadingList ? '正在加载待提交结算单...' : '暂无可提交审批的结算单' }}
        </section>
      </main>
    </div>
  </SettlementPageFrame>
</template>

<script>
import SettlementPageFrame from './SettlementPageFrame'
import SettlementPageHeader from './SettlementPageHeader'
import SettlementMetricCard from './SettlementMetricCard'
import SettlementStatusBadge from './SettlementStatusBadge'
import { settlementListAPI, submitApprovalAPI } from '@/api/FinancialSettlementCenter'
import {
  getAccountingOrgId,
  getCurrentUserId,
  getItems,
  getPayload,
  isSubmittable,
  normalizeSettlement
} from './settlementHelpers'

export default {
  name: 'SubmitforApproval',
  components: {
    SettlementPageFrame,
    SettlementPageHeader,
    SettlementMetricCard,
    SettlementStatusBadge
  },
  data() {
    return {
      loadingList: false,
      submitting: false,
      submitRows: [],
      selectedRow: null,
      result: null,
      form: {
        userid: getCurrentUserId(),
        business_name: '财务结算'
      }
    }
  },
  mounted() {
    this.loadList()
  },
  methods: {
    async loadList() {
      const accountingOrgid = getAccountingOrgId(this.$route)
      if (!accountingOrgid) {
        this.$message.warning('未获取到核算机构 ID')
        return
      }

      this.loadingList = true
      try {
        const payload = getPayload(await settlementListAPI({
          accounting_orgid: accountingOrgid,
          current_page: 1,
          page_size: 100
        }))
        this.submitRows = getItems(payload).map(normalizeSettlement).filter(row => isSubmittable(row.status))
        const routeId = this.$route.query.id
        this.selectedRow = this.submitRows.find(row => row.id === routeId) || this.submitRows[0] || null
      } catch (error) {
        this.$message.error(error.message || '待提交结算单查询失败')
      } finally {
        this.loadingList = false
      }
    },
    selectRow(row) {
      this.selectedRow = row
      this.result = null
      this.$router.replace({
        name: 'FinancialSubmitforApproval',
        query: { id: row.id }
      })
    },
    async submitApproval() {
      if (!this.selectedRow) return
      if (!this.form.userid || !this.form.business_name) {
        this.$message.warning('请填写操作用户 ID 和审批业务名')
        return
      }

      this.submitting = true
      try {
        const payload = getPayload(await submitApprovalAPI({
          settlement_id: this.selectedRow.id,
          userid: this.form.userid,
          business_name: this.form.business_name
        }))
        this.result = normalizeSettlement(payload.settlement || payload)
        this.result.status = this.result.status === 'draft' ? 'approving' : this.result.status
        this.$message.success('审批提交成功')
        await this.loadList()
      } catch (error) {
        this.$message.error(error.message || '提交审批失败')
      } finally {
        this.submitting = false
      }
    }
  }
}
</script>
