<template>
  <doc-alert title="财务" url="https://www.yuque.com/goodrain/mom/finance" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="会计期间" prop="period">
        <el-date-picker
          v-model="queryParams.period"
          type="month"
          placeholder="选择会计期间"
          format="YYYY-MM"
          value-format="YYYYMM"
          :clearable="false"
          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-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleSave"
          v-hasPermi="['erp:subject-opening-balance:update']"
        >
          <Icon icon="ep:finished" class="mr-5px" /> 保存调整
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          @click="handleCalculateNextPeriod"
          v-hasPermi="['erp:subject-opening-balance:query']"
        >
          <Icon icon="ep:position" class="mr-5px" /> 计算下期期初
        </el-button>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="openingBalanceList"
      border
      fit
      highlight-current-row
      :show-overflow-tooltip="true"
    >
      <el-table-column label="序号" type="index" align="center" width="60" />
      
      <el-table-column label="科目编码" prop="subjectCode" width="120" />
      
      <el-table-column label="科目名称" prop="subjectName" min-width="200" show-overflow-tooltip />
      
      <el-table-column label="期初余额" width="200">
        <template #default="{ row }">
          <el-input-number
            v-model="row.balance"
            :precision="2"
            :min="0"
            controls-position="right"
            style="width: 100%"
            :disabled="!row.canEdit"
          />
        </template>
      </el-table-column>
      
      <el-table-column label="余额方向" prop="direction" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="getDirectionTagType(row.direction)">
            {{ row.direction }}
          </el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="150" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
            v-if="!row.canEdit"
            link
            type="primary"
            size="small"
            @click="handleEdit(row)"
            v-hasPermi="['erp:subject-opening-balance:update']"
          >
            修改
          </el-button>
          <el-button
            v-else
            link
            type="success"
            size="small"
            @click="handleCancelEdit(row)"
          >
            取消
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ContentWrap>

  <!-- 计算下期期初对话框 -->
  <el-dialog
    v-model="calculateDialogVisible"
    title="计算下期期初余额"
    width="500px"
  >
    <el-form ref="calculateFormRef" :model="calculateForm" :rules="calculateRules" label-width="120px">
      <el-form-item label="当前期间" prop="currentPeriod">
        <el-input v-model="calculateForm.currentPeriod" disabled />
      </el-form-item>
      <el-form-item label="下期期间" prop="nextPeriod">
        <el-input v-model="calculateForm.nextPeriod" disabled />
      </el-form-item>
      <el-form-item label="提示信息">
        <el-alert
          title="此操作将根据当前期间的期末余额计算并生成下期期初余额，请谨慎操作！"
          type="warning"
          :closable="false"
          show-icon
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="calculateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCalculate">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { OpeningBalanceApi, OpeningBalanceVO } from '@/api/erp/finance/opening-balance/index'
import { SubjectApi, SubjectVO } from '@/api/erp/finance/subject'
import ContentWrap from '@/components/ContentWrap/src/ContentWrap.vue'
import Icon from '@/components/Icon/src/Icon.vue'

defineOptions({ name: 'ErpOpeningBalance' })

// 响应式数据
const loading = ref(true)
const queryParams = reactive({
  period: formatDateToPeriod(new Date())
})
const openingBalanceList = ref<OpeningBalanceVO[]>([])
const calculateDialogVisible = ref(false)
const calculateForm = reactive({
  currentPeriod: '',
  nextPeriod: ''
})
const calculateRules = reactive({})

// 计算下期期间
function getNextPeriod(period: string): string {
  const year = parseInt(period.substring(0, 4))
  const month = parseInt(period.substring(4, 6))
  
  let nextYear = year
  let nextMonth = month + 1
  
  if (nextMonth > 12) {
    nextYear++
    nextMonth = 1
  }
  
  return `${nextYear}${String(nextMonth).padStart(2, '0')}`
}

// 月份格式化函数
function formatDateToPeriod(date: Date): string {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  return `${year}${month}`
}

// 获取期初余额列表
const getList = async () => {
  loading.value = true
  try {
    // 获取所有科目信息
    const subjectsRes: any = await SubjectApi.getSubjectSimpleList()
    console.log('科目列表数据:', subjectsRes) // 添加调试日志
    const subjects: SubjectVO[] = Array.isArray(subjectsRes) ? subjectsRes : subjectsRes?.data || [] // 修复数据访问方式
    
    // 获取已存在的期初余额
    const res: any = await OpeningBalanceApi.getOpeningBalanceListByPeriod(queryParams.period)
    console.log('期初余额数据:', res) // 添加调试日志
    const existingBalances = Array.isArray(res) ? res : res?.data || [] // 修复数据访问方式
    
    console.log('处理后的科目数量:', subjects.length) // 添加调试日志
    console.log('处理后的期初余额数量:', existingBalances.length) // 添加调试日志
    
    // 合并数据，对于没有期初余额的科目，初始化为0
    const mergedList: OpeningBalanceVO[] = subjects.map((subject: SubjectVO) => {
      const existing = existingBalances.find((item: any) => item.subjectId === subject.id)
      console.log('匹配结果:', subject.code, subject.name, existing) // 添加调试日志
      return {
        id: existing?.id || undefined,
        subjectId: subject.id,
        subjectCode: subject.code,
        subjectName: subject.name,
        period: queryParams.period,
        balance: existing ? parseFloat(existing.balance) : 0,
        direction: existing ? existing.direction : '借',
        canEdit: false // 默认不可编辑
      }
    })
    
    console.log('最终合并列表:', mergedList) // 添加调试日志
    openingBalanceList.value = mergedList
  } catch (error) {
    console.error(error)
    ElMessage.error('获取期初余额列表失败')
  } finally {
    loading.value = false
  }
}

// 获取方向标签类型
const getDirectionTagType = (direction: string) => {
  if (direction === '借') return 'primary'
  if (direction === '贷') return 'danger'
  return 'info'
}

// 处理查询
const handleQuery = () => {
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.period = formatDateToPeriod(new Date())
  getList()
}

// 处理编辑
const handleEdit = (row: OpeningBalanceVO) => {
  row.canEdit = true
}

// 取消编辑
const handleCancelEdit = (row: OpeningBalanceVO) => {
  row.canEdit = false
  // 重置为原始值，重新加载数据
  getList()
}

// 保存调整
const handleSave = async () => {
  try {
    // 检查是否有修改的数据
    const modifiedList = openingBalanceList.value.filter(item => item.canEdit)
    if (modifiedList.length === 0) {
      ElMessage.warning('没有可保存的数据')
      return
    }

    // 准备提交数据
    const submitData = modifiedList.map(item => ({
      id: item.id,
      subjectId: item.subjectId,
      period: item.period,
      balance: item.balance,
      direction: item.direction
    }))

    await OpeningBalanceApi.batchUpdateOpeningBalance(submitData)
    ElMessage.success('保存成功')
    
    // 退出编辑模式
    openingBalanceList.value.forEach(item => {
      item.canEdit = false
    })
    
    // 重新加载数据
    getList()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 计算下期期初余额
const handleCalculateNextPeriod = () => {
  calculateForm.currentPeriod = queryParams.period
  calculateForm.nextPeriod = getNextPeriod(queryParams.period)
  calculateDialogVisible.value = true
}

// 确认计算
const confirmCalculate = async () => {
  try {
    // 这里应该调用实际的后端计算下期期初余额的API
    // 暂时只显示提示信息
    ElMessage.success(`已启动计算 ${calculateForm.currentPeriod} -> ${calculateForm.nextPeriod} 期间的期初余额`)
    calculateDialogVisible.value = false
  } catch (error) {
    console.error('计算失败:', error)
    ElMessage.error('计算失败')
  }
}

onMounted(() => {
  getList()
})
</script>