<template>
  <div class="cash-flow-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:cash-flow-sheet:create']">
              <Icon icon="ep:check" class="mr-5px" /> 保存
            </el-button>
            <el-button type="info" plain @click="handleAddRowAtEnd" v-hasPermi="['erp:cash-flow-sheet:addline']">
              <Icon icon="ep:plus" class="mr-5px" /> 添加行
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </div>

    <!-- 现金流量表主体 -->
    <ContentWrap>
      <div class="cash-flow-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="cash-flow-table" border="1" cellspacing="0" cellpadding="0">
          <thead>
            <tr>
              <th width="300">项目</th>
              <th width="80">行次</th>
              <th width="180">金额</th>
              <th width="300">补充资料</th>
              <th width="80">行次</th>
              <th width="180">金额</th>
              <th width="100" class="no-print" v-hasPermi="['erp:cash-flow-sheet:addline']">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(row, index) in cashFlowSheetData" :key="index" :class="{ 'total-row': row.isTotal, 'category-row': row.isCategory }">
              <td :class="{ 'text-left': true, 'indent': row.indent }">
                <el-input
                  v-model="row.mainItem"
                  class="item-input"
                  size="small"
                  placeholder=""
                  clearable
                />
              </td>
              <td class="text-center">
                <el-input
                  v-model="row.mainLineNo"
                  class="line-no-input"
                  size="small"
                  placeholder=""
                  maxlength="10"
                />
              </td>
              <td class="text-right">
                <el-input-number
                  :model-value="row.mainAmount ?? undefined"
                  @update:model-value="row.mainAmount = $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.supplementItem"
                  class="item-input"
                  size="small"
                  placeholder=""
                  clearable
                />
              </td>
              <td class="text-center">
                <el-input
                  v-model="row.supplementLineNo"
                  class="line-no-input"
                  size="small"
                  placeholder=""
                  maxlength="10"
                />
              </td>
              <td class="text-right">
                <el-input-number
                  :model-value="row.supplementAmount ?? undefined"
                  @update:model-value="row.supplementAmount = $event ?? null"
                  :precision="2"
                  :controls="false"
                  :min="undefined"
                  class="amount-input"
                  size="small"
                  placeholder=""
                />
              </td>
              <td class="text-center action-cell" v-hasPermi="['erp:cash-flow-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 { CashFlowSheetApi } from '@/api/erp/threetables/cashflow'
import type { CashFlowSheetRowVO } from '@/api/erp/threetables/cashflow'

/** 现金流量表 */
defineOptions({ name: 'CashFlowSheet' })

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 CashFlowSheetRow {
  mainItem: string
  mainLineNo: string
  mainAmount: number | null
  supplementItem: string
  supplementLineNo: string
  supplementAmount: number | null
  isTotal?: boolean
  isCategory?: boolean
  indent?: boolean
}

// 默认现金流量表数据模板（根据图片格式）
const defaultCashFlowSheetData: CashFlowSheetRow[] = [
  // 经营活动产生的现金流量
  { mainItem: '一、经营活动产生的现金流量：', mainLineNo: '', mainAmount: null, supplementItem: '1、将净利润调节为经营活动现金流量：', supplementLineNo: '', supplementAmount: null, isCategory: true },
  { mainItem: '销售商品、提供劳务收到的现金', mainLineNo: '1', mainAmount: null, supplementItem: '净利润', supplementLineNo: '1', supplementAmount: null, indent: true },
  { mainItem: '收到的税费返还', mainLineNo: '2', mainAmount: null, supplementItem: '加：计提的资产减值准备', supplementLineNo: '2', supplementAmount: null, indent: true },
  { mainItem: '收到的其他与经营活动有关的现金', mainLineNo: '3', mainAmount: null, supplementItem: '固定资产折旧', supplementLineNo: '3', supplementAmount: null, indent: true },
  { mainItem: '现金流入小计', mainLineNo: '4', mainAmount: null, supplementItem: '无形资产摊销', supplementLineNo: '4', supplementAmount: null, isTotal: true },
  { mainItem: '购买商品、接受劳务支付的现金', mainLineNo: '5', mainAmount: null, supplementItem: '长期待摊费用摊销', supplementLineNo: '5', supplementAmount: null, indent: true },
  { mainItem: '支付给职工以及为职工支付的现金', mainLineNo: '6', mainAmount: null, supplementItem: '处置固定资产、无形资产和其他长期资产的损失（减：收益）', supplementLineNo: '6', supplementAmount: null, indent: true },
  { mainItem: '支付的各项税费', mainLineNo: '7', mainAmount: null, supplementItem: '固定资产报废损失', supplementLineNo: '7', supplementAmount: null, indent: true },
  { mainItem: '支付的其他与经营活动有关的现金', mainLineNo: '8', mainAmount: null, supplementItem: '公允价值变动损失（减：收益）', supplementLineNo: '8', supplementAmount: null, indent: true },
  { mainItem: '现金流出小计', mainLineNo: '9', mainAmount: null, supplementItem: '财务费用', supplementLineNo: '9', supplementAmount: null, isTotal: true },
  { mainItem: '经营活动产生的现金流量净额', mainLineNo: '10', mainAmount: null, supplementItem: '投资损失（减：收益）', supplementLineNo: '10', supplementAmount: null, isTotal: true },

  // 投资活动产生的现金流量
  { mainItem: '二、投资活动产生的现金流量：', mainLineNo: '', mainAmount: null, supplementItem: '递延所得税资产减少（减：增加）', supplementLineNo: '11', supplementAmount: null, isCategory: true },
  { mainItem: '收回投资所收到的现金', mainLineNo: '11', mainAmount: null, supplementItem: '递延所得税负债增加（减：减少）', supplementLineNo: '12', supplementAmount: null, indent: true },
  { mainItem: '取得投资收益所收到的现金', mainLineNo: '12', mainAmount: null, supplementItem: '存货的减少（减：增加）', supplementLineNo: '13', supplementAmount: null, indent: true },
  { mainItem: '处置固定资产、无形资产和其他长期资产所收回的现金净额', mainLineNo: '13', mainAmount: null, supplementItem: '经营性应收项目的减少（减：增加）', supplementLineNo: '14', supplementAmount: null, indent: true },
  { mainItem: '处置子公司及其他营业单位收到的现金净额', mainLineNo: '14', mainAmount: null, supplementItem: '经营性应付项目的增加（减：减少）', supplementLineNo: '15', supplementAmount: null, indent: true },
  { mainItem: '收到的其他与投资活动有关的现金', mainLineNo: '15', mainAmount: null, supplementItem: '其他', supplementLineNo: '16', supplementAmount: null, indent: true },
  { mainItem: '现金流入小计', mainLineNo: '16', mainAmount: null, supplementItem: '经营活动产生的现金流量净额', supplementLineNo: '17', supplementAmount: null, isTotal: true },
  { mainItem: '购建固定资产、无形资产和其他长期资产所支付的现金', mainLineNo: '17', mainAmount: null, supplementItem: '2、不涉及现金收支的投资和筹资活动：', supplementLineNo: '', supplementAmount: null, isCategory: true },
  { mainItem: '投资所支付的现金', mainLineNo: '18', mainAmount: null, supplementItem: '债务转为资本', supplementLineNo: '18', supplementAmount: null, indent: true },
  { mainItem: '支付的其他与投资活动有关的现金', mainLineNo: '19', mainAmount: null, supplementItem: '一年内到期的可转换公司债券', supplementLineNo: '19', supplementAmount: null, indent: true },
  { mainItem: '现金流出小计', mainLineNo: '20', mainAmount: null, supplementItem: '融资租入固定资产', supplementLineNo: '20', supplementAmount: null, isTotal: true },
  { mainItem: '投资活动产生的现金流量净额', mainLineNo: '21', mainAmount: null, supplementItem: '3、现金及现金等价物净增加情况：', supplementLineNo: '', supplementAmount: null, isTotal: true },

  // 筹资活动产生的现金流量
  { mainItem: '三、筹资活动产生的现金流量：', mainLineNo: '', mainAmount: null, supplementItem: '现金的期末余额', supplementLineNo: '21', supplementAmount: null, isCategory: true },
  { mainItem: '吸收投资所收到的现金', mainLineNo: '22', mainAmount: null, supplementItem: '减：现金的期初余额', supplementLineNo: '22', supplementAmount: null, indent: true },
  { mainItem: '借款所收到的现金', mainLineNo: '23', mainAmount: null, supplementItem: '加：现金等价物的期末余额', supplementLineNo: '23', supplementAmount: null, indent: true },
  { mainItem: '收到的其他与筹资活动有关的现金', mainLineNo: '24', mainAmount: null, supplementItem: '减：现金等价物的期初余额', supplementLineNo: '24', supplementAmount: null, indent: true },
  { mainItem: '现金流入小计', mainLineNo: '25', mainAmount: null, supplementItem: '现金及现金等价物净增加额', supplementLineNo: '25', supplementAmount: null, isTotal: true },
  { mainItem: '偿还债务所支付的现金', mainLineNo: '26', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, indent: true },
  { mainItem: '分配股利、利润或偿付利息所支付的现金', mainLineNo: '27', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, indent: true },
  { mainItem: '支付的其他与筹资活动有关的现金', mainLineNo: '28', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, indent: true },
  { mainItem: '现金流出小计', mainLineNo: '29', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, isTotal: true },
  { mainItem: '筹资活动产生的现金流量净额', mainLineNo: '30', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, isTotal: true },
  { mainItem: '四、汇率变动对现金的影响', mainLineNo: '31', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, isTotal: true },
  { mainItem: '五、现金及现金等价物净增加额', mainLineNo: '32', mainAmount: null, supplementItem: '', supplementLineNo: '', supplementAmount: null, isTotal: true }
]

// 现金流量表数据
const cashFlowSheetData = ref<CashFlowSheetRow[]>([])

// 指导意见
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 CashFlowSheetApi.getCashFlowSheet(formattedReportDate)

    if (data && data.length > 0) {
      // 从后端获取数据
      cashFlowSheetData.value = data.map(item => ({
        mainItem: item.mainItem || '',
        mainLineNo: item.mainLineNo || '',
        mainAmount: item.mainAmount,
        supplementItem: item.supplementItem || '',
        supplementLineNo: item.supplementLineNo || '',
        supplementAmount: item.supplementAmount,
        isTotal: item.isTotal || false,
        isCategory: item.isCategory || false,
        indent: item.indent || false
      }))

      // 更新公司名称
      if (data[0]?.companyName) {
        queryParams.companyName = data[0].companyName
      }
      // 更新指导意见
      if (data[0]?.guidanceOpinion) {
        guidanceOpinion.value = data[0].guidanceOpinion
      } else {
        guidanceOpinion.value = ''
      }
    } else {
      // 如果没有数据，使用默认模板
      cashFlowSheetData.value = JSON.parse(JSON.stringify(defaultCashFlowSheetData))
      guidanceOpinion.value = ''
    }
  } catch (error) {
    console.error('查询现金流量表失败:', error)
    // 查询失败时使用默认模板
    cashFlowSheetData.value = JSON.parse(JSON.stringify(defaultCashFlowSheetData))
  } 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:300px;">项目</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:80px;">行次</th>
            <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:300px;">补充资料</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:80px;">行次</th>
            <th style="border:1px solid #000;padding:8px;background:#f5f7fa;font-weight:bold;text-align:center;width:180px;">金额</th>
          </tr>
        </thead>
        <tbody>
    `

    cashFlowSheetData.value.forEach(row => {
      const mainAmount = row.mainAmount !== null && row.mainAmount !== undefined
        ? formatAmount(row.mainAmount) : ''
      const supplementAmount = row.supplementAmount !== null && row.supplementAmount !== undefined
        ? formatAmount(row.supplementAmount) : ''

      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.mainItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:center;${boldStyle}">${(row.mainLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:right;${boldStyle}">${mainAmount}</td>
          <td style="border:1px solid #000;padding:8px;text-align:left;${indentStyle}${boldStyle}">${(row.supplementItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:center;${boldStyle}">${(row.supplementLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
          <td style="border:1px solid #000;padding:8px;text-align:right;${boldStyle}">${supplementAmount}</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;
        }
        .cash-flow-table {
          width: 100%;
          border-collapse: collapse;
          margin-bottom: 4px;
          font-size: 6.5px;
          table-layout: fixed;
        }
        .cash-flow-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;
        }
        .cash-flow-table td {
          padding: 1px;
          border: 1px solid #000;
          color: #303133;
          font-size: 6.5px;
          word-wrap: break-word;
          overflow: hidden;
          line-height: 1.2;
        }
        .cash-flow-table td.text-left {
          text-align: left;
        }
        .cash-flow-table td.text-left.indent {
          padding-left: 6px;
        }
        .cash-flow-table td.text-center {
          text-align: center;
        }
        .cash-flow-table td.text-right {
          text-align: right;
          padding-right: 3px;
        }
        .cash-flow-table .total-row {
          font-weight: bold;
          background-color: #fafafa;
        }
        .cash-flow-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;
          }
          .cash-flow-table {
            font-size: 5.5px;
          }
          .cash-flow-table th,
          .cash-flow-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;
          }
          .cash-flow-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>${queryParams.reportDate || ''}年度</div>
          <div>单位：元</div>
        </div>
      </div>
      <table class="cash-flow-table" border="1" cellspacing="0" cellpadding="0">
        <thead>
          <tr>
            <th style="width: 25%;">项目</th>
            <th style="width: 7%;">行次</th>
            <th style="width: 15%;">金额</th>
            <th style="width: 25%;">补充资料</th>
            <th style="width: 7%;">行次</th>
            <th style="width: 15%;">金额</th>
          </tr>
        </thead>
        <tbody>
  `

  // 添加表格数据行
  cashFlowSheetData.value.forEach(row => {
    const mainAmount = row.mainAmount !== null && row.mainAmount !== undefined
      ? formatAmount(row.mainAmount) : ''
    const supplementAmount = row.supplementAmount !== null && row.supplementAmount !== undefined
      ? formatAmount(row.supplementAmount) : ''

    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.mainItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-center">${(row.mainLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-right">${mainAmount}</td>
        <td class="text-left${indentClass}">${(row.supplementItem || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-center">${(row.supplementLineNo || '').replace(/</g, '&lt;').replace(/>/g, '&gt;')}</td>
        <td class="text-right">${supplementAmount}</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: CashFlowSheetRowVO[] = cashFlowSheetData.value.map(row => ({
      mainItem: row.mainItem,
      mainLineNo: row.mainLineNo,
      mainAmount: row.mainAmount,
      supplementItem: row.supplementItem,
      supplementLineNo: row.supplementLineNo,
      supplementAmount: row.supplementAmount,
      isTotal: row.isTotal,
      isCategory: row.isCategory,
      indent: row.indent
    }))

    await CashFlowSheetApi.saveCashFlowSheet({
      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: CashFlowSheetRow = {
    mainItem: '',
    mainLineNo: '',
    mainAmount: null,
    supplementItem: '',
    supplementLineNo: '',
    supplementAmount: null,
    isTotal: false,
    isCategory: false,
    indent: false
  }
  cashFlowSheetData.value.splice(index + 1, 0, newRow)
}

/** 在末尾添加行 */
const handleAddRowAtEnd = () => {
  const newRow: CashFlowSheetRow = {
    mainItem: '',
    mainLineNo: '',
    mainAmount: null,
    supplementItem: '',
    supplementLineNo: '',
    supplementAmount: null,
    isTotal: false,
    isCategory: false,
    indent: false
  }
  cashFlowSheetData.value.push(newRow)
}

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

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

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

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

<style lang="scss" scoped>
.cash-flow-sheet-container {
  .cash-flow-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;
        }
      }
    }

    .cash-flow-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 {
    .cash-flow-table {
      .action-cell {
        display: none !important;
      }

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


