<template>
  <div class="balance-sheet-container">
    <!-- 页面标题和操作栏 -->
    <div class="no-print">
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="100px"
        >
          <el-form-item label="报表日期" prop="reportDate">
            <el-date-picker
              v-model="queryParams.reportDate"
              type="month"
              placeholder="选择报表日期"
              format="YYYY-MM"
              value-format="YYYY-MM"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery" type="primary">
              <Icon icon="ep:search" class="mr-5px" /> 查询
            </el-button>
            <el-button @click="resetQuery">
              <Icon icon="ep:refresh" class="mr-5px" /> 重置
            </el-button>
            <el-button type="success" plain @click="handleExport" :loading="exportLoading">
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
            <el-button type="warning" plain @click="handlePrint">
              <Icon icon="ep:printer" class="mr-5px" /> 打印
            </el-button>
            <el-button type="success" @click="handleSave" :loading="saveLoading" v-hasPermi="['erp:balance-sheet:create']">
              <Icon icon="ep:check" class="mr-5px" /> 保存
            </el-button>
            <el-button type="info" plain @click="handleAddRowAtEnd" v-hasPermi="['erp:balance-sheet:addline']">
              <Icon icon="ep:plus" class="mr-5px" /> 添加行
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </div>

    <!-- 资产负债表主体 -->
    <ContentWrap>
      <div class="balance-sheet" v-loading="loading">
        <!-- 表头信息 -->
        <div class="sheet-header">
          <div class="header-left">
            <span>编制单位：</span>
            <el-input
              v-model="queryParams.companyName"
              class="company-name-input"
              size="small"
              clearable
            />
          </div>
          <div class="header-center">
            <h2>资产负债表</h2>
          </div>
          <div class="header-right">
<!--            <div>{{ queryParams.reportDate || '____-__-__' }}</div>-->
            <div>单位：元</div>
          </div>
        </div>

        <!-- 表格主体 -->
        <table class="balance-table" border="1" cellspacing="0" cellpadding="0">
          <thead>
            <tr>
              <th width="180">资产</th>
              <th width="50">行次</th>
              <th width="140">期末余额</th>
              <th width="140">年初余额</th>
              <th width="220">负债和所有者权益(或股东权益)</th>
              <th width="50">行次</th>
              <th width="140">期末余额</th>
              <th width="140">年初余额</th>
              <th width="100" class="no-print" v-hasPermi="['erp:balance-sheet:addline']">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in balanceSheetData" :key="index" :class="{ 'total-row': row.isTotal, 'category-row': row.isCategory }">
              <td :class="{ 'text-left': true, 'indent': row.indent }">
                <el-input
                  v-model="row.assetItem"
                  class="item-input"
                  size="small"
                  placeholder=""
                  clearable
                />
              </td>
              <td class="text-center">
                <el-input
                  v-model="row.assetLineNo"
                  class="line-no-input"
                  size="small"
                  placeholder=""
                  maxlength="10"
                />
              </td>
              <td class="text-right">
                <el-input-number
                  :model-value="row.assetEndAmount ?? undefined"
                  @update:model-value="row.assetEndAmount = $event ?? null"
                  :precision="2"
                  :controls="false"
                  :min="undefined"
                  class="amount-input"
                  size="small"
                  placeholder=""
                />
              </td>
              <td class="text-right">
                <el-input-number
                  :model-value="row.assetBeginAmount ?? undefined"
                  @update:model-value="row.assetBeginAmount = $event ?? null"
                  :precision="2"
                  :controls="false"
                  :min="undefined"
                  class="amount-input"
                  size="small"
                  placeholder=""
                />
              </td>
              <td :class="{ 'text-left': true, 'indent': row.indent }">
                <el-input
                  v-model="row.liabilityItem"
                  class="item-input"
                  size="small"
                  placeholder=""
                  clearable
                />
              </td>
              <td class="text-center">
                <el-input
                  v-model="row.liabilityLineNo"
                  class="line-no-input"
                  size="small"
                  placeholder=""
                  maxlength="10"
                />
              </td>
              <td class="text-right">
                <el-input-number
                  :model-value="row.liabilityEndAmount ?? undefined"
                  @update:model-value="row.liabilityEndAmount = $event ?? null"
                  :precision="2"
                  :controls="false"
                  :min="undefined"
                  class="amount-input"
                  size="small"
                  placeholder=""
                />
              </td>
              <td class="text-right">
                <el-input-number
                  :model-value="row.liabilityBeginAmount ?? undefined"
                  @update:model-value="row.liabilityBeginAmount = $event ?? null"
                  :precision="2"
                  :controls="false"
                  :min="undefined"
                  class="amount-input"
                  size="small"
                  placeholder=""
                />
              </td>
              <td class="text-center action-cell" v-hasPermi="['erp:balance-sheet:addline']">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleAddRow(index)"
                  title="在此行下方添加新行"
                >
                  <Icon icon="ep:plus" />
                </el-button>
                <el-button
                  link
                  type="danger"
                  size="small"
                  @click="handleDeleteRow(index)"
                  :disabled="row.isTotal || row.isCategory"
                  :title="(row.isTotal || row.isCategory) ? '合计行或分类行不能删除' : '删除此行'"
                >
                  <Icon icon="ep:delete" />
                </el-button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 报表说明 -->
        <div class="sheet-footer">
          <div class="footer-item">
            <span>单位负责人：</span>
            <span>会计负责人：</span>
            <span>制表人：</span>
          </div>
        </div>

        <!-- 指导意见 -->
        <div class="guidance-opinion">
          <div class="guidance-label">指导意见：</div>
          <el-input
            v-model="guidanceOpinion"
            type="textarea"
            :rows="12"
            placeholder="请输入指导意见"
            class="guidance-input"
          />
        </div>
      </div>
    </ContentWrap>
  </div>
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import { BalanceSheetApi } from '@/api/erp/threetables/balancesheet'
import type { BalanceSheetRowVO } from '@/api/erp/threetables/balancesheet'

/** 资产负债表 */
defineOptions({ name: 'BalanceSheet' })

const message = useMessage()

const loading = ref(false)
const exportLoading = ref(false)
const saveLoading = ref(false)
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  companyName: '',
  reportDate: formatDate(new Date(), 'YYYY-MM')
})

// 资产负债表数据结构
interface BalanceSheetRow {
  assetItem: string
  assetLineNo: string
  assetEndAmount: number | null
  assetBeginAmount: number | null
  liabilityItem: string
  liabilityLineNo: string
  liabilityEndAmount: number | null
  liabilityBeginAmount: number | null
  isTotal?: boolean
  isCategory?: boolean
  indent?: boolean
  guidanceOpinion?: string
}

// 默认资产负债表数据模板（根据图片格式）
const defaultBalanceSheetData: BalanceSheetRow[] = [
  // 流动资产部分
  // { assetItem: '流动资产：', assetLineNo: '', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '流动负债：', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  // { assetItem: '货币资金', assetLineNo: '1', assetEndAmount: 8439308.33, assetBeginAmount: 7771670.60, liabilityItem: '短期借款', liabilityLineNo: '31', liabilityEndAmount: 2999990.42, liabilityBeginAmount: 3000000.00, indent: true },
  // { assetItem: '短期投资', assetLineNo: '2', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付票据', liabilityLineNo: '32', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '应收票据', assetLineNo: '3', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付账款', liabilityLineNo: '33', liabilityEndAmount: 2461797.19, liabilityBeginAmount: 10137975.66, indent: true },
  // { assetItem: '应收账款', assetLineNo: '4', assetEndAmount: 11438689.00, assetBeginAmount: 20362914.30, liabilityItem: '预收账款', liabilityLineNo: '34', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '预付账款', assetLineNo: '5', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付职工薪酬', liabilityLineNo: '35', liabilityEndAmount: 328563.99, liabilityBeginAmount: 222734.77, indent: true },
  // { assetItem: '应收股利', assetLineNo: '6', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应交税费', liabilityLineNo: '36', liabilityEndAmount: -267220.32, liabilityBeginAmount: -142312.96, indent: true },
  // { assetItem: '应收利息', assetLineNo: '7', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付利息', liabilityLineNo: '37', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '其他应收款', assetLineNo: '8', assetEndAmount: 748893.60, assetBeginAmount: 1257515.97, liabilityItem: '应付利润', liabilityLineNo: '38', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '存货', assetLineNo: '9', assetEndAmount: 2274640.70, assetBeginAmount: 3641895.30, liabilityItem: '其他应付款', liabilityLineNo: '39', liabilityEndAmount: 8403.48, liabilityBeginAmount: 133483.96, indent: true },
  // { assetItem: '其中：原材料', assetLineNo: '10', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '其他流动负债', liabilityLineNo: '40', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '在产品', assetLineNo: '11', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '流动负债合计：', liabilityLineNo: '41', liabilityEndAmount: 5531534.76, liabilityBeginAmount: 13351881.43, isTotal: true },
  // { assetItem: '库存商品', assetLineNo: '12', assetEndAmount: 2274640.70, assetBeginAmount: 3210212.13, liabilityItem: '非流动负债：', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  // { assetItem: '周转材料', assetLineNo: '13', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '长期借款', liabilityLineNo: '42', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '其他流动资产', assetLineNo: '14', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '长期应付款', liabilityLineNo: '43', liabilityEndAmount: 500000.00, liabilityBeginAmount: 500000.00, indent: true },
  // { assetItem: '流动资产合计：', assetLineNo: '15', assetEndAmount: 22901531.63, assetBeginAmount: 33033996.17, liabilityItem: '递延收益', liabilityLineNo: '44', liabilityEndAmount: 544937.17, liabilityBeginAmount: 544937.17, isTotal: true },
  // { assetItem: '非流动资产：', assetLineNo: '', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '其他非流动负债', liabilityLineNo: '45', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  // { assetItem: '长期债券投资', assetLineNo: '16', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '非流动负债合计：', liabilityLineNo: '46', liabilityEndAmount: 1044937.17, liabilityBeginAmount: 1044937.17, isTotal: true },
  // { assetItem: '长期股权投资', assetLineNo: '17', assetEndAmount: 300000.00, assetBeginAmount: 300000.00, liabilityItem: '负债合计：', liabilityLineNo: '47', liabilityEndAmount: 6576471.93, liabilityBeginAmount: 14396818.60, isTotal: true },
  // { assetItem: '固定资产原价', assetLineNo: '18', assetEndAmount: 3181098.58, assetBeginAmount: 416496.82, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '减：累计折旧', assetLineNo: '19', assetEndAmount: 416496.82, assetBeginAmount: 151187.09, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '固定资产账面价值', assetLineNo: '20', assetEndAmount: 2764601.76, assetBeginAmount: 265309.73, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '在建工程', assetLineNo: '21', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '工程物资', assetLineNo: '22', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '固定资产清理', assetLineNo: '23', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '生产性生物资产', assetLineNo: '24', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '所有者权益(或股东权益)：', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  // { assetItem: '无形资产', assetLineNo: '25', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '实收资本（或股本）', liabilityLineNo: '48', liabilityEndAmount: 2750000.00, liabilityBeginAmount: 2750000.00, indent: true },
  // { assetItem: '开发支出', assetLineNo: '26', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '资本公积', liabilityLineNo: '49', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '长期待摊费用', assetLineNo: '27', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '盈余公积', liabilityLineNo: '50', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  // { assetItem: '其他非流动资产', assetLineNo: '28', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '未分配利润', liabilityLineNo: '51', liabilityEndAmount: 16639661.46, liabilityBeginAmount: 16452487.30, indent: true },
  // { assetItem: '非流动资产合计：', assetLineNo: '29', assetEndAmount: 3064601.76, assetBeginAmount: 565309.73, liabilityItem: '所有者权益(或股东权益)合计：', liabilityLineNo: '52', liabilityEndAmount: 19389661.46, liabilityBeginAmount: 19202487.30, isTotal: true },
  // { assetItem: '资产总计：', assetLineNo: '30', assetEndAmount: 25966133.39, assetBeginAmount: 33599305.90, liabilityItem: '负债和所有者权益(或股东权益)总计：', liabilityLineNo: '53', liabilityEndAmount: 25966133.39, liabilityBeginAmount: 33599305.90, isTotal: true }



  { assetItem: '流动资产：', assetLineNo: '', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '流动负债：', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  { assetItem: '货币资金', assetLineNo: '1', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '短期借款', liabilityLineNo: '31', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '短期投资', assetLineNo: '2', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付票据', liabilityLineNo: '32', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '应收票据', assetLineNo: '3', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付账款', liabilityLineNo: '33', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '应收账款', assetLineNo: '4', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '预收账款', liabilityLineNo: '34', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '预付账款', assetLineNo: '5', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付职工薪酬', liabilityLineNo: '35', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '应收股利', assetLineNo: '6', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应交税费', liabilityLineNo: '36', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '应收利息', assetLineNo: '7', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付利息', liabilityLineNo: '37', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '其他应收款', assetLineNo: '8', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '应付利润', liabilityLineNo: '38', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '存货', assetLineNo: '9', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '其他应付款', liabilityLineNo: '39', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '其中：原材料', assetLineNo: '10', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '其他流动负债', liabilityLineNo: '40', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '在产品', assetLineNo: '11', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '流动负债合计：', liabilityLineNo: '41', liabilityEndAmount: null, liabilityBeginAmount: null, isTotal: true },
  { assetItem: '库存商品', assetLineNo: '12', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '非流动负债：', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  { assetItem: '周转材料', assetLineNo: '13', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '长期借款', liabilityLineNo: '42', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '其他流动资产', assetLineNo: '14', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '长期应付款', liabilityLineNo: '43', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '流动资产合计：', assetLineNo: '15', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '递延收益', liabilityLineNo: '44', liabilityEndAmount: null, liabilityBeginAmount: null, isTotal: true },
  { assetItem: '非流动资产：', assetLineNo: '', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '其他非流动负债', liabilityLineNo: '45', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  { assetItem: '长期债券投资', assetLineNo: '16', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '非流动负债合计：', liabilityLineNo: '46', liabilityEndAmount: null, liabilityBeginAmount: null, isTotal: true },
  { assetItem: '长期股权投资', assetLineNo: '17', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '负债合计：', liabilityLineNo: '47', liabilityEndAmount: null, liabilityBeginAmount: null, isTotal: true },
  { assetItem: '固定资产原价', assetLineNo: '18', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '减：累计折旧', assetLineNo: '19', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '固定资产账面价值', assetLineNo: '20', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '在建工程', assetLineNo: '21', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '工程物资', assetLineNo: '22', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '固定资产清理', assetLineNo: '23', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '生产性生物资产', assetLineNo: '24', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '所有者权益(或股东权益)：', liabilityLineNo: '', liabilityEndAmount: null, liabilityBeginAmount: null, isCategory: true },
  { assetItem: '无形资产', assetLineNo: '25', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '实收资本（或股本）', liabilityLineNo: '48', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '开发支出', assetLineNo: '26', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '资本公积', liabilityLineNo: '49', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '长期待摊费用', assetLineNo: '27', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '盈余公积', liabilityLineNo: '50', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '其他非流动资产', assetLineNo: '28', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '未分配利润', liabilityLineNo: '51', liabilityEndAmount: null, liabilityBeginAmount: null, indent: true },
  { assetItem: '非流动资产合计：', assetLineNo: '29', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '所有者权益(或股东权益)合计：', liabilityLineNo: '52', liabilityEndAmount: null, liabilityBeginAmount: null, isTotal: true },
  { assetItem: '资产总计：', assetLineNo: '30', assetEndAmount: null, assetBeginAmount: null, liabilityItem: '负债和所有者权益(或股东权益)总计：', liabilityLineNo: '53', liabilityEndAmount: null, liabilityBeginAmount: null, isTotal: true }
]

// 资产负债表数据
const balanceSheetData = ref<BalanceSheetRow[]>([])

// 指导意见
const guidanceOpinion = ref('')

/** 查询列表 */
const getList = async () => {
  if (!queryParams.reportDate) {
    message.warning('请选择报表日期')
    return
  }

  loading.value = true
  try {
    // 确保报表日期格式为 YYYY-MM
    const formattedReportDate = formatReportDate(queryParams.reportDate)
    const data = await BalanceSheetApi.getBalanceSheet(formattedReportDate)

    if (data && data.length > 0) {
      // 从后端获取数据
      balanceSheetData.value = data.map(item => ({
        assetItem: item.assetItem || '',
        assetLineNo: item.assetLineNo || '',
        assetEndAmount: item.assetEndAmount,
        assetBeginAmount: item.assetBeginAmount,
        liabilityItem: item.liabilityItem || '',
        liabilityLineNo: item.liabilityLineNo || '',
        liabilityEndAmount: item.liabilityEndAmount,
        liabilityBeginAmount: item.liabilityBeginAmount,
        isTotal: item.isTotal || false,
        isCategory: item.isCategory || false,
        indent: item.indent || false,
        guidanceOpinion: item.guidanceOpinion || ''
      }))

      // 更新公司名称
      if (data[0]?.companyName) {
        queryParams.companyName = data[0].companyName
      }
      // 更新指导意见
      if (data[0]?.guidanceOpinion) {
        guidanceOpinion.value = data[0].guidanceOpinion
      } else {
        guidanceOpinion.value = ''
      }
    } else {
      // 如果没有数据，使用默认模板
      balanceSheetData.value = JSON.parse(JSON.stringify(defaultBalanceSheetData))
      guidanceOpinion.value = ''
    }
  } catch (error) {
    console.error('查询资产负债表失败:', error)
    // 查询失败时使用默认模板
    balanceSheetData.value = JSON.parse(JSON.stringify(defaultBalanceSheetData))
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.companyName = ''
  queryParams.reportDate = formatDate(new Date(), 'YYYY-MM')
  handleQuery()
}

/** 格式化金额 */
const formatAmount = (amount: number | null) => {
  if (amount === null || amount === undefined) {
    return ''
  }
  return amount.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true

    // 构建表格HTML，将输入框值转换为格式化文本
    let tableHtml = `
      <table border="1" cellspacing="0" cellpadding="0" style="border-collapse:collapse;width:100%;font-family:Arial;">
        <thead>
          <tr>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:180px;">资产</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:50px;">行次</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:140px;">期末余额</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:140px;">年初余额</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:220px;">负债和所有者权益(或股东权益)</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:50px;">行次</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:140px;">期末余额</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:140px;">年初余额</th>
          </tr>
        </thead>
        <tbody>
    `

    balanceSheetData.value.forEach(row => {
      const assetEndAmount = row.assetEndAmount !== null && row.assetEndAmount !== undefined
        ? formatAmount(row.assetEndAmount) : ''
      const assetBeginAmount = row.assetBeginAmount !== null && row.assetBeginAmount !== undefined
        ? formatAmount(row.assetBeginAmount) : ''
      const liabilityEndAmount = row.liabilityEndAmount !== null && row.liabilityEndAmount !== undefined
        ? formatAmount(row.liabilityEndAmount) : ''
      const liabilityBeginAmount = row.liabilityBeginAmount !== null && row.liabilityBeginAmount !== undefined
        ? formatAmount(row.liabilityBeginAmount) : ''

      const indentStyle = row.indent ? 'padding-left:20px;' : ''
      const boldStyle = (row.isTotal || row.isCategory) ? 'font-weight:bold;' : ''
      const bgStyle = row.isTotal ? 'background-color:#fafafa;' : ''

      tableHtml += `
        <tr style="${bgStyle}">
          <td style="border:1px solid #000;padding:8px;text-align:left;${indentStyle}${boldStyle}">${(row.assetItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:center;${boldStyle}">${(row.assetLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:right;${boldStyle}">${assetEndAmount}</td>
          <td style="border:1px solid #000;padding:8px;text-align:right;${boldStyle}">${assetBeginAmount}</td>
          <td style="border:1px solid #000;padding:8px;text-align:left;${indentStyle}${boldStyle}">${(row.liabilityItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:center;${boldStyle}">${(row.liabilityLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:right;${boldStyle}">${liabilityEndAmount}</td>
          <td style="border:1px solid #000;padding:8px;text-align:right;${boldStyle}">${liabilityBeginAmount}</td>
        </tr>
      `
    })

    tableHtml += `
        </tbody>
      </table>
    `

    const title = '资产负债表'
    const subTitleLeft = `编制单位：${queryParams.companyName || ''}`
    const subTitleRight = `${queryParams.reportDate || ''}    单位：元`
    const html = `<!DOCTYPE html><html><head><meta charset="UTF-8" />
      <style>
        body { margin: 20px; font-family: Arial, sans-serif; }
        .header { display: flex; justify-content: space-between; margin-bottom: 15px; font-size: 14px; }
        .title { font-size: 18px; font-weight: bold; text-align: center; margin: 15px 0; }
      </style>
      </head><body>
      <div class="header">
        <div>${subTitleLeft}</div>
        <div>${subTitleRight}</div>
      </div>
      <div class="title">${title}</div>
      ${tableHtml}
      <div style="margin-top: 30px; display: flex; justify-content: space-around; font-size: 14px;">
        <span>单位负责人：</span>
        <span>会计负责人：</span>
        <span>制表人：</span>
      </div>
    </body></html>`

    // 使用带 BOM 的 HTML 以提高 Excel 兼容性
    const blob = new Blob(["\ufeff", html], { type: 'application/vnd.ms-excel;charset=utf-8' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `资产负债表_${queryParams.reportDate || ''}.xls`
    a.click()
    URL.revokeObjectURL(url)
    message.success('导出成功')
  } catch (e) {
    console.error('导出失败:', e)
    message.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

/** 打印按钮操作 */
const handlePrint = () => {
  // 构建打印内容HTML
  let printHtml = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>资产负债表</title>
      <style>
        * {
          margin: 0;
          padding: 0;
          box-sizing: border-box;
        }
        body {
          font-family: Arial, sans-serif;
          padding: 8mm 15mm;
          max-width: 180mm;
          margin: 0 auto;
        }
        .sheet-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;
          margin-bottom: 3px;
          padding: 0;
        }
        .header-left {
          flex: 1;
          font-size: 9px;
        }
        .header-center {
          flex: 1;
          text-align: center;
        }
        .header-center h2 {
          font-size: 13px;
          font-weight: bold;
          margin: 0;
          padding: 2px 8px;
          color: #000;
          border: 1px solid #000;
          display: inline-block;
        }
        .header-right {
          flex: 1;
          text-align: right;
          font-size: 9px;
        }
        .balance-table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 4px;
          font-size: 6.5px;
          table-layout: fixed;
        }
        .balance-table th {
          background-color: #f5f7fa;
          color: #303133;
          font-weight: bold;
          padding: 1px;
          text-align: center;
          border: 1px solid #000;
          font-size: 6.5px;
          word-wrap: break-word;
          line-height: 1.2;
        }
        .balance-table td {
          padding: 1px;
          border: 1px solid #000;
          color: #303133;
          font-size: 6.5px;
          word-wrap: break-word;
          overflow: hidden;
          line-height: 1.2;
        }
        .balance-table td.text-left {
          text-align: left;
        }
        .balance-table td.text-left.indent {
          padding-left: 6px;
        }
        .balance-table td.text-center {
          text-align: center;
        }
        .balance-table td.text-right {
          text-align: right;
          padding-right: 3px;
        }
        .balance-table .total-row {
          font-weight: bold;
          background-color: #fafafa;
        }
        .balance-table .category-row {
          font-weight: bold;
        }
        .sheet-footer {
          margin-top: 3px;
          padding-top: 2px;
        }
        .footer-item {
          display: flex;
          justify-content: space-around;
          font-size: 8px;
        }
        .footer-item span {
          flex: 1;
          text-align: center;
        }
        @media print {
          body {
            padding: 8mm 15mm;
            max-width: 180mm;
            margin: 0 auto;
          }
          @page {
            size: A4;
            margin: 8mm 15mm;
          }
          .balance-table {
            font-size: 5.5px;
          }
          .balance-table th,
          .balance-table td {
            font-size: 12px;
            padding: 1px;
            line-height: 1.1;
          }
          .header-center h2 {
            font-size: 11px;
            padding: 2px 6px;
          }
          .header-left,
          .header-right {
            font-size: 8px;
          }
          .footer-item {
            font-size: 7px;
          }
          .sheet-header {
            margin-bottom: 2px;
          }
          .balance-table {
            margin-bottom: 3px;
          }
        }
      </style>
    </head>
    <body>
      <div class="sheet-header">
        <div class="header-left">
          <span>编制单位：${queryParams.companyName || ''}</span>
        </div>
        <div class="header-center">
          <h2>资产负债表</h2>
        </div>
        <div class="header-right">
          <div>单位：元</div>
        </div>
      </div>
      <table class="balance-table" border="1" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th style="width: 16%;">资产</th>
            <th style="width: 5%;">行次</th>
            <th style="width: 12%;">期末余额</th>
            <th style="width: 12%;">年初余额</th>
            <th style="width: 16%;">负债和所有者权益(或股东权益)</th>
            <th style="width: 5%;">行次</th>
            <th style="width: 12%;">期末余额</th>
            <th style="width: 12%;">年初余额</th>
          </tr>
        </thead>
        <tbody>
  `

  // 添加表格数据行
  balanceSheetData.value.forEach(row => {
    const assetEndAmount = row.assetEndAmount !== null && row.assetEndAmount !== undefined
      ? formatAmount(row.assetEndAmount) : ''
    const assetBeginAmount = row.assetBeginAmount !== null && row.assetBeginAmount !== undefined
      ? formatAmount(row.assetBeginAmount) : ''
    const liabilityEndAmount = row.liabilityEndAmount !== null && row.liabilityEndAmount !== undefined
      ? formatAmount(row.liabilityEndAmount) : ''
    const liabilityBeginAmount = row.liabilityBeginAmount !== null && row.liabilityBeginAmount !== undefined
      ? formatAmount(row.liabilityBeginAmount) : ''

    const indentClass = row.indent ? ' indent' : ''
    const rowClass = row.isTotal ? 'total-row' : (row.isCategory ? 'category-row' : '')

    printHtml += `
      <tr class="${rowClass}">
        <td class="text-left${indentClass}">${(row.assetItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-center">${(row.assetLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-right">${assetEndAmount}</td>
        <td class="text-right">${assetBeginAmount}</td>
        <td class="text-left${indentClass}">${(row.liabilityItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-center">${(row.liabilityLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-right">${liabilityEndAmount}</td>
        <td class="text-right">${liabilityBeginAmount}</td>
      </tr>
    `
  })

  printHtml += `
        </tbody>
      </table>
      <div class="sheet-footer">
        <div class="footer-item">
          <span>单位负责人：</span>
          <span>会计负责人：</span>
          <span>制表人：</span>
        </div>
      </div>
    </body>
    </html>
  `

  // 打开新窗口并打印
  const printWindow = window.open('', '_blank')
  if (printWindow) {
    printWindow.document.write(printHtml)
    printWindow.document.close()
    printWindow.onload = () => {
      setTimeout(() => {
        printWindow.print()
        // 打印后可以选择关闭窗口
        // printWindow.close()
      }, 250)
    }
  } else {
    message.error('无法打开打印窗口，请检查浏览器弹窗设置')
  }
}

/** 格式化报表日期为 YYYY-MM 格式 */
const formatReportDate = (dateStr: string): string => {
  if (!dateStr) return ''
  // 如果已经是 YYYY-MM 格式，直接返回
  if (/^\d{4}-\d{2}$/.test(dateStr)) {
    return dateStr
  }
  // 如果是 YYYY-MM-DD 格式，提取前7个字符
  if (/^\d{4}-\d{2}-\d{2}/.test(dateStr)) {
    return dateStr.substring(0, 7)
  }
  // 其他情况，尝试解析并格式化
  try {
    const date = new Date(dateStr)
    return formatDate(date, 'YYYY-MM')
  } catch {
    return dateStr.substring(0, 7)
  }
}

/** 保存按钮操作 */
const handleSave = async () => {
  if (!queryParams.reportDate) {
    message.warning('请选择报表日期')
    return
  }

  saveLoading.value = true
  try {
    // 确保报表日期格式为 YYYY-MM
    const formattedReportDate = formatReportDate(queryParams.reportDate)

    const saveData: BalanceSheetRowVO[] = balanceSheetData.value.map(row => ({
      assetItem: row.assetItem,
      assetLineNo: row.assetLineNo,
      assetEndAmount: row.assetEndAmount,
      assetBeginAmount: row.assetBeginAmount,
      liabilityItem: row.liabilityItem,
      liabilityLineNo: row.liabilityLineNo,
      liabilityEndAmount: row.liabilityEndAmount,
      liabilityBeginAmount: row.liabilityBeginAmount,
      isTotal: row.isTotal,
      isCategory: row.isCategory,
      indent: row.indent
    }))

    await BalanceSheetApi.saveBalanceSheet({
      reportDate: formattedReportDate,
      companyName: queryParams.companyName,
      guidanceOpinion: guidanceOpinion.value,
      rows: saveData
    })

    message.success('保存成功')
  } catch (error) {
    console.error('保存资产负债表失败:', error)
    message.error('保存失败，请重试')
  } finally {
    saveLoading.value = false
  }
}

/** 添加行（在指定索引后插入） */
const handleAddRow = (index: number) => {
  const newRow: BalanceSheetRow = {
    assetItem: '',
    assetLineNo: '',
    assetEndAmount: null,
    assetBeginAmount: null,
    liabilityItem: '',
    liabilityLineNo: '',
    liabilityEndAmount: null,
    liabilityBeginAmount: null,
    isTotal: false,
    isCategory: false,
    indent: false,
    guidanceOpinion: ''
  }
  balanceSheetData.value.splice(index + 1, 0, newRow)
}

/** 在末尾添加行 */
const handleAddRowAtEnd = () => {
  const newRow: BalanceSheetRow = {
    assetItem: '',
    assetLineNo: '',
    assetEndAmount: null,
    assetBeginAmount: null,
    liabilityItem: '',
    liabilityLineNo: '',
    liabilityEndAmount: null,
    liabilityBeginAmount: null,
    isTotal: false,
    isCategory: false,
    indent: false,
    guidanceOpinion: ''
  }
  balanceSheetData.value.push(newRow)
}

/** 删除行 */
const handleDeleteRow = (index: number) => {
  const row = balanceSheetData.value[index]

  // 保护合计行和分类行
  if (row.isTotal || row.isCategory) {
    message.warning('合计行或分类行不能删除')
    return
  }

  // 确认删除
  message.confirm(`确定要删除第 ${index + 1} 行吗？`, '提示').then(() => {
    balanceSheetData.value.splice(index, 1)
    message.success('删除成功')
  }).catch(() => {
    // 取消删除
  })
}

/** 初始化 */
onMounted(() => {
  // 初始化时使用默认数据
  balanceSheetData.value = JSON.parse(JSON.stringify(defaultBalanceSheetData))
  getList()
})
</script>

<style lang="scss" scoped>
.balance-sheet-container {
  .balance-sheet {
    background: #fff;
    padding: 20px;

    .sheet-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 10px;
      padding: 10px 0;

      .header-left {
        flex: 1;
        font-size: 14px;
        color: #303133;
        display: flex;
        align-items: center;
        gap: 8px;

        .company-name-input {
          width: 200px;

          :deep(.el-input__wrapper) {
            border: none;
            box-shadow: none;
            background: transparent;
            border-radius: 0;
            padding: 0 4px;
          }

          :deep(.el-input__wrapper:hover) {
            border: none;
            box-shadow: none;
          }

          :deep(.el-input__wrapper.is-focus) {
            border: none;
            box-shadow: none;
          }

          :deep(.el-input__inner) {
            padding: 0;
            font-size: 14px;
          }
        }
      }

      .header-center {
        flex: 1;
        text-align: center;

        h2 {
          font-size: 22px;
          font-weight: bold;
          margin: 0;
          padding: 0;
          color: #000;
          border: 2px solid #000;
          display: inline-block;
          padding: 5px 15px;
        }
      }

      .header-right {
        flex: 1;
        text-align: right;
        font-size: 14px;
        color: #303133;

        div {
          margin-bottom: 5px;
        }
      }
    }

    .balance-table {
      width: 100%;
      border-collapse: collapse;
      margin-bottom: 20px;
      font-size: 13px;

      th {
        background-color: #f5f7fa;
        color: #303133;
        font-weight: bold;
        padding: 10px 8px;
        text-align: center;
        border: 1px solid #000;

        &.no-print {
          @media print {
            display: none;
          }
        }
      }

      td {
        padding: 8px;
        border: 1px solid #000;
        color: #303133;

        &.text-left {
          text-align: left;

          &.indent {
            padding-left: 20px;
          }
        }

        &.text-center {
          text-align: center;
        }

        &.text-right {
          text-align: right;
          padding-right: 10px;

          .amount-input {
            width: 100%;

            :deep(.el-input__wrapper) {
              padding: 2px 8px;
              border: none;
              box-shadow: none;
              background: transparent;
            }

            :deep(.el-input__wrapper:hover) {
              border: none;
              box-shadow: none;
            }

            :deep(.el-input__wrapper.is-focus) {
              border: 1px solid var(--el-input-border-color, #dcdfe6);
              box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--el-color-primary)) inset;
            }

            :deep(.el-input__inner) {
              text-align: right;
              padding: 0;
            }
          }
        }

        &.action-cell {
          padding: 4px;
          text-align: center;

          .el-button {
            padding: 4px 8px;
          }
        }

        .item-input {
          width: 100%;

          :deep(.el-input__wrapper) {
            padding: 2px 8px;
            border: none;
            box-shadow: none;
            background: transparent;
          }

          :deep(.el-input__wrapper:hover) {
            border: none;
            box-shadow: none;
          }

          :deep(.el-input__wrapper.is-focus) {
            border: 1px solid var(--el-input-border-color, #dcdfe6);
            box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--el-color-primary)) inset;
          }

          :deep(.el-input__inner) {
            padding: 0;
            text-align: left;
          }
        }

        .line-no-input {
          width: 100%;

          :deep(.el-input__wrapper) {
            padding: 2px 4px;
            border: none;
            box-shadow: none;
            background: transparent;
          }

          :deep(.el-input__wrapper:hover) {
            border: none;
            box-shadow: none;
          }

          :deep(.el-input__wrapper.is-focus) {
            border: 1px solid var(--el-input-border-color, #dcdfe6);
            box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--el-color-primary)) inset;
          }

          :deep(.el-input__inner) {
            padding: 0;
            text-align: center;
          }
        }
      }

      .total-row {
        font-weight: bold;
        background-color: #fafafa;

        td {
          font-weight: bold;
        }
      }

      .category-row {
        font-weight: bold;

        td {
          font-weight: bold;
        }
      }
    }

    .sheet-footer {
      margin-top: 20px;
      padding-top: 10px;

      .footer-item {
        display: flex;
        justify-content: space-around;
        font-size: 14px;
        color: #303133;

        span {
          flex: 1;
          text-align: center;
        }
      }
    }

    .guidance-opinion {
      margin-top: 20px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fafafa;

      .guidance-label {
        font-size: 14px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 10px;
      }

      .guidance-input {
        width: 100%;
      }
    }
  }

  // 打印时隐藏操作列
  @media print {
    .balance-table {
      .action-cell {
        display: none !important;
      }

      th.no-print {
        display: none !important;
      }
    }
  }
}
</style>

